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