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