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