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