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