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