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