Fix: Do not send notify IDs that are not 0, 1 or 2
[lcr.git] / mISDN.cpp
1 /*****************************************************************************\
2 **                                                                           **
3 ** Linux Call Router                                                         **
4 **                                                                           **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg                                              **
7 **                                                                           **
8 ** mISDN port abstraction for dss1                                           **
9 **                                                                           **
10 \*****************************************************************************/ 
11
12 #include "main.h"
13 #include "myisdn.h"
14 #include <mISDN/q931.h>
15
16 #undef offsetof
17 #ifdef __compiler_offsetof
18 #define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
19 #else
20 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
21 #endif
22
23 #ifndef container_of
24 #define container_of(ptr, type, member) ({                      \
25         const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
26         (type *)( (char *)__mptr - offsetof(type,member) );})
27 #endif
28
29 // timeouts if activating/deactivating response from mISDN got lost
30 #define B_TIMER_ACTIVATING 1 // seconds
31 #define B_TIMER_DEACTIVATING 1 // seconds
32
33 /* list of mISDN ports */
34 struct mISDNport *mISDNport_first;
35
36 /* noise randomizer */
37 unsigned char mISDN_rand[256];
38 int mISDN_rand_count = 0;
39
40 #ifdef OLD_MT_ASSIGN
41 unsigned int mt_assign_pid = ~0;
42 #endif
43
44 int mISDNsocket = -1;
45 static int upqueue_pipe[2];
46 static struct lcr_fd upqueue_fd;
47 int upqueue_avail = 0;
48
49 static int mISDN_upqueue(struct lcr_fd *fd, unsigned int what, void *instance, int i);
50 static int mISDN_timeout(struct lcr_timer *timer, void *instance, int i);
51
52 static int my_mISDNlib_debug(const char *file, int line, const char *func, int level, const char *fmt, va_list va)
53 {
54         int ret = 0;
55
56         if (debug_fp > 0)
57                 ret = vfprintf(debug_fp, fmt, va);
58         return ret;
59 }
60
61 static struct mi_ext_fn_s myfn;
62
63 int mISDN_initialize(void)
64 {
65         char filename[256];
66
67         /* try to open raw socket to check kernel */
68         mISDNsocket = socket(PF_ISDN, SOCK_RAW, ISDN_P_BASE);
69         if (mISDNsocket < 0) {
70                 fprintf(stderr, "Cannot open mISDN due to '%s'. (Does your Kernel support socket based mISDN? Protocol family is %d.)\n", strerror(errno), PF_ISDN);
71                 return(-1);
72         }
73
74         /* init mlayer3 */
75         // set debug printout function
76         myfn.prt_debug = my_mISDNlib_debug;
77
78         init_layer3(4, &myfn); // buffer of 4
79
80         /* open debug, if enabled and not only stack debugging */
81         if (options.deb) {
82                 SPRINT(filename, "%s/debug.log", LOG_DIR);
83                 debug_fp = fopen(filename, "a");
84         }
85
86         if (options.deb & DEBUG_STACK)
87                 mISDN_set_debug_level(0xfffffeff);
88         else
89                 mISDN_set_debug_level(0);
90
91         if (pipe(upqueue_pipe) < 0)
92                 FATAL("Failed to open pipe\n");
93         memset(&upqueue_fd, 0, sizeof(upqueue_fd));
94         upqueue_fd.fd = upqueue_pipe[0];
95         register_fd(&upqueue_fd, LCR_FD_READ, mISDN_upqueue, NULL, 0);
96
97         return(0);
98 }
99
100 void mISDN_deinitialize(void)
101 {
102         cleanup_layer3();
103
104         if (debug_fp)
105                 fclose(debug_fp);
106         debug_fp = NULL;
107
108         if (mISDNsocket > -1)
109                 close(mISDNsocket);
110
111         if (upqueue_fd.inuse) {
112                 unregister_fd(&upqueue_fd);
113                 close(upqueue_pipe[0]);
114                 close(upqueue_pipe[1]);
115         }
116         upqueue_avail = 0;
117 }
118
119 static int load_timer(struct lcr_timer *timer, void *instance, int index);
120
121 /*
122  * constructor
123  */
124 PmISDN::PmISDN(int type, mISDNport *mISDNport, char *portname, struct port_settings *settings, struct interface *interface, int channel, int exclusive, int mode) : Port(type, portname, settings, interface)
125 {
126         p_m_mISDNport = mISDNport;
127         p_m_portnum = mISDNport->portnum;
128         p_m_b_index = -1;
129         p_m_b_channel = 0;
130         p_m_b_exclusive = 0;
131         p_m_b_reserve = 0;
132         p_m_b_mode = mode;
133         p_m_tx_gain = mISDNport->ifport->interface->tx_gain;
134         p_m_rx_gain = mISDNport->ifport->interface->rx_gain;
135         p_m_conf = 0;
136         p_m_mute = 0;
137         p_m_txdata = 0;
138         p_m_delay = 0;
139         p_m_tx_dejitter = 0;
140         p_m_preload = ISDN_LOAD;
141         p_m_disable_dejitter = 0;
142         p_m_echo = 0;
143         p_m_tone = 0;
144         p_m_rxoff = 0;
145         p_m_inband_send_on = 0;
146         p_m_inband_receive_on = 0;
147         p_m_dtmf = !mISDNport->ifport->nodtmf;
148         p_m_dtmf_threshold = mISDNport->ifport->dtmf_threshold;
149         memset(&p_m_timeout, 0, sizeof(p_m_timeout));
150         add_timer(&p_m_timeout, mISDN_timeout, this, 0);
151         SCPY(p_m_pipeline, mISDNport->ifport->interface->pipeline);
152         
153         /* audio */
154         memset(&p_m_loadtimer, 0, sizeof(p_m_loadtimer));
155         add_timer(&p_m_loadtimer, load_timer, this, 0);
156         p_m_load = 0;
157         p_m_last_tv_sec = 0;
158
159         /* crypt */
160         p_m_crypt = 0;
161         p_m_crypt_listen = 0;
162         p_m_crypt_msg_loops = 0;
163         p_m_crypt_msg_loops = 0;
164         p_m_crypt_msg_len = 0;
165         p_m_crypt_msg[0] = '\0';
166         p_m_crypt_msg_current = 0;
167         p_m_crypt_key_len = 0;
168         p_m_crypt_listen = 0;
169         p_m_crypt_listen_state = 0;
170         p_m_crypt_listen_len = 0;
171         p_m_crypt_listen_msg[0] = '\0';
172         p_m_crypt_listen_crc = 0;
173         if (mISDNport->ifport->interface->bf_len >= 4 && mISDNport->ifport->interface->bf_len <= 56) {
174                 memcpy(p_m_crypt_key, mISDNport->ifport->interface->bf_key, p_m_crypt_key_len);
175                 p_m_crypt_key_len = mISDNport->ifport->interface->bf_len;
176                 p_m_crypt = 1;
177         }
178
179         /* if any channel requested by constructor */
180         if (channel == CHANNEL_ANY) {
181                 /* reserve channel */
182                 p_m_b_reserve = 1;
183                 mISDNport->b_reserved++;
184         }
185
186         /* reserve channel */
187         if (channel > 0) // only if constructor was called with a channel resevation
188                 seize_bchannel(channel, exclusive);
189
190         /* we increase the number of objects: */
191         mISDNport->use++;
192         PDEBUG(DEBUG_ISDN, "Created new mISDNPort(%s). Currently %d objects use, port #%d\n", portname, mISDNport->use, p_m_portnum);
193 //inband_receive_on();
194 }
195
196
197 /*
198  * destructor
199  */
200 PmISDN::~PmISDN()
201 {
202         struct lcr_msg *message;
203
204         del_timer(&p_m_timeout);
205         del_timer(&p_m_loadtimer);
206
207         /* remove bchannel relation */
208         drop_bchannel();
209
210         /* release epoint */
211         while (p_epointlist) {
212                 PDEBUG(DEBUG_ISDN, "destroy mISDNPort(%s). endpoint still exists, releaseing.\n", p_name);
213                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
214                 message->param.disconnectinfo.cause = 16;
215                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
216                 message_put(message);
217                 /* remove from list */
218                 free_epointlist(p_epointlist);
219         }
220
221         /* we decrease the number of objects: */
222         p_m_mISDNport->use--;
223         PDEBUG(DEBUG_ISDN, "destroyed mISDNPort(%s). Currently %d objects\n", p_name, p_m_mISDNport->use);
224 }
225
226
227 /*
228  * trace
229  */
230 void chan_trace_header(struct mISDNport *mISDNport, class PmISDN *port, const char *msgtext, int direction)
231 {
232         /* init trace with given values */
233         start_trace(mISDNport?mISDNport->portnum:-1,
234                     (mISDNport)?((mISDNport->ifport)?mISDNport->ifport->interface:NULL):NULL,
235                     port?numberrize_callerinfo(port->p_callerinfo.id, port->p_callerinfo.ntype, options.national, options.international):NULL,
236                     port?port->p_dialinginfo.id:NULL,
237                     direction,
238                     CATEGORY_CH,
239                     port?port->p_serial:0,
240                     msgtext);
241 }
242
243
244 /*
245  * layer trace header
246  */
247 static struct isdn_message {
248         const char *name;
249         unsigned int value;
250 } isdn_message[] = {
251         {"PH_ACTIVATE", L1_ACTIVATE_REQ},
252         {"PH_DEACTIVATE", L1_DEACTIVATE_REQ},
253         {"DL_ESTABLISH", L2_ESTABLISH_REQ},
254         {"DL_RELEASE", L2_RELEASE_REQ},
255         {"UNKNOWN", L3_UNKNOWN_REQ},
256         {"MT_TIMEOUT", L3_TIMEOUT_REQ},
257         {"MT_SETUP", L3_SETUP_REQ},
258         {"MT_SETUP_ACK", L3_SETUP_ACKNOWLEDGE_REQ},
259         {"MT_PROCEEDING", L3_PROCEEDING_REQ},
260         {"MT_ALERTING", L3_ALERTING_REQ},
261         {"MT_CONNECT", L3_CONNECT_REQ},
262         {"MT_CONNECT_ACK", L3_CONNECT_ACKNOWLEDGE_REQ},
263         {"MT_DISCONNECT", L3_DISCONNECT_REQ},
264         {"MT_RELEASE", L3_RELEASE_REQ},
265         {"MT_RELEASE_COMP", L3_RELEASE_COMPLETE_REQ},
266         {"MT_INFORMATION", L3_INFORMATION_REQ},
267         {"MT_PROGRESS", L3_PROGRESS_REQ},
268         {"MT_NOTIFY", L3_NOTIFY_REQ},
269         {"MT_SUSPEND", L3_SUSPEND_REQ},
270         {"MT_SUSPEND_ACK", L3_SUSPEND_ACKNOWLEDGE_REQ},
271         {"MT_SUSPEND_REJ", L3_SUSPEND_REJECT_REQ},
272         {"MT_RESUME", L3_RESUME_REQ},
273         {"MT_RESUME_ACK", L3_RESUME_ACKNOWLEDGE_REQ},
274         {"MT_RESUME_REJ", L3_RESUME_REJECT_REQ},
275         {"MT_HOLD", L3_HOLD_REQ},
276         {"MT_HOLD_ACK", L3_HOLD_ACKNOWLEDGE_REQ},
277         {"MT_HOLD_REJ", L3_HOLD_REJECT_REQ},
278         {"MT_RETRIEVE", L3_RETRIEVE_REQ},
279         {"MT_RETRIEVE_ACK", L3_RETRIEVE_ACKNOWLEDGE_REQ},
280         {"MT_RETRIEVE_REJ", L3_RETRIEVE_REJECT_REQ},
281         {"MT_FACILITY", L3_FACILITY_REQ},
282         {"MT_STATUS", L3_STATUS_REQ},
283         {"MT_RESTART", L3_RESTART_REQ},
284         {"MT_NEW_L3ID", L3_NEW_L3ID_REQ},
285         {"MT_RELEASE_L3ID", L3_RELEASE_L3ID_REQ},
286         {NULL, 0},
287 };
288 static const char *isdn_prim[4] = {
289         " REQUEST",
290         " CONFIRM",
291         " INDICATION",
292         " RESPONSE",
293 };
294 void l1l2l3_trace_header(struct mISDNport *mISDNport, class PmISDN *port, unsigned int msg, int direction)
295 {
296         int i;
297         char msgtext[64];
298
299         SCPY(msgtext, "<<UNKNOWN MESSAGE>>");
300         /* select message and primitive text */
301         i = 0;
302         while(isdn_message[i].name) {
303 //              if (msg == L3_NOTIFY_REQ) printf("val = %x %s\n", isdn_message[i].value, isdn_message[i].name);
304                 if (isdn_message[i].value == (msg&0xffffff00)) {
305                         SCPY(msgtext, isdn_message[i].name);
306                         break;
307                 }
308                 i++;
309         }
310         SCAT(msgtext, isdn_prim[msg&0x00000003]);
311
312         /* add direction */
313         if (direction && (msg&0xffffff00)!=L3_NEW_L3ID_REQ && (msg&0xffffff00)!=L3_RELEASE_L3ID_REQ) {
314                 if (mISDNport) {
315                         if (mISDNport->ntmode) {
316                                 if (direction == DIRECTION_OUT)
317                                         SCAT(msgtext, " N->U");
318                                 else
319                                         SCAT(msgtext, " N<-U");
320                         } else {
321                                 if (direction == DIRECTION_OUT)
322                                         SCAT(msgtext, " U->N");
323                                 else
324                                         SCAT(msgtext, " U<-N");
325                         }
326                 }
327         }
328
329         /* init trace with given values */
330         start_trace(mISDNport?mISDNport->portnum:-1,
331                     mISDNport?(mISDNport->ifport?mISDNport->ifport->interface:NULL):NULL,
332                     port?numberrize_callerinfo(port->p_callerinfo.id, port->p_callerinfo.ntype, options.national, options.international):NULL,
333                     port?port->p_dialinginfo.id:NULL,
334                     direction,
335                     CATEGORY_CH,
336                     port?port->p_serial:0,
337                     msgtext);
338 }
339
340
341 /*
342  * send control information to the channel (dsp-module)
343  */
344 void ph_control(struct mISDNport *mISDNport, class PmISDN *isdnport, int sock, unsigned int c1, unsigned int c2, const char *trace_name, int trace_value)
345 {
346         unsigned char buffer[MISDN_HEADER_LEN+sizeof(int)+sizeof(int)];
347         struct mISDNhead *ctrl = (struct mISDNhead *)buffer;
348         unsigned int *d = (unsigned int *)(buffer+MISDN_HEADER_LEN);
349         int ret;
350         int len = 8;
351
352         if (sock < 0)
353                 return;
354
355         if (c1 == DTMF_TONE_START && c2 == 0) {
356                 len = 4;
357         }
358
359         ctrl->prim = PH_CONTROL_REQ;
360         ctrl->id = 0;
361         *d++ = c1;
362         *d++ = c2;
363         ret = sendto(sock, buffer, MISDN_HEADER_LEN+len, 0, NULL, 0);
364         if (ret <= 0)
365                 PERROR("Failed to send to socket %d\n", sock);
366         chan_trace_header(mISDNport, isdnport, "BCHANNEL control", DIRECTION_OUT);
367         if (c1 == DSP_CONF_JOIN)
368                 add_trace(trace_name, NULL, "0x%08x", trace_value);
369         else
370                 add_trace(trace_name, NULL, "%d", trace_value);
371         end_trace();
372 }
373
374 void ph_control_block(struct mISDNport *mISDNport, class PmISDN *isdnport, int sock, unsigned int c1, void *c2, int c2_len, const char *trace_name, int trace_value)
375 {
376         unsigned char buffer[MISDN_HEADER_LEN+sizeof(int)+c2_len];
377         struct mISDNhead *ctrl = (struct mISDNhead *)buffer;
378         unsigned int *d = (unsigned int *)(buffer+MISDN_HEADER_LEN);
379         int ret;
380
381         if (sock < 0)
382                 return;
383
384         ctrl->prim = PH_CONTROL_REQ;
385         ctrl->id = 0;
386         *d++ = c1;
387         memcpy(d, c2, c2_len);
388         ret = sendto(sock, buffer, MISDN_HEADER_LEN+sizeof(int)+c2_len, 0, NULL, 0);
389         if (ret <= 0)
390                 PERROR("Failed to send to socket %d\n", sock);
391         chan_trace_header(mISDNport, isdnport, "BCHANNEL control", DIRECTION_OUT);
392         add_trace(trace_name, NULL, "%d", trace_value);
393         end_trace();
394 }
395
396 static int b_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int i);
397
398 /*
399  * subfunction for bchannel_event
400  * create stack
401  */
402 static int _bchannel_create(struct mISDNport *mISDNport, int i)
403 {
404         int ret;
405         struct sockaddr_mISDN addr;
406
407         if (mISDNport->b_sock[i].inuse) {
408                 PERROR("Error: Socket already created for index %d\n", i);
409                 return(0);
410         }
411
412         /* open socket */
413 //#warning testing without DSP
414 //      mISDNport->b_sock[i].fd = socket(PF_ISDN, SOCK_DGRAM, (mISDNport->b_mode[i]==B_MODE_HDLC)?ISDN_P_B_HDLC:ISDN_P_B_RAW);
415         mISDNport->b_sock[i].fd = socket(PF_ISDN, SOCK_DGRAM, (mISDNport->b_mode[i]==B_MODE_HDLC)?ISDN_P_B_L2DSPHDLC:ISDN_P_B_L2DSP);
416         if (mISDNport->b_sock[i].fd < 0) {
417                 PERROR("Error: Failed to open bchannel-socket for index %d with mISDN-DSP layer. Did you load mISDN_dsp.ko?\n", i);
418                 return(0);
419         }
420
421         /* register callback for read */
422         register_fd(&mISDNport->b_sock[i], LCR_FD_READ, b_sock_callback, mISDNport, i);
423         
424         /* bind socket to bchannel */
425         addr.family = AF_ISDN;
426         addr.dev = mISDNport->portnum;
427         addr.channel = i+1+(i>=15);
428         ret = bind(mISDNport->b_sock[i].fd, (struct sockaddr *)&addr, sizeof(addr));
429         if (ret < 0) {
430                 PERROR("Error: Failed to bind bchannel-socket for index %d with mISDN-DSP layer (errno=%d). Did you load mISDN_dsp.ko?\n", i, errno);
431                 close(mISDNport->b_sock[i].fd);
432                 unregister_fd(&mISDNport->b_sock[i]);
433                 return(0);
434         }
435
436         chan_trace_header(mISDNport, mISDNport->b_port[i], "BCHANNEL create socket", DIRECTION_OUT);
437         add_trace("channel", NULL, "%d", i+1+(i>=15));
438         add_trace("socket", NULL, "%d", mISDNport->b_sock[i].fd);
439         end_trace();
440
441         return(1);
442 }
443
444
445 /*
446  * subfunction for bchannel_event
447  * activate / deactivate request
448  */
449 static void _bchannel_activate(struct mISDNport *mISDNport, int i, int activate, int timeout)
450 {
451         struct mISDNhead act;
452         int ret;
453
454         if (!mISDNport->b_sock[i].inuse)
455                 return;
456         act.prim = (activate)?PH_ACTIVATE_REQ:PH_DEACTIVATE_REQ; 
457         act.id = 0;
458         ret = sendto(mISDNport->b_sock[i].fd, &act, MISDN_HEADER_LEN, 0, NULL, 0);
459         if (ret <= 0)
460                 PERROR("Failed to send to socket %d\n", mISDNport->b_sock[i].fd);
461
462         /* trace */
463         chan_trace_header(mISDNport, mISDNport->b_port[i], activate ? "BCHANNEL activate" : "BCHANNEL deactivate", DIRECTION_OUT);
464         add_trace("channel", NULL, "%d", i+1+(i>=15));
465         if (timeout)
466                 add_trace("event", NULL, "timeout recovery");
467         end_trace();
468 }
469
470
471 /*
472  * subfunction for bchannel_event
473  * set features
474  */
475 static void _bchannel_configure(struct mISDNport *mISDNport, int i)
476 {
477         struct PmISDN *port;
478         int handle, mode;
479
480         if (!mISDNport->b_sock[i].inuse)
481                 return;
482         handle = mISDNport->b_sock[i].fd;
483         port = mISDNport->b_port[i];
484         mode = mISDNport->b_mode[i];
485         if (!port) {
486                 PERROR("bchannel index i=%d not associated with a port object\n", i);
487                 return;
488         }
489
490         /* set dsp features */
491         if (port->p_m_txdata)
492                 ph_control(mISDNport, port, handle, (port->p_m_txdata)?DSP_TXDATA_ON:DSP_TXDATA_OFF, 0, "DSP-TXDATA", port->p_m_txdata);
493         if (port->p_m_delay && mode == B_MODE_TRANSPARENT)
494                 ph_control(mISDNport, port, handle, DSP_DELAY, port->p_m_delay, "DSP-DELAY", port->p_m_delay);
495         if (port->p_m_tx_dejitter && mode == B_MODE_TRANSPARENT)
496                 ph_control(mISDNport, port, handle, DSP_TX_DEJITTER, port->p_m_tx_dejitter, "DSP-TX_DEJITTER", port->p_m_tx_dejitter);
497         if (port->p_m_tx_gain && mode == B_MODE_TRANSPARENT)
498                 ph_control(mISDNport, port, handle, DSP_VOL_CHANGE_TX, port->p_m_tx_gain, "DSP-TX_GAIN", port->p_m_tx_gain);
499         if (port->p_m_rx_gain && mode == B_MODE_TRANSPARENT)
500                 ph_control(mISDNport, port, handle, DSP_VOL_CHANGE_RX, port->p_m_rx_gain, "DSP-RX_GAIN", port->p_m_rx_gain);
501         if (port->p_m_pipeline[0] && mode == B_MODE_TRANSPARENT)
502                 ph_control_block(mISDNport, port, handle, DSP_PIPELINE_CFG, port->p_m_pipeline, strlen(port->p_m_pipeline)+1, "DSP-PIPELINE", 0);
503         if (port->p_m_conf && !port->p_m_mute)
504                 ph_control(mISDNport, port, handle, DSP_CONF_JOIN, port->p_m_conf, "DSP-CONF", port->p_m_conf);
505         if (port->p_m_echo)
506                 ph_control(mISDNport, port, handle, DSP_ECHO_ON, 0, "DSP-ECHO", 1);
507         if (port->p_m_tone && mode == B_MODE_TRANSPARENT)
508                 ph_control(mISDNport, port, handle, DSP_TONE_PATT_ON, port->p_m_tone, "DSP-TONE", port->p_m_tone);
509         if (port->p_m_rxoff)
510                 ph_control(mISDNport, port, handle, DSP_RECEIVE_OFF, 0, "DSP-RXOFF", 1);
511 //      if (port->p_m_txmix && mode == B_MODE_TRANSPARENT)
512 //              ph_control(mISDNport, port, handle, DSP_MIX_ON, 0, "DSP-MIX", 1);
513         if (port->p_m_dtmf && mode == B_MODE_TRANSPARENT)
514                 ph_control(mISDNport, port, handle, DTMF_TONE_START, port->p_m_dtmf_threshold, "DSP-DTMF", 1);
515         if (port->p_m_crypt && mode == B_MODE_TRANSPARENT)
516                 ph_control_block(mISDNport, port, handle, DSP_BF_ENABLE_KEY, port->p_m_crypt_key, port->p_m_crypt_key_len, "DSP-CRYPT", port->p_m_crypt_key_len);
517 }
518
519
520 void PmISDN::set_conf(int oldconf, int newconf)
521 {
522                 if (oldconf != newconf) {
523                         PDEBUG(DEBUG_BCHANNEL, "we change conference from conf=%d to conf=%d.\n", oldconf, newconf);
524                         if (p_m_b_index > -1)
525                         if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE)
526                                 ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, (newconf)?DSP_CONF_JOIN:DSP_CONF_SPLIT, newconf, "DSP-CONF", newconf);
527                 } else
528                         PDEBUG(DEBUG_BCHANNEL, "we already have conf=%d.\n", newconf);
529 }
530
531
532 /*
533  * subfunction for bchannel_event
534  * destroy stack
535  */
536 static void _bchannel_destroy(struct mISDNport *mISDNport, int i)
537 {
538         if (!mISDNport->b_sock[i].inuse)
539                 return;
540         chan_trace_header(mISDNport, mISDNport->b_port[i], "BCHANNEL remove socket", DIRECTION_OUT);
541         add_trace("channel", NULL, "%d", i+1+(i>=15));
542         add_trace("socket", NULL, "%d", mISDNport->b_sock[i].fd);
543         end_trace();
544         close(mISDNport->b_sock[i].fd);
545         unregister_fd(&mISDNport->b_sock[i]);
546 }
547
548
549 /*
550 bchannel procedure
551 ------------------
552
553 A bchannel goes through the following states in this order:
554
555 - B_STATE_IDLE
556 No one is using the bchannel.
557 It is available and not linked to Port class, nor reserved.
558
559 - B_STATE_ACTIVATING
560 The bchannel stack is created and an activation request is sent.
561 It MAY be linked to Port class, but already unlinked due to Port class removal.
562
563 - B_STATE_ACTIVE
564 The bchannel is active and cofigured to the Port class needs.
565 Also it is linked to a Port class, otherwhise it would be deactivated.
566
567 - B_STATE_DEACTIVATING
568 The bchannel is in deactivating state, due to deactivation request.
569 It may be linked to a Port class, that likes to reactivate it.
570
571 - B_STATE_IDLE
572 See above.
573 After deactivating bchannel, and if not used, the bchannel becomes idle again.
574
575 A bchannel can have the following events:
576
577 - B_EVENT_USE
578 A bchannel is required by a Port class.
579
580 - B_EVENT_ACTIVATED
581 The bchannel beomes active.
582
583 - B_EVENT_DROP
584 The bchannel is not required by Port class anymore
585
586 - B_EVENT_DEACTIVATED
587 The bchannel becomes inactive.
588
589 All actions taken on these events depend on the current bchannel's state and if it is linked to a Port class.
590
591 */
592
593 /*
594  * process bchannel events
595  * - mISDNport is a pointer to the port's structure
596  * - i is the index of the bchannel
597  * - event is the B_EVENT_* value
598  * - port is the PmISDN class pointer
599  */
600 void bchannel_event(struct mISDNport *mISDNport, int i, int event)
601 {
602         class PmISDN *b_port = mISDNport->b_port[i];
603         int state = mISDNport->b_state[i];
604         int timer = -1; // no change
605 #if 0
606         int p_m_tx_gain = 0;
607         int p_m_rx_gain = 0;
608         char *p_m_pipeline = NULL;
609         unsigned char *p_m_crypt_key = NULL;
610         int p_m_crypt_key_len = 0;
611         int p_m_crypt_key_type = 0;
612
613         if (b_port) {
614                 p_m_tx_gain = b_port->p_m_tx_gain;
615                 p_m_rx_gain = b_port->p_m_rx_gain;
616                 p_m_pipeline = b_port->p_m_pipeline;
617                 p_m_crypt_key = b_port->p_m_crypt_key;
618                 p_m_crypt_key_len = b_port->p_m_crypt_key_len;
619                 p_m_crypt_key_type = /*b_port->p_m_crypt_key_type*/1;
620         }
621 #endif
622
623         switch(event) {
624                 case B_EVENT_USE:
625                 /* port must be linked in order to allow activation */
626                 if (!b_port)
627                         FATAL("bchannel must be linked to a Port class\n");
628                 switch(state) {
629                         case B_STATE_IDLE:
630                         /* create stack and send activation request */
631                         if (_bchannel_create(mISDNport, i)) {
632                                 _bchannel_activate(mISDNport, i, 1, 0);
633                                 state = B_STATE_ACTIVATING;
634                                 timer = B_TIMER_ACTIVATING;
635                         }
636                         break;
637
638                         case B_STATE_ACTIVATING:
639                         /* do nothing, because it is already activating */
640                         break;
641
642                         default:
643                         /* problems that might ocurr:
644                          * B_EVENT_USE is received when channel already in use.
645                          */
646                         PERROR("Illegal event %d at state %d, please correct.\n", event, state);
647                 }
648                 break;
649
650
651                 case B_EVENT_ACTIVATED:
652                 timer = 0;
653                 switch(state) {
654                         case B_STATE_ACTIVATING:
655                         if (b_port) {
656                                 /* bchannel is active and used by Port class, so we configure bchannel */
657                                 _bchannel_configure(mISDNport, i);
658                                 state = B_STATE_ACTIVE;
659                                 b_port->p_m_load = 0;
660                                 b_port->update_load();
661                         } else {
662                                 /* bchannel is active, but not used anymore (or has wrong stack config), so we deactivate */
663                                 _bchannel_activate(mISDNport, i, 0, 0);
664                                 state = B_STATE_DEACTIVATING;
665                                 timer = B_TIMER_DEACTIVATING;
666                         }
667                         break;
668
669                         default:
670                         PERROR("Illegal event %d at state %d, please correct.\n", event, state);
671                 }
672                 break;
673
674                 case B_EVENT_DROP:
675                 if (!b_port)
676                         FATAL("bchannel must be linked to a Port class\n");
677                 switch(state) {
678                         case B_STATE_IDLE:
679                         /* bchannel is idle due to an error, so we do nothing */
680                         break;
681
682                         case B_STATE_ACTIVATING:
683                         /* do nothing because we must wait until bchanenl is active before deactivating */
684                         break;
685
686                         case B_STATE_ACTIVE:
687                         /* bchannel is active, so we deactivate */
688                         _bchannel_activate(mISDNport, i, 0, 0);
689                         state = B_STATE_DEACTIVATING;
690                         timer = B_TIMER_DEACTIVATING;
691                         break;
692
693                         case B_STATE_DEACTIVATING:
694                         /* we may have taken an already deactivating bchannel, but do not require it anymore, so we do nothing */
695                         break;
696
697                         default:
698                         PERROR("Illegal event %d at state %d, please correct.\n", event, state);
699                 }
700                 break;
701
702                 case B_EVENT_DEACTIVATED:
703                 timer = 0;
704                 switch(state) {
705                         case B_STATE_IDLE:
706                         /* ignore due to deactivation confirm after unloading */
707                         break;
708
709                         case B_STATE_DEACTIVATING:
710                         _bchannel_destroy(mISDNport, i);
711                         state = B_STATE_IDLE;
712                         if (b_port) {
713                                 /* bchannel is now deactivate, but is requied by Port class, so we reactivate */
714                                 if (_bchannel_create(mISDNport, i)) {
715                                         _bchannel_activate(mISDNport, i, 1, 0);
716                                         state = B_STATE_ACTIVATING;
717                                         timer = B_TIMER_ACTIVATING;
718                                 }
719                         }
720                         break;
721
722                         default:
723                         PERROR("Illegal event %d at state %d, please correct.\n", event, state);
724                 }
725                 break;
726
727                 case B_EVENT_TIMEOUT:
728                 timer = 0;
729                 switch(state) {
730                         case B_STATE_IDLE:
731                         /* ignore due to deactivation confirm after unloading */
732                         break;
733
734                         case B_STATE_ACTIVATING:
735                         _bchannel_activate(mISDNport, i, 1, 1);
736                         timer = B_TIMER_ACTIVATING;
737                         break;
738
739                         case B_STATE_DEACTIVATING:
740                         _bchannel_activate(mISDNport, i, 0, 1);
741                         timer = B_TIMER_DEACTIVATING;
742                         break;
743
744                         default:
745                         PERROR("Illegal event %d at state %d, please correct.\n", event, state);
746                 }
747                 break;
748
749                 default:
750                 PERROR("Illegal event %d, please correct.\n", event);
751         }
752
753         mISDNport->b_state[i] = state;
754         if (timer == 0)
755                 unsched_timer(&mISDNport->b_timer[i]);
756         else if (timer > 0)
757                 schedule_timer(&mISDNport->b_timer[i], timer, 0);
758 }
759
760
761
762
763 /*
764  * check for available channel and reserve+set it.
765  * give channel number or SEL_CHANNEL_ANY or SEL_CHANNEL_NO
766  * give exclusiv flag
767  * returns -(cause value) or x = channel x or 0 = no channel
768  * NOTE: no activation is done here
769  */
770 int PmISDN::seize_bchannel(int channel, int exclusive)
771 {
772         int i;
773
774         /* the channel is what we have */
775         if (p_m_b_channel == channel)
776                 return(channel);
777
778         /* if channel already in use, release it */
779         if (p_m_b_channel)
780                 drop_bchannel();
781
782         /* if CHANNEL_NO */
783         if (channel==CHANNEL_NO || channel==0)
784                 return(0);
785         
786         /* is channel in range ? */
787         if (channel==16
788          || (channel>p_m_mISDNport->b_num && channel<16)
789          || ((channel-1)>p_m_mISDNport->b_num && channel>16)) /* channel-1 because channel 16 is not counted */
790                 return(-6); /* channel unacceptable */
791
792         /* request exclusive channel */
793         if (exclusive && channel>0) {
794                 i = channel-1-(channel>16);
795                 if (p_m_mISDNport->b_port[i])
796                         return(-44); /* requested channel not available */
797                 goto seize;
798         }
799
800         /* ask for channel */
801         if (channel>0) {
802                 i = channel-1-(channel>16);
803                 if (p_m_mISDNport->b_port[i] == NULL)
804                         goto seize;
805         }
806
807         /* search for channel */
808         i = 0;
809         while(i < p_m_mISDNport->b_num) {
810                 if (!p_m_mISDNport->b_port[i]) {
811                         channel = i+1+(i>=15);
812                         goto seize;
813                 }
814                 i++;
815         }
816         return(-34); /* no free channel */
817
818 seize:
819         PDEBUG(DEBUG_BCHANNEL, "PmISDN(%s) seizing bchannel %d (index %d)\n", p_name, channel, i);
820
821         /* link Port, set parameters */
822         p_m_mISDNport->b_port[i] = this;
823         p_m_b_index = i;
824         p_m_b_channel = channel;
825         p_m_b_exclusive = exclusive;
826         p_m_mISDNport->b_mode[i] = p_m_b_mode;
827
828         /* reserve channel */
829         if (!p_m_b_reserve) {
830                 p_m_b_reserve = 1;
831                 p_m_mISDNport->b_reserved++;
832         }
833
834         return(channel);
835 }
836
837 /*
838  * drop reserved channel and unset it.
839  * deactivation is also done
840  */
841 void PmISDN::drop_bchannel(void)
842 {
843         /* unreserve channel */
844         if (p_m_b_reserve)
845                 p_m_mISDNport->b_reserved--;
846         p_m_b_reserve = 0;
847
848         /* if not in use */
849         if (p_m_b_index < 0)
850                 return;
851         if (!p_m_b_channel)
852                 return;
853
854         PDEBUG(DEBUG_BCHANNEL, "PmISDN(%s) dropping bchannel\n", p_name);
855
856         if (p_m_mISDNport->b_state[p_m_b_index] != B_STATE_IDLE)
857                 bchannel_event(p_m_mISDNport, p_m_b_index, B_EVENT_DROP);
858         p_m_mISDNport->b_port[p_m_b_index] = NULL;
859         p_m_mISDNport->b_mode[p_m_b_index] = 0;
860         p_m_b_index = -1;
861         p_m_b_channel = 0;
862         p_m_b_exclusive = 0;
863 }
864
865
866 /*
867  * handler
868
869 audio transmission procedure:
870 -----------------------------
871
872 * priority
873 three sources of audio transmission:
874 - crypto-data high priority
875 - tones high priority (also high)
876 - remote-data low priority
877
878 * elapsed
879 a variable that temporarily shows the number of samples elapsed since last transmission process.
880 p_m_last_tv_* is used to store that last timestamp. this is used to calculate the time elapsed.
881
882 * load
883 a variable that is increased whenever data is transmitted.
884 it is decreased while time elapses. it stores the number of samples that
885 are currently loaded to dsp module.
886 since clock in dsp module is the same clock for user space process, these 
887 times have no skew.
888
889 * levels
890 there are two levels:
891 p_m_preload will give the load that have to be kept in dsp.
892 ISDN_MAXLOAD (2*p_m_preload) will give the maximum load before dropping.
893
894 * procedure for low priority data
895 see txfromup() for procedure
896 in short: remote data is ignored during high priority tones
897
898 * procedure for high priority data
899 whenever load is below p_m_preload, load is filled up to p_m_preload
900 if no more data is available, load becomes empty again.
901
902 'load' variable:
903 0                    p_m_preload           ISDN_MAXLOAD
904 +--------------------+----------------------+
905 |                    |                      |
906 +--------------------+----------------------+
907
908 on empty load or on load below p_m_preload, the load is inceased to p_m_preload:
909 0                    p_m_preload           ISDN_MAXLOAD
910 +--------------------+----------------------+
911 |TTTTTTTTTTTTTTTTTTTT|                      |
912 +--------------------+----------------------+
913
914 on empty load, remote-audio causes the load with the remote audio to be increased to p_m_preload.
915 0                    p_m_preload           ISDN_MAXLOAD
916 +--------------------+----------------------+
917 |TTTTTTTTTTTTTTTTTTTTRRRRR                  |
918 +--------------------+----------------------+
919
920  */
921 void PmISDN::update_load(void)
922 {
923         /* don't trigger load event if event already active */
924         if (p_m_loadtimer.active)
925                 return;
926
927         schedule_timer(&p_m_loadtimer, 0, 0); /* no delay the first time */
928 }
929
930 static int load_timer(struct lcr_timer *timer, void *instance, int index)
931 {
932         class PmISDN *isdnport = (class PmISDN *)instance;
933
934         isdnport->load_tx();
935
936         return 0;
937 }
938
939 void PmISDN::load_tx(void)
940 {
941         int elapsed = 0;
942         int ret;
943         struct timeval current_time;
944
945         /* get elapsed */
946         gettimeofday(&current_time, NULL);
947         if (p_m_last_tv_sec) {
948                 elapsed = 8000 * (current_time.tv_sec - p_m_last_tv_sec)
949                         + 8 * (current_time.tv_usec/1000 - p_m_last_tv_msec);
950         }
951         /* set clock of last process! */
952         p_m_last_tv_sec = current_time.tv_sec;
953         p_m_last_tv_msec = current_time.tv_usec/1000;
954
955         /* process only if we have samples and we are active */
956         if (p_m_mISDNport->b_state[p_m_b_index] != B_STATE_ACTIVE)
957                 return;
958
959         if (elapsed) {
960                 /* update load */
961                 if (elapsed < p_m_load)
962                         p_m_load -= elapsed;
963                 else
964                         p_m_load = 0;
965
966                 /* to send data, tone must be on */
967                 if ((p_tone_name[0] || p_dov_tx || p_m_crypt_msg_loops || p_m_inband_send_on) /* what tones? */
968                  && (p_m_load < p_m_preload) /* not too much load? */
969                  && (p_state==PORT_STATE_CONNECT || p_m_mISDNport->tones || p_m_inband_send_on)) { /* connected or inband-tones? */
970                         int tosend = p_m_preload - p_m_load, length; 
971                         unsigned char buf[MISDN_HEADER_LEN+tosend];
972                         struct mISDNhead *frm = (struct mISDNhead *)buf;
973                         unsigned char *p = buf+MISDN_HEADER_LEN;
974
975                         /* copy inband signalling (e.g. used by ss5) */
976                         if (p_m_inband_send_on && tosend) {
977                                 tosend -= inband_send(p, tosend);
978                         }
979
980                         /* copy crypto loops */
981                         while (p_m_crypt_msg_loops && tosend) {
982                                 /* how much do we have to send */
983                                 length = p_m_crypt_msg_len - p_m_crypt_msg_current;
984
985                                 /* clip tosend */
986                                 if (length > tosend)
987                                         length = tosend;
988
989                                 /* copy message (part) to buffer */
990                                 memcpy(p, p_m_crypt_msg+p_m_crypt_msg_current, length);
991
992                                 /* new position */
993                                 p_m_crypt_msg_current += length;
994                                 if (p_m_crypt_msg_current == p_m_crypt_msg_len) {
995                                         /* next loop */
996                                         p_m_crypt_msg_current = 0;
997                                         p_m_crypt_msg_loops--;
998                                         if (!p_m_crypt_msg_loops)
999                                                 update_rxoff();
1000 //                                      puts("eine loop weniger");
1001                                 }
1002
1003                                 /* new length */
1004                                 tosend -= length;
1005                         }
1006
1007                         /* copy dov */
1008                         if (p_dov_tx) {
1009                                 tosend -= dov_tx(p, tosend);
1010                         }
1011
1012                         /* copy tones */
1013                         if (p_tone_name[0] && tosend) {
1014                                 tosend -= read_audio(p, tosend);
1015                         }
1016
1017                         /* send data */
1018                         if (p_m_preload - p_m_load - tosend > 0) {
1019                                 frm->prim = PH_DATA_REQ;
1020                                 frm->id = 0;
1021                                 ret = sendto(p_m_mISDNport->b_sock[p_m_b_index].fd, buf, MISDN_HEADER_LEN+p_m_preload-p_m_load-tosend, 0, NULL, 0);
1022                                 if (ret <= 0)
1023                                         PERROR("Failed to send to socket %d (samples = %d)\n", p_m_mISDNport->b_sock[p_m_b_index].fd, p_m_preload-p_m_load-tosend);
1024                                 p_m_load += p_m_preload - p_m_load - tosend;
1025                         }
1026                 }
1027         }
1028
1029         schedule_timer(&p_m_loadtimer, 0, PORT_TRANSMIT * 125);
1030 }
1031
1032 /* handle timeouts */
1033 static int mISDN_timeout(struct lcr_timer *timer, void *instance, int i)
1034 {
1035         class PmISDN *isdnport = (class PmISDN *)instance;
1036         struct lcr_msg *message;
1037
1038         PDEBUG(DEBUG_ISDN, "(%s) timeout after %d seconds detected (state=%d).\n", isdnport->p_name, isdnport->p_m_timeout.timeout.tv_sec, isdnport->p_state);
1039         /* send timeout to endpoint */
1040         message = message_create(isdnport->p_serial, ACTIVE_EPOINT(isdnport->p_epointlist), PORT_TO_EPOINT, MESSAGE_TIMEOUT);
1041         message->param.state = isdnport->p_state;
1042         message_put(message);
1043
1044         return 0;
1045 }
1046         
1047
1048 /*
1049  * whenever we get audio data from bchannel, we process it here
1050  */
1051 void PmISDN::bchannel_receive(struct mISDNhead *hh, unsigned char *data, int len)
1052 {
1053         unsigned int cont = *((unsigned int *)data);
1054         struct lcr_msg *message;
1055         unsigned char *p;
1056         int l;
1057
1058         if (hh->prim == PH_CONTROL_IND) {
1059                 if (len < 4) {
1060                         PERROR("SHORT READ OF PH_CONTROL INDICATION\n");
1061                         return;
1062                 }
1063                 if ((cont&(~DTMF_TONE_MASK)) == DTMF_TONE_VAL) {
1064                         chan_trace_header(p_m_mISDNport, this, "BCHANNEL control", DIRECTION_IN);
1065                         add_trace("DTMF", NULL, "%c", cont & DTMF_TONE_MASK);
1066                         if (!p_m_dtmf)
1067                                 add_trace("info", NULL, "DTMF is disabled");
1068                         end_trace();
1069                         if (!p_m_dtmf)
1070                                 return;
1071                         if (p_type == PORT_TYPE_POTS_FXS_IN && p_state == PORT_STATE_IN_OVERLAP) {
1072                                 class Pfxs *pfxs = (class Pfxs *)this;
1073                                 if (!pfxs->p_m_fxs_allow_dtmf) {
1074                                         PDEBUG(DEBUG_PORT, "PmISDN(%s) DTMF for FXS currently disabled\n", p_name);
1075                                         return;
1076                                 }
1077                                 SCCAT(p_dialinginfo.id, cont & DTMF_TONE_MASK);
1078                                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_INFORMATION);
1079                                 message->param.information.id[0] = cont & DTMF_TONE_MASK;
1080                                 PDEBUG(DEBUG_PORT, "PmISDN(%s) PH_CONTROL INDICATION  INFORMATION digit '%s'\n", p_name, message->param.information.id);
1081                                 message_put(message);
1082                         } else {
1083                                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_DTMF);
1084                                 message->param.dtmf = cont & DTMF_TONE_MASK;
1085                                 PDEBUG(DEBUG_PORT, "PmISDN(%s) PH_CONTROL INDICATION  DTMF digit '%c'\n", p_name, message->param.dtmf);
1086                                 message_put(message);
1087                         }
1088                         return;
1089                 }
1090                 switch(cont) {
1091                         case DSP_BF_REJECT:
1092                         chan_trace_header(p_m_mISDNport, this, "BCHANNEL control", DIRECTION_IN);
1093                         add_trace("DSP-CRYPT", NULL, "error");
1094                         end_trace();
1095                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CRYPT);
1096                         message->param.crypt.type = CC_ERROR_IND;
1097                         PDEBUG(DEBUG_PORT, "PmISDN(%s) PH_CONTROL INDICATION  reject of blowfish.\n", p_name);
1098                         message_put(message);
1099                         break;
1100
1101                         case DSP_BF_ACCEPT:
1102                         chan_trace_header(p_m_mISDNport, this, "BCHANNEL control", DIRECTION_IN);
1103                         add_trace("DSP-CRYPT", NULL, "ok");
1104                         end_trace();
1105                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CRYPT);
1106                         message->param.crypt.type = CC_ACTBF_CONF;
1107                         PDEBUG(DEBUG_PORT, "PmISDN(%s) PH_CONTROL INDICATION  accept of blowfish.\n", p_name);
1108                         message_put(message);
1109                         break;
1110
1111                         default:
1112                         chan_trace_header(p_m_mISDNport, this, "BCHANNEL control", DIRECTION_IN);
1113                         add_trace("unknown", NULL, "0x%x", cont);
1114                         end_trace();
1115                 }
1116                 return;
1117         }
1118         if (hh->prim == PH_CONTROL_IND) {
1119                 switch(hh->id) {
1120                         default:
1121                         chan_trace_header(p_m_mISDNport, this, "BCHANNEL control", DIRECTION_IN);
1122                         add_trace("unknown", NULL, "0x%x", hh->id);
1123                         end_trace();
1124                 }
1125                 return;
1126         }
1127         if (hh->prim == PH_DATA_REQ || hh->prim == DL_DATA_REQ) {
1128                 if (!p_m_txdata) {
1129                         /* if tx is off, it may happen that fifos send us pending informations, we just ignore them */
1130                         PDEBUG(DEBUG_BCHANNEL, "PmISDN(%s) ignoring tx data, because 'txdata' is turned off\n", p_name);
1131                         return;
1132                 }
1133                 /* see below (same condition) */
1134                 if (p_state!=PORT_STATE_CONNECT
1135                          && !p_m_mISDNport->tones)
1136                         return;
1137 //              printf(".");fflush(stdout);return;
1138                 if (p_record)
1139                         record(data, len, 1); // from up
1140                 if (p_tap)
1141                         tap(data, len, 1); // from up
1142                 return;
1143         }
1144         if (hh->prim != PH_DATA_IND && hh->prim != DL_DATA_IND) {
1145                 PERROR("Bchannel received unknown primitve: 0x%x\n", hh->prim);
1146                 return;
1147         }
1148
1149         /* dov is processed */
1150         if (p_dov_rx)
1151                 dov_rx(data, len);
1152
1153         /* inband is processed */
1154         if (p_m_inband_receive_on)
1155                 inband_receive(data, len);
1156
1157         /* send to remote, if bridged */
1158         bridge_tx(data, len);
1159
1160         /* calls will not process any audio data unless
1161          * the call is connected OR tones feature is enabled.
1162          */
1163 #ifndef DEBUG_COREBRIDGE
1164         if (p_state!=PORT_STATE_CONNECT
1165          && !p_m_mISDNport->tones)
1166                 return;
1167 #endif
1168
1169 #if 0
1170         /* the bearer capability must be audio in order to send and receive
1171          * audio prior or after connect.
1172          */
1173         if (!(p_bearerinfo.capability&CLASS_CAPABILITY_AUDIO) && p_state!=PORT_STATE_CONNECT)
1174                 return;
1175 #endif
1176
1177         /* if rx is off, it may happen that fifos send us pending informations, we just ignore them */
1178         if (p_m_rxoff) {
1179                 PDEBUG(DEBUG_BCHANNEL, "PmISDN(%s) ignoring data, because rx is turned off\n", p_name);
1180                 return;
1181         }
1182
1183         /* record data */
1184         if (p_record)
1185                 record(data, len, 0); // from down
1186         if (p_tap)
1187                 tap(data, len, 0); // from down
1188
1189         /* randomize and listen to crypt message if enabled */
1190         if (p_m_crypt_listen) {
1191                 /* the noisy randomizer */
1192                 p = data;
1193                 l = len;
1194                 while(l--)
1195                         mISDN_rand[mISDN_rand_count & 0xff] += *p++;
1196
1197                 cryptman_listen_bch(data, len);
1198         }
1199 }
1200
1201
1202 /*
1203  * set echotest
1204  */
1205 void PmISDN::set_echotest(int echo)
1206 {
1207         if (p_m_echo != echo) {
1208                 p_m_echo = echo;
1209                 PDEBUG(DEBUG_ISDN, "we set echo to echo=%d.\n", p_m_echo);
1210                 if (p_m_b_channel)
1211                         if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE)
1212                                 ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, p_m_echo?DSP_ECHO_ON:DSP_ECHO_OFF, 0, "DSP-ECHO", p_m_echo);
1213         }
1214 }
1215
1216 /*
1217  * set tone
1218  */
1219 void PmISDN::set_tone(const char *dir, const char *tone)
1220 {
1221         int id = TONE_OFF;
1222         int dsp = DSP_NONE;
1223
1224         /* if no directory is given (by extension), we use interface.conf or options.conf */
1225         if (!dir || !dir[0]) {
1226                 if (p_m_mISDNport->ifport->tones_dir[0])
1227                         dir = p_m_mISDNport->ifport->tones_dir;
1228                 else if (options.tones_dir[0])
1229                         dir = options.tones_dir;
1230         }
1231
1232         if (!tone)
1233                 tone = "";
1234         PDEBUG(DEBUG_ISDN, "isdn port now plays tone:'%s'.\n", tone);
1235         if (!tone[0]) {
1236                 id = TONE_OFF;
1237                 goto setdsp;
1238         }
1239
1240         /* check for dsp tones */
1241         if (!strcmp(dir, "american"))
1242                 dsp = DSP_AMERICAN;
1243         if (!strcmp(dir, "german"))
1244                 dsp = DSP_GERMAN;
1245         if (!strcmp(dir, "oldgerman"))
1246                 dsp = DSP_OLDGERMAN;
1247
1248         /* check if we NOT really have to use a dsp-tone */
1249         if (dsp == DSP_NONE) {
1250                 nodsp:
1251                 if (p_m_tone)
1252                 if (p_m_b_index > -1)
1253                 if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT) {
1254                         PDEBUG(DEBUG_ISDN, "we reset tone from id=%d to OFF.\n", p_m_tone);
1255                         ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_TONE_PATT_OFF, 0, "DSP-TONE", 0);
1256                 }
1257                 p_m_tone = 0;
1258                 Port::set_tone(dir, tone);
1259                 return;
1260         }
1261
1262         /* now we USE dsp-tone, convert name */
1263         if (!strcmp(tone, "dialtone")) {
1264                 switch(dsp) {
1265                 case DSP_AMERICAN: id = TONE_AMERICAN_DIALTONE; break;
1266                 case DSP_GERMAN: id = TONE_GERMAN_DIALTONE; break;
1267                 case DSP_OLDGERMAN: id = TONE_GERMAN_OLDDIALTONE; break;
1268                 }
1269         } else if (!strcmp(tone, "dialpbx")) {
1270                 switch(dsp) {
1271                 case DSP_AMERICAN: id = TONE_AMERICAN_DIALPBX; break;
1272                 case DSP_GERMAN: id = TONE_GERMAN_DIALPBX; break;
1273                 case DSP_OLDGERMAN: id = TONE_GERMAN_OLDDIALPBX; break;
1274                 }
1275         } else if (!strcmp(tone, "ringing")) {
1276                 switch(dsp) {
1277                 case DSP_AMERICAN: id = TONE_AMERICAN_RINGING; break;
1278                 case DSP_GERMAN: id = TONE_GERMAN_RINGING; break;
1279                 case DSP_OLDGERMAN: id = TONE_GERMAN_OLDRINGING; break;
1280                 }
1281         } else if (!strcmp(tone, "ringpbx")) {
1282                 switch(dsp) {
1283                 case DSP_AMERICAN: id = TONE_AMERICAN_RINGPBX; break;
1284                 case DSP_GERMAN: id = TONE_GERMAN_RINGPBX; break;
1285                 case DSP_OLDGERMAN: id = TONE_GERMAN_OLDRINGPBX; break;
1286                 }
1287         } else if (!strcmp(tone, "busy")) {
1288                 busy:
1289                 switch(dsp) {
1290                 case DSP_AMERICAN: id = TONE_AMERICAN_BUSY; break;
1291                 case DSP_GERMAN: id = TONE_GERMAN_BUSY; break;
1292                 case DSP_OLDGERMAN: id = TONE_GERMAN_OLDBUSY; break;
1293                 }
1294         } else if (!strcmp(tone, "release")) {
1295                 hangup:
1296                 switch(dsp) {
1297                 case DSP_AMERICAN: id = TONE_AMERICAN_HANGUP; break;
1298                 case DSP_GERMAN: id = TONE_GERMAN_HANGUP; break;
1299                 case DSP_OLDGERMAN: id = TONE_GERMAN_OLDHANGUP; break;
1300                 }
1301         } else if (!strcmp(tone, "cause_10"))
1302                 goto hangup;
1303         else if (!strcmp(tone, "cause_11"))
1304                 goto busy;
1305         else if (!strcmp(tone, "cause_22")) {
1306                 switch(dsp) {
1307                 case DSP_AMERICAN: id = TONE_SPECIAL_INFO; break;
1308                 case DSP_GERMAN: id = TONE_GERMAN_GASSENBESETZT; break;
1309                 case DSP_OLDGERMAN: id = TONE_GERMAN_OLDBUSY; break;
1310                 }
1311         } else if (!strncmp(tone, "cause_", 6))
1312                 id = TONE_SPECIAL_INFO;
1313         else
1314                 id = TONE_OFF;
1315
1316         /* if we have a tone that is not supported by dsp */
1317         if (id==TONE_OFF && tone[0])
1318                 goto nodsp;
1319
1320         setdsp:
1321         if (p_m_tone != id) {
1322                 /* set new tone */
1323                 p_m_tone = id;
1324                 PDEBUG(DEBUG_ISDN, "we set tone to id=%d.\n", p_m_tone);
1325                 if (p_m_b_index > -1)
1326                 if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT)
1327                         ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, p_m_tone?DSP_TONE_PATT_ON:DSP_TONE_PATT_OFF, p_m_tone, "DSP-TONE", p_m_tone);
1328         }
1329         /* turn user-space tones off in cases of no tone OR dsp tone */
1330         Port::set_tone("",NULL);
1331 }
1332
1333
1334 /* MESSAGE_mISDNSIGNAL */
1335 //extern struct lcr_msg *dddebug;
1336 void PmISDN::message_mISDNsignal(unsigned int epoint_id, int message_id, union parameter *param)
1337 {
1338         int oldconf, newconf;
1339         switch(param->mISDNsignal.message) {
1340                 case mISDNSIGNAL_VOLUME:
1341                 if (p_m_tx_gain != param->mISDNsignal.tx_gain) {
1342                         p_m_tx_gain = param->mISDNsignal.tx_gain;
1343                         PDEBUG(DEBUG_BCHANNEL, "we change tx-volume to shift=%d.\n", p_m_tx_gain);
1344                         if (p_m_b_index > -1)
1345                         if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT)
1346                                 ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_VOL_CHANGE_TX, p_m_tx_gain, "DSP-TX_GAIN", p_m_tx_gain);
1347                 } else
1348                         PDEBUG(DEBUG_BCHANNEL, "we already have tx-volume shift=%d.\n", p_m_rx_gain);
1349                 if (p_m_rx_gain != param->mISDNsignal.rx_gain) {
1350                         p_m_rx_gain = param->mISDNsignal.rx_gain;
1351                         PDEBUG(DEBUG_BCHANNEL, "we change rx-volume to shift=%d.\n", p_m_rx_gain);
1352                         if (p_m_b_index > -1)
1353                         if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT)
1354                                 ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_VOL_CHANGE_RX, p_m_rx_gain, "DSP-RX_GAIN", p_m_rx_gain);
1355                 } else
1356                         PDEBUG(DEBUG_BCHANNEL, "we already have rx-volume shift=%d.\n", p_m_rx_gain);
1357                 break;
1358
1359                 case mISDNSIGNAL_CONF:
1360                 oldconf = p_m_mute?0:p_m_conf;
1361                 p_m_conf = param->mISDNsignal.conf;
1362                 newconf = p_m_mute?0:p_m_conf;
1363                 set_conf(oldconf, newconf);
1364                 break;
1365
1366                 case mISDNSIGNAL_DELAY:
1367                 if (p_m_delay != param->mISDNsignal.delay) {
1368                         p_m_delay = param->mISDNsignal.delay;
1369                         PDEBUG(DEBUG_BCHANNEL, "we change delay mode to delay=%d.\n", p_m_delay);
1370                         if (p_m_b_index > -1)
1371                         if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT)
1372                                 ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, p_m_delay?DSP_DELAY:DSP_JITTER, p_m_delay, "DSP-DELAY", p_m_delay);
1373                 } else
1374                         PDEBUG(DEBUG_BCHANNEL, "we already have delay=%d.\n", p_m_delay);
1375                 break;
1376
1377                 default:
1378                 PERROR("PmISDN(%s) unsupported signal message %d.\n", p_name, param->mISDNsignal.message);
1379         }
1380 }
1381
1382 /* MESSAGE_CRYPT */
1383 void PmISDN::message_crypt(unsigned int epoint_id, int message_id, union parameter *param)
1384 {
1385         struct lcr_msg *message;
1386
1387         switch(param->crypt.type) {
1388                 case CC_ACTBF_REQ:           /* activate blowfish */
1389                 p_m_crypt = 1;
1390                 p_m_crypt_key_len = param->crypt.len;
1391                 if (p_m_crypt_key_len > (int)sizeof(p_m_crypt_key)) {
1392                         PERROR("PmISDN(%s) key too long %d > %d\n", p_name, p_m_crypt_key_len, sizeof(p_m_crypt_key));
1393                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CRYPT);
1394                         message->param.crypt.type = CC_ERROR_IND;
1395                         message_put(message);
1396                         break;
1397                 }
1398                 memcpy(p_m_crypt_key, param->crypt.data, p_m_crypt_key_len);
1399                 crypt_off:
1400                 PDEBUG(DEBUG_BCHANNEL, "we set encryption to crypt=%d. (0 means OFF)\n", p_m_crypt);
1401                 if (p_m_b_index > -1)
1402                 if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT)
1403                         ph_control_block(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, p_m_crypt?DSP_BF_ENABLE_KEY:DSP_BF_DISABLE, p_m_crypt_key, p_m_crypt_key_len, "DSP-CRYPT", p_m_crypt_key_len);
1404                 break;
1405
1406                 case CC_DACT_REQ:            /* deactivate session encryption */
1407                 p_m_crypt = 0;
1408                 goto crypt_off;
1409                 break;
1410
1411                 case CR_LISTEN_REQ:          /* start listening to messages */
1412                 p_m_crypt_listen = 1;
1413                 update_rxoff();
1414                 p_m_crypt_listen_state = 0;
1415                 break;
1416
1417                 case CR_UNLISTEN_REQ:        /* stop listening to messages */
1418                 p_m_crypt_listen = 0;
1419                 update_rxoff();
1420                 break;
1421
1422                 case CR_MESSAGE_REQ:         /* send message */
1423                 p_m_crypt_msg_len = cryptman_encode_bch(param->crypt.data, param->crypt.len, p_m_crypt_msg, sizeof(p_m_crypt_msg));
1424                 if (!p_m_crypt_msg_len) {
1425                         PERROR("PmISDN(%s) message too long %d > %d\n", p_name, param->crypt.len-1, sizeof(p_m_crypt_msg));
1426                         break;
1427                 }
1428                 p_m_crypt_msg_current = 0; /* reset */
1429                 p_m_crypt_msg_loops = 6; /* enable */
1430                 update_rxoff();
1431 #if 0
1432                 /* disable txmix, or we get corrupt data due to audio process */
1433                 if (p_m_txmix && p_m_b_index>=0 && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT) {
1434                         PDEBUG(DEBUG_BCHANNEL, "for sending CR_MESSAGE_REQ, we reset txmix from txmix=%d.\n", p_m_txmix);
1435                         ph_control(p_m_mISDNport, this, p_mISDNport->b_sock[p_m_b_index].fd, DSP_MIX_OFF, 0, "DSP-TXMIX", 0);
1436                 }
1437 #endif
1438                 break;
1439
1440                 default:
1441                 PERROR("PmISDN(%s) unknown crypt message %d\n", p_name, param->crypt.type);
1442         }
1443
1444 }
1445
1446 /* MESSAGE_VOOTP */
1447 void PmISDN::message_vootp(unsigned int epoint_id, int message_id, union parameter *param)
1448 {
1449         struct lcr_msg *message;
1450
1451         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_UPDATEBRIDGE);
1452         message_put(message);
1453
1454 #if 0
1455 does not make sense, since remote port may dejitter
1456         if (param->vootp.enable) {
1457                 PDEBUG(DEBUG_ISDN, "PmISDN(%s) received vootp enable order, so we disable de-jitter.\n", p_name);
1458                 p_m_disable_dejitter = 1;
1459         }
1460 #endif
1461         update_rxoff();
1462 }
1463
1464 /*
1465  * endpoint sends messages to the port
1466  */
1467 int PmISDN::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1468 {
1469         /* messages also handled by base class */
1470         switch(message_id) {
1471                 case MESSAGE_VOOTP: /* crypt control command */
1472                 PDEBUG(DEBUG_ISDN, "PmISDN(%s) received VoOTP encryption\n", p_name);
1473                 message_vootp(epoint_id, message_id, param);
1474                 break;
1475         }
1476
1477         if (Port::message_epoint(epoint_id, message_id, param)) {
1478                 if (message_id == MESSAGE_BRIDGE)
1479                         update_rxoff();
1480                 return 1;
1481         }
1482
1483         /* messages not handled by base class */
1484         switch(message_id) {
1485                 case MESSAGE_mISDNSIGNAL: /* user command */
1486                 PDEBUG(DEBUG_ISDN, "PmISDN(%s) received special ISDN SIGNAL %d.\n", p_name, param->mISDNsignal.message);
1487                 message_mISDNsignal(epoint_id, message_id, param);
1488                 return 1;
1489
1490                 case MESSAGE_CRYPT: /* crypt control command */
1491                 PDEBUG(DEBUG_ISDN, "PmISDN(%s) received encryption command '%d'.\n", p_name, param->crypt.type);
1492                 message_crypt(epoint_id, message_id, param);
1493                 return 1;
1494
1495                 case MESSAGE_DISABLE_DEJITTER:
1496                 PDEBUG(DEBUG_ISDN, "PmISDN(%s) received de-jitter disable order.\n", p_name);
1497                 p_m_disable_dejitter = 1;
1498                 p_m_preload = param->queue;
1499                 update_rxoff();
1500                 return 1;
1501         }
1502
1503         return 0;
1504 }
1505
1506 void PmISDN::update_rxoff(void)
1507 {
1508         int tx_dejitter = 0;
1509
1510         /* call bridges in user space OR crypto OR recording */
1511         if (p_bridge || p_m_crypt_msg_loops || p_m_crypt_listen || p_record || p_tap || p_m_inband_receive_on || p_dov_rx) {
1512                 /* rx IS required */
1513                 if (p_m_rxoff) {
1514                         /* turn on RX */
1515                         p_m_rxoff = 0;
1516                         PDEBUG(DEBUG_BCHANNEL, "%s: receive data is required, so we turn them on\n", __FUNCTION__);
1517                         if (p_m_b_index > -1)
1518                                 if (p_m_mISDNport->b_port[p_m_b_index] && p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE)
1519                                         ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_RECEIVE_ON, 0, "DSP-RXOFF", 0);
1520                 }
1521         } else {
1522                 /* rx NOT required */
1523                 if (!p_m_rxoff) {
1524                         /* turn off RX */
1525                         p_m_rxoff = 1;
1526                         PDEBUG(DEBUG_BCHANNEL, "%s: receive data is not required, so we turn them off\n", __FUNCTION__);
1527                         if (p_m_b_index > -1)
1528                                 if (p_m_mISDNport->b_port[p_m_b_index] && p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE)
1529                                         ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_RECEIVE_OFF, 0, "DSP-RXOFF", 1);
1530                 }
1531         }
1532         /* recording / tapping */
1533         if (p_record || p_tap) {
1534                 /* txdata IS required */
1535                 if (!p_m_txdata) {
1536                         /* turn on RX */
1537                         p_m_txdata = 1;
1538                         PDEBUG(DEBUG_BCHANNEL, "%s: transmit data is required, so we turn them on\n", __FUNCTION__);
1539                         if (p_m_b_index > -1)
1540                                 if (p_m_mISDNport->b_port[p_m_b_index] && p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE)
1541                                         ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_TXDATA_ON, 0, "DSP-TXDATA", 1);
1542                 }
1543         } else {
1544                 /* txdata NOT required */
1545                 if (p_m_txdata) {
1546                         /* turn off RX */
1547                         p_m_txdata = 0;
1548                         PDEBUG(DEBUG_BCHANNEL, "%s: transmit data is not required, so we turn them off\n", __FUNCTION__);
1549                         if (p_m_b_index > -1)
1550                                 if (p_m_mISDNport->b_port[p_m_b_index] && p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE)
1551                                         ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_TXDATA_OFF, 0, "DSP-TXDATA", 0);
1552                 }
1553         }
1554         /* dejitter on bridge */
1555         if (p_bridge && !p_m_disable_dejitter)
1556                 tx_dejitter = 1;
1557         if (p_m_tx_dejitter != tx_dejitter) {
1558                 p_m_tx_dejitter = tx_dejitter;
1559                 PDEBUG(DEBUG_BCHANNEL, "we change dejitter mode to %s.\n", (p_m_tx_dejitter) ? "on" : "off");
1560                 if (p_m_b_index > -1)
1561                         if (p_m_mISDNport->b_state[p_m_b_index] == B_STATE_ACTIVE && p_m_mISDNport->b_mode[p_m_b_index] == B_MODE_TRANSPARENT)
1562                                 ph_control(p_m_mISDNport, this, p_m_mISDNport->b_sock[p_m_b_index].fd, DSP_TX_DEJITTER, p_m_tx_dejitter, "DSP-TX_DEJITTER", p_m_tx_dejitter);
1563         }
1564 }
1565
1566 static int mISDN_upqueue(struct lcr_fd *fd, unsigned int what, void *instance, int i)
1567 {
1568         struct mISDNport *mISDNport;
1569         struct mbuffer *mb;
1570         struct l3_msg *l3m;
1571         char byte;
1572         int __attribute__((__unused__)) ret;
1573
1574         /* unset global semaphore */
1575         upqueue_avail = 0;
1576         // with a very small incident, upqueue_avail may be set by mISDN thread and
1577         // another byte may be sent to the pipe, which causes a call to this function
1578         // again with nothing in the upqueue. this is no problem.
1579         ret = read(fd->fd, &byte, 1);
1580
1581         /* process all ports */
1582         mISDNport = mISDNport_first;
1583         while(mISDNport) {
1584                 /* handle queued up-messages (d-channel) */
1585                 while ((mb = mdequeue(&mISDNport->upqueue))) {
1586                         l3m = &mb->l3;
1587                         switch(l3m->type) {
1588                                 case MPH_ACTIVATE_IND:
1589                                 if (mISDNport->l1link != 1) {
1590                                         l1l2l3_trace_header(mISDNport, NULL, L1_ACTIVATE_IND, DIRECTION_IN);
1591                                         end_trace();
1592                                         mISDNport->l1link = 1;
1593                                 }
1594                                 break;
1595         
1596                                 case MPH_DEACTIVATE_IND:
1597                                 if (mISDNport->l1link != 0) {
1598                                         l1l2l3_trace_header(mISDNport, NULL, L1_DEACTIVATE_IND, DIRECTION_IN);
1599                                         end_trace();
1600                                         mISDNport->l1link = 0;
1601                                 }
1602                                 break;
1603
1604                                 case MPH_INFORMATION_IND:
1605                                 PDEBUG(DEBUG_ISDN, "Received MPH_INFORMATION_IND for port %d (%s).\n", mISDNport->portnum, mISDNport->ifport->interface->name);
1606                                 switch (l3m->pid) {
1607                                         case L1_SIGNAL_LOS_ON:
1608                                         mISDNport->los = 1;
1609                                         break;
1610                                         case L1_SIGNAL_LOS_OFF:
1611                                         mISDNport->los = 0;
1612                                         break;
1613                                         case L1_SIGNAL_AIS_ON:
1614                                         mISDNport->ais = 1;
1615                                         break;
1616                                         case L1_SIGNAL_AIS_OFF:
1617                                         mISDNport->ais = 0;
1618                                         break;
1619                                         case L1_SIGNAL_RDI_ON:
1620                                         mISDNport->rdi = 1;
1621                                         break;
1622                                         case L1_SIGNAL_RDI_OFF:
1623                                         mISDNport->rdi = 0;
1624                                         break;
1625                                         case L1_SIGNAL_SLIP_TX:
1626                                         mISDNport->slip_tx++;
1627                                         break;
1628                                         case L1_SIGNAL_SLIP_RX:
1629                                         mISDNport->slip_rx++;
1630                                         break;
1631                                 }
1632                                 break;
1633
1634                                 case MT_L2ESTABLISH:
1635                                 l1l2l3_trace_header(mISDNport, NULL, L2_ESTABLISH_IND, DIRECTION_IN);
1636                                 add_trace("tei", NULL, "%d", l3m->pid);
1637                                 end_trace();
1638                                 mISDNport->l2link = 1;
1639                                 if (l3m->pid < 128)
1640                                         mISDNport->l2mask[l3m->pid >> 3] |= (1 << (l3m->pid & 7));
1641                                 if ((!mISDNport->ntmode || mISDNport->ptp) && l3m->pid < 127) {
1642                                         if (mISDNport->l2establish.active) {
1643                                                 unsched_timer(&mISDNport->l2establish);
1644                                                 PDEBUG(DEBUG_ISDN, "the link became active before l2establish timer expiry.\n");
1645                                         }
1646                                 }
1647                                 break;
1648
1649                                 case MT_L2RELEASE:
1650                                 if (l3m->pid < 128)
1651                                         mISDNport->l2mask[l3m->pid >> 3] &= ~(1 << (l3m->pid & 7));
1652                                 if (!mISDNport->l2establish.active) {
1653                                         l1l2l3_trace_header(mISDNport, NULL, L2_RELEASE_IND, DIRECTION_IN);
1654                                         add_trace("tei", NULL, "%d", l3m->pid);
1655                                         end_trace();
1656                                         /* down if not nt-ptmp */ 
1657                                         if (!mISDNport->ntmode || mISDNport->ptp)
1658                                                 mISDNport->l2link = 0;
1659                                 }
1660                                 if ((!mISDNport->ntmode || mISDNport->ptp) && l3m->pid < 127) {
1661                                         if (!mISDNport->l2establish.active && mISDNport->l2hold) {
1662                                                 PDEBUG(DEBUG_ISDN, "set timer and establish.\n");
1663                                                 schedule_timer(&mISDNport->l2establish, 5, 0);
1664                                                 mISDNport->ml3->to_layer3(mISDNport->ml3, MT_L2ESTABLISH, 0, NULL);
1665                                         }
1666                                 }
1667                                 break;
1668
1669                                 default:
1670                                 /* l3-data is sent to LCR */
1671                                 stack2manager(mISDNport, l3m->type, l3m->pid, l3m);
1672                         }
1673                         /* free message */
1674                         free_l3_msg(l3m);
1675                 }
1676                 mISDNport = mISDNport->next;
1677         }
1678         return 0;
1679 }
1680
1681 /* l2 establish timer fires */
1682 static int l2establish_timeout(struct lcr_timer *timer, void *instance, int i)
1683 {
1684         struct mISDNport *mISDNport = (struct mISDNport *)instance;
1685
1686         if (mISDNport->l2hold && (mISDNport->ptp || !mISDNport->ntmode)) {
1687                 PDEBUG(DEBUG_ISDN, "the L2 establish timer expired, we try to establish the link portnum=%d.\n", mISDNport->portnum);
1688                 mISDNport->ml3->to_layer3(mISDNport->ml3, MT_L2ESTABLISH, 0, NULL);
1689                 schedule_timer(&mISDNport->l2establish, 5, 0); /* 5 seconds */
1690         }
1691
1692         return 0;
1693 }
1694
1695 /* handle frames from bchannel */
1696 static int b_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int i)
1697 {
1698         struct mISDNport *mISDNport = (struct mISDNport *)instance;
1699         unsigned char buffer[2048+MISDN_HEADER_LEN];
1700         struct mISDNhead *hh = (struct mISDNhead *)buffer;
1701         int ret;
1702
1703         ret = recv(fd->fd, buffer, sizeof(buffer), 0);
1704         if (ret < 0) {
1705                 PERROR("read error frame, errno %d\n", errno);
1706                 return 0;
1707         }
1708         if (ret < (int)MISDN_HEADER_LEN) {
1709                 PERROR("read short frame, got %d, expected %d\n", ret, (int)MISDN_HEADER_LEN);
1710                 return 0;
1711         }
1712         switch(hh->prim) {
1713                 /* we don't care about confirms, we use rx data to sync tx */
1714                 case PH_DATA_CNF:
1715                 break;
1716
1717                 /* we receive audio data, we respond to it AND we send tones */
1718                 case PH_DATA_IND:
1719                 case DL_DATA_IND:
1720                 case PH_DATA_REQ:
1721                 case DL_DATA_REQ:
1722                 case PH_CONTROL_IND:
1723                 if (mISDNport->b_port[i])
1724                         mISDNport->b_port[i]->bchannel_receive(hh, buffer+MISDN_HEADER_LEN, ret-MISDN_HEADER_LEN);
1725                 else
1726                         PDEBUG(DEBUG_BCHANNEL, "b-channel is not associated to an ISDNPort (socket %d), ignoring.\n", fd->fd);
1727                 break;
1728
1729                 case PH_ACTIVATE_IND:
1730                 case DL_ESTABLISH_IND:
1731                 case PH_ACTIVATE_CNF:
1732                 case DL_ESTABLISH_CNF:
1733                 PDEBUG(DEBUG_BCHANNEL, "DL_ESTABLISH confirm: bchannel is now activated (socket %d).\n", fd->fd);
1734                 bchannel_event(mISDNport, i, B_EVENT_ACTIVATED);
1735                 break;
1736
1737                 case PH_DEACTIVATE_IND:
1738                 case DL_RELEASE_IND:
1739                 case PH_DEACTIVATE_CNF:
1740                 case DL_RELEASE_CNF:
1741                 PDEBUG(DEBUG_BCHANNEL, "DL_RELEASE confirm: bchannel is now de-activated (socket %d).\n", fd->fd);
1742                 bchannel_event(mISDNport, i, B_EVENT_DEACTIVATED);
1743                 break;
1744
1745                 default:
1746                 PERROR("child message not handled: prim(0x%x) socket(%d) msg->len(%d)\n", hh->prim, fd->fd, ret-MISDN_HEADER_LEN);
1747         }
1748
1749         return 0;
1750 }
1751
1752 /* process timer events for bchannel handling */
1753 static int b_timer_timeout(struct lcr_timer *timer, void *instance, int i)
1754 {
1755         struct mISDNport *mISDNport = (struct mISDNport *)instance;
1756
1757         bchannel_event(mISDNport, i, B_EVENT_TIMEOUT);
1758
1759         return 0;
1760 }
1761
1762
1763 int do_layer3(struct mlayer3 *ml3, unsigned int cmd, unsigned int pid, struct l3_msg *l3m)
1764 {
1765         /* IMPORTAINT:
1766          *
1767          * l3m must be queued, except for MT_ASSIGN
1768          *
1769          */
1770         struct mISDNport *mISDNport = (struct mISDNport *)ml3->priv;
1771         struct mbuffer *mb;
1772
1773 #ifdef OLD_MT_ASSIGN
1774         /* special MT_ASSIGN handling:
1775          *
1776          * if we request a PID from mlayer, we always do it while lcr is locked.
1777          * therefore we must check the MT_ASSIGN reply first before we lock.
1778          * this is because the MT_ASSIGN reply is received with the requesting
1779          * process, not by the mlayer thread!
1780          * this means, that the reply is sent during call of the request.
1781          * we must check if we get a reply and we know that we lcr is currently
1782          * locked.
1783          */
1784         if (cmd==MT_ASSIGN && (pid&MISDN_PID_CR_FLAG) && (pid>>16)==MISDN_CES_MASTER) {
1785                 /* let's do some checking if someone changes stack behaviour */
1786                 if (mt_assign_pid != 0)
1787                         FATAL("someone played with the mISDNuser stack. MT_ASSIGN not currently expected.\n");
1788                 mt_assign_pid = pid;
1789                 return(0);
1790         }
1791 #endif
1792         /* queue message, create, if required */
1793         if (!l3m) {
1794                 l3m = alloc_l3_msg();
1795                 if (!l3m)
1796                         FATAL("No memory for layer 3 message\n");
1797         }
1798         mb = container_of(l3m, struct mbuffer, l3);
1799         l3m->type = cmd;
1800         l3m->pid = pid;
1801         mqueue_tail(&mISDNport->upqueue, mb);
1802         if (!upqueue_avail) {
1803                 // multiple threads may cause multiple calls of this section, but this
1804                 // results only in multiple processing of the upqueue read.
1805                 // this is no problem.
1806                 upqueue_avail = 1;
1807                 char byte = 0;
1808                 int __attribute__((__unused__)) ret;
1809                 ret = write(upqueue_pipe[1], &byte, 1);
1810         }
1811         return 0;
1812 }
1813
1814 int mISDN_getportbyname(int sock, int cnt, char *portname)
1815 {
1816         struct mISDN_devinfo devinfo;
1817         int port = 0, ret;
1818
1819         /* resolve name */
1820         while (port < cnt) {
1821                 devinfo.id = port;
1822                 ret = ioctl(sock, IMGETDEVINFO, &devinfo);
1823                 if (ret < 0)
1824                         return ret;
1825                 if (!strcasecmp(devinfo.name, portname))
1826                         break;
1827                 port++;
1828         }
1829         if (port == cnt)
1830                 return -EIO;
1831
1832         return (port);
1833 }
1834
1835 #ifdef ISDN_P_FXS_POTS
1836 /* handle frames from pots */
1837 static int pots_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int i)
1838 {
1839         struct mISDNport *mISDNport = (struct mISDNport *)instance;
1840         unsigned char buffer[2048+MISDN_HEADER_LEN];
1841         struct mISDNhead *hh = (struct mISDNhead *)buffer;
1842         unsigned int cont;
1843         int ret;
1844
1845         ret = recv(fd->fd, buffer, sizeof(buffer), 0);
1846         if (ret < 0) {
1847                 PERROR("read error frame, errno %d\n", errno);
1848                 return 0;
1849         }
1850         if (ret < (int)MISDN_HEADER_LEN) {
1851                 PERROR("read short frame, got %d, expected %d\n", ret, (int)MISDN_HEADER_LEN);
1852                 return 0;
1853         }
1854         switch(hh->prim) {
1855         case PH_CONTROL_IND:
1856                 cont = *((unsigned int *)(buffer + MISDN_HEADER_LEN));
1857                 /* l1-control is sent to LCR */
1858                 if (mISDNport->ntmode)
1859                         stack2manager_fxs(mISDNport, cont);
1860                 else
1861                         PERROR("FXO not supported!\n");
1862                 break;
1863         case PH_ACTIVATE_REQ:
1864                 break;
1865
1866         default:
1867                 PERROR("child message not handled: prim(0x%x) socket(%d) msg->len(%d)\n", hh->prim, fd->fd, ret-MISDN_HEADER_LEN);
1868         }
1869
1870         return 0;
1871 }
1872 #endif
1873
1874 /*
1875  * global function to add a new card (port)
1876  */
1877 struct mISDNport *mISDNport_open(struct interface_port *ifport)
1878 {
1879         int ret;
1880         struct mISDNport *mISDNport, **mISDNportp;
1881         int port = ifport->portnum;
1882         int ptp = ifport->ptp;
1883         int force_nt = ifport->nt;
1884         int l1hold = ifport->l1hold;
1885         int l2hold = ifport->l2hold;
1886         int ss5 = ifport->ss5;
1887         int i, cnt;
1888         int pri, bri, pots;
1889         int nt, te;
1890 //      struct mlayer3 *ml3;
1891         struct mISDN_devinfo devinfo;
1892         unsigned int protocol, prop;
1893
1894         /* check port counts */
1895         ret = ioctl(mISDNsocket, IMGETCOUNT, &cnt);
1896         if (ret < 0) {
1897                 fprintf(stderr, "Cannot get number of mISDN devices. (ioctl IMGETCOUNT failed ret=%d)\n", ret);
1898                 return(NULL);
1899         }
1900
1901         if (cnt <= 0) {
1902                 PERROR_RUNTIME("Found no card. Please be sure to load card drivers.\n");
1903                 return(NULL);
1904         }
1905         if (port < 0) {
1906                 port = mISDN_getportbyname(mISDNsocket, cnt, ifport->portname);
1907                 if (port < 0) {
1908                         PERROR_RUNTIME("Port name '%s' not found, use 'misdn_info' tool to list all existing ports.\n", ifport->portname);
1909                         return(NULL);
1910                 }
1911                 // note: 'port' has still the port number
1912         }
1913         if (port>cnt || port<0) {
1914                 PERROR_RUNTIME("Port (%d) given at 'ports' (options.conf) is out of existing port range (%d-%d)\n", port, 0, cnt);
1915                 return(NULL);
1916         }
1917
1918         /* get port attributes */
1919         pri = bri = pots = nt = te = 0;
1920         devinfo.id = port;
1921         ret = ioctl(mISDNsocket, IMGETDEVINFO, &devinfo);
1922         if (ret < 0) {
1923                 PERROR_RUNTIME("Cannot get device information for port %d. (ioctl IMGETDEVINFO failed ret=%d)\n", port, ret);
1924                 return(NULL);
1925         }
1926         if (devinfo.Dprotocols & (1 << ISDN_P_TE_S0)) {
1927                 bri = 1;
1928                 te = 1;
1929         }
1930         if (devinfo.Dprotocols & (1 << ISDN_P_NT_S0)) {
1931                 bri = 1;
1932                 nt = 1;
1933         }
1934         if (devinfo.Dprotocols & (1 << ISDN_P_TE_E1)) {
1935                 pri = 1;
1936                 te = 1;
1937         }
1938         if (devinfo.Dprotocols & (1 << ISDN_P_NT_E1)) {
1939                 pri = 1;
1940                 nt = 1;
1941         }
1942 #ifdef ISDN_P_FXS_POTS
1943         if (devinfo.Dprotocols & (1 << ISDN_P_FXO_POTS)) {
1944                 pots = 1;
1945                 te = 1;
1946         }
1947         if (devinfo.Dprotocols & (1 << ISDN_P_FXS_POTS)) {
1948                 pots = 1;
1949                 nt = 1;
1950         }
1951 #endif
1952         if (force_nt && !nt) {
1953                 if (!pots)
1954                         PERROR_RUNTIME("Port %d does not support NT-mode\n", port);
1955                 else
1956                         PERROR_RUNTIME("Port %d does not support FXS-mode\n", port);
1957                 return(NULL);
1958         }
1959         if (bri && pri) {
1960                 PERROR_RUNTIME("Port %d supports BRI and PRI?? What kind of controller is that?. (Can't use this!)\n", port);
1961                 return(NULL);
1962         }
1963         if (!bri && !pri && !pots) {
1964                 PERROR_RUNTIME("Port %d does not support BRI nor PRI nor POTS!\n", port);
1965                 return(NULL);
1966         }
1967         if (!nt && !te) {
1968                 PERROR_RUNTIME("Port %d does not support NT-mode nor TE-mode!\n", port);
1969                 return(NULL);
1970         }
1971         /* set NT by turning off TE */
1972         if (force_nt && nt)
1973                 te = 0;
1974         /* if TE an NT is supported (and not forced to NT), turn off NT */
1975         if (te && nt)
1976                 nt = 0;
1977         if (pots && te) {
1978                 PERROR_RUNTIME("Port %d uses FXO-mode, but not supported by LCR!\n", port);
1979                 return(NULL);
1980         }
1981
1982         /* check for double use of port */
1983         if (nt) {
1984                 mISDNport = mISDNport_first;
1985                 while(mISDNport) {
1986                         if (mISDNport->portnum == port)
1987                                 break;
1988                         mISDNport = mISDNport->next;
1989                 }
1990                 if (mISDNport) {
1991                         PERROR_RUNTIME("Port %d already in use by LCR. You can't use a NT port multiple times.\n", port);
1992                         return(NULL);
1993                 }
1994         }
1995
1996         /* check for continous channelmap with no bchannel on slot 16 */
1997         if (test_channelmap(0, devinfo.channelmap)) {
1998                 PERROR_RUNTIME("Port %d provides channel 0, but we cannot access it!\n", port);
1999                 return(NULL);
2000         }
2001         i = 1;
2002         while(i < (int)devinfo.nrbchan + 1) {
2003                 if (i == 16) {
2004                         if (test_channelmap(i, devinfo.channelmap)) {
2005                                 PERROR("Port %d provides bchannel 16. Pleas upgrade mISDN, if this port is mISDN loopback interface.\n", port);
2006                                 return(NULL);
2007                         }
2008                 } else {
2009                         if (!test_channelmap(i, devinfo.channelmap)) {
2010                                 PERROR_RUNTIME("Port %d has no channel on slot %d!\n", port, i);
2011                                 return(NULL);
2012                         }
2013                 }
2014                 i++;
2015         }
2016
2017         /* add mISDNport structure */
2018         mISDNportp = &mISDNport_first;
2019         while(*mISDNportp)
2020                 mISDNportp = &((*mISDNportp)->next);
2021         mISDNport = (struct mISDNport *)MALLOC(sizeof(struct mISDNport));
2022         add_timer(&mISDNport->l2establish, l2establish_timeout, mISDNport, 0);
2023         if (ss5) {
2024                 /* ss5 link is always active */
2025                 mISDNport->l1link = 1;
2026                 mISDNport->l2link = 1;
2027         } else {
2028                 mISDNport->l1link = -1;
2029                 mISDNport->l2link = -1;
2030         }
2031         pmemuse++;
2032         *mISDNportp = mISDNport;
2033
2034         /* if pri, must set PTP */
2035         if (pri)
2036                 ptp = 1;
2037
2038         /* set ss5 params */
2039         if (ss5) {
2040                 /* try to keep interface enabled */
2041                 l1hold = 1;
2042                 l2hold = 0;
2043         }
2044         /* set l2hold */
2045         switch (l2hold) {
2046                 case -1: // off
2047                 l2hold = 0;
2048                 break;
2049                 case 1: // on
2050                 l2hold = 1;
2051                 break;
2052                 default:
2053                 if (ptp)
2054                         l2hold = 1;
2055                 else
2056                         l2hold = 0;
2057                 break;
2058         }
2059                 
2060         /* allocate ressources of port */
2061         if (!pots) {
2062                 /* ISDN */
2063                 protocol = (nt)?L3_PROTOCOL_DSS1_NET:L3_PROTOCOL_DSS1_USER;
2064                 prop = (1 << MISDN_FLG_L2_CLEAN);
2065                 if (ptp) // ptp forced
2066                        prop |= (1 << MISDN_FLG_PTP);
2067                 if (nt) // supports hold/retrieve on nt-mode
2068                        prop |= (1 << MISDN_FLG_NET_HOLD);
2069                 if (l1hold) // supports layer 1 hold
2070                        prop |= (1 << MISDN_FLG_L1_HOLD);
2071                 if (l2hold) // supports layer 2 hold
2072                        prop |= (1 << MISDN_FLG_L2_HOLD);
2073                 /* open layer 3 and init upqueue */
2074                 /* queue must be initializes, because l3-thread may send messages during open_layer3() */
2075                 mqueue_init(&mISDNport->upqueue);
2076                 mISDNport->ml3 = open_layer3(port, protocol, prop , do_layer3, mISDNport);
2077                 if (!mISDNport->ml3) {
2078                         mqueue_purge(&mISDNport->upqueue);
2079                         PERROR_RUNTIME("open_layer3() failed for port %d\n", port);
2080                         start_trace(port,
2081                                 ifport->interface,
2082                                 NULL,
2083                                 NULL,
2084                                 DIRECTION_NONE,
2085                                 CATEGORY_CH,
2086                                 0,
2087                                 "PORT (open failed)");
2088                         end_trace();
2089                         mISDNport_close(mISDNport);
2090                         return(NULL);
2091                 }
2092         } else {
2093 #ifdef ISDN_P_FXS_POTS
2094                 /* POTS */
2095                 int sock, ret;
2096                 struct sockaddr_mISDN addr;
2097                 struct mISDNhead act;
2098
2099                 /* open socket */
2100                 /* queue must be initializes, because even pots interfaces are checked at mISDN_upqueue loop */
2101                 mqueue_init(&mISDNport->upqueue);
2102                 sock = socket(PF_ISDN, SOCK_DGRAM, (nt) ? ISDN_P_FXS_POTS : ISDN_P_FXO_POTS);
2103                 if (sock < 0) {
2104                         PERROR_RUNTIME("Cannot open mISDN due to '%s'.\n", strerror(errno));
2105                         return NULL;
2106                 }
2107                 /* bind socket to dchannel */
2108                 addr.family = AF_ISDN;
2109                 addr.dev = port;
2110                 addr.channel = 0;
2111                 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
2112                 if (ret < 0) {
2113                         PERROR_RUNTIME("Error: Failed to bind pots control channel\n");
2114                         start_trace(port,
2115                                 ifport->interface,
2116                                 NULL,
2117                                 NULL,
2118                                 DIRECTION_NONE,
2119                                 CATEGORY_CH,
2120                                 0,
2121                                 "PORT (open failed)");
2122                         end_trace();
2123                         return(NULL);
2124                 }
2125                 act.prim = PH_ACTIVATE_REQ; 
2126                 act.id = 0;
2127                 ret = sendto(sock, &act, MISDN_HEADER_LEN, 0, NULL, 0);
2128                 if (ret <= 0)
2129                         PERROR("Failed to send to socket %d\n", sock);
2130                 mISDNport->pots_sock.fd = sock;
2131                 register_fd(&mISDNport->pots_sock, LCR_FD_READ, pots_sock_callback, mISDNport, i);
2132 #endif
2133         }
2134
2135         SCPY(mISDNport->name, devinfo.name);
2136         mISDNport->b_num = devinfo.nrbchan;
2137         mISDNport->portnum = port;
2138         mISDNport->ntmode = nt;
2139         mISDNport->pots = pots;
2140         mISDNport->tespecial = ifport->tespecial;
2141         mISDNport->pri = pri;
2142         mISDNport->ptp = ptp;
2143         mISDNport->l1hold = l1hold;
2144         mISDNport->l2hold = l2hold;
2145         mISDNport->ss5 = ss5;
2146         PDEBUG(DEBUG_ISDN, "Port has %d b-channels.\n", mISDNport->b_num);
2147         i = 0;
2148         while(i < mISDNport->b_num) {
2149                 mISDNport->b_state[i] = B_STATE_IDLE;
2150                 add_timer(&mISDNport->b_timer[i], b_timer_timeout, mISDNport, i);
2151                 i++;
2152         }
2153
2154         /* if ptp, pull up the link */
2155         if (!pots && mISDNport->l2hold && (mISDNport->ptp || !mISDNport->ntmode)) {
2156                 mISDNport->ml3->to_layer3(mISDNport->ml3, MT_L2ESTABLISH, 0, NULL);
2157                 l1l2l3_trace_header(mISDNport, NULL, L2_ESTABLISH_REQ, DIRECTION_OUT);
2158                 add_trace("tei", NULL, "%d", 0);
2159                 end_trace();
2160                 schedule_timer(&mISDNport->l2establish, 5, 0); /* 5 seconds */
2161         }
2162
2163         /* for POTS or nt-mode ptmp the link is always up */
2164         if (pots || (mISDNport->ntmode && !mISDNport->ptp))
2165                 mISDNport->l2link = 1;
2166
2167         PDEBUG(DEBUG_BCHANNEL, "using 'mISDN_dsp.o' module\n");
2168
2169         start_trace(mISDNport->portnum,
2170                     ifport->interface,
2171                     NULL,
2172                     NULL,
2173                     DIRECTION_NONE,
2174                     CATEGORY_CH,
2175                     0,
2176                     "PORT (open)");
2177         if (!pots)
2178                 add_trace("mode", NULL, (mISDNport->ntmode)?"network":"terminal");
2179         else
2180                 add_trace("mode", NULL, (mISDNport->ntmode)?"FXS":"FXO");
2181         add_trace("channels", NULL, "%d", mISDNport->b_num);
2182         if (mISDNport->ss5)
2183                 add_trace("ccitt#5", NULL, "enabled");
2184         end_trace();
2185
2186         return(mISDNport);
2187 }
2188
2189
2190 /*
2191  * load static port instances, if required by mISDNport
2192  */
2193 void mISDNport_static(struct mISDNport *mISDNport)
2194 {
2195         int i;
2196
2197         i = 0;
2198         while(i < mISDNport->b_num) {
2199 #ifdef WITH_SS5
2200                 if (mISDNport->ss5)
2201                         ss5_create_channel(mISDNport, i);
2202 #endif
2203                 i++;
2204         }
2205 }
2206
2207
2208 /*
2209  * function to free ALL cards (ports)
2210  */
2211 void mISDNport_close_all(void)
2212 {
2213         /* free all ports */
2214         while(mISDNport_first)
2215                 mISDNport_close(mISDNport_first);
2216 }
2217
2218 /*
2219  * free only one port
2220  */
2221 void mISDNport_close(struct mISDNport *mISDNport)
2222 {
2223         struct mISDNport **mISDNportp;
2224         class Port *port;
2225         class PmISDN *isdnport;
2226         int i;
2227
2228         /* remove all port instance that are linked to this mISDNport */
2229         again:
2230         port = port_first;
2231         while(port) {
2232                 if ((port->p_type&PORT_CLASS_MASK) == PORT_CLASS_mISDN) {
2233                         isdnport = (class PmISDN *)port;
2234                         if (isdnport->p_m_mISDNport && isdnport->p_m_mISDNport == mISDNport) {
2235                                 PDEBUG(DEBUG_ISDN, "port %s uses mISDNport %d, destroying it.\n", isdnport->p_name, mISDNport->portnum);
2236                                 delete isdnport;
2237                                 goto again;
2238                         }
2239                 }
2240                 port = port->next;
2241         }
2242
2243         /* only if we are already part of interface */
2244         if (mISDNport->ifport) {
2245                 start_trace(mISDNport->portnum,
2246                             mISDNport->ifport->interface,
2247                             NULL,
2248                             NULL,
2249                             DIRECTION_NONE,
2250                             CATEGORY_CH,
2251                             0,
2252                             "PORT (close)");
2253                 end_trace();
2254         }
2255
2256         /* free bchannels */
2257         i = 0;
2258         while(i < mISDNport->b_num) {
2259                 if (mISDNport->b_sock[i].inuse) {
2260                         _bchannel_destroy(mISDNport, i);
2261                         PDEBUG(DEBUG_BCHANNEL, "freeing %s port %d bchannel (index %d).\n", (mISDNport->ntmode)?"NT":"TE", mISDNport->portnum, i);
2262                 }
2263                 if (mISDNport->b_timer[i].inuse) {
2264                         del_timer(&mISDNport->b_timer[i]);
2265                 }
2266                 i++;
2267         }
2268         del_timer(&mISDNport->l2establish);
2269
2270         /* close layer 3, if open */
2271         if (mISDNport->ml3) {
2272                 close_layer3(mISDNport->ml3);
2273         }
2274
2275         /* close layer 1, if open */
2276         if (mISDNport->pots_sock.fd) {
2277                 unregister_fd(&mISDNport->pots_sock);
2278                 close(mISDNport->pots_sock.fd);
2279         }
2280
2281         /* purge upqueue */
2282         mqueue_purge(&mISDNport->upqueue);
2283
2284         /* remove from list */
2285         mISDNportp = &mISDNport_first;
2286         while(*mISDNportp) {
2287                 if (*mISDNportp == mISDNport) {
2288                         *mISDNportp = (*mISDNportp)->next;
2289                         mISDNportp = NULL;
2290                         break;
2291                 }
2292                 mISDNportp = &((*mISDNportp)->next);
2293         }
2294
2295         if (mISDNportp)
2296                 FATAL("mISDNport not in list\n");
2297         
2298         FREE(mISDNport, sizeof(struct mISDNport));
2299         pmemuse--;
2300
2301 }
2302
2303
2304 /*
2305  * enque data from remote port
2306  */
2307 int PmISDN::bridge_rx(unsigned char *data, int length)
2308 {
2309         unsigned char buf[MISDN_HEADER_LEN+((length>p_m_preload)?length:p_m_preload)];
2310         struct mISDNhead *hh = (struct mISDNhead *)buf;
2311         int ret;
2312
2313         if ((ret = Port::bridge_rx(data, length)))
2314                 return ret;
2315
2316         if (p_m_b_index < 0)
2317                 return -EIO;
2318         if (p_m_mISDNport->b_state[p_m_b_index] != B_STATE_ACTIVE)
2319                 return -EINVAL;
2320
2321         /* check if high priority tones exist
2322          * ignore data in this case
2323          */
2324         if (p_tone_name[0] || p_dov_tx || p_m_crypt_msg_loops || p_m_inband_send_on)
2325                 return -EBUSY;
2326
2327         /* preload procedure
2328          * if transmit buffer in DSP module is empty,
2329          * preload it to DSP_LOAD to prevent jitter gaps.
2330          * 
2331          * if load runs empty, preload again.
2332          */
2333         if (p_m_disable_dejitter && p_m_load == 0 && p_m_preload > 0) {
2334 //printf("preload=%d\n", p_m_preload);
2335                 hh->prim = PH_DATA_REQ; 
2336                 hh->id = 0;
2337                 memset(buf+MISDN_HEADER_LEN, silence, p_m_preload);
2338                 ret = sendto(p_m_mISDNport->b_sock[p_m_b_index].fd, buf, MISDN_HEADER_LEN+p_m_preload, 0, NULL, 0);
2339                 if (ret <= 0)
2340                         PERROR("Failed to send to socket %d\n", p_m_mISDNport->b_sock[p_m_b_index].fd);
2341                 p_m_load += p_m_preload;
2342                 schedule_timer(&p_m_loadtimer, 0, PORT_TRANSMIT * 125);
2343         }
2344
2345         /* drop if load would exceed ISDN_MAXLOAD
2346          * this keeps the delay not too high
2347          */
2348 //printf("load=%d len=%d 2*preload=%d\n", p_m_load, length, p_m_preload << 1);
2349         if (p_m_disable_dejitter && p_m_preload > 0 && p_m_load+length > (p_m_preload << 1))
2350                 return -EINVAL;
2351
2352         /* make and send frame */
2353         hh->prim = PH_DATA_REQ;
2354         hh->id = 0;
2355         memcpy(buf+MISDN_HEADER_LEN, data, length);
2356         ret = sendto(p_m_mISDNport->b_sock[p_m_b_index].fd, buf, MISDN_HEADER_LEN+length, 0, NULL, 0);
2357         if (ret <= 0)
2358                 PERROR("Failed to send to socket %d\n", p_m_mISDNport->b_sock[p_m_b_index].fd);
2359         p_m_load += length;
2360
2361         return 0;
2362 }
2363
2364 int PmISDN::inband_send(unsigned char *buffer, int len)
2365 {
2366         PERROR("this function must be derived to function!\n");
2367         return 0;
2368 }
2369
2370 void PmISDN::inband_send_on(void)
2371 {
2372         PDEBUG(DEBUG_PORT, "turning inband signalling send on.\n");
2373         p_m_inband_send_on = 1;
2374 }
2375
2376 void PmISDN::inband_send_off(void)
2377 {
2378         PDEBUG(DEBUG_PORT, "turning inband signalling send off.\n");
2379         p_m_inband_send_on = 0;
2380 }
2381
2382 void PmISDN::inband_receive(unsigned char *buffer, int len)
2383 {
2384 //
2385 //      if (len >= SS5_DECODER_NPOINTS)
2386 //              ss5_decode(buffer, SS5_DECODER_NPOINTS);
2387         PERROR("this function must be derived to function!\n");
2388 }
2389
2390 void PmISDN::inband_receive_on(void)
2391 {
2392         /* this must work during constructor, see ss5.cpp */
2393         PDEBUG(DEBUG_PORT, "turning inband signalling receive on.\n");
2394         p_m_inband_receive_on = 1;
2395         update_rxoff();
2396 }
2397
2398 void PmISDN::inband_receive_off(void)
2399 {
2400         PDEBUG(DEBUG_PORT, "turning inband signalling receive off.\n");
2401         p_m_inband_receive_on = 0;
2402         update_rxoff();
2403 }
2404
2405 void PmISDN::mute_on(void)
2406 {
2407         if (p_m_mute)
2408                 return;
2409         PDEBUG(DEBUG_PORT, "turning mute on.\n");
2410         p_m_mute = 1;
2411         set_conf(p_m_conf, 0);
2412 }
2413
2414 void PmISDN::mute_off(void)
2415 {
2416         if (!p_m_mute)
2417                 return;
2418         PDEBUG(DEBUG_PORT, "turning mute off.\n");
2419         p_m_mute = 0;
2420         set_conf(0, p_m_conf);
2421 }
2422
2423