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