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