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