Added support to chan_lcr for Asterisk version > 10
[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 }
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_peer;
876         char local_ip[16];
877         const char *remote = inst->remote_peer;
878         char sdp_str[512], pt_str[32];
879         struct in_addr ia;
880         struct epoint_list *epointlist;
881         sip_cseq_t *cseq = NULL;
882         struct lcr_msg *message;
883         int lcr_media = { (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW };
884         unsigned char lcr_payload = { (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW };
885         int *media_types;
886         unsigned char *payload_types;
887         int payloads = 0;
888         int i;
889
890         PDEBUG(DEBUG_SIP, "Doing Setup (inst %p)\n", inst);
891
892         memcpy(&p_dialinginfo, &param->setup.dialinginfo, sizeof(p_dialinginfo));
893         memcpy(&p_callerinfo, &param->setup.callerinfo, sizeof(p_callerinfo));
894         memcpy(&p_redirinfo, &param->setup.redirinfo, sizeof(p_redirinfo));
895
896         if (param->setup.rtpinfo.port) {
897                 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
898                 p_s_rtp_bridge = 1;
899                 media_types = param->setup.rtpinfo.media_types;
900                 payload_types = param->setup.rtpinfo.payload_types;
901                 payloads = param->setup.rtpinfo.payloads;
902                 p_s_rtp_ip_local = param->setup.rtpinfo.ip;
903                 p_s_rtp_port_local = param->setup.rtpinfo.port;
904                 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
905                 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
906         } else {
907                 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
908                 p_s_rtp_bridge = 0;
909                 media_types = &lcr_media;
910                 payload_types = &lcr_payload;
911                 payloads = 1;
912
913                 /* open local RTP peer (if not bridging) */
914                 if (rtp_open() < 0) {
915                         PERROR("Failed to open RTP sockets\n");
916                         /* send release message to endpoit */
917                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
918                         message->param.disconnectinfo.cause = 41;
919                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
920                         message_put(message);
921                         new_state(PORT_STATE_RELEASE);
922                         trigger_work(&p_s_delete);
923                         return 0;
924                 }
925         }
926
927         p_s_handle = nua_handle(inst->nua, NULL, TAG_END());
928         if (!p_s_handle) {
929                 PERROR("Failed to create handle\n");
930                 /* send release message to endpoit */
931                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
932                 message->param.disconnectinfo.cause = 41;
933                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
934                 message_put(message);
935                 new_state(PORT_STATE_RELEASE);
936                 trigger_work(&p_s_delete);
937                 return 0;
938         }
939         /* apply handle */
940         sip_trace_header(this, "NEW handle", DIRECTION_IN);
941         add_trace("handle", "new", "0x%x", p_s_handle);
942         end_trace();
943
944         if (!p_s_rtp_ip_local) {
945                 char *p;
946
947                 /* extract IP from local peer */
948                 SCPY(local_ip, local);
949                 p = strchr(local_ip, ':');
950                 if (p)
951                         *p = '\0';
952                 PDEBUG(DEBUG_SIP, "RTP local IP not known, so we use our local SIP ip %s\n", local_ip);
953                 inet_pton(AF_INET, local_ip, &p_s_rtp_ip_local);
954                 p_s_rtp_ip_local = ntohl(p_s_rtp_ip_local);
955         }
956         ia.s_addr = htonl(p_s_rtp_ip_local);
957         SPRINT(sdp_str,
958                 "v=0\n"
959                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
960                 "s=SIP Call\n"
961                 "c=IN IP4 %s\n"
962                 "t=0 0\n"
963                 "m=audio %d RTP/AVP"
964                 , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local);
965         for (i = 0; i < payloads; i++) {
966                 SPRINT(pt_str, " %d", payload_types[i]);
967                 SCAT(sdp_str, pt_str);
968         }
969         SCAT(sdp_str, "\n");
970         for (i = 0; i < payloads; i++) {
971                 SPRINT(pt_str, "a=rtpmap:%d %s/8000\n", payload_types[i], media_type2name(media_types[i]));
972                 SCAT(sdp_str, pt_str);
973         }
974         PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
975
976         SPRINT(from, "sip:%s@%s", param->setup.callerinfo.id, local);
977         SPRINT(to, "sip:%s@%s", param->setup.dialinginfo.id, remote);
978
979         sip_trace_header(this, "INVITE", DIRECTION_OUT);
980         add_trace("from", "uri", "%s", from);
981         add_trace("to", "uri", "%s", to);
982         add_trace("rtp", "ip", "%s", inet_ntoa(ia));
983         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
984         for (i = 0; i < payloads; i++)
985                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_types[i]), payload_types[i]);
986         end_trace();
987
988 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
989
990         nua_invite(p_s_handle,
991                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
992                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
993                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
994                 NUTAG_MEDIA_ENABLE(0),
995                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
996                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
997         new_state(PORT_STATE_OUT_SETUP);
998
999 #if 0
1000         PDEBUG(DEBUG_SIP, "do overlap\n");
1001         new_state(PORT_STATE_OUT_OVERLAP);
1002         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_OVERLAP);
1003         message_put(message);
1004 #else
1005         PDEBUG(DEBUG_SIP, "do proceeding\n");
1006         new_state(PORT_STATE_OUT_PROCEEDING);
1007         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1008         message_put(message);
1009 #endif
1010
1011         /* attach only if not already */
1012         epointlist = p_epointlist;
1013         while(epointlist) {
1014                 if (epointlist->epoint_id == epoint_id)
1015                         break;
1016                 epointlist = epointlist->next;
1017         }
1018         if (!epointlist)
1019                 epointlist_new(epoint_id);
1020
1021         return 0;
1022 }
1023         
1024 int Psip::message_notify(unsigned int epoint_id, int message_id, union parameter *param)
1025 {
1026 //      char sdp_str[256];
1027 //      struct in_addr ia;
1028
1029         switch (param->notifyinfo.notify) {
1030         case INFO_NOTIFY_REMOTE_HOLD:
1031 #if 0
1032                 SPRINT(sdp_str,
1033                         "v=0\n"
1034                         "o=LCR-Sofia-SIP 0 0 IN IP4 0.0.0.0\n"
1035                         "s=SIP Call\n"
1036                         "c=IN IP4 0.0.0.0\n"
1037                         "t=0 0\n"
1038                         );
1039                 PDEBUG(DEBUG_SIP, "Using SDP for hold: %s\n", sdp_str);
1040                 nua_info(p_s_handle,
1041 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1042 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1043 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1044                         NUTAG_MEDIA_ENABLE(0),
1045                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1046                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1047 #endif
1048                 break;
1049         case INFO_NOTIFY_REMOTE_RETRIEVAL:
1050 #if 0
1051                 ia.s_addr = htonl(p_s_rtp_ip_local);
1052                 SPRINT(sdp_str,
1053                         "v=0\n"
1054                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
1055                         "s=SIP Call\n"
1056                         "c=IN IP4 %s\n"
1057                         "t=0 0\n"
1058                         "m=audio %d RTP/AVP %d\n"
1059                         "a=rtpmap:%d %s/8000\n"
1060                         , 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));
1061                 PDEBUG(DEBUG_SIP, "Using SDP for rertieve: %s\n", sdp_str);
1062                 nua_info(p_s_handle,
1063 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1064 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1065 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1066                         NUTAG_MEDIA_ENABLE(0),
1067                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1068                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1069 #endif
1070                 break;
1071         }
1072
1073         return 0;
1074 }
1075
1076 int Psip::message_dtmf(unsigned int epoint_id, int message_id, union parameter *param)
1077 {
1078         char dtmf_str[64];
1079         
1080         /* prepare DTMF info payload */
1081         SPRINT(dtmf_str,
1082                 "Signal=%c\n"
1083                 "Duration=160\n"
1084                 , param->dtmf);
1085
1086         /* start invite to handle DTMF */
1087         nua_info(p_s_handle,
1088                 NUTAG_MEDIA_ENABLE(0),
1089                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1090                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1091         
1092         return 0;
1093 }
1094
1095 /* NOTE: incomplete and not working */
1096 int Psip::message_information(unsigned int epoint_id, int message_id, union parameter *param)
1097 {
1098         char dtmf_str[64];
1099         
1100         /* prepare DTMF info payload */
1101         SPRINT(dtmf_str,
1102                 "Signal=%s\n"
1103                 "Duration=160\n"
1104                 , param->information.id);
1105
1106         /* start invite to handle DTMF */
1107         nua_info(p_s_handle,
1108                 NUTAG_MEDIA_ENABLE(0),
1109                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1110                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1111         
1112         return 0;
1113 }
1114
1115 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1116 {
1117         if (Port::message_epoint(epoint_id, message_id, param))
1118                 return 1;
1119
1120         switch(message_id) {
1121                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1122                 if (p_state != PORT_STATE_IN_SETUP
1123                  && p_state != PORT_STATE_IN_PROCEEDING)
1124                         return 0;
1125                 nua_respond(p_s_handle, SIP_180_RINGING, TAG_END());
1126                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1127                 add_trace("respond", "value", "180 Ringing");
1128                 end_trace();
1129                 new_state(PORT_STATE_IN_ALERTING);
1130                 return 1;
1131
1132                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1133                 if (p_state != PORT_STATE_IN_SETUP
1134                  && p_state != PORT_STATE_IN_PROCEEDING
1135                  && p_state != PORT_STATE_IN_ALERTING)
1136                         return 0;
1137                 message_connect(epoint_id, message_id, param);
1138                 return 1;
1139
1140                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1141                 case MESSAGE_RELEASE: /* call has been released */
1142                 message_release(epoint_id, message_id, param);
1143                 return 1;
1144
1145                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1146                 message_setup(epoint_id, message_id, param);
1147                 return 1;
1148
1149                 case MESSAGE_INFORMATION: /* overlap dialing */
1150                 if (p_state != PORT_STATE_OUT_OVERLAP)
1151                         return 0;
1152                 message_information(epoint_id, message_id, param);
1153                 return 1;
1154
1155                 case MESSAGE_DTMF: /* DTMF info to be transmitted via INFO transaction */
1156                 if (p_state == PORT_STATE_CONNECT)
1157                         message_dtmf(epoint_id, message_id, param);
1158                 case MESSAGE_NOTIFY: /* notification about remote hold/retrieve */
1159                 if (p_state == PORT_STATE_CONNECT)
1160                         message_notify(epoint_id, message_id, param);
1161                 return(1);
1162
1163                 default:
1164                 PDEBUG(DEBUG_SIP, "PORT(%s) SP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1165         }
1166
1167         return 0;
1168 }
1169
1170 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)
1171 {
1172         *payloads = 0;
1173
1174         if (!sip->sip_payload) {
1175                 PDEBUG(DEBUG_SIP, "no payload given\n");
1176                 return 0;
1177         }
1178
1179         sdp_parser_t *parser;
1180         sdp_session_t *sdp;
1181         sdp_media_t *m;
1182         sdp_attribute_t *attr;
1183         sdp_rtpmap_t *map;
1184         sdp_connection_t *conn;
1185
1186         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1187
1188         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1189         if (!parser) {
1190                 return 400;
1191         }
1192         if (!(sdp = sdp_session(parser))) {
1193                 sdp_parser_free(parser);
1194                 return 400;
1195         }
1196         for (m = sdp->sdp_media; m; m = m->m_next) {
1197                 if (m->m_proto != sdp_proto_rtp)
1198                         continue;
1199                 if (m->m_type != sdp_media_audio)
1200                         continue;
1201                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1202                 *port = m->m_port;
1203                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1204                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1205                 }
1206                 if (m->m_connections) {
1207                         conn = m->m_connections;
1208                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1209                         inet_pton(AF_INET, conn->c_address, ip);
1210                         *ip = ntohl(p_s_rtp_ip_remote);
1211                 } else {
1212                         char *p = sip->sip_payload->pl_data;
1213                         char addr[16];
1214
1215                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1216                         p = strstr(p, "c=IN IP4 ");
1217                         if (!p) {
1218                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1219                                 sdp_parser_free(parser);
1220                                 return 400;
1221                         }
1222                         SCPY(addr, p + 9);
1223                         if ((p = strchr(addr, '\n'))) *p = '\0';
1224                         if ((p = strchr(addr, '\r'))) *p = '\0';
1225                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1226                         inet_pton(AF_INET, addr, ip);
1227                         *ip = ntohl(p_s_rtp_ip_remote);
1228                 }
1229                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1230                         int media_type = 0;
1231
1232                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d' pt='%d'\n", map->rm_encoding, map->rm_rate, map->rm_pt);
1233                         /* append to payload list, if there is space */
1234                         add_trace("rtp", "payload", "%s:%d", map->rm_encoding, map->rm_pt);
1235                         if (map->rm_pt == PAYLOAD_TYPE_ALAW)
1236                                 media_type = MEDIA_TYPE_ALAW;
1237                         else if (map->rm_pt == PAYLOAD_TYPE_ULAW)
1238                                 media_type = MEDIA_TYPE_ULAW;
1239                         else if (map->rm_pt == PAYLOAD_TYPE_GSM)
1240                                 media_type = MEDIA_TYPE_GSM;
1241                         else if (!strcmp(map->rm_encoding, "GSM-EFR"))
1242                                 media_type = MEDIA_TYPE_GSM_EFR;
1243                         else if (!strcmp(map->rm_encoding, "AMR"))
1244                                 media_type = MEDIA_TYPE_AMR;
1245                         else if (!strcmp(map->rm_encoding, "GSM-HR"))
1246                                 media_type = MEDIA_TYPE_GSM_HR;
1247                         if (media_type && *payloads <= max_payloads) {
1248                                 *payload_types++ = map->rm_pt;
1249                                 *media_types++ = media_type;
1250                                 (*payloads)++;
1251                         }
1252                 }
1253         }
1254
1255         sdp_parser_free(parser);
1256
1257         return 0;
1258 }
1259
1260 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[])
1261 {
1262         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1263         const char *from = "", *to = "";
1264         int ret;
1265         class Endpoint *epoint;
1266         struct lcr_msg *message;
1267         struct interface *interface;
1268         int media_types[32];
1269         uint8_t payload_types[32];
1270         int payloads = 0;
1271
1272         interface = getinterfacebyname(inst->interface_name);
1273         if (!interface) {
1274                 PERROR("Cannot find interface %s.\n", inst->interface_name);
1275                 return;
1276         }
1277
1278         if (sip->sip_from && sip->sip_from->a_url)
1279                 from = sip->sip_from->a_url->url_user;
1280         if (sip->sip_to && sip->sip_to->a_url)
1281                 to = sip->sip_to->a_url->url_user;
1282         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1283
1284         sip_trace_header(this, "Payload received", DIRECTION_NONE);
1285         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1286         if (!ret) {
1287                 /* if no RTP bridge, we must support LAW codec, otherwise we forward what we have */
1288                 if (!p_s_rtp_bridge) {
1289                         int i;
1290
1291                         /* check if supported payload type exists */
1292                         for (i = 0; i < payloads; i++) {
1293                                 if (media_types[i] == ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW))
1294                                         break;
1295                         }
1296                         if (i == payloads) {
1297                                 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1298                                 ret = 415;
1299                         }
1300                 }
1301         }
1302         end_trace();
1303         if (ret) {
1304                 if (ret == 400)
1305                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1306                 else
1307                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1308                 nua_handle_destroy(nh);
1309                 p_s_handle = NULL;
1310                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1311                 if (ret == 400)
1312                         add_trace("respond", "value", "415 Unsupported Media");
1313                 else
1314                         add_trace("respond", "value", "400 Bad Request");
1315                 add_trace("reason", NULL, "offered codec does not match");
1316                 end_trace();
1317                 new_state(PORT_STATE_RELEASE);
1318                 trigger_work(&p_s_delete);
1319                 return;
1320         }
1321
1322         /* open local RTP peer (if not bridging) */
1323         if (!p_s_rtp_bridge && rtp_open() < 0) {
1324                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1325                 nua_handle_destroy(nh);
1326                 p_s_handle = NULL;
1327                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1328                 add_trace("respond", "value", "500 Internal Server Error");
1329                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1330                 end_trace();
1331                 new_state(PORT_STATE_RELEASE);
1332                 trigger_work(&p_s_delete);
1333                 return;
1334         }
1335
1336         /* apply handle */
1337         sip_trace_header(this, "NEW handle", DIRECTION_IN);
1338         add_trace("handle", "new", "0x%x", nh);
1339         p_s_handle = nh;
1340         end_trace();
1341
1342         sip_trace_header(this, "INVITE", DIRECTION_IN);
1343         add_trace("rtp", "port", "%d", p_s_rtp_port_remote);
1344         /* caller information */
1345         if (!from[0]) {
1346                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1347                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1348                 add_trace("calling", "present", "unavailable");
1349         } else {
1350                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1351                 add_trace("calling", "present", "allowed");
1352                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1353                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1354                 SCPY(p_callerinfo.id, from);
1355                 add_trace("calling", "number", "%s", from);
1356         }
1357         SCPY(p_callerinfo.interface, inst->interface_name);
1358         /* dialing information */
1359         if (to[0]) {
1360                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1361                 SCAT(p_dialinginfo.id, to);
1362                 add_trace("dialing", "number", "%s", to);
1363         }
1364         /* redir info */
1365         /* bearer capability */
1366         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1367         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1368         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1369         add_trace("bearer", "capa", "speech");
1370         add_trace("bearer", "mode", "circuit");
1371         /* if packet mode works some day, see dss1.cpp for conditions */
1372         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1373
1374         end_trace();
1375
1376         /* create endpoint */
1377         if (p_epointlist)
1378                 FATAL("Incoming call but already got an endpoint.\n");
1379         if (!(epoint = new Endpoint(p_serial, 0)))
1380                 FATAL("No memory for Endpoint instance\n");
1381         epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
1382         epointlist_new(epoint->ep_serial);
1383
1384 #ifdef NUTAG_AUTO100
1385         /* send trying (proceeding) */
1386         nua_respond(nh, SIP_100_TRYING, TAG_END());
1387         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1388         add_trace("respond", "value", "100 Trying");
1389         end_trace();
1390 #endif
1391
1392         new_state(PORT_STATE_IN_PROCEEDING);
1393
1394         /* send setup message to endpoit */
1395         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1396         message->param.setup.port_type = p_type;
1397 //      message->param.setup.dtmf = 0;
1398         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1399         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1400         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1401 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1402 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1403 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1404         if (p_s_rtp_bridge) {
1405                 int i;
1406
1407                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
1408                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
1409                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
1410                 /* add codecs to setup message */
1411                 for (i = 0; i < payloads; i++) {
1412                         message->param.setup.rtpinfo.media_types[i] = media_types[i];
1413                         message->param.setup.rtpinfo.payload_types[i] = payload_types[i];
1414                         if (i == sizeof(message->param.setup.rtpinfo.payload_types))
1415                                 break;
1416                 }
1417                 message->param.setup.rtpinfo.payloads = i;
1418         }
1419         message_put(message);
1420
1421 #if 0
1422 issues:
1423 - send tones that are clocked with timer, unless data is received from bridge
1424         /* send progress, if tones are available and if we don't bridge */
1425         if (!p_s_rtp_bridge && interface->is_tones == IS_YES) {
1426                 char sdp_str[256];
1427                 struct in_addr ia;
1428                 unsigned char payload_type;
1429
1430                 PDEBUG(DEBUG_SIP, "Connecting audio, since we have tones available\n");
1431                 payload_type = (options.law=='a') ? RTP_PT_ALAW : RTP_PT_ULAW;
1432                 /* open local RTP peer (if not bridging) */
1433                 if (rtp_connect() < 0) {
1434                         nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1435                         nua_handle_destroy(nh);
1436                         p_s_handle = NULL;
1437                         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1438                         add_trace("respond", "value", "500 Internal Server Error");
1439                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
1440                         end_trace();
1441                         new_state(PORT_STATE_RELEASE);
1442                         trigger_work(&p_s_delete);
1443                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1444                         message->param.disconnectinfo.cause = 41;
1445                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1446                         message_put(message);
1447                         new_state(PORT_STATE_RELEASE);
1448                         trigger_work(&p_s_delete);
1449                         return;
1450                 }
1451
1452                 ia.s_addr = htonl(p_s_rtp_ip_local);
1453
1454                 SPRINT(sdp_str,
1455                         "v=0\n"
1456                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\n"
1457                         "s=SIP Call\n"
1458                         "c=IN IP4 %s\n"
1459                         "t=0 0\n"
1460                         "m=audio %d RTP/AVP %d\n"
1461                         "a=rtpmap:%d %s/8000\n"
1462                         , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local, payload_type, payload_type, payload_type2name(payload_type));
1463                 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1464
1465                 nua_respond(p_s_handle, SIP_183_SESSION_PROGRESS,
1466                         NUTAG_MEDIA_ENABLE(0),
1467                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1468                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1469                 new_state(PORT_STATE_CONNECT);
1470                 sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1471                 add_trace("respond", "value", "183 SESSION PROGRESS");
1472                 add_trace("reason", NULL, "audio available");
1473                 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1474                 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1475                 add_trace("rtp", "payload", "%d", payload_type);
1476                 end_trace();
1477         }
1478 #endif
1479 }
1480
1481 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[])
1482 {
1483         struct lcr_msg *message;
1484         int cause = 0;
1485
1486         PDEBUG(DEBUG_SIP, "bye received\n");
1487
1488         sip_trace_header(this, "BYE", DIRECTION_IN);
1489         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1490                 cause = atoi(sip->sip_reason->re_cause);
1491                 add_trace("cause", "value", "%d", cause);
1492         }
1493         end_trace();
1494
1495 // let stack do bye automaticall, since it will not accept our response for some reason
1496 //      nua_respond(nh, SIP_200_OK, TAG_END());
1497         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1498         add_trace("respond", "value", "200 OK");
1499         end_trace();
1500 //      nua_handle_destroy(nh);
1501         p_s_handle = NULL;
1502
1503         rtp_close();
1504
1505         while(p_epointlist) {
1506                 /* send setup message to endpoit */
1507                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1508                 message->param.disconnectinfo.cause = cause ? : 16;
1509                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1510                 message_put(message);
1511                 /* remove epoint */
1512                 free_epointlist(p_epointlist);
1513         }
1514         new_state(PORT_STATE_RELEASE);
1515         trigger_work(&p_s_delete);
1516 }
1517
1518 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[])
1519 {
1520         struct lcr_msg *message;
1521
1522         PDEBUG(DEBUG_SIP, "cancel received\n");
1523
1524         sip_trace_header(this, "CANCEL", DIRECTION_IN);
1525         end_trace();
1526
1527         nua_handle_destroy(nh);
1528         p_s_handle = NULL;
1529
1530         rtp_close();
1531
1532         while(p_epointlist) {
1533                 /* send setup message to endpoit */
1534                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1535                 message->param.disconnectinfo.cause = 16;
1536                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1537                 message_put(message);
1538                 /* remove epoint */
1539                 free_epointlist(p_epointlist);
1540         }
1541         new_state(PORT_STATE_RELEASE);
1542         trigger_work(&p_s_delete);
1543 }
1544
1545 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[])
1546 {
1547         PDEBUG(DEBUG_SIP, "bye response received\n");
1548
1549         nua_handle_destroy(nh);
1550         p_s_handle = NULL;
1551
1552         rtp_close();
1553
1554         trigger_work(&p_s_delete);
1555 }
1556
1557 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[])
1558 {
1559         PDEBUG(DEBUG_SIP, "cancel response received\n");
1560
1561         nua_handle_destroy(nh);
1562         p_s_handle = NULL;
1563
1564         rtp_close();
1565
1566         trigger_work(&p_s_delete);
1567 }
1568
1569 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[])
1570 {
1571         struct lcr_msg *message;
1572         int cause = 0, location = 0;
1573         int media_types[32];
1574         uint8_t payload_types[32];
1575         int payloads = 0;
1576
1577         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
1578
1579         sip_trace_header(this, "RESPOND", DIRECTION_OUT);
1580         add_trace("respond", "value", "%d", status);
1581         end_trace();
1582
1583         /* connect audio */
1584         if (status == 183 || (status >= 200 && status <= 299)) {
1585                 int ret;
1586
1587                 sip_trace_header(this, "Payload received", DIRECTION_NONE);
1588                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1589                 if (!ret) {
1590                         if (payloads != 1)
1591                                 ret = 415;
1592                         else if (!p_s_rtp_bridge) {
1593                                 if (media_types[0] != ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW)) {
1594                                         add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1595                                         ret = 415;
1596                                 }
1597                         }
1598                 }
1599                 end_trace();
1600                 if (ret) {
1601                         nua_cancel(nh, TAG_END());
1602                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1603                         add_trace("reason", NULL, "accepted codec does not match");
1604                         end_trace();
1605                         cause = 88;
1606                         location = LOCATION_PRIVATE_LOCAL;
1607                         goto release_with_cause;
1608                 }
1609
1610                 /* connect to remote RTP (if not bridging) */
1611                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
1612                         nua_cancel(nh, TAG_END());
1613                         sip_trace_header(this, "CANCEL", DIRECTION_OUT);
1614                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1615                         end_trace();
1616                         cause = 31;
1617                         location = LOCATION_PRIVATE_LOCAL;
1618                         goto release_with_cause;
1619                 }
1620         }
1621
1622         /* process 1xx */
1623         switch (status) {
1624         case 100:
1625 #if 0
1626                 PDEBUG(DEBUG_SIP, "do proceeding\n");
1627                 new_state(PORT_STATE_OUT_PROCEEDING);
1628                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1629                 message_put(message);
1630 #endif
1631                 return;
1632         case 180:
1633                 PDEBUG(DEBUG_SIP, "do alerting\n");
1634                 new_state(PORT_STATE_OUT_ALERTING);
1635                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
1636                 message_put(message);
1637                 return;
1638         case 183:
1639                 PDEBUG(DEBUG_SIP, "do progress\n");
1640                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
1641                 message->param.progressinfo.progress = 8;
1642                 message->param.progressinfo.location = 10;
1643                 if (p_s_rtp_bridge) {
1644                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1645                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
1646                         message->param.progressinfo.rtpinfo.media_types[0] = media_types[0];
1647                         message->param.progressinfo.rtpinfo.payload_types[0] = payload_types[0];
1648                         message->param.progressinfo.rtpinfo.payloads = 1;
1649                 }
1650                 message_put(message);
1651                 return;
1652         default:
1653                 if (status < 100 || status > 199)
1654                         break;
1655                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
1656
1657                 return;
1658         }
1659
1660         /* process 2xx */
1661         if (status >= 200 && status <= 299) {
1662                 PDEBUG(DEBUG_SIP, "do connect\n");
1663                 nua_ack(nh, TAG_END());
1664                 new_state(PORT_STATE_CONNECT);
1665                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
1666                 if (p_s_rtp_bridge) {
1667                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
1668                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
1669                         message->param.connectinfo.rtpinfo.media_types[0] = media_types[0];
1670                         message->param.connectinfo.rtpinfo.payload_types[0] = payload_types[0];
1671                         message->param.connectinfo.rtpinfo.payloads = 1;
1672                 }
1673                 message_put(message);
1674                 return;
1675         }
1676         cause = status2cause(status);
1677         location = LOCATION_BEYOND;
1678
1679 release_with_cause:
1680         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
1681
1682         while(p_epointlist) {
1683                 /* send setup message to endpoit */
1684                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1685                 message->param.disconnectinfo.cause = cause;
1686                 message->param.disconnectinfo.location = location;
1687                 message_put(message);
1688                 /* remove epoint */
1689                 free_epointlist(p_epointlist);
1690         }
1691
1692         new_state(PORT_STATE_RELEASE);
1693
1694         rtp_close();
1695
1696         trigger_work(&p_s_delete);
1697 }
1698
1699 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[])
1700 {
1701         struct sip_inst *inst = (struct sip_inst *) magic;
1702         class Port *port;
1703         class Psip *psip = NULL;
1704
1705         PDEBUG(DEBUG_SIP, "Event %d from stack received (handle=%p)\n", event, nh);
1706         if (!nh)
1707                 return;
1708
1709         /* create or find port instance */
1710         if (event == nua_i_invite)
1711         {
1712                 char name[64];
1713                 struct interface *interface = interface_first;
1714
1715                 /* create call instance */
1716                 SPRINT(name, "%s-%d-in", inst->interface_name, 0);
1717                 while (interface) {
1718                         if (!strcmp(interface->name, inst->interface_name))
1719                                 break;
1720                         interface = interface->next;
1721                 }
1722                 if (!interface) {
1723                         PERROR("Cannot find interface %s.\n", inst->interface_name);
1724                         return;
1725                 }
1726                 if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
1727                         FATAL("Cannot create Port instance.\n");
1728         } else {
1729                 port = port_first;
1730                 while(port) {
1731                         if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
1732                                 psip = (class Psip *)port;
1733                                 if (psip->p_s_handle == nh) {
1734                                         break;
1735                                 }
1736                         }
1737                         port = port->next;
1738                 }
1739         }
1740         if (!psip) {
1741                 PERROR("no SIP Port found for handel %p\n", nh);
1742                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1743                 nua_handle_destroy(nh);
1744                 return;
1745         }
1746
1747         switch (event) {
1748         case nua_r_set_params:
1749                 PDEBUG(DEBUG_SIP, "setparam response\n");
1750                 break;
1751         case nua_i_error:
1752                 PDEBUG(DEBUG_SIP, "error received\n");
1753                 break;
1754         case nua_i_state:
1755                 PDEBUG(DEBUG_SIP, "state change received\n");
1756                 break;
1757         case nua_i_register:
1758                 PDEBUG(DEBUG_SIP, "register received\n");
1759                 break;
1760         case nua_i_invite:
1761                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1762                 break;
1763         case nua_i_ack:
1764                 PDEBUG(DEBUG_SIP, "ack received\n");
1765                 break;
1766         case nua_i_active:
1767                 PDEBUG(DEBUG_SIP, "active received\n");
1768                 break;
1769         case nua_i_bye:
1770                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1771                 break;
1772         case nua_i_cancel:
1773                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1774                 break;
1775         case nua_r_bye:
1776                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
1777                 break;
1778         case nua_r_cancel:
1779                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
1780                 break;
1781         case nua_r_invite:
1782                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
1783                 break;
1784         case nua_i_terminated:
1785                 PDEBUG(DEBUG_SIP, "terminated received\n");
1786                 break;
1787         default:
1788                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
1789         }
1790 }
1791
1792 /* received shutdown due to termination of RTP */
1793 void Psip::rtp_shutdown(void)
1794 {
1795         struct lcr_msg *message;
1796
1797         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
1798
1799         sip_trace_header(this, "RTP terminated", DIRECTION_IN);
1800         end_trace();
1801
1802         nua_handle_destroy(p_s_handle);
1803         p_s_handle = NULL;
1804
1805         while(p_epointlist) {
1806                 /* send setup message to endpoit */
1807                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1808                 message->param.disconnectinfo.cause = 16;
1809                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1810                 message_put(message);
1811                 /* remove epoint */
1812                 free_epointlist(p_epointlist);
1813         }
1814         new_state(PORT_STATE_RELEASE);
1815         trigger_work(&p_s_delete);
1816 }
1817
1818 int sip_init_inst(struct interface *interface)
1819 {
1820         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
1821
1822         interface->sip_inst = inst;
1823         SCPY(inst->interface_name, interface->name);
1824         SCPY(inst->local_peer, interface->sip_local_peer);
1825         SCPY(inst->remote_peer, interface->sip_remote_peer);
1826
1827         /* init root object */
1828         inst->root = su_root_create(inst);
1829         if (!inst->root) {
1830                 PERROR("Failed to create SIP root\n");
1831                 sip_exit_inst(interface);
1832                 return -EINVAL;
1833         }
1834
1835         inst->nua = nua_create(inst->root, sip_callback, inst, TAG_NULL());
1836         if (!inst->nua) {
1837                 PERROR("Failed to create SIP stack object\n");
1838                 sip_exit_inst(interface);
1839                 return -EINVAL;
1840         }
1841         nua_set_params(inst->nua,
1842                 SIPTAG_ALLOW_STR("INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
1843                 NUTAG_APPL_METHOD("INVITE"),
1844                 NUTAG_APPL_METHOD("ACK"),
1845 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
1846                 NUTAG_APPL_METHOD("CANCEL"),
1847                 NUTAG_APPL_METHOD("OPTIONS"),
1848                 NUTAG_APPL_METHOD("NOTIFY"),
1849                 NUTAG_APPL_METHOD("INFO"),
1850                 NUTAG_AUTOACK(0),
1851 #ifdef NUTAG_AUTO100
1852                 NUTAG_AUTO100(0),
1853 #endif
1854                 NUTAG_AUTOALERT(0),
1855                 NUTAG_AUTOANSWER(0),
1856                 TAG_NULL());
1857
1858         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
1859
1860         return 0;
1861 }
1862
1863 void sip_exit_inst(struct interface *interface)
1864 {
1865         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
1866
1867         if (!inst)
1868                 return;
1869         if (inst->root)
1870                 su_root_destroy(inst->root);
1871         if (inst->nua) {
1872                 nua_destroy(inst->nua);
1873         }
1874         FREE(inst, sizeof(*inst));
1875         interface->sip_inst = NULL;
1876
1877         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
1878 }
1879
1880 extern su_log_t su_log_default[];
1881 extern su_log_t nua_log[];
1882 //extern su_log_t soa_log[];
1883
1884 int sip_init(void)
1885 {
1886         int i;
1887
1888         /* init SOFIA lib */
1889         su_init();
1890         su_home_init(sip_home);
1891
1892         if (options.deb & DEBUG_SIP) {
1893                 su_log_set_level(su_log_default, 9);
1894                 su_log_set_level(nua_log, 9);
1895                 //su_log_set_level(soa_log, 9);
1896         }
1897
1898         for (i = 0; i < 256; i++)
1899                 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);
1900
1901         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
1902
1903         return 0;
1904 }
1905
1906 void sip_exit(void)
1907 {
1908         su_home_deinit(sip_home);
1909         su_deinit();
1910
1911         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
1912 }
1913
1914 void sip_handle(void)
1915 {
1916         struct interface *interface = interface_first;
1917         struct sip_inst *inst;
1918
1919         while (interface) {
1920                 if (interface->sip_inst) {
1921                         inst = (struct sip_inst *) interface->sip_inst;
1922                         su_root_step(inst->root, 0);
1923                 }
1924                 interface = interface->next;
1925         }
1926 }
1927
1928 /* deletes when back in event loop */
1929 static int delete_event(struct lcr_work *work, void *instance, int index)
1930 {
1931         class Psip *psip = (class Psip *)instance;
1932
1933         delete psip;
1934
1935         return 0;
1936 }
1937