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