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