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