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