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         struct interface *interface;
890         int media_type;
891         unsigned char payload_type;
892
893         interface = getinterfacebyname(inst->interface_name);
894         if (!interface) {
895                 PERROR("Cannot find interface %s.\n", inst->interface_name);
896                 return 0;
897         }
898
899         if (param->connectinfo.rtpinfo.port) {
900                 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
901                 p_s_rtp_bridge = 1;
902                 media_type = param->connectinfo.rtpinfo.media_types[0];
903                 payload_type = param->connectinfo.rtpinfo.payload_types[0];
904                 p_s_rtp_ip_local = param->connectinfo.rtpinfo.ip;
905                 p_s_rtp_port_local = param->connectinfo.rtpinfo.port;
906                 PDEBUG(DEBUG_SIP, "payload type %d\n", payload_type);
907                 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
908                 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
909         } else {
910                 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
911                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
912                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
913                 /* open local RTP peer (if not bridging) */
914                 if (!p_s_rtp_is_connected && rtp_connect() < 0) {
915                         nua_cancel(p_s_handle, TAG_END());
916                         nua_handle_destroy(p_s_handle);
917                         p_s_handle = NULL;
918                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
919                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
920                         end_trace();
921                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
922                         message->param.disconnectinfo.cause = 41;
923                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
924                         message_put(message);
925                         new_state(PORT_STATE_RELEASE);
926                         trigger_work(&p_s_delete);
927                         return 0;
928                 }
929         }
930
931         memset(&ia, 0, sizeof(ia));
932         ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
933         if (p_s_rtp_bridge || interface->is_tones != IS_YES) {
934                 SPRINT(sdp_str,
935                         "v=0\r\n"
936                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\r\n"
937                         "s=SIP Call\r\n"
938                         "c=IN IP4 %s\r\n"
939                         "t=0 0\r\n"
940                         "m=audio %d RTP/AVP %d\r\n"
941                         "a=rtpmap:%d %s/8000\r\n"
942                         , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local, payload_type, payload_type, media_type2name(media_type));
943                 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
944         }
945
946         /* NOTE:
947          * If this response causes corrupt messages, like SDP body inside or
948          * before header, check if the sofia-sip-gcc-4.8.patch was applied.
949          * If it is still corrupted, try to disable optimization when compiling
950          * sofia-sip.
951          */
952         nua_respond(p_s_handle, SIP_200_OK,
953                 NUTAG_MEDIA_ENABLE(0),
954                 TAG_IF(sdp_str[0], SIPTAG_CONTENT_TYPE_STR("application/sdp")),
955                 TAG_IF(sdp_str[0], SIPTAG_PAYLOAD_STR(sdp_str)),
956                 TAG_END());
957
958         new_state(PORT_STATE_CONNECT);
959         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
960         add_trace("respond", "value", "200 OK");
961         add_trace("reason", NULL, "call connected");
962         if (sdp_str[0]) {
963                 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
964                 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
965                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
966         }
967         end_trace();
968
969         return 0;
970 }
971
972 int Psip::message_release(unsigned int epoint_id, int message_id, union parameter *param)
973 {
974         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
975         struct lcr_msg *message;
976         char cause_str[128] = "";
977         int cause = param->disconnectinfo.cause;
978         int location = param->disconnectinfo.cause;
979         int status;
980         const char *status_text;
981
982         if (cause > 0 && cause <= 127) {
983                 SPRINT(cause_str, "Q.850;cause=%d;text=\"%s\"", cause, isdn_cause[cause].english);
984         }
985
986         switch (p_state) {
987         case PORT_STATE_OUT_SETUP:
988         case PORT_STATE_OUT_PROCEEDING:
989         case PORT_STATE_OUT_ALERTING:
990                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will cancel\n");
991                 sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
992                 if (cause_str[0])
993                         add_trace("cause", "value", "%d", cause);
994                 end_trace();
995                 nua_cancel(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
996                 break;
997         case PORT_STATE_IN_SETUP:
998         case PORT_STATE_IN_PROCEEDING:
999         case PORT_STATE_IN_ALERTING:
1000                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will respond\n");
1001                 status = cause2status(cause, location, &status_text);
1002                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1003                 if (cause_str[0])
1004                         add_trace("cause", "value", "%d", cause);
1005                 add_trace("respond", "value", "%d %s", status, status_text);
1006                 end_trace();
1007                 nua_respond(p_s_handle, status, status_text, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
1008                 nua_handle_destroy(p_s_handle);
1009                 p_s_handle = NULL;
1010                 trigger_work(&p_s_delete);
1011                 break;
1012         default:
1013                 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will perform nua_bye\n");
1014                 sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_OUT);
1015                 if (cause_str[0])
1016                         add_trace("cause", "value", "%d", cause);
1017                 end_trace();
1018                 nua_bye(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
1019         }
1020
1021         if (message_id == MESSAGE_DISCONNECT) {
1022                 while(p_epointlist) {
1023                         message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1024                         message->param.disconnectinfo.cause = CAUSE_NORMAL;
1025                         message->param.disconnectinfo.location = LOCATION_BEYOND;
1026                         message_put(message);
1027                         /* remove epoint */
1028                         free_epointlist(p_epointlist);
1029                 }
1030         }
1031
1032         new_state(PORT_STATE_RELEASE);
1033
1034         return(0);
1035 }
1036
1037 int Psip::message_setup(unsigned int epoint_id, int message_id, union parameter *param)
1038 {
1039         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1040         char from[128] = "";
1041         char asserted_id[128] = "", asserted_msg[256] = "";
1042         char to[128] = "";
1043         char contact[128] = "";
1044         const char *local = inst->local_peer;
1045         char local_ip[16];
1046         const char *remote = inst->remote_peer;
1047         char sdp_str[512], pt_str[32];
1048         struct in_addr ia;
1049         struct epoint_list *epointlist;
1050         sip_cseq_t *cseq = NULL;
1051         struct lcr_msg *message;
1052         int lcr_media = { (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW };
1053         unsigned char lcr_payload = { (options.law=='a') ? (unsigned char )PAYLOAD_TYPE_ALAW : (unsigned char )PAYLOAD_TYPE_ULAW };
1054         int *media_types;
1055         unsigned char *payload_types;
1056         int payloads = 0;
1057         int i;
1058
1059         if (!remote[0]) {
1060                 sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_OUT);
1061                 add_trace("failed", "reason", "No remote peer set or no peer has registered to us.");
1062                 end_trace();
1063                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1064                 message->param.disconnectinfo.cause = 27;
1065                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1066                 message_put(message);
1067                 new_state(PORT_STATE_RELEASE);
1068                 trigger_work(&p_s_delete);
1069                 return 0;
1070         }
1071         
1072         PDEBUG(DEBUG_SIP, "Doing Setup (inst %p)\n", inst);
1073
1074         memcpy(&p_dialinginfo, &param->setup.dialinginfo, sizeof(p_dialinginfo));
1075         memcpy(&p_callerinfo, &param->setup.callerinfo, sizeof(p_callerinfo));
1076 //      memcpy(&p_redirinfo, &param->setup.redirinfo, sizeof(p_redirinfo));
1077         do_screen(1, p_callerinfo.id, sizeof(p_callerinfo.id), &p_callerinfo.ntype, &p_callerinfo.present, inst->interface_name);
1078 //      do_screen(1, p_redirinfo.id, sizeof(p_redirinfo.id), &p_redirinfo.ntype, &p_redirinfo.present, inst->interface_name);
1079
1080         if (param->setup.rtpinfo.port) {
1081                 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1082                 p_s_rtp_bridge = 1;
1083                 media_types = param->setup.rtpinfo.media_types;
1084                 payload_types = param->setup.rtpinfo.payload_types;
1085                 payloads = param->setup.rtpinfo.payloads;
1086                 p_s_rtp_ip_local = param->setup.rtpinfo.ip;
1087                 p_s_rtp_port_local = param->setup.rtpinfo.port;
1088                 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
1089                 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
1090         } else {
1091                 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
1092                 p_s_rtp_bridge = 0;
1093                 media_types = &lcr_media;
1094                 payload_types = &lcr_payload;
1095                 payloads = 1;
1096
1097                 /* open local RTP peer (if not bridging) */
1098                 if (rtp_open() < 0) {
1099                         PERROR("Failed to open RTP sockets\n");
1100                         /* send release message to endpoit */
1101                         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1102                         message->param.disconnectinfo.cause = 41;
1103                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1104                         message_put(message);
1105                         new_state(PORT_STATE_RELEASE);
1106                         trigger_work(&p_s_delete);
1107                         return 0;
1108                 }
1109                 if (!p_s_rtp_ip_local) {
1110                         char *p;
1111
1112                         /* extract IP from local peer */
1113                         SCPY(local_ip, local);
1114                         p = strchr(local_ip, ':');
1115                         if (p)
1116                                 *p = '\0';
1117                         PDEBUG(DEBUG_SIP, "RTP local IP not known, so we use our local SIP ip %s\n", local_ip);
1118                         inet_pton(AF_INET, local_ip, &p_s_rtp_ip_local);
1119                         p_s_rtp_ip_local = ntohl(p_s_rtp_ip_local);
1120                 }
1121         }
1122
1123         memset(&ia, 0, sizeof(ia));
1124         ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1125         p_s_handle = nua_handle(inst->nua, NULL, TAG_END());
1126         if (!p_s_handle) {
1127                 PERROR("Failed to create handle\n");
1128                 /* send release message to endpoit */
1129                 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1130                 message->param.disconnectinfo.cause = 41;
1131                 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1132                 message_put(message);
1133                 new_state(PORT_STATE_RELEASE);
1134                 trigger_work(&p_s_delete);
1135                 return 0;
1136         }
1137         /* apply handle to trace */
1138 //      sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1139 //      add_trace("handle", "new", "0x%x", p_s_handle);
1140 //      end_trace();
1141
1142         SPRINT(sdp_str,
1143                 "v=0\r\n"
1144                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\r\n"
1145                 "s=SIP Call\r\n"
1146                 "c=IN IP4 %s\r\n"
1147                 "t=0 0\r\n"
1148                 "m=audio %d RTP/AVP"
1149                 , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local);
1150         for (i = 0; i < payloads; i++) {
1151                 SPRINT(pt_str, " %d", payload_types[i]);
1152                 SCAT(sdp_str, pt_str);
1153         }
1154         SCAT(sdp_str, "\r\n");
1155         for (i = 0; i < payloads; i++) {
1156                 SPRINT(pt_str, "a=rtpmap:%d %s/8000\r\n", payload_types[i], media_type2name(media_types[i]));
1157                 SCAT(sdp_str, pt_str);
1158         }
1159         PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
1160
1161         SPRINT(from, "sip:%s@%s", p_callerinfo.id, remote);
1162         SPRINT(to, "sip:%s@%s", p_dialinginfo.id, remote);
1163         if (inst->asserted_id[0]) {
1164                 SPRINT(asserted_id, "sip:%s@%s", inst->asserted_id, remote);
1165                 SPRINT(asserted_msg, "P-Asserted-Identity: <%s>", asserted_id);
1166         }
1167         if (inst->public_ip[0])
1168                 SPRINT(contact, "sip:%s@%s", p_callerinfo.id, inst->public_ip);
1169
1170         sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_OUT);
1171         add_trace("from", "uri", "%s", from);
1172         add_trace("to", "uri", "%s", to);
1173         if (asserted_id[0])
1174                 add_trace("assert-id", "uri", "%s", asserted_id);
1175         add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1176         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1177         for (i = 0; i < payloads; i++)
1178                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_types[i]), payload_types[i]);
1179         end_trace();
1180
1181 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
1182
1183         nua_invite(p_s_handle,
1184                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1185                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
1186                 TAG_IF(asserted_msg[0], SIPTAG_HEADER_STR(asserted_msg)),
1187                 TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
1188                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1189                 NUTAG_MEDIA_ENABLE(0),
1190                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1191                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1192         new_state(PORT_STATE_OUT_SETUP);
1193
1194         p_s_invite_direction = DIRECTION_OUT;
1195
1196 #if 0
1197         PDEBUG(DEBUG_SIP, "do overlap\n");
1198         new_state(PORT_STATE_OUT_OVERLAP);
1199         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_OVERLAP);
1200         message_put(message);
1201 #else
1202         PDEBUG(DEBUG_SIP, "do proceeding\n");
1203         new_state(PORT_STATE_OUT_PROCEEDING);
1204         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1205         message_put(message);
1206 #endif
1207
1208         /* attach only if not already */
1209         epointlist = p_epointlist;
1210         while(epointlist) {
1211                 if (epointlist->epoint_id == epoint_id)
1212                         break;
1213                 epointlist = epointlist->next;
1214         }
1215         if (!epointlist)
1216                 epointlist_new(epoint_id);
1217
1218         return 0;
1219 }
1220         
1221 int Psip::message_notify(unsigned int epoint_id, int message_id, union parameter *param)
1222 {
1223 //      char 
1224 //      struct in_addr ia;
1225
1226         switch (param->notifyinfo.notify) {
1227         case INFO_NOTIFY_REMOTE_HOLD:
1228 #if 0
1229                 SPRINT(sdp_str,
1230                         "v=0\r\n"
1231                         "o=LCR-Sofia-SIP 0 0 IN IP4 0.0.0.0\r\n"
1232                         "s=SIP Call\r\n"
1233                         "c=IN IP4 0.0.0.0\r\n"
1234                         "t=0 0\r\n"
1235                         );
1236                 PDEBUG(DEBUG_SIP, "Using SDP for hold: %s\n", sdp_str);
1237                 nua_info(p_s_handle,
1238 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1239 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1240 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1241                         NUTAG_MEDIA_ENABLE(0),
1242                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1243                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1244 #endif
1245                 break;
1246         case INFO_NOTIFY_REMOTE_RETRIEVAL:
1247 #if 0
1248                 memset(&ia, 0, sizeof(ia));
1249                 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1250                 SPRINT(sdp_str,
1251                         "v=0\r\n"
1252                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\r\n"
1253                         "s=SIP Call\r\n"
1254                         "c=IN IP4 %s\r\n"
1255                         "t=0 0\r\n"
1256                         "m=audio %d RTP/AVP %d\r\n"
1257                         "a=rtpmap:%d %s/8000\r\n"
1258                         , 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));
1259                 PDEBUG(DEBUG_SIP, "Using SDP for rertieve: %s\n", sdp_str);
1260                 nua_info(p_s_handle,
1261 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1262 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1263 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1264                         NUTAG_MEDIA_ENABLE(0),
1265                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1266                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1267 #endif
1268                 break;
1269         }
1270
1271         return 0;
1272 }
1273
1274 int Psip::message_dtmf(unsigned int epoint_id, int message_id, union parameter *param)
1275 {
1276         char dtmf_str[64];
1277         
1278         /* prepare DTMF info payload */
1279         SPRINT(dtmf_str,
1280                 "Signal=%c\n"
1281                 "Duration=160\n"
1282                 , param->dtmf);
1283
1284         /* start invite to handle DTMF */
1285         nua_info(p_s_handle,
1286                 NUTAG_MEDIA_ENABLE(0),
1287                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1288                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1289         
1290         return 0;
1291 }
1292
1293 /* NOTE: incomplete and not working */
1294 int Psip::message_information(unsigned int epoint_id, int message_id, union parameter *param)
1295 {
1296         char dtmf_str[64];
1297         
1298         /* prepare DTMF info payload */
1299         SPRINT(dtmf_str,
1300                 "Signal=%s\n"
1301                 "Duration=160\n"
1302                 , param->information.id);
1303
1304         /* start invite to handle DTMF */
1305         nua_info(p_s_handle,
1306                 NUTAG_MEDIA_ENABLE(0),
1307                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1308                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1309         
1310         return 0;
1311 }
1312
1313 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1314 {
1315         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1316
1317         if (Port::message_epoint(epoint_id, message_id, param))
1318                 return 1;
1319
1320         switch(message_id) {
1321                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1322                 if (p_state != PORT_STATE_IN_SETUP
1323                  && p_state != PORT_STATE_IN_PROCEEDING)
1324                         return 0;
1325                 nua_respond(p_s_handle, SIP_180_RINGING, TAG_END());
1326                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1327                 add_trace("respond", "value", "180 Ringing");
1328                 end_trace();
1329                 new_state(PORT_STATE_IN_ALERTING);
1330                 return 1;
1331
1332                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1333                 if (p_state != PORT_STATE_IN_SETUP
1334                  && p_state != PORT_STATE_IN_PROCEEDING
1335                  && p_state != PORT_STATE_IN_ALERTING)
1336                         return 0;
1337                 message_connect(epoint_id, message_id, param);
1338                 return 1;
1339
1340                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1341                 case MESSAGE_RELEASE: /* call has been released */
1342                 message_release(epoint_id, message_id, param);
1343                 return 1;
1344
1345                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1346                 message_setup(epoint_id, message_id, param);
1347                 return 1;
1348
1349                 case MESSAGE_INFORMATION: /* overlap dialing */
1350                 if (p_state != PORT_STATE_OUT_OVERLAP)
1351                         return 0;
1352                 message_information(epoint_id, message_id, param);
1353                 return 1;
1354
1355                 case MESSAGE_DTMF: /* DTMF info to be transmitted via INFO transaction */
1356                 if (p_state == PORT_STATE_CONNECT)
1357                         message_dtmf(epoint_id, message_id, param);
1358                 case MESSAGE_NOTIFY: /* notification about remote hold/retrieve */
1359                 if (p_state == PORT_STATE_CONNECT)
1360                         message_notify(epoint_id, message_id, param);
1361                 return(1);
1362
1363                 default:
1364                 PDEBUG(DEBUG_SIP, "PORT(%s) SP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1365         }
1366
1367         return 0;
1368 }
1369
1370 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)
1371 {
1372         *payloads = 0;
1373
1374         if (!sip->sip_payload) {
1375                 PDEBUG(DEBUG_SIP, "no payload given\n");
1376                 return 0;
1377         }
1378
1379         sdp_parser_t *parser;
1380         sdp_session_t *sdp;
1381         sdp_media_t *m;
1382         sdp_attribute_t *attr;
1383         sdp_rtpmap_t *map;
1384         sdp_connection_t *conn;
1385
1386         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1387
1388         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1389         if (!parser) {
1390                 return 400;
1391         }
1392         if (!(sdp = sdp_session(parser))) {
1393                 sdp_parser_free(parser);
1394                 return 400;
1395         }
1396         for (m = sdp->sdp_media; m; m = m->m_next) {
1397                 if (m->m_proto != sdp_proto_rtp)
1398                         continue;
1399                 if (m->m_type != sdp_media_audio)
1400                         continue;
1401                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1402                 *port = m->m_port;
1403                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1404                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1405                 }
1406                 if (m->m_connections) {
1407                         conn = m->m_connections;
1408                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1409                         inet_pton(AF_INET, conn->c_address, ip);
1410                         *ip = ntohl(p_s_rtp_ip_remote);
1411                 } else {
1412                         char *p = sip->sip_payload->pl_data;
1413                         char addr[16];
1414
1415                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1416                         p = strstr(p, "c=IN IP4 ");
1417                         if (!p) {
1418                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1419                                 sdp_parser_free(parser);
1420                                 return 400;
1421                         }
1422                         SCPY(addr, p + 9);
1423                         if ((p = strchr(addr, '\n'))) *p = '\0';
1424                         if ((p = strchr(addr, '\r'))) *p = '\0';
1425                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1426                         inet_pton(AF_INET, addr, ip);
1427                         *ip = ntohl(p_s_rtp_ip_remote);
1428                 }
1429                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1430                         int media_type = 0;
1431
1432                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d' pt='%d'\n", map->rm_encoding, map->rm_rate, map->rm_pt);
1433                         /* append to payload list, if there is space */
1434                         add_trace("rtp", "payload", "%s:%d", map->rm_encoding, map->rm_pt);
1435                         if (map->rm_pt == PAYLOAD_TYPE_ALAW)
1436                                 media_type = MEDIA_TYPE_ALAW;
1437                         else if (map->rm_pt == PAYLOAD_TYPE_ULAW)
1438                                 media_type = MEDIA_TYPE_ULAW;
1439                         else if (map->rm_pt == PAYLOAD_TYPE_GSM)
1440                                 media_type = MEDIA_TYPE_GSM;
1441                         else if (!strcmp(map->rm_encoding, "GSM-EFR"))
1442                                 media_type = MEDIA_TYPE_GSM_EFR;
1443                         else if (!strcmp(map->rm_encoding, "AMR"))
1444                                 media_type = MEDIA_TYPE_AMR;
1445                         else if (!strcmp(map->rm_encoding, "GSM-HR"))
1446                                 media_type = MEDIA_TYPE_GSM_HR;
1447                         if (media_type && *payloads <= max_payloads) {
1448                                 *payload_types++ = map->rm_pt;
1449                                 *media_types++ = media_type;
1450                                 (*payloads)++;
1451                         }
1452                 }
1453         }
1454
1455         sdp_parser_free(parser);
1456
1457         return 0;
1458 }
1459
1460 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[])
1461 {
1462         sip_www_authenticate_t const *authenticate = NULL;
1463         char const *realm = NULL;
1464         char const *scheme = NULL;
1465         int i;
1466         char *cur;
1467         char authentication[256] = "";
1468         PDEBUG(DEBUG_SIP, "challenge order received\n");
1469
1470         if (!inst->auth_user[0]) {
1471                 PDEBUG(DEBUG_SIP, "No credentials available\n");
1472                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1473                 add_trace("error", NULL, "There are no credentials given for interface");
1474                 end_trace();
1475                 return -1;
1476         }
1477
1478         if (sip->sip_www_authenticate) {
1479                 authenticate = sip->sip_www_authenticate;
1480         } else if (sip->sip_proxy_authenticate) {
1481                 authenticate = sip->sip_proxy_authenticate;
1482         } else {
1483                 PDEBUG(DEBUG_SIP, "No authentication header found\n");
1484                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1485                 add_trace("error", NULL, "Authentication method unknwon");
1486                 end_trace();
1487                 return -1;
1488         }
1489
1490         scheme = (char const *) authenticate->au_scheme;
1491         if (authenticate->au_params) {
1492                 for (i = 0; (cur = (char *) authenticate->au_params[i]); i++) {
1493                         if ((realm = strstr(cur, "realm="))) {
1494                                 realm += 6;
1495                                 break;
1496                         }
1497                 }
1498         }
1499
1500         if (!scheme || !realm) {
1501                 PDEBUG(DEBUG_SIP, "No scheme or no realm in authentication header found\n");
1502                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1503                 add_trace("error", NULL, "Authentication header has no realm or scheme");
1504                 end_trace();
1505                 return -1;
1506         }
1507
1508         SPRINT(authentication, "%s:%s:%s:%s", scheme, realm, inst->auth_user, inst->auth_password);
1509         PDEBUG(DEBUG_SIP, "auth: '%s'\n", authentication);
1510
1511         sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1512         add_trace("scheme", NULL, "%s", scheme);
1513         add_trace("realm", NULL, "%s", realm);
1514         add_trace("user", NULL, "%s", inst->auth_user);
1515         add_trace("pass", NULL, "%s", inst->auth_password);
1516         end_trace();
1517
1518         nua_authenticate(nh, /*SIPTAG_EXPIRES_STR("3600"),*/ NUTAG_AUTH(authentication), TAG_END());
1519
1520         return 0;
1521 }
1522
1523 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[])
1524 {
1525         #define NUTAG_WITH_THIS_MSG(msg) nutag_with, tag_ptr_v(msg)
1526         nua_saved_event_t saved[1];
1527         sip_contact_t const *contact = NULL;
1528         contact = sip->sip_contact;
1529         nua_save_event(nua, saved);
1530         nua_event_data_t const *data = nua_event_data(saved);
1531
1532         if (contact->m_url->url_host)
1533                 SCPY(inst->remote_peer, contact->m_url->url_host);
1534         if (contact->m_url->url_port && contact->m_url->url_port[0]) {
1535                 SCAT(inst->remote_peer, ":");
1536                 SCAT(inst->remote_peer, contact->m_url->url_port);
1537         }
1538
1539         sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_IN);
1540         add_trace("contact", "uri", "%s", inst->remote_peer);
1541         end_trace();
1542
1543         sip_trace_header(NULL, inst->interface_name, "RESPOND", DIRECTION_OUT);
1544         add_trace("respond", "value", "200 OK");
1545         add_trace("reason", NULL, "peer registered");
1546         end_trace();
1547
1548         nua_respond(nh, SIP_200_OK, SIPTAG_CONTACT(sip->sip_contact), NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1549         nua_handle_destroy(nh);
1550         inst->register_handle = NULL;
1551 }
1552
1553 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[])
1554 {
1555         int rc;
1556
1557         sip_trace_header(NULL, inst->interface_name, "STATUS", DIRECTION_IN);
1558         add_trace("value", NULL, "%d", status);
1559         add_trace("phrase", NULL, "%s", phrase);
1560         end_trace();
1561
1562         switch (status) {
1563         case 200:
1564                 status_200:
1565                 /* if not registered, become registered and start register interval timer */
1566                 if (inst->register_state != REGISTER_STATE_REGISTERED) {
1567                         if (inst->register_interval)
1568                                 schedule_timer(&inst->register_retry_timer, inst->register_interval, 0);
1569                         inst->register_state = REGISTER_STATE_REGISTERED;
1570                 }
1571                 /* start option timer */
1572                 if (inst->options_interval)
1573                         schedule_timer(&inst->register_option_timer, inst->options_interval, 0);
1574                 break;
1575         case 401:
1576         case 407:
1577                 PDEBUG(DEBUG_SIP, "Register challenge received\n");
1578                 rc = challenge(inst, NULL, status, phrase, nua, magic, nh, hmagic, sip, tags);
1579                 if (rc < 0)
1580                         goto status_400;
1581                 break;
1582         default:
1583                 if (status >= 200 && status <= 299)
1584                         goto status_200;
1585                 if (status < 400)
1586                         break;
1587                 status_400:
1588                 PDEBUG(DEBUG_SIP, "Register failed, starting register timer\n");
1589                 inst->register_state = REGISTER_STATE_FAILED;
1590                 nua_handle_destroy(nh);
1591                 inst->register_handle = NULL;
1592                 /* stop option timer */
1593                 unsched_timer(&inst->register_option_timer);
1594                 /* if failed, start register interval timer with REGISTER_RETRY_TIMER */
1595                 schedule_timer(&inst->register_retry_timer, REGISTER_RETRY_TIMER);
1596         }
1597 }
1598
1599 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[])
1600 {
1601         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1602         const char *from = "", *to = "", *name = "";
1603         char imsi[16] = "";
1604         int ret;
1605         class Endpoint *epoint;
1606         struct lcr_msg *message;
1607         struct interface *interface;
1608         int media_types[32];
1609         uint8_t payload_types[32];
1610         int payloads = 0;
1611         int media_type;
1612
1613         interface = getinterfacebyname(inst->interface_name);
1614         if (!interface) {
1615                 PERROR("Cannot find interface %s.\n", inst->interface_name);
1616                 return;
1617         }
1618
1619         if (p_state != PORT_STATE_IDLE) {
1620                 sip_trace_header(this, inst->interface_name, "RE-INVITE", DIRECTION_IN);
1621                 end_trace();
1622                 nua_respond(p_s_handle, SIP_200_OK,
1623                         NUTAG_MEDIA_ENABLE(0),
1624                         TAG_END());
1625                 return;
1626         }
1627
1628         if (sip->sip_from) {
1629                 if (sip->sip_from->a_url)
1630                         from = sip->sip_from->a_url->url_user;
1631                 if (sip->sip_from->a_display) {
1632                         name = sip->sip_from->a_display;
1633                         if (!strncmp(name, "\"IMSI", 5)) {
1634                                 strncpy(imsi, name + 5, 15);
1635                                 imsi[15] = '\0';
1636                                 name = "";
1637                         }
1638                 }
1639         }
1640         if (sip->sip_to) {
1641                 if (sip->sip_to->a_url)
1642                         to = sip->sip_to->a_url->url_user;
1643         }
1644         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1645
1646         sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
1647         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1648         if (!ret) {
1649                 /* if no RTP bridge, we must support LAW codec, otherwise we forward what we have */
1650                 if (!p_s_rtp_bridge) {
1651                         int i;
1652
1653                         /* check if supported payload type exists */
1654                         for (i = 0; i < payloads; i++) {
1655                                 if (media_types[i] == ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW))
1656                                         break;
1657                         }
1658                         if (i == payloads) {
1659                                 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1660                                 ret = 415;
1661                         }
1662                 }
1663         }
1664         end_trace();
1665         if (ret) {
1666                 if (ret == 400)
1667                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1668                 else
1669                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1670                 nua_handle_destroy(nh);
1671                 p_s_handle = NULL;
1672                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1673                 if (ret == 400)
1674                         add_trace("respond", "value", "415 Unsupported Media");
1675                 else
1676                         add_trace("respond", "value", "400 Bad Request");
1677                 add_trace("reason", NULL, "offered codec does not match");
1678                 end_trace();
1679                 new_state(PORT_STATE_RELEASE);
1680                 trigger_work(&p_s_delete);
1681                 return;
1682         }
1683
1684         /* open local RTP peer (if not bridging) */
1685         if (!p_s_rtp_bridge && rtp_open() < 0) {
1686                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1687                 nua_handle_destroy(nh);
1688                 p_s_handle = NULL;
1689                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1690                 add_trace("respond", "value", "500 Internal Server Error");
1691                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1692                 end_trace();
1693                 new_state(PORT_STATE_RELEASE);
1694                 trigger_work(&p_s_delete);
1695                 return;
1696         }
1697
1698         /* apply handle */
1699 //      sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1700 //      add_trace("handle", "new", "0x%x", nh);
1701 //      end_trace();
1702 //
1703         p_s_handle = nh;
1704
1705         sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_IN);
1706         add_trace("rtp", "port", "%d", p_s_rtp_port_remote);
1707         /* caller information */
1708         if (!from[0]) {
1709                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1710                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1711                 add_trace("calling", "present", "unavailable");
1712         } else {
1713                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1714                 add_trace("calling", "present", "allowed");
1715                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1716                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1717                 SCPY(p_callerinfo.id, from);
1718                 add_trace("calling", "number", "%s", from);
1719                 SCPY(p_callerinfo.name, name);
1720                 if (name[0])
1721                         add_trace("calling", "name", "%s", name);
1722                 SCPY(p_callerinfo.imsi, imsi);
1723                 if (imsi[0])
1724                         add_trace("calling", "imsi", "%s", imsi);
1725         }
1726         SCPY(p_callerinfo.interface, inst->interface_name);
1727         /* dialing information */
1728         if (to[0]) {
1729                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1730                 SCAT(p_dialinginfo.id, to);
1731                 add_trace("dialing", "number", "%s", to);
1732         }
1733         /* redir info */
1734         /* bearer capability */
1735         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1736         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1737         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1738         add_trace("bearer", "capa", "speech");
1739         add_trace("bearer", "mode", "circuit");
1740         /* if packet mode works some day, see dss1.cpp for conditions */
1741         p_capainfo.source_mode = B_MODE_TRANSPARENT;
1742
1743         end_trace();
1744
1745         /* create endpoint */
1746         if (p_epointlist)
1747                 FATAL("Incoming call but already got an endpoint.\n");
1748         if (!(epoint = new Endpoint(p_serial, 0)))
1749                 FATAL("No memory for Endpoint instance\n");
1750         epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
1751         epointlist_new(epoint->ep_serial);
1752
1753 #ifdef NUTAG_AUTO100
1754         /* send trying (proceeding) */
1755         nua_respond(nh, SIP_100_TRYING, TAG_END());
1756         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1757         add_trace("respond", "value", "100 Trying");
1758         end_trace();
1759 #endif
1760
1761         new_state(PORT_STATE_IN_PROCEEDING);
1762
1763         /* send setup message to endpoit */
1764         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
1765         message->param.setup.port_type = p_type;
1766 //      message->param.setup.dtmf = 0;
1767         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
1768         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
1769         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
1770 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
1771 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
1772 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
1773         if (p_s_rtp_bridge) {
1774                 int i;
1775
1776                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
1777                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
1778                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
1779                 /* add codecs to setup message */
1780                 for (i = 0; i < payloads; i++) {
1781                         message->param.setup.rtpinfo.media_types[i] = media_types[i];
1782                         message->param.setup.rtpinfo.payload_types[i] = payload_types[i];
1783                         if (i == sizeof(message->param.setup.rtpinfo.payload_types))
1784                                 break;
1785                 }
1786                 message->param.setup.rtpinfo.payloads = i;
1787         }
1788         message_put(message);
1789
1790         PDEBUG(DEBUG_SIP, "Invite received, scheduling option timer\n");
1791         /* start option timer */
1792         if (inst->options_interval)
1793                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
1794         p_s_invite_direction = DIRECTION_IN;
1795
1796         /* send progress, if tones are available and if we don't bridge */
1797         if (!p_s_rtp_bridge && interface->is_tones == IS_YES) {
1798                 char sdp_str[256];
1799                 struct in_addr ia;
1800                 unsigned char payload_type;
1801
1802                 PDEBUG(DEBUG_SIP, "Connecting audio, since we have tones available\n");
1803                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1804                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1805                 /* open local RTP peer (if not bridging) */
1806                 if (rtp_connect() < 0) {
1807                         nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1808                         nua_handle_destroy(nh);
1809                         p_s_handle = NULL;
1810                         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1811                         add_trace("respond", "value", "500 Internal Server Error");
1812                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
1813                         end_trace();
1814                         new_state(PORT_STATE_RELEASE);
1815                         trigger_work(&p_s_delete);
1816                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1817                         message->param.disconnectinfo.cause = 41;
1818                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1819                         message_put(message);
1820                         new_state(PORT_STATE_RELEASE);
1821                         trigger_work(&p_s_delete);
1822                         return;
1823                 }
1824
1825                 memset(&ia, 0, sizeof(ia));
1826                 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1827                 SPRINT(sdp_str,
1828                         "v=0\r\n"
1829                         "o=LCR-Sofia-SIP 0 0 IN IP4 %s\r\n"
1830                         "s=SIP Call\r\n"
1831                         "c=IN IP4 %s\r\n"
1832                         "t=0 0\r\n"
1833                         "m=audio %d RTP/AVP %d\r\n"
1834                         "a=rtpmap:%d %s/8000\r\n"
1835                         , inet_ntoa(ia), inet_ntoa(ia), p_s_rtp_port_local, payload_type, payload_type, media_type2name(media_type));
1836                 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1837
1838                 nua_respond(p_s_handle, SIP_183_SESSION_PROGRESS,
1839                         NUTAG_MEDIA_ENABLE(0),
1840                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1841                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1842                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1843                 add_trace("respond", "value", "183 SESSION PROGRESS");
1844                 add_trace("reason", NULL, "audio available");
1845                 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1846                 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1847                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
1848                 end_trace();
1849         }
1850 }
1851
1852 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[])
1853 {
1854         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1855         struct lcr_msg *message;
1856         int cause = 0;
1857
1858         PDEBUG(DEBUG_SIP, "bye received\n");
1859
1860         sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_IN);
1861         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
1862                 cause = atoi(sip->sip_reason->re_cause);
1863                 add_trace("cause", "value", "%d", cause);
1864         }
1865         end_trace();
1866
1867 // let stack do bye automaticall, since it will not accept our response for some reason
1868 //      nua_respond(nh, SIP_200_OK, TAG_END());
1869         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1870         add_trace("respond", "value", "200 OK");
1871         end_trace();
1872 //      nua_handle_destroy(nh);
1873         p_s_handle = NULL;
1874
1875         rtp_close();
1876
1877         while(p_epointlist) {
1878                 /* send setup message to endpoit */
1879                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1880                 message->param.disconnectinfo.cause = cause ? : 16;
1881                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1882                 message_put(message);
1883                 /* remove epoint */
1884                 free_epointlist(p_epointlist);
1885         }
1886         new_state(PORT_STATE_RELEASE);
1887         trigger_work(&p_s_delete);
1888 }
1889
1890 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[])
1891 {
1892         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1893         struct lcr_msg *message;
1894
1895         PDEBUG(DEBUG_SIP, "cancel received\n");
1896
1897         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_IN);
1898         end_trace();
1899
1900         nua_handle_destroy(nh);
1901         p_s_handle = NULL;
1902
1903         rtp_close();
1904
1905         while(p_epointlist) {
1906                 /* send setup message to endpoit */
1907                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1908                 message->param.disconnectinfo.cause = 16;
1909                 message->param.disconnectinfo.location = LOCATION_BEYOND;
1910                 message_put(message);
1911                 /* remove epoint */
1912                 free_epointlist(p_epointlist);
1913         }
1914         new_state(PORT_STATE_RELEASE);
1915         trigger_work(&p_s_delete);
1916 }
1917
1918 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[])
1919 {
1920         PDEBUG(DEBUG_SIP, "bye response received\n");
1921
1922         nua_handle_destroy(nh);
1923         p_s_handle = NULL;
1924
1925         rtp_close();
1926
1927         trigger_work(&p_s_delete);
1928 }
1929
1930 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[])
1931 {
1932         PDEBUG(DEBUG_SIP, "cancel response received\n");
1933
1934         nua_handle_destroy(nh);
1935         p_s_handle = NULL;
1936
1937         rtp_close();
1938
1939         trigger_work(&p_s_delete);
1940 }
1941
1942 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[])
1943 {
1944         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1945         struct lcr_msg *message;
1946         int cause = 0, location = 0;
1947         int media_types[32];
1948         uint8_t payload_types[32];
1949         int payloads = 0;
1950
1951         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
1952
1953         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1954         add_trace("respond", "value", "%d", status);
1955         end_trace();
1956
1957         /* connect audio */
1958         if (status == 183 || (status >= 200 && status <= 299)) {
1959                 int ret;
1960
1961                 sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
1962                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1963                 if (!ret) {
1964                         if (payloads != 1)
1965                                 ret = 415;
1966                         else if (!p_s_rtp_bridge) {
1967                                 if (media_types[0] != ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW)) {
1968                                         add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1969                                         ret = 415;
1970                                 }
1971                         }
1972                 }
1973                 end_trace();
1974                 if (ret) {
1975                         nua_cancel(nh, TAG_END());
1976                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
1977                         add_trace("reason", NULL, "accepted codec does not match");
1978                         end_trace();
1979                         cause = 88;
1980                         location = LOCATION_PRIVATE_LOCAL;
1981                         goto release_with_cause;
1982                 }
1983
1984                 /* connect to remote RTP (if not bridging) */
1985                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
1986                         nua_cancel(nh, TAG_END());
1987                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
1988                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1989                         end_trace();
1990                         cause = 31;
1991                         location = LOCATION_PRIVATE_LOCAL;
1992                         goto release_with_cause;
1993                 }
1994         }
1995
1996         PDEBUG(DEBUG_SIP, "Invite response, scheduling option timer\n");
1997         /* start option timer */
1998         if (inst->options_interval)
1999                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2000
2001         switch (status) {
2002         case 100:
2003 #if 0
2004                 PDEBUG(DEBUG_SIP, "do proceeding\n");
2005                 new_state(PORT_STATE_OUT_PROCEEDING);
2006                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
2007                 message_put(message);
2008 #endif
2009                 return;
2010         case 180:
2011                 PDEBUG(DEBUG_SIP, "do alerting\n");
2012                 new_state(PORT_STATE_OUT_ALERTING);
2013                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
2014                 message_put(message);
2015                 return;
2016         case 183:
2017                 PDEBUG(DEBUG_SIP, "do progress\n");
2018                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
2019                 message->param.progressinfo.progress = 8;
2020                 message->param.progressinfo.location = 10;
2021                 if (p_s_rtp_bridge) {
2022                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2023                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
2024                         message->param.progressinfo.rtpinfo.media_types[0] = media_types[0];
2025                         message->param.progressinfo.rtpinfo.payload_types[0] = payload_types[0];
2026                         message->param.progressinfo.rtpinfo.payloads = 1;
2027                 }
2028                 message_put(message);
2029                 return;
2030         case 200:
2031                 status_200:
2032                 PDEBUG(DEBUG_SIP, "do connect\n");
2033                 nua_ack(nh, TAG_END());
2034                 new_state(PORT_STATE_CONNECT);
2035                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
2036                 if (p_s_rtp_bridge) {
2037                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2038                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
2039                         message->param.connectinfo.rtpinfo.media_types[0] = media_types[0];
2040                         message->param.connectinfo.rtpinfo.payload_types[0] = payload_types[0];
2041                         message->param.connectinfo.rtpinfo.payloads = 1;
2042                 }
2043                 message_put(message);
2044                 return;
2045         default:
2046                 if (status >= 200 && status <= 299)
2047                         goto status_200;
2048                 if (status < 100 || status > 199)
2049                         break;
2050                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
2051
2052                 return;
2053         }
2054
2055         cause = status2cause(status);
2056         location = LOCATION_BEYOND;
2057
2058 release_with_cause:
2059         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
2060
2061         while(p_epointlist) {
2062                 /* send setup message to endpoit */
2063                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2064                 message->param.disconnectinfo.cause = cause;
2065                 message->param.disconnectinfo.location = location;
2066                 message_put(message);
2067                 /* remove epoint */
2068                 free_epointlist(p_epointlist);
2069         }
2070
2071         new_state(PORT_STATE_RELEASE);
2072
2073         rtp_close();
2074
2075         trigger_work(&p_s_delete);
2076 }
2077
2078 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[])
2079 {
2080         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2081         int cause = 0, location = 0;
2082         struct lcr_msg *message;
2083
2084         PDEBUG(DEBUG_SIP, "options result %d received\n", status);
2085
2086         if (status >= 200 && status <= 299) {
2087                 PDEBUG(DEBUG_SIP, "options ok, scheduling timer\n");
2088                 /* restart option timer */
2089                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2090                 return;
2091         }
2092
2093         nua_handle_destroy(nh);
2094         p_s_handle = NULL;
2095
2096         rtp_close();
2097
2098         cause = status2cause(status);
2099         location = LOCATION_BEYOND;
2100
2101         while(p_epointlist) {
2102                 /* send setup message to endpoit */
2103                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2104                 message->param.disconnectinfo.cause = cause;
2105                 message->param.disconnectinfo.location = location;
2106                 message_put(message);
2107                 /* remove epoint */
2108                 free_epointlist(p_epointlist);
2109         }
2110         new_state(PORT_STATE_RELEASE);
2111         trigger_work(&p_s_delete);
2112 }
2113
2114 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[])
2115 {
2116         struct sip_inst *inst = (struct sip_inst *) magic;
2117         class Port *port;
2118         class Psip *psip = NULL;
2119         int rc;
2120
2121         PDEBUG(DEBUG_SIP, "Event %d from SIP stack received (handle=%p)\n", event, nh);
2122         if (!nh)
2123                 return;
2124
2125         /* hunt for existing handles */
2126         port = port_first;
2127         while(port) {
2128                 if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
2129                         psip = (class Psip *)port;
2130                         if (psip->p_s_handle == nh) {
2131                                 break;
2132                         }
2133                 }
2134                 port = port->next;
2135         }
2136         if (!port)
2137                 psip = NULL;
2138
2139         /* new handle */
2140         if (!psip && inst->register_handle != nh) {
2141                 switch (event) {
2142                 case nua_i_register:
2143                         PDEBUG(DEBUG_SIP, "New register instance\n");
2144                         inst->register_handle = nh;
2145                         break;
2146                 case nua_i_invite:
2147                     {
2148                         char name[64];
2149                         struct interface *interface = interface_first;
2150
2151                         PDEBUG(DEBUG_SIP, "New psip instance\n");
2152
2153                         /* create call instance */
2154                         SPRINT(name, "%s-%d-in", inst->interface_name, 0);
2155                         while (interface) {
2156                                 if (!strcmp(interface->name, inst->interface_name))
2157                                         break;
2158                                 interface = interface->next;
2159                         }
2160                         if (!interface) {
2161                                 PERROR("Cannot find interface %s.\n", inst->interface_name);
2162                                 return;
2163                         }
2164                         if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
2165                                 FATAL("Cannot create Port instance.\n");
2166                         break;
2167                     }
2168                 default:
2169                         PDEBUG(DEBUG_SIP, "Destroying unknown instance\n");
2170                         nua_handle_destroy(nh);
2171                 }
2172         }
2173
2174         /* handle register process */
2175         if (inst->register_handle == nh) {
2176                 switch (event) {
2177                 case nua_i_register:
2178                         i_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2179                         break;
2180                 case nua_r_register:
2181                         r_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2182                         break;
2183                 default:
2184                         PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2185                 }
2186                 return;
2187         }
2188
2189         /* handle port process */
2190         if (!psip) {
2191                 PERROR("no SIP Port found for handel %p\n", nh);
2192                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2193                 nua_handle_destroy(nh);
2194                 return;
2195         }
2196
2197         if (status) {
2198                 sip_trace_header(psip, inst->interface_name, "STATUS", DIRECTION_OUT);
2199                 add_trace("value", NULL, "%d", status);
2200                 add_trace("phrase", NULL, "%s", phrase);
2201                 end_trace();
2202         }
2203
2204         switch (status) {
2205         case 401:
2206         case 407:
2207                 rc = challenge(inst, psip, status, phrase, nua, magic, nh, hmagic, sip, tags);
2208                 if (rc >= 0)
2209                         return;
2210         }
2211
2212         switch (event) {
2213         case nua_r_set_params:
2214                 PDEBUG(DEBUG_SIP, "setparam response\n");
2215                 break;
2216         case nua_r_options:
2217                 psip->r_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2218                 break;
2219         case nua_i_error:
2220                 PDEBUG(DEBUG_SIP, "error received\n");
2221                 break;
2222         case nua_i_state:
2223                 PDEBUG(DEBUG_SIP, "state change received\n");
2224                 break;
2225         case nua_i_invite:
2226                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2227                 break;
2228         case nua_i_ack:
2229                 PDEBUG(DEBUG_SIP, "ack received\n");
2230                 break;
2231         case nua_i_active:
2232                 PDEBUG(DEBUG_SIP, "active received\n");
2233                 break;
2234         case nua_i_bye:
2235                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2236                 break;
2237         case nua_i_cancel:
2238                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2239                 break;
2240         case nua_r_bye:
2241                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2242                 break;
2243         case nua_r_cancel:
2244                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2245                 break;
2246         case nua_r_invite:
2247                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2248                 break;
2249         case nua_i_terminated:
2250                 PDEBUG(DEBUG_SIP, "terminated received\n");
2251                 break;
2252         default:
2253                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2254         }
2255 }
2256
2257 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)
2258 {
2259         struct sip_inst *inst = (struct sip_inst *) magic;
2260         su_sockaddr_t sa;
2261         socklen_t addrlen;
2262
2263         PDEBUG(DEBUG_SIP, "Event %d from STUN stack received\n", event);
2264
2265         switch (event) {
2266         case stun_discovery_done:
2267                 addrlen = sizeof(sa);
2268                 memset(&sa, 0, addrlen);
2269                 if (stun_discovery_get_address(sd, &sa, &addrlen) < 0) {
2270                         PDEBUG(DEBUG_SIP, "stun_discovery_get_address failed\n");
2271                         goto failed;
2272                 }
2273                 su_inet_ntop(sa.su_family, SU_ADDR(&sa), inst->public_ip, sizeof(inst->public_ip));
2274                 inst->stun_state = STUN_STATE_RESOLVED;
2275                 /* start timer for next stun request with inst->stun_interval */
2276                 schedule_timer(&inst->stun_retry_timer, inst->stun_interval, 0);
2277                 sip_trace_header(NULL, inst->interface_name, "STUN resolved", DIRECTION_OUT);
2278                 add_trace("ip", "addr", "%s", inst->public_ip);
2279                 end_trace();
2280                 break;
2281         default:
2282 failed:
2283                 PDEBUG(DEBUG_SIP, "STUN failed, starting timer\n");
2284                 inst->stun_state = STUN_STATE_FAILED;
2285                 /* start timer for next stun request (after failing) with STUN_RETRY_TIMER */
2286                 schedule_timer(&inst->stun_retry_timer, STUN_RETRY_TIMER);
2287                 sip_trace_header(NULL, inst->interface_name, "STUN failed", DIRECTION_OUT);
2288                 end_trace();
2289         }
2290 }
2291
2292 /* received shutdown due to termination of RTP */
2293 void Psip::rtp_shutdown(void)
2294 {
2295         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2296         struct lcr_msg *message;
2297
2298         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
2299
2300         sip_trace_header(this, inst->interface_name, "RTP terminated", DIRECTION_IN);
2301         end_trace();
2302
2303         nua_handle_destroy(p_s_handle);
2304         p_s_handle = NULL;
2305
2306         while(p_epointlist) {
2307                 /* send setup message to endpoit */
2308                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2309                 message->param.disconnectinfo.cause = 16;
2310                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2311                 message_put(message);
2312                 /* remove epoint */
2313                 free_epointlist(p_epointlist);
2314         }
2315         new_state(PORT_STATE_RELEASE);
2316         trigger_work(&p_s_delete);
2317 }
2318
2319 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index)
2320 {
2321         class Psip *psip = (class Psip *)instance;
2322         struct sip_inst *inst = (struct sip_inst *) psip->p_s_sip_inst;
2323
2324         sip_trace_header(psip, inst->interface_name, "OPTIONS", psip->p_s_invite_direction);
2325         end_trace();
2326
2327         nua_options(psip->p_s_handle,
2328                 TAG_END());
2329
2330         return 0;
2331 }
2332
2333 static int stun_retry_timer(struct lcr_timer *timer, void *instance, int index)
2334 {
2335         struct sip_inst *inst = (struct sip_inst *)instance;
2336
2337         PDEBUG(DEBUG_SIP, "timeout, restart stun lookup\n");
2338         inst->stun_state = STUN_STATE_UNRESOLVED;
2339
2340         return 0;
2341 }
2342
2343 static int register_retry_timer(struct lcr_timer *timer, void *instance, int index)
2344 {
2345         struct sip_inst *inst = (struct sip_inst *)instance;
2346
2347         PDEBUG(DEBUG_SIP, "timeout, restart register\n");
2348         /* if we have a handle, destroy it and becom unregistered, so registration is
2349          * triggered next */
2350         if (inst->register_handle) {
2351                 /* stop option timer */
2352                 unsched_timer(&inst->register_option_timer);
2353                 nua_handle_destroy(inst->register_handle);
2354                 inst->register_handle = NULL;
2355         }
2356         inst->register_state = REGISTER_STATE_UNREGISTERED;
2357
2358         return 0;
2359 }
2360
2361 static int register_option_timer(struct lcr_timer *timer, void *instance, int index)
2362 {
2363         struct sip_inst *inst = (struct sip_inst *)instance;
2364         sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_OUT);
2365         end_trace();
2366
2367         nua_options(inst->register_handle,
2368                 TAG_END());
2369
2370         return 0;
2371 }
2372
2373 int sip_init_inst(struct interface *interface)
2374 {
2375         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
2376         char local[256];
2377
2378         interface->sip_inst = inst;
2379         SCPY(inst->interface_name, interface->name);
2380         SCPY(inst->local_peer, interface->sip_local_peer);
2381         SCPY(inst->remote_peer, interface->sip_remote_peer);
2382         SCPY(inst->asserted_id, interface->sip_asserted_id);
2383         if (interface->sip_register) {
2384                 inst->register_state = REGISTER_STATE_UNREGISTERED;
2385                 SCPY(inst->register_user, interface->sip_register_user);
2386                 SCPY(inst->register_host, interface->sip_register_host);
2387         }
2388         SCPY(inst->auth_user, interface->sip_auth_user);
2389         SCPY(inst->auth_password, interface->sip_auth_password);
2390         inst->register_interval = interface->sip_register_interval;
2391         inst->options_interval = interface->sip_options_interval;
2392
2393         inst->rtp_port_from = interface->rtp_port_from;
2394         inst->rtp_port_to = interface->rtp_port_to;
2395         if (!inst->rtp_port_from || !inst->rtp_port_to) {
2396                 inst->rtp_port_from = RTP_PORT_BASE;
2397                 inst->rtp_port_to = RTP_PORT_MAX;
2398         }
2399         inst->next_rtp_port = inst->rtp_port_from;
2400
2401         /* create timers */
2402         memset(&inst->stun_retry_timer, 0, sizeof(inst->stun_retry_timer));
2403         add_timer(&inst->stun_retry_timer, stun_retry_timer, inst, 0);
2404         memset(&inst->register_retry_timer, 0, sizeof(inst->register_retry_timer));
2405         add_timer(&inst->register_retry_timer, register_retry_timer, inst, 0);
2406         memset(&inst->register_option_timer, 0, sizeof(inst->register_option_timer));
2407         add_timer(&inst->register_option_timer, register_option_timer, inst, 0);
2408
2409         /* init root object */
2410         inst->root = su_root_create(inst);
2411         if (!inst->root) {
2412                 PERROR("Failed to create SIP root\n");
2413                 sip_exit_inst(interface);
2414                 return -EINVAL;
2415         }
2416
2417         SPRINT(local, "sip:%s",inst->local_peer);
2418         if (!strchr(inst->local_peer, ':'))
2419                 SCAT(local, ":5060");
2420         inst->nua = nua_create(inst->root, sip_callback, inst, NUTAG_URL(local), TAG_END());
2421         if (!inst->nua) {
2422                 PERROR("Failed to create SIP stack object\n");
2423                 sip_exit_inst(interface);
2424                 return -EINVAL;
2425         }
2426         nua_set_params(inst->nua,
2427                 SIPTAG_ALLOW_STR("REGISTER,INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
2428                 NUTAG_APPL_METHOD("REGISTER"),
2429                 NUTAG_APPL_METHOD("INVITE"),
2430                 NUTAG_APPL_METHOD("ACK"),
2431 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
2432                 NUTAG_APPL_METHOD("CANCEL"),
2433                 NUTAG_APPL_METHOD("OPTIONS"),
2434                 NUTAG_APPL_METHOD("NOTIFY"),
2435                 NUTAG_APPL_METHOD("INFO"),
2436                 NUTAG_AUTOACK(0),
2437 #ifdef NUTAG_AUTO100
2438                 NUTAG_AUTO100(0),
2439 #endif
2440                 NUTAG_AUTOALERT(0),
2441                 NUTAG_AUTOANSWER(0),
2442                 TAG_NULL());
2443
2444         SCPY(inst->public_ip, interface->sip_public_ip);
2445         if (interface->sip_stun_server[0]) {
2446 #if 0
2447                 inst->stun_root = su_root_create(inst);
2448                 if (!inst->stun_root) {
2449                         PERROR("Failed to create STUN root\n");
2450                         sip_exit_inst(interface);
2451                         return -EINVAL;
2452                 }
2453                 auch im exit
2454 #endif
2455                 SCPY(inst->stun_server, interface->sip_stun_server);
2456                 inst->stun_interval = interface->sip_stun_interval;
2457                 inst->stun_handle = stun_handle_init(inst->root,
2458                         STUNTAG_SERVER(inst->stun_server),
2459                         TAG_NULL());
2460                 if (!inst->stun_handle) {
2461                         PERROR("Failed to create STUN handle\n");
2462                         sip_exit_inst(interface);
2463                         return -EINVAL;
2464                 }
2465                 inst->stun_socket = su_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
2466                 if (inst->stun_socket < 0) {
2467                         PERROR("Failed to create STUN socket\n");
2468                         sip_exit_inst(interface);
2469                         return -EINVAL;
2470                 }
2471                 inst->stun_state = STUN_STATE_UNRESOLVED;
2472         }
2473
2474         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
2475
2476         any_sip_interface = 1;
2477
2478         return 0;
2479 }
2480
2481 void sip_exit_inst(struct interface *interface)
2482 {
2483         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
2484
2485         if (!inst)
2486                 return;
2487         del_timer(&inst->stun_retry_timer);
2488         del_timer(&inst->register_retry_timer);
2489         del_timer(&inst->register_option_timer);
2490         if (inst->stun_socket)
2491                 su_close(inst->stun_socket);
2492         if (inst->stun_handle)
2493                 stun_handle_destroy(inst->stun_handle);
2494         if (inst->register_handle)
2495                 nua_handle_destroy(inst->register_handle);
2496         if (inst->root)
2497                 su_root_destroy(inst->root);
2498         if (inst->nua)
2499                 nua_destroy(inst->nua);
2500         FREE(inst, sizeof(*inst));
2501         interface->sip_inst = NULL;
2502
2503         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
2504
2505         /* check if there is any other SIP interface left */
2506         interface = interface_first;
2507         while (interface) {
2508                 if (interface->sip_inst)
2509                         break;
2510                 interface = interface->next;
2511         }
2512         if (!interface)
2513                 any_sip_interface = 0;
2514 }
2515
2516 extern su_log_t su_log_default[];
2517 extern su_log_t nua_log[];
2518 //extern su_log_t soa_log[];
2519
2520 int sip_init(void)
2521 {
2522         int i;
2523
2524         /* init SOFIA lib */
2525         su_init();
2526         su_home_init(sip_home);
2527
2528         if (options.deb & DEBUG_SIP) {
2529                 su_log_set_level(su_log_default, 9);
2530                 su_log_set_level(nua_log, 9);
2531                 //su_log_set_level(soa_log, 9);
2532         }
2533
2534         for (i = 0; i < 256; i++)
2535                 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);
2536
2537         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
2538
2539         return 0;
2540 }
2541
2542 void sip_exit(void)
2543 {
2544         su_home_deinit(sip_home);
2545         su_deinit();
2546
2547         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
2548 }
2549
2550 static void sip_handle_stun(struct sip_inst *inst)
2551 {
2552         int rc;
2553
2554         switch (inst->stun_state) {
2555         case STUN_STATE_UNRESOLVED:
2556                 PDEBUG(DEBUG_SIP, "Trying to to get local IP from stun server\n");
2557                 rc = stun_bind(inst->stun_handle, stun_bind_cb, (stun_discovery_magic_t *)inst,
2558                         STUNTAG_SOCKET(inst->stun_socket),
2559                         STUNTAG_REGISTER_EVENTS(1),
2560                         TAG_NULL());
2561                 if (rc < 0) {
2562                         PERROR("Failed to call stun_bind()\n");
2563                         inst->stun_state = STUN_STATE_FAILED;
2564                         break;
2565                 }
2566                 inst->stun_state = STUN_STATE_RESOLVING;
2567                 sip_trace_header(NULL, inst->interface_name, "STUN resolving", DIRECTION_OUT);
2568                 add_trace("server", "addr", "%s", inst->stun_server);
2569                 end_trace();
2570                 break;
2571         }
2572 }
2573
2574 static void sip_handle_register(struct sip_inst *inst)
2575 {
2576         char from[128] = "";
2577         char to[128] = "";
2578         char contact[128] = "";
2579
2580         switch (inst->register_state) {
2581         case REGISTER_STATE_UNREGISTERED:
2582                 /* wait for resoved stun */
2583                 if (inst->stun_handle && inst->stun_state != STUN_STATE_RESOLVED)
2584                         return;
2585
2586                 PDEBUG(DEBUG_SIP, "Registering to peer\n");
2587                 inst->register_handle = nua_handle(inst->nua, NULL, TAG_END());
2588                 if (!inst->register_handle) {
2589                         PERROR("Failed to create handle\n");
2590                         inst->register_state = REGISTER_STATE_FAILED;
2591                         break;
2592                 }
2593                 /* apply handle to trace */
2594 //              sip_trace_header(NULL, inst->interface_name, "NEW handle", DIRECTION_NONE);
2595 //              add_trace("handle", "new", "0x%x", inst->register_handle);
2596 //              end_trace();
2597
2598                 SPRINT(from, "sip:%s@%s", inst->register_user, inst->register_host);
2599                 SPRINT(to, "sip:%s@%s", inst->register_user, inst->register_host);
2600                 if (inst->public_ip[0])
2601                         SPRINT(contact, "sip:%s@%s", inst->register_user, inst->public_ip);
2602
2603                 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_OUT);
2604                 add_trace("from", "uri", "%s", from);
2605                 add_trace("to", "uri", "%s", to);
2606                 end_trace();
2607
2608                 nua_register(inst->register_handle,
2609                         TAG_IF(from[0], SIPTAG_FROM_STR(from)),
2610                         TAG_IF(to[0], SIPTAG_TO_STR(to)),
2611                         TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
2612                         TAG_END());
2613
2614                 inst->register_state = REGISTER_STATE_REGISTERING;
2615
2616                 break;
2617         }
2618         
2619 }
2620
2621 void sip_handle(void)
2622 {
2623         struct interface *interface = interface_first;
2624         struct sip_inst *inst;
2625
2626         while (interface) {
2627                 if (interface->sip_inst) {
2628                         inst = (struct sip_inst *) interface->sip_inst;
2629                         su_root_step(inst->root, 0);
2630                         sip_handle_stun(inst);
2631                         sip_handle_register(inst);
2632                 }
2633                 interface = interface->next;
2634         }
2635 }
2636
2637 /* deletes when back in event loop */
2638 static int delete_event(struct lcr_work *work, void *instance, int index)
2639 {
2640         class Psip *psip = (class Psip *)instance;
2641
2642         delete psip;
2643
2644         return 0;
2645 }
2646
2647
2648 /*
2649  * generate audio, if no data is received from bridge
2650  */
2651
2652 void Psip::set_tone(const char *dir, const char *tone)
2653 {
2654         Port::set_tone(dir, tone);
2655
2656         update_load();
2657 }
2658
2659 void Psip::update_load(void)
2660 {
2661         /* don't trigger load event if event already active */
2662         if (p_s_load_timer.active)
2663                 return;
2664
2665         /* don't start timer if ... */
2666         if (!p_tone_name[0] && !p_dov_tx)
2667                 return;
2668
2669         p_s_next_tv_sec = 0;
2670         schedule_timer(&p_s_load_timer, 0, 0); /* no delay the first time */
2671 }
2672
2673 static int load_timer(struct lcr_timer *timer, void *instance, int index)
2674 {
2675         class Psip *psip = (class Psip *)instance;
2676
2677         /* stop timer if ... */
2678         if (!psip->p_tone_name[0] && !psip->p_dov_tx)
2679                 return 0;
2680
2681         psip->load_tx();
2682
2683         return 0;
2684 }
2685
2686 #define SEND_SIP_LEN 160
2687
2688 void Psip::load_tx(void)
2689 {
2690         int diff;
2691         struct timeval current_time;
2692         int tosend = SEND_SIP_LEN, i;
2693         unsigned char buf[SEND_SIP_LEN], *p = buf;
2694
2695         /* get elapsed */
2696         gettimeofday(&current_time, NULL);
2697         if (!p_s_next_tv_sec) {
2698                 /* if timer expired the first time, set next expected timeout 160 samples in advance */
2699                 p_s_next_tv_sec = current_time.tv_sec;
2700                 p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2701                 if (p_s_next_tv_usec >= 1000000) {
2702                         p_s_next_tv_usec -= 1000000;
2703                         p_s_next_tv_sec++;
2704                 }
2705                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125);
2706         } else {
2707                 diff = 1000000 * (current_time.tv_sec - p_s_next_tv_sec)
2708                         + (current_time.tv_usec - p_s_next_tv_usec);
2709                 if (diff < -SEND_SIP_LEN * 125 || diff > SEND_SIP_LEN * 125) {
2710                         /* if clock drifts too much, set next timeout event to current timer + 160 */
2711                         diff = 0;
2712                         p_s_next_tv_sec = current_time.tv_sec;
2713                         p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2714                         if (p_s_next_tv_usec >= 1000000) {
2715                                 p_s_next_tv_usec -= 1000000;
2716                                 p_s_next_tv_sec++;
2717                         }
2718                 } else {
2719                         /* if diff is positive, it took too long, so next timeout will be earlier */
2720                         p_s_next_tv_usec += SEND_SIP_LEN * 125;
2721                         if (p_s_next_tv_usec >= 1000000) {
2722                                 p_s_next_tv_usec -= 1000000;
2723                                 p_s_next_tv_sec++;
2724                         }
2725                 }
2726                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125 - diff);
2727         }
2728
2729         /* copy tones */
2730         if (p_tone_name[0]) {
2731                 tosend -= read_audio(p, tosend);
2732         } else
2733         if (p_dov_tx) {
2734                 tosend -= dov_tx(p, tosend);
2735         }
2736         if (tosend) {
2737                 PERROR("buffer is not completely filled\n");
2738                 return;
2739         }
2740
2741         p = buf;
2742         for (i = 0; i < SEND_SIP_LEN; i++) {
2743                 *p = flip[*p];
2744                 p++;
2745         }
2746         /* transmit data via rtp */
2747         rtp_send_frame(buf, SEND_SIP_LEN, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
2748 }
2749
2750 #warning den source-port beim registrieren einstellen