Adding simple bridge application to forward calls without PBX app.
[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 = interface_first;
1165
1166         while (interface) {
1167                 if (!strcmp(interface->name, inst->interface_name))
1168                         break;
1169                 interface = interface->next;
1170         }
1171         if (!interface) {
1172                 PERROR("Cannot find interface %s.\n", inst->interface_name);
1173                 return;
1174         }
1175
1176         if (sip->sip_from && sip->sip_from->a_url)
1177                 from = sip->sip_from->a_url->url_user;
1178         if (sip->sip_to && sip->sip_to->a_url)
1179                 to = sip->sip_to->a_url->url_user;
1180         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1181
1182         if (p_s_rtp_bridge)
1183                 payload_type = 3; // FIXME: use list and forward list to remote side
1184         else
1185                 payload_type = (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW;
1186         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_type);
1187         if (ret) {
1188                 if (ret == 400)
1189                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1190                 else
1191                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1192                 nua_handle_destroy(nh);
1193                 p_s_handle = NULL;
1194                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1195                 if (ret == 400)
1196                         add_trace("respond", "value", "415 Unsupported Media");
1197                 else
1198                         add_trace("respond", "value", "400 Bad Request");
1199                 add_trace("reason", NULL, "offered codec does not match");
1200                 end_trace();
1201                 new_state(PORT_STATE_RELEASE);
1202                 trigger_work(&p_s_delete);
1203                 return;
1204         }
1205
1206         /* open local RTP peer (if not bridging) */
1207         if (!p_s_rtp_bridge && rtp_open() < 0) {
1208                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1209                 nua_handle_destroy(nh);
1210                 p_s_handle = NULL;
1211                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1212                 add_trace("respond", "value", "500 Internal Server Error");
1213                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1214                 end_trace();
1215                 new_state(PORT_STATE_RELEASE);
1216                 trigger_work(&p_s_delete);
1217                 return;
1218         }
1219
1220         /* apply handle */
1221         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1222         add_trace("handle", "new", "0x%x", nh);
1223         p_s_handle = nh;
1224         end_trace();
1225
1226         sip_trace_header(this, "INVITE", DIRECTION_IN);
1227         add_trace("RTP", "port", "%d", p_s_rtp_port_remote);
1228         /* caller information */
1229         if (!from[0]) {
1230                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1231                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1232                 add_trace("calling", "present", "unavailable");
1233         } else {
1234                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1235                 add_trace("calling", "present", "allowed");
1236                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1237                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1238                 SCPY(p_callerinfo.id, from);
1239                 add_trace("calling", "number", "%s", from);
1240         }
1241         SCPY(p_callerinfo.interface, inst->interface_name);
1242         /* dialing information */
1243         if (to[0]) {
1244                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1245                 SCAT(p_dialinginfo.id, to);
1246                 add_trace("dialing", "number", "%s", to);
1247         }
1248         /* redir info */
1249         /* bearer capability */
1250         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1251         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1252         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1253         add_trace("bearer", "capa", "speech");
1254         add_trace("bearer", "mode", "circuit");
1255         /* if packet mode works some day, see dss1.cpp for conditions */
1256         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1257
1258         end_trace();
1259
1260         /* create endpoint */
1261         if (p_epointlist)
1262                 FATAL("Incoming call but already got an endpoint.\n");
1263         if (!(epoint = new Endpoint(p_serial, 0)))
1264                 FATAL("No memory for Endpoint instance\n");
1265         epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
1266         epointlist_new(epoint->ep_serial);
1267
1268         /* send trying (proceeding) */
1269         nua_respond(nh, SIP_100_TRYING, TAG_END());
1270         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1271         add_trace("respond", "value", "100 Trying");
1272         end_trace();
1273
1274         new_state(PORT_STATE_IN_PROCEEDING);
1275
1276         /* send setup message to endpoit */
1277         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1278         message->param.setup.port_type = p_type;
1279 //      message->param.setup.dtmf = 0;
1280         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1281         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1282         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1283 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1284 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1285 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1286         if (p_s_rtp_bridge) {
1287                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
1288                 message->param.setup.rtpinfo.payload_type = payload_type;
1289                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
1290                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
1291         }
1292         message_put(message);
1293 }
1294
1295 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[])
1296 {
1297         struct lcr_msg *message;
1298         int cause = 0;
1299
1300         PDEBUG(DEBUG_SIP, "bye received\n");
1301
1302         sip_trace_header(this, "BYE", DIRECTION_IN);
1303         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1304                 cause = atoi(sip->sip_reason->re_cause);
1305                 add_trace("cause", "value", "%d", cause);
1306         }
1307         end_trace();
1308
1309 // let stack do bye automaticall, since it will not accept our response for some reason
1310 //      nua_respond(nh, SIP_200_OK, TAG_END());
1311         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1312         add_trace("respond", "value", "200 OK");
1313         end_trace();
1314 //      nua_handle_destroy(nh);
1315         p_s_handle = NULL;
1316
1317         rtp_close();
1318
1319         while(p_epointlist) {
1320                 /* send setup message to endpoit */
1321                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1322                 message->param.disconnectinfo.cause = cause ? : 16;
1323                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1324                 message_put(message);
1325                 /* remove epoint */
1326                 free_epointlist(p_epointlist);
1327         }
1328         new_state(PORT_STATE_RELEASE);
1329         trigger_work(&p_s_delete);
1330 }
1331
1332 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[])
1333 {
1334         struct lcr_msg *message;
1335
1336         PDEBUG(DEBUG_SIP, "cancel received\n");
1337
1338         sip_trace_header(this, "CANCEL", DIRECTION_IN);
1339         end_trace();
1340
1341         nua_handle_destroy(nh);
1342         p_s_handle = NULL;
1343
1344         rtp_close();
1345
1346         while(p_epointlist) {
1347                 /* send setup message to endpoit */
1348                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1349                 message->param.disconnectinfo.cause = 16;
1350                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1351                 message_put(message);
1352                 /* remove epoint */
1353                 free_epointlist(p_epointlist);
1354         }
1355         new_state(PORT_STATE_RELEASE);
1356         trigger_work(&p_s_delete);
1357 }
1358
1359 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[])
1360 {
1361         PDEBUG(DEBUG_SIP, "bye response received\n");
1362
1363         nua_handle_destroy(nh);
1364         p_s_handle = NULL;
1365
1366         rtp_close();
1367
1368         trigger_work(&p_s_delete);
1369 }
1370
1371 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[])
1372 {
1373         PDEBUG(DEBUG_SIP, "cancel response received\n");
1374
1375         nua_handle_destroy(nh);
1376         p_s_handle = NULL;
1377
1378         rtp_close();
1379
1380         trigger_work(&p_s_delete);
1381 }
1382
1383 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[])
1384 {
1385         struct lcr_msg *message;
1386         int cause = 0, location = 0;
1387
1388         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
1389
1390         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1391         add_trace("respond", "value", "%d", status);
1392         end_trace();
1393
1394         /* connect audio */
1395         if (status == 183 || (status >= 200 && status <= 299)) {
1396                 int ret;
1397                 uint8_t payload_type;
1398
1399                 if (p_s_rtp_bridge)
1400                         payload_type = p_s_rtp_payload_type;
1401                 else
1402                         payload_type = (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW;
1403                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_type);
1404                 if (ret) {
1405                         if (ret == 400)
1406                                 nua_cancel(nh, TAG_END());
1407                         else
1408                                 nua_cancel(nh, TAG_END());
1409                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1410                         add_trace("reason", NULL, "offered codec does not match");
1411                         end_trace();
1412                         cause = 88;
1413                         location = LOCATION_PRIVATE_LOCAL;
1414                         goto release_with_cause;
1415                 }
1416
1417                 /* connect to remote RTP (if not bridging) */
1418                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
1419                         nua_cancel(nh, TAG_END());
1420                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1421                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1422                         end_trace();
1423                         cause = 31;
1424                         location = LOCATION_PRIVATE_LOCAL;
1425                         goto release_with_cause;
1426                 }
1427         }
1428
1429         /* process 1xx */
1430         switch (status) {
1431         case 100:
1432                 PDEBUG(DEBUG_SIP, "do proceeding\n");
1433                 new_state(PORT_STATE_OUT_PROCEEDING);
1434                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1435                 message_put(message);
1436                 return;
1437         case 180:
1438                 PDEBUG(DEBUG_SIP, "do alerting\n");
1439                 new_state(PORT_STATE_OUT_ALERTING);
1440                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
1441                 message_put(message);
1442                 return;
1443         case 183:
1444                 PDEBUG(DEBUG_SIP, "do progress\n");
1445                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
1446                 message->param.progressinfo.progress = 8;
1447                 message->param.progressinfo.location = 10;
1448                 if (p_s_rtp_bridge) {
1449                         message->param.progressinfo.rtpinfo.payload_type = p_s_rtp_payload_type;
1450                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1451                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
1452                 }
1453                 message_put(message);
1454                 return;
1455         default:
1456                 if (status < 100 || status > 199)
1457                         break;
1458                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
1459
1460                 return;
1461         }
1462
1463         /* process 2xx */
1464         if (status >= 200 && status <= 299) {
1465                 PDEBUG(DEBUG_SIP, "do connect\n");
1466                 nua_ack(nh, TAG_END());
1467                 new_state(PORT_STATE_CONNECT);
1468                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
1469                 if (p_s_rtp_bridge) {
1470                         message->param.connectinfo.rtpinfo.payload_type = p_s_rtp_payload_type;
1471                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1472                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
1473                 }
1474                 message_put(message);
1475                 return;
1476         }
1477         cause = status2cause(status);
1478         location = LOCATION_BEYOND;
1479
1480 release_with_cause:
1481         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
1482
1483         while(p_epointlist) {
1484                 /* send setup message to endpoit */
1485                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1486                 message->param.disconnectinfo.cause = cause;
1487                 message->param.disconnectinfo.location = location;
1488                 message_put(message);
1489                 /* remove epoint */
1490                 free_epointlist(p_epointlist);
1491         }
1492
1493         new_state(PORT_STATE_RELEASE);
1494
1495         rtp_close();
1496
1497         trigger_work(&p_s_delete);
1498 }
1499
1500 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[])
1501 {
1502         struct sip_inst *inst = (struct sip_inst *) magic;
1503         class Port *port;
1504         class Psip *psip = NULL;
1505
1506         PDEBUG(DEBUG_SIP, "Event %d from stack received (handle=%p)\n", event, nh);
1507         if (!nh)
1508                 return;
1509
1510         /* create or find port instance */
1511         if (event == nua_i_invite)
1512         {
1513                 char name[64];
1514                 struct interface *interface = interface_first;
1515
1516                 /* create call instance */
1517                 SPRINT(name, "%s-%d-in", inst->interface_name, 0);
1518                 while (interface) {
1519                         if (!strcmp(interface->name, inst->interface_name))
1520                                 break;
1521                         interface = interface->next;
1522                 }
1523                 if (!interface) {
1524                         PERROR("Cannot find interface %s.\n", inst->interface_name);
1525                         return;
1526                 }
1527                 if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
1528                         FATAL("Cannot create Port instance.\n");
1529         } else {
1530                 port = port_first;
1531                 while(port) {
1532                         if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
1533                                 psip = (class Psip *)port;
1534                                 if (psip->p_s_handle == nh) {
1535                                         break;
1536                                 }
1537                         }
1538                         port = port->next;
1539                 }
1540         }
1541         if (!psip) {
1542                 PERROR("no SIP Port found for handel %p\n", nh);
1543                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1544                 nua_handle_destroy(nh);
1545                 return;
1546         }
1547
1548         switch (event) {
1549         case nua_r_set_params:
1550                 PDEBUG(DEBUG_SIP, "setparam response\n");
1551                 break;
1552         case nua_i_error:
1553                 PDEBUG(DEBUG_SIP, "error received\n");
1554                 break;
1555         case nua_i_state:
1556                 PDEBUG(DEBUG_SIP, "state change received\n");
1557                 break;
1558         case nua_i_register:
1559                 PDEBUG(DEBUG_SIP, "register received\n");
1560                 break;
1561         case nua_i_invite:
1562                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1563                 break;
1564         case nua_i_ack:
1565                 PDEBUG(DEBUG_SIP, "ack received\n");
1566                 break;
1567         case nua_i_active:
1568                 PDEBUG(DEBUG_SIP, "active received\n");
1569                 break;
1570         case nua_i_bye:
1571                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1572                 break;
1573         case nua_i_cancel:
1574                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1575                 break;
1576         case nua_r_bye:
1577                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1578                 break;
1579         case nua_r_cancel:
1580                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1581                 break;
1582         case nua_r_invite:
1583                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1584                 break;
1585         case nua_i_terminated:
1586                 PDEBUG(DEBUG_SIP, "terminated received\n");
1587                 break;
1588         default:
1589                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
1590         }
1591 }
1592
1593 /* received shutdown due to termination of RTP */
1594 void Psip::rtp_shutdown(void)
1595 {
1596         struct lcr_msg *message;
1597
1598         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
1599
1600         sip_trace_header(this, "RTP terminated", DIRECTION_IN);
1601         end_trace();
1602
1603         nua_handle_destroy(p_s_handle);
1604         p_s_handle = NULL;
1605
1606         while(p_epointlist) {
1607                 /* send setup message to endpoit */
1608                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1609                 message->param.disconnectinfo.cause = 16;
1610                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1611                 message_put(message);
1612                 /* remove epoint */
1613                 free_epointlist(p_epointlist);
1614         }
1615         new_state(PORT_STATE_RELEASE);
1616         trigger_work(&p_s_delete);
1617 }
1618
1619 int sip_init_inst(struct interface *interface)
1620 {
1621         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
1622
1623         interface->sip_inst = inst;
1624         SCPY(inst->interface_name, interface->name);
1625         SCPY(inst->local_ip, interface->sip_local_ip);
1626         SCPY(inst->remote_ip, interface->sip_remote_ip);
1627
1628         /* init root object */
1629         inst->root = su_root_create(inst);
1630         if (!inst->root) {
1631                 PERROR("Failed to create SIP root\n");
1632                 sip_exit_inst(interface);
1633                 return -EINVAL;
1634         }
1635
1636         inst->nua = nua_create(inst->root, sip_callback, inst, TAG_NULL());
1637         if (!inst->nua) {
1638                 PERROR("Failed to create SIP stack object\n");
1639                 sip_exit_inst(interface);
1640                 return -EINVAL;
1641         }
1642         nua_set_params(inst->nua,
1643                 SIPTAG_ALLOW_STR("INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
1644                 NUTAG_APPL_METHOD("INVITE"),
1645                 NUTAG_APPL_METHOD("ACK"),
1646 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
1647                 NUTAG_APPL_METHOD("CANCEL"),
1648                 NUTAG_APPL_METHOD("OPTIONS"),
1649                 NUTAG_APPL_METHOD("NOTIFY"),
1650                 NUTAG_APPL_METHOD("INFO"),
1651                 NUTAG_AUTOACK(0),
1652                 NUTAG_AUTO100(0),
1653                 NUTAG_AUTOALERT(0),
1654                 NUTAG_AUTOANSWER(0),
1655                 TAG_NULL());
1656
1657         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
1658
1659         return 0;
1660 }
1661
1662 void sip_exit_inst(struct interface *interface)
1663 {
1664         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
1665
1666         if (!inst)
1667                 return;
1668         if (inst->root)
1669                 su_root_destroy(inst->root);
1670         if (inst->nua) {
1671                 nua_destroy(inst->nua);
1672         }
1673         FREE(inst, sizeof(*inst));
1674         interface->sip_inst = NULL;
1675
1676         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
1677 }
1678
1679 extern su_log_t su_log_default[];
1680 extern su_log_t nua_log[];
1681 //extern su_log_t soa_log[];
1682
1683 int sip_init(void)
1684 {
1685         int i;
1686
1687         /* init SOFIA lib */
1688         su_init();
1689         su_home_init(sip_home);
1690
1691         if (options.deb & DEBUG_SIP) {
1692                 su_log_set_level(su_log_default, 9);
1693                 su_log_set_level(nua_log, 9);
1694                 //su_log_set_level(soa_log, 9);
1695         }
1696
1697         for (i = 0; i < 256; i++)
1698                 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);
1699
1700         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
1701
1702         return 0;
1703 }
1704
1705 void sip_exit(void)
1706 {
1707         su_home_deinit(sip_home);
1708         su_deinit();
1709
1710         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
1711 }
1712
1713 void sip_handle(void)
1714 {
1715         struct interface *interface = interface_first;
1716         struct sip_inst *inst;
1717
1718         while (interface) {
1719                 if (interface->sip_inst) {
1720                         inst = (struct sip_inst *) interface->sip_inst;
1721                         su_root_step(inst->root, 0);
1722                 }
1723                 interface = interface->next;
1724         }
1725 }
1726
1727 /* deletes when back in event loop */
1728 static int delete_event(struct lcr_work *work, void *instance, int index)
1729 {
1730         class Psip *psip = (class Psip *)instance;
1731
1732         delete psip;
1733
1734         return 0;
1735 }
1736