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