Forward DTMF as message directly from GSM BS to SIP.
[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_payload_type = (options.law=='a') ? RTP_PT_ALAW : RTP_PT_ULAW;
872
873                 /* open local RTP peer (if not bridging) */
874                 if (rtp_open() < 0) {
875                         struct lcr_msg *message;
876
877                         PERROR("Failed to open RTP sockets\n");
878                         /* send release message to endpoit */
879                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
880                         message->param.disconnectinfo.cause = 41;
881                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
882                         message_put(message);
883                         new_state(PORT_STATE_RELEASE);
884                         trigger_work(&p_s_delete);
885                         return 0;
886                 }
887         }
888         SPRINT(from, "sip:%s@%s", param->setup.callerinfo.id, local);
889         SPRINT(to, "sip:%s@%s", param->setup.dialinginfo.id, remote);
890
891         sip_trace_header(this, "INVITE", DIRECTION_OUT);
892         add_trace("from", "uri", "%s", from);
893         add_trace("to", "uri", "%s", to);
894         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
895         end_trace();
896
897         p_s_handle = nua_handle(inst->nua, NULL, TAG_END());
898         if (!p_s_handle) {
899                 struct lcr_msg *message;
900
901                 PERROR("Failed to create handle\n");
902                 /* send release message to endpoit */
903                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
904                 message->param.disconnectinfo.cause = 41;
905                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
906                 message_put(message);
907                 new_state(PORT_STATE_RELEASE);
908                 trigger_work(&p_s_delete);
909                 return 0;
910         }
911         /* apply handle */
912         sip_trace_header(this, "NEW handle", DIRECTION_IN);
913         add_trace("handle", "new", "0x%x", p_s_handle);
914         end_trace();
915
916         if (!p_s_rtp_ip_local) {
917                 PDEBUG(DEBUG_SIP, "RTP local IP not known, so we use our local SIP ip %s\n", local);
918                 inet_pton(AF_INET, local, &p_s_rtp_ip_local);
919                 p_s_rtp_ip_local = ntohl(p_s_rtp_ip_local);
920         }
921         ia.s_addr = htonl(p_s_rtp_ip_local);
922         SPRINT(sdp_str,
923                 "v=0\n"
924                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
925                 "s=SIP Call\n"
926                 "c=IN IP4 %s\n"
927                 "t=0 0\n"
928                 "m=audio %d RTP/AVP %d\n"
929                 "a=rtpmap:%d %s/8000\n"
930                 , 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));
931         PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
932
933 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
934
935         nua_invite(p_s_handle,
936                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
937                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
938                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
939                 NUTAG_MEDIA_ENABLE(0),
940                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
941                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
942         new_state(PORT_STATE_OUT_SETUP);
943
944         /* attach only if not already */
945         epointlist = p_epointlist;
946         while(epointlist) {
947                 if (epointlist->epoint_id == epoint_id)
948                         break;
949                 epointlist = epointlist->next;
950         }
951         if (!epointlist)
952                 epointlist_new(epoint_id);
953
954         return 0;
955 }
956         
957 int Psip::message_notify(unsigned int epoint_id, int message_id, union parameter *param)
958 {
959 //      char sdp_str[256];
960 //      struct in_addr ia;
961
962         switch (param->notifyinfo.notify) {
963         case INFO_NOTIFY_REMOTE_HOLD:
964 #if 0
965                 SPRINT(sdp_str,
966                         "v=0\n"
967                         "o=LCR-Sofia-SIP 0 0 IN IP4 0.0.0.0\n"
968                         "s=SIP Call\n"
969                         "c=IN IP4 0.0.0.0\n"
970                         "t=0 0\n"
971                         );
972                 PDEBUG(DEBUG_SIP, "Using SDP for hold: %s\n", sdp_str);
973                 nua_info(p_s_handle,
974 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
975 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
976 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
977                         NUTAG_MEDIA_ENABLE(0),
978                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
979                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
980 #endif
981                 break;
982         case INFO_NOTIFY_REMOTE_RETRIEVAL:
983 #if 0
984                 ia.s_addr = htonl(p_s_rtp_ip_local);
985                 SPRINT(sdp_str,
986                         "v=0\n"
987                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
988                         "s=SIP Call\n"
989                         "c=IN IP4 %s\n"
990                         "t=0 0\n"
991                         "m=audio %d RTP/AVP %d\n"
992                         "a=rtpmap:%d %s/8000\n"
993                         , 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));
994                 PDEBUG(DEBUG_SIP, "Using SDP for rertieve: %s\n", sdp_str);
995                 nua_info(p_s_handle,
996 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
997 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
998 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
999                         NUTAG_MEDIA_ENABLE(0),
1000                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1001                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1002 #endif
1003                 break;
1004         }
1005
1006         return 0;
1007 }
1008
1009 int Psip::message_dtmf(unsigned int epoint_id, int message_id, union parameter *param)
1010 {
1011         char dtmf_str[64];
1012         
1013         /* prepare DTMF info payload */
1014         SPRINT(dtmf_str,
1015                 "Signal=%c\n"
1016                 "Duration=160\n"
1017                 , param->dtmf);
1018
1019         /* start invite to handle DTMF */
1020         nua_info(p_s_handle,
1021                 NUTAG_MEDIA_ENABLE(0),
1022                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1023                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1024         
1025         return 0;
1026 }
1027
1028 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1029 {
1030         if (Port::message_epoint(epoint_id, message_id, param))
1031                 return 1;
1032
1033         switch(message_id) {
1034                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1035                 if (p_state != PORT_STATE_IN_SETUP
1036                  && p_state != PORT_STATE_IN_PROCEEDING)
1037                         return 0;
1038                 nua_respond(p_s_handle, SIP_180_RINGING, TAG_END());
1039                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1040                 add_trace("respond", "value", "180 Ringing");
1041                 end_trace();
1042                 new_state(PORT_STATE_IN_ALERTING);
1043                 return 1;
1044
1045                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1046                 if (p_state != PORT_STATE_IN_SETUP
1047                  && p_state != PORT_STATE_IN_PROCEEDING
1048                  && p_state != PORT_STATE_IN_ALERTING)
1049                         return 0;
1050                 message_connect(epoint_id, message_id, param);
1051                 return 1;
1052
1053                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1054                 case MESSAGE_RELEASE: /* call has been released */
1055                 message_release(epoint_id, message_id, param);
1056                 return 1;
1057
1058                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1059                 message_setup(epoint_id, message_id, param);
1060                 return 1;
1061
1062                 case MESSAGE_DTMF: /* DTMF info to be transmitted via INFO transaction */
1063                 if (p_state == PORT_STATE_CONNECT)
1064                         message_dtmf(epoint_id, message_id, param);
1065                 case MESSAGE_NOTIFY: /* notification about remote hold/retrieve */
1066                 if (p_state == PORT_STATE_CONNECT)
1067                         message_notify(epoint_id, message_id, param);
1068                 return(1);
1069
1070                 default:
1071                 PDEBUG(DEBUG_SIP, "PORT(%s) SP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1072         }
1073
1074         return 0;
1075 }
1076
1077 int Psip::parse_sdp(sip_t const *sip, unsigned int *ip, unsigned short *port, uint8_t payload_type)
1078 {
1079         int codec_supported = 0;
1080
1081         if (!sip->sip_payload) {
1082                 PDEBUG(DEBUG_SIP, "no payload given\n");
1083                 return 0;
1084         }
1085
1086         sdp_parser_t *parser;
1087         sdp_session_t *sdp;
1088         sdp_media_t *m;
1089         sdp_attribute_t *attr;
1090         sdp_rtpmap_t *map;
1091         sdp_connection_t *conn;
1092
1093         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1094
1095         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1096         if (!parser) {
1097                 return 400;
1098         }
1099         if (!(sdp = sdp_session(parser))) {
1100                 sdp_parser_free(parser);
1101                 return 400;
1102         }
1103         for (m = sdp->sdp_media; m; m = m->m_next) {
1104                 if (m->m_proto != sdp_proto_rtp)
1105                         continue;
1106                 if (m->m_type != sdp_media_audio)
1107                         continue;
1108                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1109                 *port = m->m_port;
1110                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1111                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1112                 }
1113                 if (m->m_connections) {
1114                         conn = m->m_connections;
1115                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1116                         inet_pton(AF_INET, conn->c_address, ip);
1117                         *ip = ntohl(p_s_rtp_ip_remote);
1118                 } else {
1119                         char *p = sip->sip_payload->pl_data;
1120                         char addr[16];
1121
1122                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1123                         p = strstr(p, "c=IN IP4 ");
1124                         if (!p) {
1125                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1126                                 sdp_parser_free(parser);
1127                                 return 400;
1128                         }
1129                         SCPY(addr, p + 9);
1130                         if ((p = strchr(addr, '\n'))) *p = '\0';
1131                         if ((p = strchr(addr, '\r'))) *p = '\0';
1132                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1133                         inet_pton(AF_INET, addr, ip);
1134                         *ip = ntohl(p_s_rtp_ip_remote);
1135                 }
1136                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1137                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d' pt='%d'\n", map->rm_encoding, map->rm_rate, map->rm_pt);
1138                         if (map->rm_pt == payload_type) {
1139                                 PDEBUG(DEBUG_SIP, "supported codec found\n");
1140                                 codec_supported = 1;
1141                                 goto done_codec;
1142                         }
1143                 }
1144         }
1145         done_codec:
1146
1147         sdp_parser_free(parser);
1148
1149         if (!codec_supported)
1150                 return 415;
1151
1152         return 0;
1153 }
1154
1155 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[])
1156 {
1157         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1158         const char *from = "", *to = "";
1159         int ret;
1160         class Endpoint *epoint;
1161         struct lcr_msg *message;
1162         uint8_t payload_type;
1163
1164         if (sip->sip_from && sip->sip_from->a_url)
1165                 from = sip->sip_from->a_url->url_user;
1166         if (sip->sip_to && sip->sip_to->a_url)
1167                 to = sip->sip_to->a_url->url_user;
1168         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1169
1170         if (p_s_rtp_bridge)
1171                 payload_type = 3; // FIXME: use list and forward list to remote side
1172         else
1173                 payload_type = (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW;
1174         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_type);
1175         if (ret) {
1176                 if (ret == 400)
1177                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1178                 else
1179                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1180                 nua_handle_destroy(nh);
1181                 p_s_handle = NULL;
1182                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1183                 if (ret == 400)
1184                         add_trace("respond", "value", "415 Unsupported Media");
1185                 else
1186                         add_trace("respond", "value", "400 Bad Request");
1187                 add_trace("reason", NULL, "offered codec does not match");
1188                 end_trace();
1189                 new_state(PORT_STATE_RELEASE);
1190                 trigger_work(&p_s_delete);
1191                 return;
1192         }
1193
1194         /* open local RTP peer (if not bridging) */
1195         if (!p_s_rtp_bridge && rtp_open() < 0) {
1196                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1197                 nua_handle_destroy(nh);
1198                 p_s_handle = NULL;
1199                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1200                 add_trace("respond", "value", "500 Internal Server Error");
1201                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1202                 end_trace();
1203                 new_state(PORT_STATE_RELEASE);
1204                 trigger_work(&p_s_delete);
1205                 return;
1206         }
1207
1208         /* apply handle */
1209         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1210         add_trace("handle", "new", "0x%x", nh);
1211         p_s_handle = nh;
1212         end_trace();
1213
1214         sip_trace_header(this, "INVITE", DIRECTION_IN);
1215         add_trace("RTP", "port", "%d", p_s_rtp_port_remote);
1216         /* caller information */
1217         if (!from[0]) {
1218                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1219                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1220                 add_trace("calling", "present", "unavailable");
1221         } else {
1222                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1223                 add_trace("calling", "present", "allowed");
1224                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1225                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1226                 SCPY(p_callerinfo.id, from);
1227                 add_trace("calling", "number", "%s", from);
1228         }
1229         SCPY(p_callerinfo.interface, inst->interface_name);
1230         /* dialing information */
1231         if (to[0]) {
1232                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1233                 SCAT(p_dialinginfo.id, to);
1234                 add_trace("dialing", "number", "%s", to);
1235         }
1236         /* redir info */
1237         /* bearer capability */
1238         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1239         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1240         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1241         add_trace("bearer", "capa", "speech");
1242         add_trace("bearer", "mode", "circuit");
1243         /* if packet mode works some day, see dss1.cpp for conditions */
1244         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1245
1246         end_trace();
1247
1248         /* create endpoint */
1249         if (p_epointlist)
1250                 FATAL("Incoming call but already got an endpoint.\n");
1251         if (!(epoint = new Endpoint(p_serial, 0)))
1252                 FATAL("No memory for Endpoint instance\n");
1253         if (!(epoint->ep_app = new DEFAULT_ENDPOINT_APP(epoint, 0))) //incoming
1254                 FATAL("No memory for Endpoint Application instance\n");
1255         epointlist_new(epoint->ep_serial);
1256
1257         /* send trying (proceeding) */
1258         nua_respond(nh, SIP_100_TRYING, TAG_END());
1259         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1260         add_trace("respond", "value", "100 Trying");
1261         end_trace();
1262
1263         new_state(PORT_STATE_IN_PROCEEDING);
1264
1265         /* send setup message to endpoit */
1266         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1267         message->param.setup.port_type = p_type;
1268 //      message->param.setup.dtmf = 0;
1269         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1270         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1271         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1272 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1273 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1274 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1275         if (p_s_rtp_bridge) {
1276                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
1277                 message->param.setup.rtpinfo.payload_type = payload_type;
1278                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
1279                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
1280         }
1281         message_put(message);
1282 }
1283
1284 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[])
1285 {
1286         struct lcr_msg *message;
1287         int cause = 0;
1288
1289         PDEBUG(DEBUG_SIP, "bye received\n");
1290
1291         sip_trace_header(this, "BYE", DIRECTION_IN);
1292         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1293                 cause = atoi(sip->sip_reason->re_cause);
1294                 add_trace("cause", "value", "%d", cause);
1295         }
1296         end_trace();
1297
1298 // let stack do bye automaticall, since it will not accept our response for some reason
1299 //      nua_respond(nh, SIP_200_OK, TAG_END());
1300         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1301         add_trace("respond", "value", "200 OK");
1302         end_trace();
1303 //      nua_handle_destroy(nh);
1304         p_s_handle = NULL;
1305
1306         rtp_close();
1307
1308         while(p_epointlist) {
1309                 /* send setup message to endpoit */
1310                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1311                 message->param.disconnectinfo.cause = cause ? : 16;
1312                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1313                 message_put(message);
1314                 /* remove epoint */
1315                 free_epointlist(p_epointlist);
1316         }
1317         new_state(PORT_STATE_RELEASE);
1318         trigger_work(&p_s_delete);
1319 }
1320
1321 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[])
1322 {
1323         struct lcr_msg *message;
1324
1325         PDEBUG(DEBUG_SIP, "cancel received\n");
1326
1327         sip_trace_header(this, "CANCEL", DIRECTION_IN);
1328         end_trace();
1329
1330         nua_handle_destroy(nh);
1331         p_s_handle = NULL;
1332
1333         rtp_close();
1334
1335         while(p_epointlist) {
1336                 /* send setup message to endpoit */
1337                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1338                 message->param.disconnectinfo.cause = 16;
1339                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1340                 message_put(message);
1341                 /* remove epoint */
1342                 free_epointlist(p_epointlist);
1343         }
1344         new_state(PORT_STATE_RELEASE);
1345         trigger_work(&p_s_delete);
1346 }
1347
1348 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[])
1349 {
1350         PDEBUG(DEBUG_SIP, "bye response received\n");
1351
1352         nua_handle_destroy(nh);
1353         p_s_handle = NULL;
1354
1355         rtp_close();
1356
1357         trigger_work(&p_s_delete);
1358 }
1359
1360 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[])
1361 {
1362         PDEBUG(DEBUG_SIP, "cancel response received\n");
1363
1364         nua_handle_destroy(nh);
1365         p_s_handle = NULL;
1366
1367         rtp_close();
1368
1369         trigger_work(&p_s_delete);
1370 }
1371
1372 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[])
1373 {
1374         struct lcr_msg *message;
1375         int cause = 0, location = 0;
1376
1377         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
1378
1379         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1380         add_trace("respond", "value", "%d", status);
1381         end_trace();
1382
1383         /* connect audio */
1384         if (status == 183 || (status >= 200 && status <= 299)) {
1385                 int ret;
1386                 uint8_t payload_type;
1387
1388                 if (p_s_rtp_bridge)
1389                         payload_type = p_s_rtp_payload_type;
1390                 else
1391                         payload_type = (options.law=='a')?RTP_PT_ALAW:RTP_PT_ULAW;
1392                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_type);
1393                 if (ret) {
1394                         if (ret == 400)
1395                                 nua_cancel(nh, TAG_END());
1396                         else
1397                                 nua_cancel(nh, TAG_END());
1398                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1399                         add_trace("reason", NULL, "offered codec does not match");
1400                         end_trace();
1401                         cause = 88;
1402                         location = LOCATION_PRIVATE_LOCAL;
1403                         goto release_with_cause;
1404                 }
1405
1406                 /* connect to remote RTP (if not bridging) */
1407                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
1408                         nua_cancel(nh, TAG_END());
1409                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1410                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1411                         end_trace();
1412                         cause = 31;
1413                         location = LOCATION_PRIVATE_LOCAL;
1414                         goto release_with_cause;
1415                 }
1416         }
1417
1418         /* process 1xx */
1419         switch (status) {
1420         case 100:
1421                 PDEBUG(DEBUG_SIP, "do proceeding\n");
1422                 new_state(PORT_STATE_OUT_PROCEEDING);
1423                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1424                 message_put(message);
1425                 return;
1426         case 180:
1427                 PDEBUG(DEBUG_SIP, "do alerting\n");
1428                 new_state(PORT_STATE_OUT_ALERTING);
1429                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
1430                 message_put(message);
1431                 return;
1432         case 183:
1433                 PDEBUG(DEBUG_SIP, "do progress\n");
1434                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
1435                 message->param.progressinfo.progress = 8;
1436                 message->param.progressinfo.location = 10;
1437                 if (p_s_rtp_bridge) {
1438                         message->param.progressinfo.rtpinfo.payload_type = p_s_rtp_payload_type;
1439                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1440                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
1441                 }
1442                 message_put(message);
1443                 return;
1444         default:
1445                 if (status < 100 || status > 199)
1446                         break;
1447                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
1448
1449                 return;
1450         }
1451
1452         /* process 2xx */
1453         if (status >= 200 && status <= 299) {
1454                 PDEBUG(DEBUG_SIP, "do connect\n");
1455                 nua_ack(nh, TAG_END());
1456                 new_state(PORT_STATE_CONNECT);
1457                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
1458                 if (p_s_rtp_bridge) {
1459                         message->param.connectinfo.rtpinfo.payload_type = p_s_rtp_payload_type;
1460                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1461                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
1462                 }
1463                 message_put(message);
1464                 return;
1465         }
1466         cause = status2cause(status);
1467         location = LOCATION_BEYOND;
1468
1469 release_with_cause:
1470         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
1471
1472         while(p_epointlist) {
1473                 /* send setup message to endpoit */
1474                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1475                 message->param.disconnectinfo.cause = cause;
1476                 message->param.disconnectinfo.location = location;
1477                 message_put(message);
1478                 /* remove epoint */
1479                 free_epointlist(p_epointlist);
1480         }
1481
1482         new_state(PORT_STATE_RELEASE);
1483
1484         rtp_close();
1485
1486         trigger_work(&p_s_delete);
1487 }
1488
1489 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[])
1490 {
1491         struct sip_inst *inst = (struct sip_inst *) magic;
1492         class Port *port;
1493         class Psip *psip = NULL;
1494
1495         PDEBUG(DEBUG_SIP, "Event %d from stack received (handle=%p)\n", event, nh);
1496         if (!nh)
1497                 return;
1498
1499         /* create or find port instance */
1500         if (event == nua_i_invite)
1501         {
1502                 char name[64];
1503                 struct interface *interface = interface_first;
1504
1505                 /* create call instance */
1506                 SPRINT(name, "%s-%d-in", inst->interface_name, 0);
1507                 while (interface) {
1508                         if (!strcmp(interface->name, inst->interface_name))
1509                                 break;
1510                         interface = interface->next;
1511                 }
1512                 if (!interface) {
1513                         PERROR("Cannot find interface %s.\n", inst->interface_name);
1514                         return;
1515                 }
1516                 if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
1517                         FATAL("Cannot create Port instance.\n");
1518         } else {
1519                 port = port_first;
1520                 while(port) {
1521                         if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
1522                                 psip = (class Psip *)port;
1523                                 if (psip->p_s_handle == nh) {
1524                                         break;
1525                                 }
1526                         }
1527                         port = port->next;
1528                 }
1529         }
1530         if (!psip) {
1531                 PERROR("no SIP Port found for handel %p\n", nh);
1532                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1533                 nua_handle_destroy(nh);
1534                 return;
1535         }
1536
1537         switch (event) {
1538         case nua_r_set_params:
1539                 PDEBUG(DEBUG_SIP, "setparam response\n");
1540                 break;
1541         case nua_i_error:
1542                 PDEBUG(DEBUG_SIP, "error received\n");
1543                 break;
1544         case nua_i_state:
1545                 PDEBUG(DEBUG_SIP, "state change received\n");
1546                 break;
1547         case nua_i_register:
1548                 PDEBUG(DEBUG_SIP, "register received\n");
1549                 break;
1550         case nua_i_invite:
1551                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1552                 break;
1553         case nua_i_ack:
1554                 PDEBUG(DEBUG_SIP, "ack received\n");
1555                 break;
1556         case nua_i_active:
1557                 PDEBUG(DEBUG_SIP, "active received\n");
1558                 break;
1559         case nua_i_bye:
1560                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1561                 break;
1562         case nua_i_cancel:
1563                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1564                 break;
1565         case nua_r_bye:
1566                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1567                 break;
1568         case nua_r_cancel:
1569                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1570                 break;
1571         case nua_r_invite:
1572                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1573                 break;
1574         case nua_i_terminated:
1575                 PDEBUG(DEBUG_SIP, "terminated received\n");
1576                 break;
1577         default:
1578                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
1579         }
1580 }
1581
1582 /* received shutdown due to termination of RTP */
1583 void Psip::rtp_shutdown(void)
1584 {
1585         struct lcr_msg *message;
1586
1587         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
1588
1589         sip_trace_header(this, "RTP terminated", DIRECTION_IN);
1590         end_trace();
1591
1592         nua_handle_destroy(p_s_handle);
1593         p_s_handle = NULL;
1594
1595         while(p_epointlist) {
1596                 /* send setup message to endpoit */
1597                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1598                 message->param.disconnectinfo.cause = 16;
1599                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1600                 message_put(message);
1601                 /* remove epoint */
1602                 free_epointlist(p_epointlist);
1603         }
1604         new_state(PORT_STATE_RELEASE);
1605         trigger_work(&p_s_delete);
1606 }
1607
1608 int sip_init_inst(struct interface *interface)
1609 {
1610         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
1611
1612         interface->sip_inst = inst;
1613         SCPY(inst->interface_name, interface->name);
1614         SCPY(inst->local_ip, interface->sip_local_ip);
1615         SCPY(inst->remote_ip, interface->sip_remote_ip);
1616
1617         /* init root object */
1618         inst->root = su_root_create(inst);
1619         if (!inst->root) {
1620                 PERROR("Failed to create SIP root\n");
1621                 sip_exit_inst(interface);
1622                 return -EINVAL;
1623         }
1624
1625         inst->nua = nua_create(inst->root, sip_callback, inst, TAG_NULL());
1626         if (!inst->nua) {
1627                 PERROR("Failed to create SIP stack object\n");
1628                 sip_exit_inst(interface);
1629                 return -EINVAL;
1630         }
1631         nua_set_params(inst->nua,
1632                 SIPTAG_ALLOW_STR("INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
1633                 NUTAG_APPL_METHOD("INVITE"),
1634                 NUTAG_APPL_METHOD("ACK"),
1635 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
1636                 NUTAG_APPL_METHOD("CANCEL"),
1637                 NUTAG_APPL_METHOD("OPTIONS"),
1638                 NUTAG_APPL_METHOD("NOTIFY"),
1639                 NUTAG_APPL_METHOD("INFO"),
1640                 NUTAG_AUTOACK(0),
1641                 NUTAG_AUTO100(0),
1642                 NUTAG_AUTOALERT(0),
1643                 NUTAG_AUTOANSWER(0),
1644                 TAG_NULL());
1645
1646         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
1647
1648         return 0;
1649 }
1650
1651 void sip_exit_inst(struct interface *interface)
1652 {
1653         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
1654
1655         if (!inst)
1656                 return;
1657         if (inst->root)
1658                 su_root_destroy(inst->root);
1659         if (inst->nua) {
1660                 nua_destroy(inst->nua);
1661         }
1662         FREE(inst, sizeof(*inst));
1663         interface->sip_inst = NULL;
1664
1665         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
1666 }
1667
1668 extern su_log_t su_log_default[];
1669 extern su_log_t nua_log[];
1670 //extern su_log_t soa_log[];
1671
1672 int sip_init(void)
1673 {
1674         int i;
1675
1676         /* init SOFIA lib */
1677         su_init();
1678         su_home_init(sip_home);
1679
1680         if (options.deb & DEBUG_SIP) {
1681                 su_log_set_level(su_log_default, 9);
1682                 su_log_set_level(nua_log, 9);
1683                 //su_log_set_level(soa_log, 9);
1684         }
1685
1686         for (i = 0; i < 256; i++)
1687                 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);
1688
1689         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
1690
1691         return 0;
1692 }
1693
1694 void sip_exit(void)
1695 {
1696         su_home_deinit(sip_home);
1697         su_deinit();
1698
1699         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
1700 }
1701
1702 void sip_handle(void)
1703 {
1704         struct interface *interface = interface_first;
1705         struct sip_inst *inst;
1706
1707         while (interface) {
1708                 if (interface->sip_inst) {
1709                         inst = (struct sip_inst *) interface->sip_inst;
1710                         su_root_step(inst->root, 0);
1711                 }
1712                 interface = interface->next;
1713         }
1714 }
1715
1716 /* deletes when back in event loop */
1717 static int delete_event(struct lcr_work *work, void *instance, int index)
1718 {
1719         class Psip *psip = (class Psip *)instance;
1720
1721         delete psip;
1722
1723         return 0;
1724 }
1725