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