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