adcc057c59abc27b13d98782c49dc821441b839c
[lcr.git] / sip.cpp
1 /*****************************************************************************\
2 **                                                                           **
3 ** Linux Call Router                                                         **
4 **                                                                           **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg                                              **
7 **                                                                           **
8 ** SIP port                                                                  **
9 **                                                                           **
10 \*****************************************************************************/ 
11
12 #include "main.h"
13 #include <sofia-sip/sip_status.h>
14 #include <sofia-sip/su_log.h>
15 #include <sofia-sip/sdp.h>
16 #include <sofia-sip/sip_header.h>
17
18 unsigned char flip[256];
19
20 //pthread_mutex_t mutex_msg;
21 su_home_t       sip_home[1];
22
23 struct sip_inst {
24         struct interface        *interface;
25         su_root_t               *root;
26         nua_t                   *nua;
27 };
28
29 static int delete_event(struct lcr_work *work, void *instance, int index);
30
31 /*
32  * initialize SIP port
33  */
34 Psip::Psip(int type, struct mISDNport *mISDNport, char *portname, struct port_settings *settings, int channel, int exclusive, int mode, struct interface *interface) : PmISDN(type, mISDNport, portname, settings, channel, exclusive, mode)
35 {
36         p_m_s_sip_inst = interface->sip_inst;
37         memset(&p_m_s_delete, 0, sizeof(p_m_s_delete));
38         add_work(&p_m_s_delete, delete_event, this, 0);
39         p_m_s_handle = 0;
40         p_m_s_magic = 0;
41         memset(&p_m_s_rtp_fd, 0, sizeof(p_m_s_rtp_fd));
42         memset(&p_m_s_rtcp_fd, 0, sizeof(p_m_s_rtcp_fd));
43         memset(&p_m_s_rtp_sin_local, 0, sizeof(p_m_s_rtp_sin_local));
44         memset(&p_m_s_rtcp_sin_local, 0, sizeof(p_m_s_rtcp_sin_local));
45         memset(&p_m_s_rtp_sin_remote, 0, sizeof(p_m_s_rtp_sin_remote));
46         memset(&p_m_s_rtcp_sin_remote, 0, sizeof(p_m_s_rtcp_sin_remote));
47         p_m_s_rtp_ip_local = 0;
48         p_m_s_rtp_ip_remote = 0;
49         p_m_s_rtp_port_local = 0;
50         p_m_s_rtp_port_remote = 0;
51         p_m_s_b_sock = -1;
52         p_m_s_b_index = -1;
53         p_m_s_b_active = 0;
54         p_m_s_rxpos = 0;
55         p_m_s_rtp_tx_action = 0;
56
57         PDEBUG(DEBUG_SIP, "Created new Psip(%s).\n", portname);
58 }
59
60
61 /*
62  * destructor
63  */
64 Psip::~Psip()
65 {
66         PDEBUG(DEBUG_SIP, "Destroyed SIP process(%s).\n", p_name);
67
68         del_work(&p_m_s_delete);
69
70         /* close audio transfer socket */
71         if (p_m_s_b_sock > -1)
72                 bchannel_close();
73
74         rtp_close();
75 }
76
77
78 static void sip_trace_header(class Psip *sip, const char *message, int direction)
79 {
80         /* init trace with given values */
81         start_trace(-1,
82                     NULL,
83                     sip?numberrize_callerinfo(sip->p_callerinfo.id, sip->p_callerinfo.ntype, options.national, options.international):NULL,
84                     sip?sip->p_dialinginfo.id:NULL,
85                     direction,
86                     CATEGORY_CH,
87                     sip?sip->p_serial:0,
88                     message);
89 }
90
91 /*
92  * RTP
93  */
94
95 /* according to RFC 3550 */
96 struct rtp_hdr {
97 #if __BYTE_ORDER == __LITTLE_ENDIAN
98         uint8_t  csrc_count:4,
99                   extension:1,
100                   padding:1,
101                   version:2;
102         uint8_t  payload_type:7,
103                   marker:1;
104 #elif __BYTE_ORDER == __BIG_ENDIAN
105         uint8_t  version:2,
106                   padding:1,
107                   extension:1,
108                   csrc_count:4;
109         uint8_t  marker:1,
110                   payload_type:7;
111 #endif
112         uint16_t sequence;
113         uint32_t timestamp;
114         uint32_t ssrc;
115 } __attribute__((packed));
116
117 struct rtp_x_hdr {
118         uint16_t by_profile;
119         uint16_t length;
120 } __attribute__((packed));
121
122 #define RTP_VERSION     2
123
124 #define RTP_PT_ULAW 0
125 #define RTP_PT_ALAW 8
126 #define RTP_PT_GSM_FULL 3
127 #define RTP_PT_GSM_HALF 96
128 #define RTP_PT_GSM_EFR 97
129 #define RTP_PT_AMR 98
130
131 /* decode an rtp frame  */
132 static int rtp_decode(class Psip *psip, unsigned char *data, int len)
133 {
134         struct rtp_hdr *rtph = (struct rtp_hdr *)data;
135         struct rtp_x_hdr *rtpxh;
136         uint8_t *payload;
137         int payload_len;
138         int x_len;
139
140         if (len < 12) {
141                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d)\n", len);
142                 return -EINVAL;
143         }
144         if (rtph->version != RTP_VERSION) {
145                 PDEBUG(DEBUG_SIP, "received RTP version %d not supported.\n", rtph->version);
146                 return -EINVAL;
147         }
148         payload = data + sizeof(struct rtp_hdr) + (rtph->csrc_count << 2);
149         payload_len = len - sizeof(struct rtp_hdr) - (rtph->csrc_count << 2);
150         if (payload_len < 0) {
151                 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d, "
152                         "csrc count = %d)\n", len, rtph->csrc_count);
153                 return -EINVAL;
154         }
155         if (rtph->extension) {
156                 if (payload_len < (int)sizeof(struct rtp_x_hdr)) {
157                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
158                                 "extension header\n");
159                         return -EINVAL;
160                 }
161                 rtpxh = (struct rtp_x_hdr *)payload;
162                 x_len = ntohs(rtpxh->length) * 4 + sizeof(struct rtp_x_hdr);
163                 payload += x_len;
164                 payload_len -= x_len;
165                 if (payload_len < 0) {
166                         PDEBUG(DEBUG_SIP, "received RTP frame too short, "
167                                 "extension header exceeds frame length\n");
168                         return -EINVAL;
169                 }
170         }
171         if (rtph->padding) {
172                 if (payload_len < 0) {
173                         PDEBUG(DEBUG_SIP, "received RTP frame too short for "
174                                 "padding length\n");
175                         return -EINVAL;
176                 }
177                 payload_len -= payload[payload_len - 1];
178                 if (payload_len < 0) {
179                         PDEBUG(DEBUG_SIP, "received RTP frame with padding "
180                                 "greater than payload\n");
181                         return -EINVAL;
182                 }
183         }
184
185         switch (rtph->payload_type) {
186         case RTP_PT_GSM_FULL:
187                 if (payload_len != 33) {
188                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
189                                 "payload length != 33 (len = %d)\n",
190                                 payload_len);
191                         return -EINVAL;
192                 }
193                 break;
194         case RTP_PT_GSM_EFR:
195                 if (payload_len != 31) {
196                         PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
197                                 "payload length != 31 (len = %d)\n",
198                                 payload_len);
199                         return -EINVAL;
200                 }
201                 break;
202         case RTP_PT_ALAW:
203                 if (options.law != 'a') {
204                         PDEBUG(DEBUG_SIP, "received Alaw, but we don't do Alaw\n");
205                         return -EINVAL;
206                 }
207                 break;
208         case RTP_PT_ULAW:
209                 if (options.law == 'a') {
210                         PDEBUG(DEBUG_SIP, "received Ulaw, but we don't do Ulaw\n");
211                         return -EINVAL;
212                 }
213                 break;
214         default:
215                 PDEBUG(DEBUG_SIP, "received RTP frame with unknown payload "
216                         "type %d\n", rtph->payload_type);
217                 return -EINVAL;
218         }
219
220         if (payload_len <= 0) {
221                 PDEBUG(DEBUG_SIP, "received RTP payload is too small: %d\n", payload_len);
222                 return 0;
223         }
224
225         psip->bchannel_send(PH_DATA_REQ, 0, payload, payload_len);
226
227         return 0;
228 }
229
230 static int rtp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
231 {
232         class Psip *psip = (class Psip *) instance;
233         int len;
234         unsigned char buffer[256];
235         int rc = 0;
236
237         if ((what & LCR_FD_READ)) {
238                 len = read(fd->fd, &buffer, sizeof(buffer));
239                 if (len <= 0) {
240                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
241 //                      psip->rtp_close();
242 //                      psip->rtp_shutdown();
243                         return len;
244                 }
245                 rc = rtp_decode(psip, buffer, len);
246         }
247
248         return rc;
249 }
250
251 static int rtcp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
252 {
253 //      class Psip *psip = (class Psip *) instance;
254         int len;
255         unsigned char buffer[256];
256
257         if ((what & LCR_FD_READ)) {
258                 len = read(fd->fd, &buffer, sizeof(buffer));
259                 if (len <= 0) {
260                         PDEBUG(DEBUG_SIP, "read result=%d\n", len);
261 //                      psip->rtp_close();
262 //                      psip->rtp_shutdown();
263                         return len;
264                 }
265                 PDEBUG(DEBUG_SIP, "rtcp!");
266         }
267
268         return 0;
269 }
270
271 #define RTP_PORT_BASE   30000
272 static unsigned int next_udp_port = RTP_PORT_BASE;
273
274 static int rtp_sub_socket_bind(int fd, struct sockaddr_in *sin_local, uint32_t ip, uint16_t port)
275 {
276         int rc;
277         socklen_t alen = sizeof(*sin_local);
278
279         sin_local->sin_family = AF_INET;
280         sin_local->sin_addr.s_addr = htonl(ip);
281         sin_local->sin_port = htons(port);
282
283         rc = bind(fd, (struct sockaddr *) sin_local, sizeof(*sin_local));
284         if (rc < 0)
285                 return rc;
286
287         /* retrieve the address we actually bound to, in case we
288          * passed INADDR_ANY as IP address */
289         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
290 }
291
292 static int rtp_sub_socket_connect(int fd, struct sockaddr_in *sin_local, struct sockaddr_in *sin_remote, uint32_t ip, uint16_t port)
293 {
294         int rc;
295         socklen_t alen = sizeof(*sin_local);
296
297         sin_remote->sin_family = AF_INET;
298         sin_remote->sin_addr.s_addr = htonl(ip);
299         sin_remote->sin_port = htons(port);
300
301         rc = connect(fd, (struct sockaddr *) sin_remote, sizeof(*sin_remote));
302         if (rc < 0) {
303                 PERROR("failed to connect to ip %08x port %d rc=%d\n", ip, port, rc);
304                 return rc;
305         }
306
307         return getsockname(fd, (struct sockaddr *) sin_local, &alen);
308 }
309
310 int Psip::rtp_open(void)
311 {
312         int rc;
313         struct in_addr ia;
314         unsigned int ip;
315
316         /* create socket */
317         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
318         if (!rc) {
319                 rtp_close();
320                 return -EIO;
321         }
322         p_m_s_rtp_fd.fd = rc;
323         register_fd(&p_m_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
324
325         rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
326         if (!rc) {
327                 rtp_close();
328                 return -EIO;
329         }
330         p_m_s_rtcp_fd.fd = rc;
331         register_fd(&p_m_s_rtcp_fd, LCR_FD_READ, rtcp_sock_callback, this, 0);
332
333         /* bind socket */
334         ip = htonl(INADDR_ANY);
335         ia.s_addr = ip;
336         for (next_udp_port = next_udp_port % 0xffff;
337              next_udp_port < 0xffff; next_udp_port += 2) {
338                 rc = rtp_sub_socket_bind(p_m_s_rtp_fd.fd, &p_m_s_rtp_sin_local, ip, next_udp_port);
339                 if (rc != 0)
340                         continue;
341
342                 rc = rtp_sub_socket_bind(p_m_s_rtcp_fd.fd, &p_m_s_rtcp_sin_local, ip, next_udp_port+1);
343                 if (rc == 0)
344                         break;
345         }
346         if (rc < 0) {
347                 PDEBUG(DEBUG_SIP, "failed to find port\n");
348                 rtp_close();
349                 return rc;
350         }
351         p_m_s_rtp_port_local = next_udp_port;
352         p_m_s_rtp_ip_local = ntohl(p_m_s_rtp_sin_local.sin_addr.s_addr);
353         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_m_s_rtp_ip_local, p_m_s_rtp_port_local);
354         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote);
355
356         return p_m_s_rtp_port_local;
357 }
358
359 int Psip::rtp_connect(void)
360 {
361         int rc;
362         struct in_addr ia;
363
364         ia.s_addr = htonl(p_m_s_rtp_ip_remote);
365         PDEBUG(DEBUG_SIP, "rtp_connect(ip=%s, port=%u)\n", inet_ntoa(ia), p_m_s_rtp_port_remote);
366
367         rc = rtp_sub_socket_connect(p_m_s_rtp_fd.fd, &p_m_s_rtp_sin_local, &p_m_s_rtp_sin_remote, p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote);
368         if (rc < 0)
369                 return rc;
370
371         rc = rtp_sub_socket_connect(p_m_s_rtcp_fd.fd, &p_m_s_rtcp_sin_local, &p_m_s_rtcp_sin_remote, p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote + 1);
372         if (rc < 0)
373                 return rc;
374
375         p_m_s_rtp_ip_local = ntohl(p_m_s_rtp_sin_local.sin_addr.s_addr);
376         PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_m_s_rtp_ip_local, p_m_s_rtp_port_local);
377         PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_m_s_rtp_ip_remote, p_m_s_rtp_port_remote);
378         p_m_s_rtp_is_connected = 1;
379
380         return 0;
381 }
382 void Psip::rtp_close(void)
383 {
384         if (p_m_s_rtp_fd.fd > 0) {
385                 unregister_fd(&p_m_s_rtp_fd);
386                 close(p_m_s_rtp_fd.fd);
387                 p_m_s_rtp_fd.fd = 0;
388         }
389         if (p_m_s_rtcp_fd.fd > 0) {
390                 unregister_fd(&p_m_s_rtcp_fd);
391                 close(p_m_s_rtcp_fd.fd);
392                 p_m_s_rtcp_fd.fd = 0;
393         }
394         if (p_m_s_rtp_is_connected) {
395                 PDEBUG(DEBUG_SIP, "rtp closed\n");
396                 p_m_s_rtp_is_connected = 0;
397         }
398 }
399
400 /* "to - from" */
401 void tv_difference(struct timeval *diff, const struct timeval *from,
402                           const struct timeval *__to)
403 {
404         struct timeval _to = *__to, *to = &_to;
405
406         if (to->tv_usec < from->tv_usec) {
407                 to->tv_sec -= 1;
408                 to->tv_usec += 1000000;
409         }
410
411         diff->tv_usec = to->tv_usec - from->tv_usec;
412         diff->tv_sec = to->tv_sec - from->tv_sec;
413 }
414
415 /* encode and send a rtp frame */
416 int Psip::rtp_send_frame(unsigned char *data, unsigned int len, int payload_type)
417 {
418         struct rtp_hdr *rtph;
419         int payload_len;
420         int duration; /* in samples */
421         unsigned char buffer[256];
422
423         if (!p_m_s_rtp_is_connected) {
424                 /* drop silently */
425                 return 0;
426         }
427
428         if (!p_m_s_rtp_tx_action) {
429                 /* initialize sequences */
430                 p_m_s_rtp_tx_action = 1;
431                 p_m_s_rtp_tx_ssrc = rand();
432                 p_m_s_rtp_tx_sequence = random();
433                 p_m_s_rtp_tx_timestamp = random();
434                 memset(&p_m_s_rtp_tx_last_tv, 0, sizeof(p_m_s_rtp_tx_last_tv));
435         }
436
437         switch (payload_type) {
438         case RTP_PT_GSM_FULL:
439                 payload_len = 33;
440                 duration = 160;
441                 break;
442         case RTP_PT_GSM_EFR:
443                 payload_len = 31;
444                 duration = 160;
445                 break;
446         case RTP_PT_ALAW:
447         case RTP_PT_ULAW:
448                 payload_len = len;
449                 duration = len;
450                 break;
451         default:
452                 PERROR("unsupported message type %d\n", payload_type);
453                 return -EINVAL;
454         }
455
456 #if 0
457         {
458                 struct timeval tv, tv_diff;
459                 long int usec_diff, frame_diff;
460
461                 gettimeofday(&tv, NULL);
462                 tv_difference(&tv_diff, &p_m_s_rtp_tx_last_tv, &tv);
463                 p_m_s_rtp_tx_last_tv = tv;
464
465                 usec_diff = tv_diff.tv_sec * 1000000 + tv_diff.tv_usec;
466                 frame_diff = (usec_diff / 20000);
467
468                 if (abs(frame_diff) > 1) {
469                         long int frame_diff_excess = frame_diff - 1;
470
471                         PDEBUG(DEBUG_SIP, "Correcting frame difference of %ld frames\n", frame_diff_excess);
472                         p_m_s_rtp_tx_sequence += frame_diff_excess;
473                         p_m_s_rtp_tx_timestamp += frame_diff_excess * duration;
474                 }
475         }
476 #endif
477
478         rtph = (struct rtp_hdr *) buffer;
479         rtph->version = RTP_VERSION;
480         rtph->padding = 0;
481         rtph->extension = 0;
482         rtph->csrc_count = 0;
483         rtph->marker = 0;
484         rtph->payload_type = payload_type;
485         rtph->sequence = htons(p_m_s_rtp_tx_sequence++);
486         rtph->timestamp = htonl(p_m_s_rtp_tx_timestamp);
487         p_m_s_rtp_tx_timestamp += duration;
488         rtph->ssrc = htonl(p_m_s_rtp_tx_ssrc);
489         memcpy(buffer + sizeof(struct rtp_hdr), data, payload_len);
490
491         if (p_m_s_rtp_fd.fd > 0) {
492                 len = write(p_m_s_rtp_fd.fd, &buffer, sizeof(struct rtp_hdr) + payload_len);
493                 if (len != sizeof(struct rtp_hdr) + payload_len) {
494                         PDEBUG(DEBUG_SIP, "write result=%d\n", len);
495 //                      rtp_close();
496 //                      rtp_shutdown();
497                         return -EIO;
498                 }
499         }
500
501         return 0;
502 }
503
504 /*
505  * bchannel handling
506  */
507
508 /* select free bchannel from loopback interface */
509 int Psip::hunt_bchannel(void)
510 {
511         return loop_hunt_bchannel(this, p_m_mISDNport);
512 }
513
514 /* close SIP side bchannel */
515 void Psip::bchannel_close(void)
516 {
517         if (p_m_s_b_sock > -1) {
518                 unregister_fd(&p_m_s_b_fd);
519                 close(p_m_s_b_sock);
520         }
521         p_m_s_b_sock = -1;
522         p_m_s_b_index = -1;
523         p_m_s_b_active = 0;
524 }
525
526 static int b_handler(struct lcr_fd *fd, unsigned int what, void *instance, int index);
527
528 /* open external side bchannel */
529 int Psip::bchannel_open(int index)
530 {
531         int ret;
532         struct sockaddr_mISDN addr;
533         struct mISDNhead act;
534
535         if (p_m_s_b_sock > -1) {
536                 PERROR("Socket already created for index %d\n", index);
537                 return(-EIO);
538         }
539
540         /* open socket */
541         ret = p_m_s_b_sock = socket(PF_ISDN, SOCK_DGRAM, ISDN_P_B_RAW);
542         if (ret < 0) {
543                 PERROR("Failed to open bchannel-socket for index %d\n", index);
544                 bchannel_close();
545                 return(ret);
546         }
547         memset(&p_m_s_b_fd, 0, sizeof(p_m_s_b_fd));
548         p_m_s_b_fd.fd = p_m_s_b_sock;
549         register_fd(&p_m_s_b_fd, LCR_FD_READ, b_handler, this, 0);
550
551
552         /* bind socket to bchannel */
553         addr.family = AF_ISDN;
554         addr.dev = mISDNloop.port;
555         addr.channel = index+1+(index>15);
556         ret = bind(p_m_s_b_sock, (struct sockaddr *)&addr, sizeof(addr));
557         if (ret < 0) {
558                 PERROR("Failed to bind bchannel-socket for index %d\n", index);
559                 bchannel_close();
560                 return(ret);
561         }
562         /* activate bchannel */
563         PDEBUG(DEBUG_SIP, "Activating SIP side channel index %i.\n", index);
564         act.prim = PH_ACTIVATE_REQ; 
565         act.id = 0;
566         ret = sendto(p_m_s_b_sock, &act, MISDN_HEADER_LEN, 0, NULL, 0);
567         if (ret < 0) {
568                 PERROR("Failed to activate index %d\n", index);
569                 bchannel_close();
570                 return(ret);
571         }
572
573         p_m_s_b_index = index;
574
575         return(0);
576 }
577
578 /* receive from bchannel */
579 void Psip::bchannel_receive(struct mISDNhead *hh, unsigned char *data, int len)
580 {
581         /* write to rx buffer */
582         while(len--) {
583                 p_m_s_rxdata[p_m_s_rxpos++] = flip[*data++];
584                 if (p_m_s_rxpos == 160) {
585                         p_m_s_rxpos = 0;
586
587                         /* transmit data via rtp */
588                         rtp_send_frame(p_m_s_rxdata, 160, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW);
589                 }
590         }
591 }
592
593 /* transmit to bchannel */
594 void Psip::bchannel_send(unsigned int prim, unsigned int id, unsigned char *data, int len)
595 {
596         unsigned char buf[MISDN_HEADER_LEN+len];
597         struct mISDNhead *hh = (struct mISDNhead *)buf;
598         unsigned char *to = buf + MISDN_HEADER_LEN;
599         int n = len;
600         int ret;
601
602         if (!p_m_s_b_active)
603                 return;
604
605         /* make and send frame */
606         hh->prim = prim;
607         hh->id = 0;
608         while(n--)
609                 *to++ = flip[*data++];
610         ret = sendto(p_m_s_b_sock, buf, MISDN_HEADER_LEN+len, 0, NULL, 0);
611         if (ret <= 0)
612                 PERROR("Failed to send to socket index %d\n", p_m_s_b_index);
613 }
614
615 /* handle socket input */
616 static int b_handler(struct lcr_fd *fd, unsigned int what, void *instance, int index)
617 {
618         class Psip *psip = (class Psip *)instance;
619         int ret;
620         unsigned char buffer[2048+MISDN_HEADER_LEN];
621         struct mISDNhead *hh = (struct mISDNhead *)buffer;
622
623         /* handle message from bchannel */
624         if (psip->p_m_s_b_sock > -1) {
625                 ret = recv(psip->p_m_s_b_sock, buffer, sizeof(buffer), 0);
626                 if (ret >= (int)MISDN_HEADER_LEN) {
627                         switch(hh->prim) {
628                                 /* we don't care about confirms, we use rx data to sync tx */
629                                 case PH_DATA_CNF:
630                                 break;
631                                 /* we receive audio data, we respond to it AND we send tones */
632                                 case PH_DATA_IND:
633                                 psip->bchannel_receive(hh, buffer+MISDN_HEADER_LEN, ret-MISDN_HEADER_LEN);
634                                 break;
635                                 case PH_ACTIVATE_IND:
636                                 psip->p_m_s_b_active = 1;
637                                 break;
638                                 case PH_DEACTIVATE_IND:
639                                 psip->p_m_s_b_active = 0;
640                                 break;
641                         }
642                 } else {
643                         if (ret < 0 && errno != EWOULDBLOCK)
644                                 PERROR("Read from GSM port, index %d failed with return code %d\n", ret);
645                 }
646         }
647
648         return 0;
649 }
650
651 /* taken from freeswitch */
652 /* map sip responses to QSIG cause codes ala RFC4497 section 8.4.4 */
653 static int status2cause(int status)
654 {
655         switch (status) {
656         case 200:
657                 return 16; //SWITCH_CAUSE_NORMAL_CLEARING;
658         case 401:
659         case 402:
660         case 403:
661         case 407:
662         case 603:
663                 return 21; //SWITCH_CAUSE_CALL_REJECTED;
664         case 404:
665                 return 1; //SWITCH_CAUSE_UNALLOCATED_NUMBER;
666         case 485:
667         case 604:
668                 return 3; //SWITCH_CAUSE_NO_ROUTE_DESTINATION;
669         case 408:
670         case 504:
671                 return 102; //SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
672         case 410:
673                 return 22; //SWITCH_CAUSE_NUMBER_CHANGED;
674         case 413:
675         case 414:
676         case 416:
677         case 420:
678         case 421:
679         case 423:
680         case 505:
681         case 513:
682                 return 127; //SWITCH_CAUSE_INTERWORKING;
683         case 480:
684                 return 180; //SWITCH_CAUSE_NO_USER_RESPONSE;
685         case 400:
686         case 481:
687         case 500:
688         case 503:
689                 return 41; //SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE;
690         case 486:
691         case 600:
692                 return 17; //SWITCH_CAUSE_USER_BUSY;
693         case 484:
694                 return 28; //SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
695         case 488:
696         case 606:
697                 return 88; //SWITCH_CAUSE_INCOMPATIBLE_DESTINATION;
698         case 502:
699                 return 38; //SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
700         case 405:
701                 return 63; //SWITCH_CAUSE_SERVICE_UNAVAILABLE;
702         case 406:
703         case 415:
704         case 501:
705                 return 79; //SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED;
706         case 482:
707         case 483:
708                 return 25; //SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR;
709         case 487:
710                 return 31; //??? SWITCH_CAUSE_ORIGINATOR_CANCEL;
711         default:
712                 return 31; //SWITCH_CAUSE_NORMAL_UNSPECIFIED;
713         }
714 }
715
716 static int cause2status(int cause, int location, const char **st)
717 {
718         int s;
719
720         switch (cause) {
721         case 1:
722                 s = 404; *st = sip_404_Not_found;
723                 break;
724         case 2:
725                 s = 404; *st = sip_404_Not_found;
726                 break;
727         case 3:
728                 s = 404; *st = sip_404_Not_found;
729                 break;
730         case 17:
731                 s = 486; *st = sip_486_Busy_here;
732                 break;
733         case 18:
734                 s = 408; *st = sip_408_Request_timeout;
735                 break;
736         case 19:
737                 s = 480; *st = sip_480_Temporarily_unavailable;
738                 break;
739         case 20:
740                 s = 480; *st = sip_480_Temporarily_unavailable;
741                 break;
742         case 21:
743                 if (location == LOCATION_USER) {
744                         s = 603; *st = sip_603_Decline;
745                 } else {
746                         s = 403; *st = sip_403_Forbidden;
747                 }
748                 break;
749         case 22:
750                 //s = 301; *st = sip_301_Moved_permanently;
751                 s = 410; *st = sip_410_Gone;
752                 break;
753         case 23:
754                 s = 410; *st = sip_410_Gone;
755                 break;
756         case 27:
757                 s = 502; *st = sip_502_Bad_gateway;
758                 break;
759         case 28:
760                 s = 484; *st = sip_484_Address_incomplete;
761                 break;
762         case 29:
763                 s = 501; *st = sip_501_Not_implemented;
764                 break;
765         case 31:
766                 s = 480; *st = sip_480_Temporarily_unavailable;
767                 break;
768         case 34:
769                 s = 503; *st = sip_503_Service_unavailable;
770                 break;
771         case 38:
772                 s = 503; *st = sip_503_Service_unavailable;
773                 break;
774         case 41:
775                 s = 503; *st = sip_503_Service_unavailable;
776                 break;
777         case 42:
778                 s = 503; *st = sip_503_Service_unavailable;
779                 break;
780         case 47:
781                 s = 503; *st = sip_503_Service_unavailable;
782                 break;
783         case 55:
784                 s = 403; *st = sip_403_Forbidden;
785                 break;
786         case 57:
787                 s = 403; *st = sip_403_Forbidden;
788                 break;
789         case 58:
790                 s = 503; *st = sip_503_Service_unavailable;
791                 break;
792         case 65:
793                 s = 488; *st = sip_488_Not_acceptable;
794                 break;
795         case 69:
796                 s = 501; *st = sip_501_Not_implemented;
797                 break;
798         case 70:
799                 s = 488; *st = sip_488_Not_acceptable;
800                 break;
801         case 79:
802                 s = 501; *st = sip_501_Not_implemented;
803                 break;
804         case 87:
805                 s = 403; *st = sip_403_Forbidden;
806                 break;
807         case 88:
808                 s = 503; *st = sip_503_Service_unavailable;
809                 break;
810         case 102:
811                 s = 504; *st = sip_504_Gateway_time_out;
812                 break;
813         default:
814                 s = 468; *st = sip_486_Busy_here;
815         }
816
817         return s;
818 }
819
820 /*
821  * endpoint sends messages to the SIP port
822  */
823
824 int Psip::message_connect(unsigned int epoint_id, int message_id, union parameter *param)
825 {
826         char sdp_str[256];
827         struct in_addr ia;
828         struct lcr_msg *message;
829
830         if (rtp_connect() < 0) {
831                 nua_cancel(p_m_s_handle, TAG_END());
832                 nua_handle_destroy(p_m_s_handle);
833                 p_m_s_handle = NULL;
834                 sip_trace_header(this, "CANCEL", DIRECTION_OUT);
835                 add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
836                 end_trace();
837                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
838                 message->param.disconnectinfo.cause = 41;
839                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
840                 message_put(message);
841                 new_state(PORT_STATE_RELEASE);
842                 trigger_work(&p_m_s_delete);
843                 return 0;
844         }
845         ia.s_addr = htonl(p_m_s_rtp_ip_local);
846
847         SPRINT(sdp_str,
848                 "v=0\n"
849                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
850                 "s=SIP Call\n"
851                 "c=IN IP4 %s\n"
852                 "t=0 0\n"
853                 "m=audio %d RTP/AVP %d\n"
854                 "a=rtpmap:%d %s/8000\n"
855                 , inet_ntoa(ia), inet_ntoa(ia), p_m_s_rtp_port_local, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?"PCMA":"PCMU");
856         PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
857
858         nua_respond(p_m_s_handle, SIP_200_OK,
859                 NUTAG_MEDIA_ENABLE(0),
860                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
861                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
862         new_state(PORT_STATE_CONNECT);
863         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
864         add_trace("respond", "value", "200 OK");
865         add_trace("reason", NULL, "call connected");
866         end_trace();
867
868         return 0;
869 }
870
871 int Psip::message_release(unsigned int epoint_id, int message_id, union parameter *param)
872 {
873         struct lcr_msg *message;
874         char cause_str[128] = "";
875         int cause = param->disconnectinfo.cause;
876         int location = param->disconnectinfo.cause;
877         int status;
878         const char *status_text;
879
880         if (cause > 0 && cause <= 127) {
881                 SPRINT(cause_str, "Q.850;cause=%d;text=\"%s\"", cause, isdn_cause[cause].english);
882         }
883
884         switch (p_state) {
885         case PORT_STATE_OUT_SETUP:
886         case PORT_STATE_OUT_PROCEEDING:
887         case PORT_STATE_OUT_ALERTING:
888                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will cancel\n");
889                 sip_trace_header(this, "CANCEL", DIRECTION_OUT);
890                 if (cause_str[0])
891                         add_trace("cause", "value", "%d", cause);
892                 end_trace();
893                 nua_cancel(p_m_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
894                 break;
895         case PORT_STATE_IN_SETUP:
896         case PORT_STATE_IN_PROCEEDING:
897         case PORT_STATE_IN_ALERTING:
898                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will respond\n");
899                 status = cause2status(cause, location, &status_text);
900                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
901                 if (cause_str[0])
902                         add_trace("cause", "value", "%d", cause);
903                 add_trace("respond", "value", "%d %s", status, status_text);
904                 end_trace();
905                 nua_respond(p_m_s_handle, status, status_text, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
906                 nua_handle_destroy(p_m_s_handle);
907                 p_m_s_handle = NULL;
908                 trigger_work(&p_m_s_delete);
909                 break;
910         default:
911                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will perform nua_bye\n");
912                 sip_trace_header(this, "BYE", DIRECTION_OUT);
913                 if (cause_str[0])
914                         add_trace("cause", "value", "%d", cause);
915                 end_trace();
916                 nua_bye(p_m_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
917         }
918
919         if (message_id == MESSAGE_DISCONNECT) {
920                 while(p_epointlist) {
921                         message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
922                         message->param.disconnectinfo.cause = CAUSE_NORMAL;
923                         message->param.disconnectinfo.location = LOCATION_BEYOND;
924                         message_put(message);
925                         /* remove epoint */
926                         free_epointlist(p_epointlist);
927                 }
928         }
929
930         new_state(PORT_STATE_RELEASE);
931
932         return(0);
933 }
934
935 int Psip::message_setup(unsigned int epoint_id, int message_id, union parameter *param)
936 {
937         struct sip_inst *inst = (struct sip_inst *) p_m_s_sip_inst;
938         char from[128];
939         char to[128];
940         const char *local = inst->interface->sip_local_ip;
941         const char *remote = inst->interface->sip_remote_ip;
942         char sdp_str[256];
943         struct in_addr ia;
944         struct epoint_list *epointlist;
945         sip_cseq_t *cseq = NULL;
946         int ret;
947         int channel;
948
949         PDEBUG(DEBUG_SIP, "Doing Setup (inst %p)\n", inst);
950
951         /* release if port is blocked */
952         if (p_m_mISDNport->ifport->block) {
953                 struct lcr_msg *message;
954
955                 sip_trace_header(this, "INVITE", DIRECTION_OUT);
956                 add_trace("failure", NULL, "Port blocked.");
957                 end_trace();
958                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
959                 message->param.disconnectinfo.cause = 27; // temp. unavail.
960                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
961                 message_put(message);
962                 new_state(PORT_STATE_RELEASE);
963                 trigger_work(&p_m_s_delete);
964                 return 0;
965         }
966
967         /* hunt channel */
968         ret = channel = hunt_bchannel();
969         if (ret < 0)
970                 goto no_channel;
971         /* open channel */
972         ret = seize_bchannel(channel, 1);
973         if (ret < 0) {
974                 struct lcr_msg *message;
975
976                 no_channel:
977                 sip_trace_header(this, "INVITE", DIRECTION_OUT);
978                 add_trace("failure", NULL, "No internal audio channel available.");
979                 end_trace();
980                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
981                 message->param.disconnectinfo.cause = 34;
982                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
983                 message_put(message);
984                 new_state(PORT_STATE_RELEASE);
985                 trigger_work(&p_m_s_delete);
986                 return 0;
987         }
988         bchannel_event(p_m_mISDNport, p_m_b_index, B_EVENT_USE);
989         if (bchannel_open(p_m_b_index))
990                 goto no_channel;
991
992         memcpy(&p_dialinginfo, &param->setup.dialinginfo, sizeof(p_dialinginfo));
993         memcpy(&p_callerinfo, &param->setup.callerinfo, sizeof(p_callerinfo));
994         memcpy(&p_redirinfo, &param->setup.redirinfo, sizeof(p_redirinfo));
995
996         /* connect to remote RTP */
997         if (rtp_open() < 0) {
998                 struct lcr_msg *message;
999
1000                 PERROR("Failed to open RTP sockets\n");
1001                 /* send release message to endpoit */
1002                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1003                 message->param.disconnectinfo.cause = 41;
1004                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1005                 message_put(message);
1006                 new_state(PORT_STATE_RELEASE);
1007                 trigger_work(&p_m_s_delete);
1008                 return 0;
1009         }
1010         SPRINT(from, "sip:%s@%s", param->setup.callerinfo.id, local);
1011         SPRINT(to, "sip:%s@%s", param->setup.dialinginfo.id, remote);
1012
1013         sip_trace_header(this, "INVITE", DIRECTION_OUT);
1014         add_trace("from", "uri", "%s", from);
1015         add_trace("to", "uri", "%s", to);
1016         add_trace("rtp", "port", "%d,%d", p_m_s_rtp_port_local, p_m_s_rtp_port_local + 1);
1017         end_trace();
1018
1019         p_m_s_handle = nua_handle(inst->nua, NULL, TAG_END());
1020         if (!p_m_s_handle) {
1021                 struct lcr_msg *message;
1022
1023                 PERROR("Failed to create handle\n");
1024                 /* send release message to endpoit */
1025                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1026                 message->param.disconnectinfo.cause = 41;
1027                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1028                 message_put(message);
1029                 new_state(PORT_STATE_RELEASE);
1030                 trigger_work(&p_m_s_delete);
1031                 return 0;
1032         }
1033         /* apply handle */
1034         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1035         add_trace("handle", "new", "0x%x", p_m_s_handle);
1036         end_trace();
1037
1038         inet_pton(AF_INET, local, &p_m_s_rtp_ip_local);
1039         p_m_s_rtp_ip_local = ntohl(p_m_s_rtp_ip_local);
1040         ia.s_addr = htonl(p_m_s_rtp_ip_local);
1041         SPRINT(sdp_str,
1042                 "v=0\n"
1043                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
1044                 "s=SIP Call\n"
1045                 "c=IN IP4 %s\n"
1046                 "t=0 0\n"
1047                 "m=audio %d RTP/AVP %d\n"
1048                 "a=rtpmap:%d %s/8000\n"
1049                 , inet_ntoa(ia), inet_ntoa(ia), p_m_s_rtp_port_local, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW, (options.law=='a')?"PCMA":"PCMU");
1050         PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
1051
1052 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
1053
1054         nua_invite(p_m_s_handle,
1055                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1056                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
1057                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1058                 NUTAG_MEDIA_ENABLE(0),
1059                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1060                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1061         new_state(PORT_STATE_OUT_SETUP);
1062
1063         /* attach only if not already */
1064         epointlist = p_epointlist;
1065         while(epointlist) {
1066                 if (epointlist->epoint_id == epoint_id)
1067                         break;
1068                 epointlist = epointlist->next;
1069         }
1070         if (!epointlist)
1071                 epointlist_new(epoint_id);
1072
1073         return 0;
1074 }
1075         
1076 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1077 {
1078         class Endpoint *epoint;
1079
1080         if (PmISDN::message_epoint(epoint_id, message_id, param))
1081                 return(1);
1082
1083         epoint = find_epoint_id(epoint_id);
1084         if (!epoint) {
1085                 PDEBUG(DEBUG_SIP, "PORT(%s) no endpoint object found where the message is from.\n", p_name);
1086                 return(0);
1087         }
1088
1089         switch(message_id) {
1090                 case MESSAGE_DATA:
1091                 return(1);
1092
1093                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1094                 if (p_state != PORT_STATE_IN_SETUP
1095                  && p_state != PORT_STATE_IN_PROCEEDING)
1096                         return 0;
1097                 nua_respond(p_m_s_handle, SIP_180_RINGING, TAG_END());
1098                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1099                 add_trace("respond", "value", "180 Ringing");
1100                 end_trace();
1101                 new_state(PORT_STATE_IN_ALERTING);
1102                 return(1);
1103
1104                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1105                 if (p_state != PORT_STATE_IN_SETUP
1106                  && p_state != PORT_STATE_IN_PROCEEDING
1107                  && p_state != PORT_STATE_IN_ALERTING)
1108                         return 0;
1109                 message_connect(epoint_id, message_id, param);
1110                 return(1);
1111
1112                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1113                 case MESSAGE_RELEASE: /* call has been released */
1114                 message_release(epoint_id, message_id, param);
1115                 return(1);
1116
1117                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1118                 message_setup(epoint_id, message_id, param);
1119                 return(1);
1120
1121                 default:
1122                 PDEBUG(DEBUG_SIP, "PORT(%s) SP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1123         }
1124
1125         return(0);
1126 }
1127
1128 int Psip::parse_sdp(sip_t const *sip, unsigned int *ip, unsigned short *port)
1129 {
1130         int codec_supported = 0;
1131
1132         if (!sip->sip_payload) {
1133                 PDEBUG(DEBUG_SIP, "no payload given\n");
1134                 return 0;
1135         }
1136
1137         sdp_parser_t *parser;
1138         sdp_session_t *sdp;
1139         sdp_media_t *m;
1140         sdp_attribute_t *attr;
1141         sdp_rtpmap_t *map;
1142         sdp_connection_t *conn;
1143
1144         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1145
1146         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1147         if (!parser) {
1148                 return 400;
1149         }
1150         if (!(sdp = sdp_session(parser))) {
1151                 sdp_parser_free(parser);
1152                 return 400;
1153         }
1154         for (m = sdp->sdp_media; m; m = m->m_next) {
1155                 if (m->m_proto != sdp_proto_rtp)
1156                         continue;
1157                 if (m->m_type != sdp_media_audio)
1158                         continue;
1159                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1160                 *port = m->m_port;
1161                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1162                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1163                 }
1164                 if (m->m_connections) {
1165                         conn = m->m_connections;
1166                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1167                         inet_pton(AF_INET, conn->c_address, ip);
1168                         *ip = ntohl(p_m_s_rtp_ip_remote);
1169                 } else {
1170                         char *p = sip->sip_payload->pl_data;
1171                         char addr[16];
1172
1173                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1174                         p = strstr(p, "c=IN IP4 ");
1175                         if (!p) {
1176                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1177                                 sdp_parser_free(parser);
1178                                 return 400;
1179                         }
1180                         SCPY(addr, p + 9);
1181                         if ((p = strchr(addr, '\n'))) *p = '\0';
1182                         if ((p = strchr(addr, '\r'))) *p = '\0';
1183                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1184                         inet_pton(AF_INET, addr, ip);
1185                         *ip = ntohl(p_m_s_rtp_ip_remote);
1186                 }
1187                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1188                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d'\n", map->rm_encoding, map->rm_rate);
1189                         if (!strcmp(map->rm_encoding, (options.law=='a')?"PCMA":"PCMU") && map->rm_rate == 8000) {
1190                                 PDEBUG(DEBUG_SIP, "supported codec found\n");
1191                                 codec_supported = 1;
1192                                 goto done_codec;
1193                         }
1194                 }
1195         }
1196         done_codec:
1197
1198         sdp_parser_free(parser);
1199
1200         if (!codec_supported)
1201                 return 415;
1202
1203         return 0;
1204 }
1205
1206 void Psip::i_invite(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tagss[])
1207 {
1208         const char *from = "", *to = "";
1209         int ret;
1210         class Endpoint *epoint;
1211         struct lcr_msg *message;
1212         int channel;
1213
1214         if (sip->sip_from && sip->sip_from->a_url)
1215                 from = sip->sip_from->a_url->url_user;
1216         if (sip->sip_to && sip->sip_to->a_url)
1217                 to = sip->sip_to->a_url->url_user;
1218         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1219
1220         ret = parse_sdp(sip, &p_m_s_rtp_ip_remote, &p_m_s_rtp_port_remote);
1221         if (ret) {
1222                 if (ret == 400)
1223                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1224                 else
1225                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1226                 nua_handle_destroy(nh);
1227                 p_m_s_handle = NULL;
1228                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1229                 if (ret == 400)
1230                         add_trace("respond", "value", "415 Unsupported Media");
1231                 else
1232                         add_trace("respond", "value", "400 Bad Request");
1233                 add_trace("reason", NULL, "offered codec does not match");
1234                 end_trace();
1235                 new_state(PORT_STATE_RELEASE);
1236                 trigger_work(&p_m_s_delete);
1237                 return;
1238         }
1239
1240         /* connect to remote RTP */
1241         if (rtp_open() < 0) {
1242                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1243                 nua_handle_destroy(nh);
1244                 p_m_s_handle = NULL;
1245                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1246                 add_trace("respond", "value", "500 Internal Server Error");
1247                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1248                 end_trace();
1249                 new_state(PORT_STATE_RELEASE);
1250                 trigger_work(&p_m_s_delete);
1251                 return;
1252         }
1253
1254         /* apply handle */
1255         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1256         add_trace("handle", "new", "0x%x", nh);
1257         p_m_s_handle = nh;
1258         end_trace();
1259
1260         /* if blocked, release call */
1261         if (p_m_mISDNport->ifport->block) {
1262                 nua_respond(nh, SIP_503_SERVICE_UNAVAILABLE, TAG_END());
1263                 nua_handle_destroy(nh);
1264                 p_m_s_handle = NULL;
1265                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1266                 add_trace("respond", "value", "503 Service Unavailable");
1267                 add_trace("reason", NULL, "port is blocked");
1268                 end_trace();
1269                 new_state(PORT_STATE_RELEASE);
1270                 trigger_work(&p_m_s_delete);
1271                 return;
1272         }
1273         sip_trace_header(this, "INVITE", DIRECTION_IN);
1274         add_trace("RTP", "port", "%d", p_m_s_rtp_port_remote);
1275         /* caller information */
1276         if (!from[0]) {
1277                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1278                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1279                 add_trace("calling", "present", "unavailable");
1280         } else {
1281                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1282                 add_trace("calling", "present", "allowed");
1283                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1284                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1285                 SCPY(p_callerinfo.id, from);
1286                 add_trace("calling", "number", "%s", from);
1287         }
1288         p_callerinfo.isdn_port = p_m_portnum;
1289         SCPY(p_callerinfo.interface, p_m_mISDNport->ifport->interface->name);
1290         /* dialing information */
1291         if (to[0]) {
1292                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1293                 SCAT(p_dialinginfo.id, to);
1294                 add_trace("dialing", "number", "%s", to);
1295         }
1296         /* redir info */
1297         /* bearer capability */
1298         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1299         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1300         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1301         add_trace("bearer", "capa", "speech");
1302         add_trace("bearer", "mode", "circuit");
1303         /* if packet mode works some day, see dss1.cpp for conditions */
1304         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1305
1306         end_trace();
1307
1308         /* hunt channel */
1309         ret = channel = hunt_bchannel();
1310         if (ret < 0)
1311                 goto no_channel;
1312
1313         /* open channel */
1314         ret = seize_bchannel(channel, 1);
1315         if (ret < 0) {
1316                 no_channel:
1317                 nua_respond(nh, SIP_480_TEMPORARILY_UNAVAILABLE, TAG_END());
1318                 nua_handle_destroy(nh);
1319                 p_m_s_handle = NULL;
1320                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1321                 add_trace("respond", "value", "480 Temporarily Unavailable");
1322                 add_trace("reason", NULL, "no channel");
1323                 end_trace();
1324                 new_state(PORT_STATE_RELEASE);
1325                 trigger_work(&p_m_s_delete);
1326                 return;
1327         }
1328         bchannel_event(p_m_mISDNport, p_m_b_index, B_EVENT_USE);
1329         if (bchannel_open(p_m_b_index))
1330                 goto no_channel;
1331
1332         /* create endpoint */
1333         if (p_epointlist)
1334                 FATAL("Incoming call but already got an endpoint.\n");
1335         if (!(epoint = new Endpoint(p_serial, 0)))
1336                 FATAL("No memory for Endpoint instance\n");
1337         if (!(epoint->ep_app = new DEFAULT_ENDPOINT_APP(epoint, 0))) //incoming
1338                 FATAL("No memory for Endpoint Application instance\n");
1339         epointlist_new(epoint->ep_serial);
1340
1341         /* send trying (proceeding) */
1342         nua_respond(nh, SIP_100_TRYING, TAG_END());
1343         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1344         add_trace("respond", "value", "100 Trying");
1345         end_trace();
1346
1347         new_state(PORT_STATE_IN_PROCEEDING);
1348
1349         /* send setup message to endpoit */
1350         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1351         message->param.setup.isdn_port = p_m_portnum;
1352         message->param.setup.port_type = p_type;
1353 //      message->param.setup.dtmf = 0;
1354         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1355         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1356         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1357 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1358 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1359 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1360         message_put(message);
1361 }
1362
1363 void Psip::i_bye(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tagss[])
1364 {
1365         struct lcr_msg *message;
1366         int cause = 0;
1367
1368         PDEBUG(DEBUG_SIP, "bye received\n");
1369
1370         sip_trace_header(this, "BYE", DIRECTION_IN);
1371         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1372                 cause = atoi(sip->sip_reason->re_cause);
1373                 add_trace("cause", "value", "%d", cause);
1374         }
1375         end_trace();
1376
1377 // let stack do bye automaticall, since it will not accept our response for some reason
1378 //      nua_respond(nh, SIP_200_OK, TAG_END());
1379         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1380         add_trace("respond", "value", "200 OK");
1381         end_trace();
1382 //      nua_handle_destroy(nh);
1383         p_m_s_handle = NULL;
1384
1385         rtp_close();
1386
1387         while(p_epointlist) {
1388                 /* send setup message to endpoit */
1389                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1390                 message->param.disconnectinfo.cause = cause ? : 16;
1391                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1392                 message_put(message);
1393                 /* remove epoint */
1394                 free_epointlist(p_epointlist);
1395         }
1396         new_state(PORT_STATE_RELEASE);
1397         trigger_work(&p_m_s_delete);
1398 }
1399
1400 void Psip::i_cancel(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tagss[])
1401 {
1402         struct lcr_msg *message;
1403
1404         PDEBUG(DEBUG_SIP, "cancel received\n");
1405
1406         sip_trace_header(this, "CANCEL", DIRECTION_IN);
1407         end_trace();
1408
1409         nua_handle_destroy(nh);
1410         p_m_s_handle = NULL;
1411
1412         rtp_close();
1413
1414         while(p_epointlist) {
1415                 /* send setup message to endpoit */
1416                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1417                 message->param.disconnectinfo.cause = 16;
1418                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1419                 message_put(message);
1420                 /* remove epoint */
1421                 free_epointlist(p_epointlist);
1422         }
1423         new_state(PORT_STATE_RELEASE);
1424         trigger_work(&p_m_s_delete);
1425 }
1426
1427 void Psip::r_bye(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tagss[])
1428 {
1429         PDEBUG(DEBUG_SIP, "bye response received\n");
1430
1431         nua_handle_destroy(nh);
1432         p_m_s_handle = NULL;
1433
1434         rtp_close();
1435
1436         trigger_work(&p_m_s_delete);
1437 }
1438
1439 void Psip::r_cancel(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tagss[])
1440 {
1441         PDEBUG(DEBUG_SIP, "cancel response received\n");
1442
1443         nua_handle_destroy(nh);
1444         p_m_s_handle = NULL;
1445
1446         rtp_close();
1447
1448         trigger_work(&p_m_s_delete);
1449 }
1450
1451 void Psip::r_invite(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tagss[])
1452 {
1453         struct lcr_msg *message;
1454         int cause = 0, location = 0;
1455
1456         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
1457
1458         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1459         add_trace("respond", "value", "%d", status);
1460         end_trace();
1461
1462         /* process 1xx */
1463         switch (status) {
1464         case 100:
1465                 PDEBUG(DEBUG_SIP, "do proceeding\n");
1466                 new_state(PORT_STATE_OUT_PROCEEDING);
1467                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1468                 message_put(message);
1469                 return;
1470         case 180:
1471                 PDEBUG(DEBUG_SIP, "do alerting\n");
1472                 new_state(PORT_STATE_OUT_ALERTING);
1473                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
1474                 message_put(message);
1475                 return;
1476         default:
1477                 if (status < 100 || status > 199)
1478                         break;
1479                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
1480
1481                 return;
1482         }
1483
1484         /* process 2xx */
1485         if (status >= 200 && status <= 299) {
1486                 int ret;
1487
1488                 ret = parse_sdp(sip, &p_m_s_rtp_ip_remote, &p_m_s_rtp_port_remote);
1489                 if (ret) {
1490                         if (ret == 400)
1491                                 nua_cancel(nh, TAG_END());
1492                         else
1493                                 nua_cancel(nh, TAG_END());
1494                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1495                         add_trace("reason", NULL, "offered codec does not match");
1496                         end_trace();
1497                         cause = 88;
1498                         location = LOCATION_PRIVATE_LOCAL;
1499                         goto release_with_cause;
1500                 }
1501
1502                 /* connect to remote RTP */
1503                 if (rtp_connect() < 0) {
1504                         nua_cancel(nh, TAG_END());
1505                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1506                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1507                         end_trace();
1508                         cause = 31;
1509                         location = LOCATION_PRIVATE_LOCAL;
1510                         goto release_with_cause;
1511                 }
1512
1513                 PDEBUG(DEBUG_SIP, "do connect\n");
1514                 nua_ack(nh, TAG_END());
1515                 new_state(PORT_STATE_CONNECT);
1516                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
1517                 message_put(message);
1518
1519                 return;
1520         }
1521
1522         cause = status2cause(status);
1523         location = LOCATION_BEYOND;
1524
1525 release_with_cause:
1526         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
1527
1528         while(p_epointlist) {
1529                 /* send setup message to endpoit */
1530                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1531                 message->param.disconnectinfo.cause = cause;
1532                 message->param.disconnectinfo.location = location;
1533                 message_put(message);
1534                 /* remove epoint */
1535                 free_epointlist(p_epointlist);
1536         }
1537
1538         new_state(PORT_STATE_RELEASE);
1539
1540         rtp_close();
1541
1542         trigger_work(&p_m_s_delete);
1543 }
1544
1545 static void sip_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1546 {
1547         struct sip_inst *inst = (struct sip_inst *) magic;
1548         class Port *port;
1549         class Psip *psip = NULL;
1550
1551         PDEBUG(DEBUG_SIP, "Event %d from stack received (handle=%p)\n", event, nh);
1552         if (!nh)
1553                 return;
1554
1555         /* create or find port instance */
1556         if (event == nua_i_invite)
1557         {
1558                 char name[64];
1559                 /* create call instance */
1560                 SPRINT(name, "%s-%d-in", inst->interface->name, 0);
1561                 if (!(psip = new Psip(PORT_TYPE_SIP_IN, (inst->interface->ifport) ? inst->interface->ifport->mISDNport : NULL, name, NULL, 0, 0, B_MODE_TRANSPARENT, inst->interface)))
1562                         FATAL("Cannot create Port instance.\n");
1563         } else {
1564                 port = port_first;
1565                 while(port) {
1566                         if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
1567                                 psip = (class Psip *)port;
1568                                 if (psip->p_m_s_handle == nh) {
1569                                         break;
1570                                 }
1571                         }
1572                         port = port->next;
1573                 }
1574         }
1575         if (!psip) {
1576                 PERROR("no SIP Port found for handel %p\n", nh);
1577                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1578                 nua_handle_destroy(nh);
1579                 return;
1580         }
1581
1582         switch (event) {
1583         case nua_r_set_params:
1584                 PDEBUG(DEBUG_SIP, "setparam response\n");
1585                 break;
1586         case nua_i_error:
1587                 PDEBUG(DEBUG_SIP, "error received\n");
1588                 break;
1589         case nua_i_state:
1590                 PDEBUG(DEBUG_SIP, "state change received\n");
1591                 break;
1592         case nua_i_register:
1593                 PDEBUG(DEBUG_SIP, "register received\n");
1594                 break;
1595         case nua_i_invite:
1596                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1597                 break;
1598         case nua_i_ack:
1599                 PDEBUG(DEBUG_SIP, "ack received\n");
1600                 break;
1601         case nua_i_active:
1602                 PDEBUG(DEBUG_SIP, "active received\n");
1603                 break;
1604         case nua_i_bye:
1605                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1606                 break;
1607         case nua_i_cancel:
1608                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1609                 break;
1610         case nua_r_bye:
1611                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1612                 break;
1613         case nua_r_cancel:
1614                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1615                 break;
1616         case nua_r_invite:
1617                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1618                 break;
1619         case nua_i_terminated:
1620                 PDEBUG(DEBUG_SIP, "terminated received\n");
1621                 break;
1622         default:
1623                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
1624         }
1625 }
1626
1627 /* received shutdown due to termination of RTP */
1628 void Psip::rtp_shutdown(void)
1629 {
1630         struct lcr_msg *message;
1631
1632         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
1633
1634         sip_trace_header(this, "RTP terminated", DIRECTION_IN);
1635         end_trace();
1636
1637         nua_handle_destroy(p_m_s_handle);
1638         p_m_s_handle = NULL;
1639
1640         while(p_epointlist) {
1641                 /* send setup message to endpoit */
1642                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1643                 message->param.disconnectinfo.cause = 16;
1644                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1645                 message_put(message);
1646                 /* remove epoint */
1647                 free_epointlist(p_epointlist);
1648         }
1649         new_state(PORT_STATE_RELEASE);
1650         trigger_work(&p_m_s_delete);
1651 }
1652
1653 int sip_init_inst(struct interface *interface)
1654 {
1655         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
1656
1657         interface->sip_inst = inst;
1658         inst->interface = interface;
1659
1660         /* init root object */
1661         inst->root = su_root_create(inst);
1662         if (!inst->root) {
1663                 PERROR("Failed to create SIP root\n");
1664                 sip_exit_inst(interface);
1665                 return -EINVAL;
1666         }
1667
1668         inst->nua = nua_create(inst->root, sip_callback, inst, TAG_NULL());
1669         if (!inst->nua) {
1670                 PERROR("Failed to create SIP stack object\n");
1671                 sip_exit_inst(interface);
1672                 return -EINVAL;
1673         }
1674         nua_set_params(inst->nua,
1675                 SIPTAG_ALLOW_STR("INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
1676                 NUTAG_APPL_METHOD("INVITE"),
1677                 NUTAG_APPL_METHOD("ACK"),
1678 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
1679                 NUTAG_APPL_METHOD("CANCEL"),
1680                 NUTAG_APPL_METHOD("OPTIONS"),
1681                 NUTAG_APPL_METHOD("NOTIFY"),
1682                 NUTAG_APPL_METHOD("INFO"),
1683                 NUTAG_AUTOACK(0),
1684                 NUTAG_AUTO100(0),
1685                 NUTAG_AUTOALERT(0),
1686                 NUTAG_AUTOANSWER(0),
1687                 TAG_NULL());
1688
1689         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
1690
1691         return 0;
1692 }
1693
1694 void sip_exit_inst(struct interface *interface)
1695 {
1696         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
1697
1698         if (!inst)
1699                 return;
1700         if (inst->root)
1701                 su_root_destroy(inst->root);
1702         if (inst->nua) {
1703                 nua_destroy(inst->nua);
1704         }
1705         FREE(inst, sizeof(*inst));
1706         interface->sip_inst = NULL;
1707
1708         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
1709 }
1710
1711 extern su_log_t su_log_default[];
1712 extern su_log_t nua_log[];
1713 //extern su_log_t soa_log[];
1714
1715 int sip_init(void)
1716 {
1717         int i;
1718
1719         /* init SOFIA lib */
1720         su_init();
1721         su_home_init(sip_home);
1722
1723         if (options.deb & DEBUG_SIP) {
1724                 su_log_set_level(su_log_default, 9);
1725                 su_log_set_level(nua_log, 9);
1726                 //su_log_set_level(soa_log, 9);
1727         }
1728
1729         for (i = 0; i < 256; i++)
1730                 flip[i] = ((i & 1) << 7) + ((i & 2) << 5) + ((i & 4) << 3) + ((i & 8) << 1) + ((i & 16) >> 1) + ((i & 32) >> 3) + ((i & 64) >> 5) + ((i & 128) >> 7);
1731
1732         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
1733
1734         return 0;
1735 }
1736
1737 void sip_exit(void)
1738 {
1739         su_home_deinit(sip_home);
1740         su_deinit();
1741
1742         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
1743 }
1744
1745 void sip_handle(void)
1746 {
1747         struct interface *interface = interface_first;
1748         struct sip_inst *inst;
1749
1750         while (interface) {
1751                 if (interface->sip_inst) {
1752                         inst = (struct sip_inst *) interface->sip_inst;
1753                         su_root_step(inst->root, 0);
1754                 }
1755                 interface = interface->next;
1756         }
1757 }
1758
1759 /* deletes when back in event loop */
1760 static int delete_event(struct lcr_work *work, void *instance, int index)
1761 {
1762         class Psip *psip = (class Psip *)instance;
1763
1764         delete psip;
1765
1766         return 0;
1767 }
1768