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