fixup sip
[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         int                     options_interval;
68         char                    auth_user[128];
69         char                    auth_password[128];
70         char                    auth_realm[128];
71         char                    auth_nonce[128];
72         su_root_t               *root;
73         nua_t                   *nua;
74
75         char                    public_ip[128];
76         int                     stun_state;
77         char                    stun_server[128];
78         stun_handle_t           *stun_handle;
79         su_socket_t             stun_socket;
80         struct lcr_timer        stun_retry_timer;
81         int                     stun_interval;
82
83         unsigned short          rtp_port_from;
84         unsigned short          rtp_port_to;
85         unsigned short          next_rtp_port;
86
87 };
88
89 static int delete_event(struct lcr_work *work, void *instance, int index);
90 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index);
91 static int load_timer(struct lcr_timer *timer, void *instance, int index);
92
93 /*
94  * initialize SIP port
95  */
96 Psip::Psip(int type, char *portname, struct port_settings *settings, struct interface *interface) : Port(type, portname, settings, interface)
97 {
98         p_s_rtp_bridge = 0;
99         if (interface->rtp_bridge)
100                 p_s_rtp_bridge = 1;
101         p_s_sip_inst = interface->sip_inst;
102         memset(&p_s_delete, 0, sizeof(p_s_delete));
103         add_work(&p_s_delete, delete_event, this, 0);
104         p_s_handle = 0;
105         p_s_magic = 0;
106         memset(&p_s_auth_nonce, 0, sizeof(p_s_auth_nonce));
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, "First 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(to, "sip:%s@%s", p_dialinginfo.id, remote);
1291         if (inst->asserted_id[0]) {
1292                 SPRINT(asserted_id, "sip:%s@%s", inst->asserted_id, remote);
1293                 SPRINT(asserted_msg, "P-Asserted-Identity: <%s>", asserted_id);
1294         }
1295         if (inst->public_ip[0]) {
1296                 char *p;
1297                 SPRINT(contact, "sip:%s@%s", p_callerinfo.id, inst->public_ip);
1298                 p = strchr(inst->local_peer, ':');
1299                 if (p)
1300                         SCAT(contact, p);
1301         }
1302
1303         sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_OUT);
1304         add_trace("from", "uri", "%s", from);
1305         add_trace("to", "uri", "%s", to);
1306         if (asserted_id[0])
1307                 add_trace("assert-id", "uri", "%s", asserted_id);
1308         struct in_addr ia;
1309         memset(&ia, 0, sizeof(ia));
1310         ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1311         add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1312         add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1313         for (i = 0; i < payloads; i++)
1314                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_types[i]), payload_types[i]);
1315         end_trace();
1316
1317 //      cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
1318
1319         nua_invite(p_s_handle,
1320                 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1321                 TAG_IF(to[0], SIPTAG_TO_STR(to)),
1322                 TAG_IF(asserted_msg[0], SIPTAG_HEADER_STR(asserted_msg)),
1323                 TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
1324                 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1325                 NUTAG_MEDIA_ENABLE(0),
1326                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1327                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1328         new_state(PORT_STATE_OUT_SETUP);
1329
1330         p_s_invite_direction = DIRECTION_OUT;
1331
1332 #if 0
1333         PDEBUG(DEBUG_SIP, "do overlap\n");
1334         new_state(PORT_STATE_OUT_OVERLAP);
1335         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_OVERLAP);
1336         message_put(message);
1337 #else
1338         PDEBUG(DEBUG_SIP, "do proceeding\n");
1339         new_state(PORT_STATE_OUT_PROCEEDING);
1340         message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1341         message_put(message);
1342 #endif
1343
1344         /* attach only if not already */
1345         epointlist = p_epointlist;
1346         while(epointlist) {
1347                 if (epointlist->epoint_id == epoint_id)
1348                         break;
1349                 epointlist = epointlist->next;
1350         }
1351         if (!epointlist)
1352                 epointlist_new(epoint_id);
1353
1354         return 0;
1355 }
1356         
1357 int Psip::message_notify(unsigned int epoint_id, int message_id, union parameter *param)
1358 {
1359 //      char 
1360 //      struct in_addr ia;
1361
1362         switch (param->notifyinfo.notify) {
1363         case INFO_NOTIFY_REMOTE_HOLD:
1364 #if 0
1365                 sdp_str = generate_sdp(0, 0, 0, NULL, NULL);
1366                 SPRINT(sdp_str,
1367                         "v=0\r\n"
1368                         "o=LCR-Sofia-SIP 0 0 IN IP4 0.0.0.0\r\n"
1369                         "s=SIP Call\r\n"
1370                         "c=IN IP4 0.0.0.0\r\n"
1371                         "t=0 0\r\n"
1372                         );
1373                 PDEBUG(DEBUG_SIP, "Using SDP for hold: %s\n", sdp_str);
1374                 nua_info(p_s_handle,
1375 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1376 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1377 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1378                         NUTAG_MEDIA_ENABLE(0),
1379                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1380                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1381 #endif
1382                 break;
1383         case INFO_NOTIFY_REMOTE_RETRIEVAL:
1384 #if 0
1385                 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1386                 PDEBUG(DEBUG_SIP, "Using SDP for rertieve: %s\n", sdp_str);
1387                 nua_info(p_s_handle,
1388 //                      TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1389 //                      TAG_IF(to[0], SIPTAG_TO_STR(to)),
1390 //                      TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1391                         NUTAG_MEDIA_ENABLE(0),
1392                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1393                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1394 #endif
1395                 break;
1396         }
1397
1398         return 0;
1399 }
1400
1401 int Psip::message_dtmf(unsigned int epoint_id, int message_id, union parameter *param)
1402 {
1403         char dtmf_str[64];
1404         
1405         /* prepare DTMF info payload */
1406         SPRINT(dtmf_str,
1407                 "Signal=%c\n"
1408                 "Duration=160\n"
1409                 , param->dtmf);
1410
1411         /* start invite to handle DTMF */
1412         nua_info(p_s_handle,
1413                 NUTAG_MEDIA_ENABLE(0),
1414                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1415                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1416         
1417         return 0;
1418 }
1419
1420 /* NOTE: incomplete and not working */
1421 int Psip::message_information(unsigned int epoint_id, int message_id, union parameter *param)
1422 {
1423         char dtmf_str[64];
1424         
1425         /* prepare DTMF info payload */
1426         SPRINT(dtmf_str,
1427                 "Signal=%s\n"
1428                 "Duration=160\n"
1429                 , param->information.id);
1430
1431         /* start invite to handle DTMF */
1432         nua_info(p_s_handle,
1433                 NUTAG_MEDIA_ENABLE(0),
1434                 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1435                 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1436         
1437         return 0;
1438 }
1439
1440 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1441 {
1442         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1443
1444         if (Port::message_epoint(epoint_id, message_id, param))
1445                 return 1;
1446
1447         switch(message_id) {
1448                 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1449                 if (p_state != PORT_STATE_IN_SETUP
1450                  && p_state != PORT_STATE_IN_PROCEEDING)
1451                         return 0;
1452                 nua_respond(p_s_handle, SIP_180_RINGING, TAG_END());
1453                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1454                 add_trace("respond", "value", "180 Ringing");
1455                 end_trace();
1456                 new_state(PORT_STATE_IN_ALERTING);
1457                 return 1;
1458
1459                 case MESSAGE_CONNECT: /* call is connected on LCR side */
1460                 if (p_state != PORT_STATE_IN_SETUP
1461                  && p_state != PORT_STATE_IN_PROCEEDING
1462                  && p_state != PORT_STATE_IN_ALERTING)
1463                         return 0;
1464                 message_connect(epoint_id, message_id, param);
1465                 return 1;
1466
1467                 case MESSAGE_DISCONNECT: /* call has been disconnected */
1468                 case MESSAGE_RELEASE: /* call has been released */
1469                 message_release(epoint_id, message_id, param);
1470                 return 1;
1471
1472                 case MESSAGE_SETUP: /* dial-out command received from epoint */
1473                 message_setup(epoint_id, message_id, param);
1474                 return 1;
1475
1476                 case MESSAGE_INFORMATION: /* overlap dialing */
1477                 if (p_state != PORT_STATE_OUT_OVERLAP)
1478                         return 0;
1479                 message_information(epoint_id, message_id, param);
1480                 return 1;
1481
1482                 case MESSAGE_DTMF: /* DTMF info to be transmitted via INFO transaction */
1483                 if (p_state == PORT_STATE_CONNECT)
1484                         message_dtmf(epoint_id, message_id, param);
1485                 case MESSAGE_NOTIFY: /* notification about remote hold/retrieve */
1486                 if (p_state == PORT_STATE_CONNECT)
1487                         message_notify(epoint_id, message_id, param);
1488                 return(1);
1489
1490                 default:
1491                 PDEBUG(DEBUG_SIP, "PORT(%s) SIP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1492         }
1493
1494         return 0;
1495 }
1496
1497 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)
1498 {
1499         *payloads = 0;
1500
1501         if (!sip->sip_payload) {
1502                 PDEBUG(DEBUG_SIP, "no payload given\n");
1503                 return 0;
1504         }
1505
1506         sdp_parser_t *parser;
1507         sdp_session_t *sdp;
1508         sdp_media_t *m;
1509         sdp_attribute_t *attr;
1510         sdp_rtpmap_t *map;
1511         sdp_connection_t *conn;
1512
1513         PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1514
1515         parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1516         if (!parser) {
1517                 return 400;
1518         }
1519         if (!(sdp = sdp_session(parser))) {
1520                 sdp_parser_free(parser);
1521                 return 400;
1522         }
1523         for (m = sdp->sdp_media; m; m = m->m_next) {
1524                 if (m->m_proto != sdp_proto_rtp)
1525                         continue;
1526                 if (m->m_type != sdp_media_audio)
1527                         continue;
1528                 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1529                 *port = m->m_port;
1530                 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1531                         PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1532                 }
1533                 if (m->m_connections) {
1534                         conn = m->m_connections;
1535                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1536                         inet_pton(AF_INET, conn->c_address, ip);
1537                         *ip = ntohl(p_s_rtp_ip_remote);
1538                 } else {
1539                         char *p = sip->sip_payload->pl_data;
1540                         char addr[16];
1541
1542                         PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1543                         p = strstr(p, "c=IN IP4 ");
1544                         if (!p) {
1545                                 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1546                                 sdp_parser_free(parser);
1547                                 return 400;
1548                         }
1549                         SCPY(addr, p + 9);
1550                         if ((p = strchr(addr, '\n'))) *p = '\0';
1551                         if ((p = strchr(addr, '\r'))) *p = '\0';
1552                         PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1553                         inet_pton(AF_INET, addr, ip);
1554                         *ip = ntohl(p_s_rtp_ip_remote);
1555                 }
1556                 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1557                         int media_type = 0;
1558
1559                         PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d' pt='%d'\n", map->rm_encoding, map->rm_rate, map->rm_pt);
1560                         /* append to payload list, if there is space */
1561                         add_trace("rtp", "payload", "%s:%d", map->rm_encoding, map->rm_pt);
1562                         if (map->rm_pt == PAYLOAD_TYPE_ALAW)
1563                                 media_type = MEDIA_TYPE_ALAW;
1564                         else if (map->rm_pt == PAYLOAD_TYPE_ULAW)
1565                                 media_type = MEDIA_TYPE_ULAW;
1566                         else if (map->rm_pt == PAYLOAD_TYPE_GSM)
1567                                 media_type = MEDIA_TYPE_GSM;
1568                         else if (!strcmp(map->rm_encoding, "GSM-EFR"))
1569                                 media_type = MEDIA_TYPE_GSM_EFR;
1570                         else if (!strcmp(map->rm_encoding, "AMR"))
1571                                 media_type = MEDIA_TYPE_AMR;
1572                         else if (!strcmp(map->rm_encoding, "GSM-HR"))
1573                                 media_type = MEDIA_TYPE_GSM_HR;
1574                         if (media_type && *payloads <= max_payloads) {
1575                                 *payload_types++ = map->rm_pt;
1576                                 *media_types++ = media_type;
1577                                 (*payloads)++;
1578                         }
1579                 }
1580         }
1581
1582         sdp_parser_free(parser);
1583
1584         return 0;
1585 }
1586
1587 const char *Psip::generate_sdp(unsigned int rtp_ip_local, unsigned short rtp_port_local, int payloads, unsigned char *payload_types, int *media_types)
1588 {
1589         struct in_addr ia;
1590         static char sdp_str[256], sub_str[128];
1591         int i;
1592
1593         memset(&ia, 0, sizeof(ia));
1594         ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1595         SPRINT(sdp_str,
1596                 "v=0\r\n"
1597                 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\r\n"
1598                 "s=SIP Call\r\n"
1599                 "c=IN IP4 %s\r\n"
1600                 "t=0 0\r\n", inet_ntoa(ia), inet_ntoa(ia));
1601         if (payloads) {
1602                 SPRINT(sub_str, "m=audio %d RTP/AVP", p_s_rtp_port_local);
1603                 SCAT(sdp_str, sub_str);
1604                 for (i = 0; i < payloads; i++) {
1605                         SPRINT(sub_str, " %d", payload_types[i]);
1606                         SCAT(sdp_str, sub_str);
1607                 }
1608                 SCAT(sdp_str, "\r\n");
1609                 for (i = 0; i < payloads; i++) {
1610                         SPRINT(sub_str, "a=rtpmap:%d %s/8000\r\n", payload_types[i], media_type2name(media_types[i]));
1611                         SCAT(sdp_str, sub_str);
1612                 }
1613         }
1614
1615         return sdp_str;
1616 }
1617
1618 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[])
1619 {
1620         sip_www_authenticate_t const *authenticate = NULL;
1621         char const *realm = NULL;
1622         char const *scheme = NULL;
1623         int i;
1624         char *cur;
1625         char authentication[256] = "";
1626         PDEBUG(DEBUG_SIP, "challenge order received\n");
1627
1628         if (!inst->auth_user[0]) {
1629                 PDEBUG(DEBUG_SIP, "No credentials available\n");
1630                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1631                 add_trace("error", NULL, "There are no credentials given for interface");
1632                 end_trace();
1633                 return -1;
1634         }
1635
1636         if (sip->sip_www_authenticate) {
1637                 authenticate = sip->sip_www_authenticate;
1638         } else if (sip->sip_proxy_authenticate) {
1639                 authenticate = sip->sip_proxy_authenticate;
1640         } else {
1641                 PDEBUG(DEBUG_SIP, "No authentication header found\n");
1642                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1643                 add_trace("error", NULL, "Authentication method unknwon");
1644                 end_trace();
1645                 return -1;
1646         }
1647
1648         scheme = (char const *) authenticate->au_scheme;
1649         if (authenticate->au_params) {
1650                 for (i = 0; (cur = (char *) authenticate->au_params[i]); i++) {
1651                         if ((realm = strstr(cur, "realm="))) {
1652                                 realm += 6;
1653                                 break;
1654                         }
1655                 }
1656         }
1657
1658         if (!scheme || !realm) {
1659                 PDEBUG(DEBUG_SIP, "No scheme or no realm in authentication header found\n");
1660                 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1661                 add_trace("error", NULL, "Authentication header has no realm or scheme");
1662                 end_trace();
1663                 return -1;
1664         }
1665
1666         SPRINT(authentication, "%s:%s:%s:%s", scheme, realm, inst->auth_user, inst->auth_password);
1667         PDEBUG(DEBUG_SIP, "auth: '%s'\n", authentication);
1668
1669         sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1670         add_trace("scheme", NULL, "%s", scheme);
1671         add_trace("realm", NULL, "%s", realm);
1672         add_trace("user", NULL, "%s", inst->auth_user);
1673         add_trace("pass", NULL, "%s", inst->auth_password);
1674         end_trace();
1675
1676         nua_authenticate(nh, /*SIPTAG_EXPIRES_STR("3600"),*/ NUTAG_AUTH(authentication), TAG_END());
1677
1678         return 0;
1679 }
1680
1681 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[])
1682 {
1683         #define NUTAG_WITH_THIS_MSG(msg) nutag_with, tag_ptr_v(msg)
1684         nua_saved_event_t saved[1];
1685         nua_save_event(nua, saved);
1686         nua_event_data_t const *data = nua_event_data(saved);
1687
1688         sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_IN);
1689         end_trace();
1690
1691         sip_trace_header(NULL, inst->interface_name, "RESPOND", DIRECTION_OUT);
1692         add_trace("respond", "value", "200 OK");
1693         end_trace();
1694
1695         nua_respond(nh, SIP_200_OK, NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1696         nua_handle_destroy(nh);
1697         inst->register_handle = NULL;
1698 }
1699
1700 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[])
1701 {
1702         #define NUTAG_WITH_THIS_MSG(msg) nutag_with, tag_ptr_v(msg)
1703         nua_saved_event_t saved[1];
1704         sip_contact_t const *contact = NULL;
1705         contact = sip->sip_contact;
1706         nua_save_event(nua, saved);
1707         nua_event_data_t const *data = nua_event_data(saved);
1708         sip_authorization_t const *authorization;
1709         char uri[256] = "";
1710         const char *auth_text = NULL;
1711         char auth_str[256] = "";
1712
1713         if (contact->m_url->url_host)
1714                 SCPY(uri, contact->m_url->url_host);
1715         if (contact->m_url->url_port && contact->m_url->url_port[0]) {
1716                 SCAT(uri, ":");
1717                 SCAT(uri, contact->m_url->url_port);
1718         }
1719
1720         if (!inst->allow_register) {
1721                 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_IN);
1722                 add_trace("error", NULL, "forbidden, because we don't accept registration");
1723                 end_trace();
1724                 nua_respond(nh, SIP_403_FORBIDDEN, NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1725                 nua_handle_destroy(nh);
1726                 inst->register_handle = NULL;
1727                 return;
1728         }
1729
1730         sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_IN);
1731         add_trace("contact", "uri", "%s", uri);
1732         end_trace();
1733
1734         sip_trace_header(NULL, inst->interface_name, "Authorization", DIRECTION_IN);
1735         if (inst->auth_realm[0]) {
1736                 authorization = sip->sip_authorization;
1737                 status = check_authorization(authorization, "REGISTER", inst->auth_user, inst->auth_password, inst->auth_realm, inst->auth_nonce, &auth_text);
1738                 if (status == 401) {
1739                         generate_nonce(inst->auth_nonce);
1740                         SPRINT(auth_str, "Digest realm=\"%s\", nonce=\"%s\", algorithm=MD5, qop=\"auth\"", inst->auth_realm, inst->auth_nonce);
1741                 }
1742         } else {
1743                 status = 200;
1744                 auth_text = "Authentication not required";
1745         }
1746         add_trace("result", NULL, "%s", auth_text);
1747         end_trace();
1748
1749         if (status == 200) {
1750                 SCPY(inst->remote_peer, uri);
1751                 inst->auth_nonce[0] = '\0';
1752         }
1753
1754         sip_trace_header(NULL, inst->interface_name, "RESPOND", DIRECTION_OUT);
1755         add_trace("respond", "value", "%d", status);
1756         add_trace("reason", NULL, "peer registers");
1757         end_trace();
1758
1759         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());
1760         nua_handle_destroy(nh);
1761         inst->register_handle = NULL;
1762 }
1763
1764 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[])
1765 {
1766         int rc;
1767
1768         sip_trace_header(NULL, inst->interface_name, "STATUS", DIRECTION_IN);
1769         add_trace("value", NULL, "%d", status);
1770         add_trace("phrase", NULL, "%s", phrase);
1771         end_trace();
1772
1773         switch (status) {
1774         case 200:
1775                 status_200:
1776                 /* if not registered, become registered and start register interval timer */
1777                 if (inst->register_state != REGISTER_STATE_REGISTERED) {
1778                         if (inst->register_interval)
1779                                 schedule_timer(&inst->register_retry_timer, inst->register_interval, 0);
1780                         inst->register_state = REGISTER_STATE_REGISTERED;
1781                 }
1782                 /* start option timer */
1783                 if (inst->options_interval)
1784                         PDEBUG(DEBUG_SIP, "register ok, scheduling option timer with %d seconds\n", inst->options_interval);
1785                         schedule_timer(&inst->register_option_timer, inst->options_interval, 0);
1786                 break;
1787         case 401:
1788         case 407:
1789                 PDEBUG(DEBUG_SIP, "Register challenge received\n");
1790                 rc = challenge(inst, NULL, status, phrase, nua, magic, nh, hmagic, sip, tags);
1791                 if (rc < 0)
1792                         goto status_400;
1793                 break;
1794         default:
1795                 if (status >= 200 && status <= 299)
1796                         goto status_200;
1797                 if (status < 400)
1798                         break;
1799                 status_400:
1800                 PDEBUG(DEBUG_SIP, "Register failed, starting register timer\n");
1801                 inst->register_state = REGISTER_STATE_FAILED;
1802                 nua_handle_destroy(nh);
1803                 inst->register_handle = NULL;
1804                 /* stop option timer */
1805                 unsched_timer(&inst->register_option_timer);
1806                 /* if failed, start register interval timer with REGISTER_RETRY_TIMER */
1807                 schedule_timer(&inst->register_retry_timer, REGISTER_RETRY_TIMER);
1808         }
1809 }
1810
1811 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[])
1812 {
1813         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1814         const char *from = "", *to = "", *name = "";
1815         char imsi[16] = "";
1816         int ret;
1817         class Endpoint *epoint;
1818         struct lcr_msg *message;
1819         struct interface *interface;
1820         const char *sdp_str = NULL;
1821         int media_types[32];
1822         uint8_t payload_types[32];
1823         int payloads = 0;
1824         unsigned char payload_type;
1825         int media_type;
1826         sip_authorization_t const *authorization;
1827         const char *auth_text = NULL;
1828         char auth_str[256] = "";
1829
1830         interface = getinterfacebyname(inst->interface_name);
1831         if (!interface) {
1832                 PERROR("Cannot find interface %s.\n", inst->interface_name);
1833                 return;
1834         }
1835
1836         if (sip->sip_from) {
1837                 if (sip->sip_from->a_url)
1838                         from = sip->sip_from->a_url->url_user;
1839                 if (sip->sip_from->a_display) {
1840                         name = sip->sip_from->a_display;
1841                         if (!strncmp(name, "\"IMSI", 5)) {
1842                                 strncpy(imsi, name + 5, 15);
1843                                 imsi[15] = '\0';
1844                                 name = "";
1845                         }
1846                 }
1847         }
1848         if (sip->sip_to) {
1849                 if (sip->sip_to->a_url)
1850                         to = sip->sip_to->a_url->url_user;
1851         }
1852         PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1853
1854         sip_trace_header(this, inst->interface_name, "Authorization", DIRECTION_IN);
1855         if (inst->auth_realm[0]) {
1856                 authorization = sip->sip_proxy_authorization;
1857                 status = check_authorization(authorization, "INVITE", inst->auth_user, inst->auth_password, inst->auth_realm, p_s_auth_nonce, &auth_text);
1858                 if (status == 401) {
1859                         generate_nonce(p_s_auth_nonce);
1860                         SPRINT(auth_str, "Digest realm=\"%s\", nonce=\"%s\", algorithm=MD5, qop=\"auth\"", inst->auth_realm, p_s_auth_nonce);
1861                 }
1862         } else {
1863                 status = 200;
1864                 auth_text = "Authentication not required";
1865         }
1866         add_trace("result", NULL, "%s", auth_text);
1867         end_trace();
1868
1869         if (status == 200) {
1870                 p_s_auth_nonce[0] = '\0';
1871         }
1872
1873         sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
1874         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1875         if (!ret) {
1876                 /* if no RTP bridge, we must support LAW codec, otherwise we forward what we have */
1877                 if (!p_s_rtp_bridge) {
1878                         int i;
1879
1880                         /* check if supported payload type exists */
1881                         for (i = 0; i < payloads; i++) {
1882                                 if (media_types[i] == ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW))
1883                                         break;
1884                         }
1885                         if (i == payloads) {
1886                                 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1887                                 ret = 415;
1888                         }
1889                 }
1890         }
1891         end_trace();
1892         if (ret) {
1893                 if (ret == 400)
1894                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1895                 else
1896                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1897                 nua_handle_destroy(nh);
1898                 p_s_handle = NULL;
1899                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1900                 if (ret == 400)
1901                         add_trace("respond", "value", "415 Unsupported Media");
1902                 else
1903                         add_trace("respond", "value", "400 Bad Request");
1904                 add_trace("reason", NULL, "offered codec does not match");
1905                 end_trace();
1906                 if (p_state != PORT_STATE_IDLE) {
1907                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1908                         message->param.disconnectinfo.cause = 41;
1909                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1910                         message_put(message);
1911                 }
1912                 new_state(PORT_STATE_RELEASE);
1913                 trigger_work(&p_s_delete);
1914                 return;
1915         }
1916
1917         /* handle re-invite */
1918         if (p_state != PORT_STATE_IDLE) {
1919                 sip_trace_header(this, inst->interface_name, "RE-INVITE", DIRECTION_IN);
1920                 end_trace();
1921                 if (p_s_rtp_bridge) {
1922                         PDEBUG(DEBUG_SIP, "RE-INVITE not implemented for RTP forwarding\n");
1923                         nua_respond(nh, SIP_501_NOT_IMPLEMENTED, TAG_END());
1924                         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1925                         add_trace("respond", "value", "501 NOT IMPLEMENTED");
1926                         add_trace("reason", NULL, "RE-INVITE not implemented for RTP forwarding");
1927                         end_trace();
1928                 } else {
1929                         PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1930                         media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1931                         payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1932                         if (rtp_connect() < 0) {
1933                                 goto rtp_failed;
1934                         }
1935                         sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1936                         PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1937                         nua_respond(p_s_handle, SIP_200_OK,
1938                                 NUTAG_MEDIA_ENABLE(0),
1939                                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1940                                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1941                 }
1942                 return;
1943         }
1944
1945         /* open local RTP peer (if not bridging) */
1946         if (!p_s_rtp_bridge && rtp_open() < 0) {
1947                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1948                 nua_handle_destroy(nh);
1949                 p_s_handle = NULL;
1950                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1951                 add_trace("respond", "value", "500 Internal Server Error");
1952                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1953                 end_trace();
1954                 new_state(PORT_STATE_RELEASE);
1955                 trigger_work(&p_s_delete);
1956                 return;
1957         }
1958
1959         /* apply handle */
1960 //      sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1961 //      add_trace("handle", "new", "0x%x", nh);
1962 //      end_trace();
1963 //
1964         p_s_handle = nh;
1965
1966         sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_IN);
1967         add_trace("rtp", "port", "%d", p_s_rtp_port_remote);
1968         /* caller information */
1969         if (!from[0]) {
1970                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1971                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1972                 add_trace("calling", "present", "unavailable");
1973         } else {
1974                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1975                 add_trace("calling", "present", "allowed");
1976                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1977                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1978                 SCPY(p_callerinfo.id, from);
1979                 add_trace("calling", "number", "%s", from);
1980                 SCPY(p_callerinfo.name, name);
1981                 if (name[0])
1982                         add_trace("calling", "name", "%s", name);
1983                 SCPY(p_callerinfo.imsi, imsi);
1984                 if (imsi[0])
1985                         add_trace("calling", "imsi", "%s", imsi);
1986         }
1987         SCPY(p_callerinfo.interface, inst->interface_name);
1988         /* dialing information */
1989         if (to[0]) {
1990                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
1991                 SCAT(p_dialinginfo.id, to);
1992                 add_trace("dialing", "number", "%s", to);
1993         }
1994         /* redir info */
1995         /* bearer capability */
1996         p_capainfo.bearer_capa = INFO_BC_SPEECH;
1997         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
1998         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
1999         add_trace("bearer", "capa", "speech");
2000         add_trace("bearer", "mode", "circuit");
2001         /* if packet mode works some day, see dss1.cpp for conditions */
2002         p_capainfo.source_mode = B_MODE_TRANSPARENT;
2003
2004         end_trace();
2005
2006         /* create endpoint */
2007         if (p_epointlist)
2008                 FATAL("Incoming call but already got an endpoint.\n");
2009         if (!(epoint = new Endpoint(p_serial, 0)))
2010                 FATAL("No memory for Endpoint instance\n");
2011         epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
2012         epointlist_new(epoint->ep_serial);
2013
2014 #ifdef NUTAG_AUTO100
2015         /* send trying (proceeding) */
2016         nua_respond(nh, SIP_100_TRYING, TAG_END());
2017         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2018         add_trace("respond", "value", "100 Trying");
2019         end_trace();
2020 #endif
2021
2022         new_state(PORT_STATE_IN_PROCEEDING);
2023
2024         /* send setup message to endpoit */
2025         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
2026         message->param.setup.port_type = p_type;
2027 //      message->param.setup.dtmf = 0;
2028         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
2029         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
2030         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
2031 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
2032 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
2033 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
2034         if (p_s_rtp_bridge) {
2035                 int i;
2036
2037                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
2038                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
2039                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
2040                 /* add codecs to setup message */
2041                 for (i = 0; i < payloads; i++) {
2042                         message->param.setup.rtpinfo.media_types[i] = media_types[i];
2043                         message->param.setup.rtpinfo.payload_types[i] = payload_types[i];
2044                         if (i == sizeof(message->param.setup.rtpinfo.payload_types))
2045                                 break;
2046                 }
2047                 message->param.setup.rtpinfo.payloads = i;
2048         }
2049         message_put(message);
2050
2051         /* start option timer */
2052         if (inst->options_interval) {
2053                 PDEBUG(DEBUG_SIP, "Invite received, scheduling option timer with %d seconds\n", inst->options_interval);
2054                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2055         }
2056
2057         p_s_invite_direction = DIRECTION_IN;
2058
2059         /* send progress, if tones are available and if we don't bridge */
2060         if (!p_s_rtp_bridge && interface->is_tones == IS_YES) {
2061                 PDEBUG(DEBUG_SIP, "Connecting audio, since we have tones available\n");
2062                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
2063                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
2064                 /* open local RTP peer (if not bridging) */
2065                 if (rtp_connect() < 0) {
2066 rtp_failed:
2067                         nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2068                         nua_handle_destroy(nh);
2069                         p_s_handle = NULL;
2070                         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2071                         add_trace("respond", "value", "500 Internal Server Error");
2072                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
2073                         end_trace();
2074                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
2075                         message->param.disconnectinfo.cause = 41;
2076                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2077                         message_put(message);
2078                         new_state(PORT_STATE_RELEASE);
2079                         trigger_work(&p_s_delete);
2080                         return;
2081                 }
2082
2083                 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
2084                 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
2085
2086                 nua_respond(p_s_handle, SIP_183_SESSION_PROGRESS,
2087                         NUTAG_MEDIA_ENABLE(0),
2088                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
2089                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
2090                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2091                 add_trace("respond", "value", "183 SESSION PROGRESS");
2092                 add_trace("reason", NULL, "audio available");
2093                 struct in_addr ia;
2094                 memset(&ia, 0, sizeof(ia));
2095                 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
2096                 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
2097                 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
2098                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
2099                 end_trace();
2100         }
2101 }
2102
2103 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[])
2104 {
2105         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2106
2107         PDEBUG(DEBUG_SIP, "options received\n");
2108
2109         sip_trace_header(this, inst->interface_name, "OPTIONS", DIRECTION_IN);
2110         end_trace();
2111
2112         nua_respond(nh, SIP_200_OK, TAG_END());
2113 }
2114
2115 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[])
2116 {
2117         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2118         struct lcr_msg *message;
2119         int cause = 0;
2120
2121         PDEBUG(DEBUG_SIP, "bye received\n");
2122
2123         sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_IN);
2124         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
2125                 cause = atoi(sip->sip_reason->re_cause);
2126                 add_trace("cause", "value", "%d", cause);
2127         }
2128         end_trace();
2129
2130 // let stack do bye automaticall, since it will not accept our response for some reason
2131 //      nua_respond(nh, SIP_200_OK, TAG_END());
2132         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2133         add_trace("respond", "value", "200 OK");
2134         end_trace();
2135 //      nua_handle_destroy(nh);
2136         p_s_handle = NULL;
2137
2138         rtp_close();
2139
2140         while(p_epointlist) {
2141                 /* send setup message to endpoit */
2142                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2143                 message->param.disconnectinfo.cause = cause ? : 16;
2144                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2145                 message_put(message);
2146                 /* remove epoint */
2147                 free_epointlist(p_epointlist);
2148         }
2149         new_state(PORT_STATE_RELEASE);
2150         trigger_work(&p_s_delete);
2151 }
2152
2153 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[])
2154 {
2155         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2156         struct lcr_msg *message;
2157
2158         PDEBUG(DEBUG_SIP, "cancel received\n");
2159
2160         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_IN);
2161         end_trace();
2162
2163         nua_handle_destroy(nh);
2164         p_s_handle = NULL;
2165
2166         rtp_close();
2167
2168         while(p_epointlist) {
2169                 /* send setup message to endpoit */
2170                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2171                 message->param.disconnectinfo.cause = 16;
2172                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2173                 message_put(message);
2174                 /* remove epoint */
2175                 free_epointlist(p_epointlist);
2176         }
2177         new_state(PORT_STATE_RELEASE);
2178         trigger_work(&p_s_delete);
2179 }
2180
2181 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[])
2182 {
2183         PDEBUG(DEBUG_SIP, "bye response received\n");
2184
2185         nua_handle_destroy(nh);
2186         p_s_handle = NULL;
2187
2188         rtp_close();
2189
2190         trigger_work(&p_s_delete);
2191 }
2192
2193 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[])
2194 {
2195         PDEBUG(DEBUG_SIP, "cancel response received\n");
2196
2197         nua_handle_destroy(nh);
2198         p_s_handle = NULL;
2199
2200         rtp_close();
2201
2202         trigger_work(&p_s_delete);
2203 }
2204
2205 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[])
2206 {
2207         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2208         struct lcr_msg *message;
2209         int cause = 0, location = 0;
2210         int media_types[32];
2211         uint8_t payload_types[32];
2212         int payloads = 0;
2213
2214         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
2215
2216         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2217         add_trace("respond", "value", "%d", status);
2218         end_trace();
2219
2220         /* connect audio */
2221         if (status == 183 || (status >= 200 && status <= 299)) {
2222                 int ret;
2223
2224                 sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
2225                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
2226                 if (!ret) {
2227                         if (payloads != 1)
2228                                 ret = 415;
2229                         else if (!p_s_rtp_bridge) {
2230                                 if (media_types[0] != ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW)) {
2231                                         add_trace("error", NULL, "Expected LAW payload type (not bridged)");
2232                                         ret = 415;
2233                                 }
2234                         }
2235                 }
2236                 end_trace();
2237                 if (ret) {
2238                         nua_cancel(nh, TAG_END());
2239                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2240                         add_trace("reason", NULL, "accepted codec does not match");
2241                         end_trace();
2242                         cause = 88;
2243                         location = LOCATION_PRIVATE_LOCAL;
2244                         goto release_with_cause;
2245                 }
2246
2247                 /* connect to remote RTP (if not bridging) */
2248                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
2249                         nua_cancel(nh, TAG_END());
2250                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2251                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
2252                         end_trace();
2253                         cause = 31;
2254                         location = LOCATION_PRIVATE_LOCAL;
2255                         goto release_with_cause;
2256                 }
2257         }
2258
2259         /* start option timer */
2260         if (inst->options_interval) {
2261                 PDEBUG(DEBUG_SIP, "Invite response, scheduling option timer with %d seconds\n", inst->options_interval);
2262                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2263         }
2264
2265         switch (status) {
2266         case 100:
2267 #if 0
2268                 PDEBUG(DEBUG_SIP, "do proceeding\n");
2269                 new_state(PORT_STATE_OUT_PROCEEDING);
2270                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
2271                 message_put(message);
2272 #endif
2273                 return;
2274         case 180:
2275                 PDEBUG(DEBUG_SIP, "do alerting\n");
2276                 new_state(PORT_STATE_OUT_ALERTING);
2277                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
2278                 message_put(message);
2279                 return;
2280         case 183:
2281                 PDEBUG(DEBUG_SIP, "do progress\n");
2282                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
2283                 message->param.progressinfo.progress = 8;
2284                 message->param.progressinfo.location = 10;
2285                 if (p_s_rtp_bridge) {
2286                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2287                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
2288                         message->param.progressinfo.rtpinfo.media_types[0] = media_types[0];
2289                         message->param.progressinfo.rtpinfo.payload_types[0] = payload_types[0];
2290                         message->param.progressinfo.rtpinfo.payloads = 1;
2291                 }
2292                 message_put(message);
2293                 return;
2294         case 200:
2295                 status_200:
2296                 PDEBUG(DEBUG_SIP, "do connect\n");
2297                 nua_ack(nh, TAG_END());
2298                 new_state(PORT_STATE_CONNECT);
2299                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
2300                 if (p_s_rtp_bridge) {
2301                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2302                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
2303                         message->param.connectinfo.rtpinfo.media_types[0] = media_types[0];
2304                         message->param.connectinfo.rtpinfo.payload_types[0] = payload_types[0];
2305                         message->param.connectinfo.rtpinfo.payloads = 1;
2306                 }
2307                 message_put(message);
2308                 return;
2309         default:
2310                 if (status >= 200 && status <= 299)
2311                         goto status_200;
2312                 if (status < 100 || status > 199)
2313                         break;
2314                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
2315
2316                 return;
2317         }
2318
2319         cause = status2cause(status);
2320         location = LOCATION_BEYOND;
2321
2322 release_with_cause:
2323         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
2324
2325         while(p_epointlist) {
2326                 /* send setup message to endpoit */
2327                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2328                 message->param.disconnectinfo.cause = cause;
2329                 message->param.disconnectinfo.location = location;
2330                 message_put(message);
2331                 /* remove epoint */
2332                 free_epointlist(p_epointlist);
2333         }
2334
2335         new_state(PORT_STATE_RELEASE);
2336
2337         rtp_close();
2338
2339         trigger_work(&p_s_delete);
2340 }
2341
2342 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[])
2343 {
2344         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2345         int cause = 0, location = 0;
2346         struct lcr_msg *message;
2347
2348         PDEBUG(DEBUG_SIP, "options result %d received\n", status);
2349
2350         if (status >= 200 && status <= 299) {
2351                 PDEBUG(DEBUG_SIP, "options ok, scheduling option timer with %d seconds\n", inst->options_interval);
2352                 /* restart option timer */
2353                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2354                 return;
2355         }
2356
2357         nua_handle_destroy(nh);
2358         p_s_handle = NULL;
2359
2360         rtp_close();
2361
2362         cause = status2cause(status);
2363         location = LOCATION_BEYOND;
2364
2365         while(p_epointlist) {
2366                 /* send setup message to endpoit */
2367                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2368                 message->param.disconnectinfo.cause = cause;
2369                 message->param.disconnectinfo.location = location;
2370                 message_put(message);
2371                 /* remove epoint */
2372                 free_epointlist(p_epointlist);
2373         }
2374         new_state(PORT_STATE_RELEASE);
2375         trigger_work(&p_s_delete);
2376 }
2377
2378 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[])
2379 {
2380         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2381
2382         PDEBUG(DEBUG_SIP, "state change received\n");
2383         sip_trace_header(this, inst->interface_name, "STATUS", DIRECTION_OUT);
2384         add_trace("value", NULL, "%d", status);
2385         add_trace("phrase", NULL, "%s", phrase);
2386         end_trace();
2387 }
2388
2389 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[])
2390 {
2391         struct sip_inst *inst = (struct sip_inst *) magic;
2392         class Port *port;
2393         class Psip *psip = NULL;
2394         int rc;
2395
2396         PDEBUG(DEBUG_SIP, "Event %d from SIP stack received (handle=%p)\n", event, nh);
2397         if (!nh)
2398                 return;
2399
2400         /* hunt for existing handles */
2401         port = port_first;
2402         while(port) {
2403                 if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
2404                         psip = (class Psip *)port;
2405                         if (psip->p_s_handle == nh) {
2406                                 PDEBUG(DEBUG_SIP, "Event found for port %s\n", psip->p_name);
2407                                 break;
2408                         }
2409                 }
2410                 port = port->next;
2411         }
2412         if (!port)
2413                 psip = NULL;
2414
2415         /* new handle */
2416         switch (event) {
2417         case nua_i_options:
2418                 if (!inst->register_handle) {
2419                         PDEBUG(DEBUG_SIP, "New options instance\n");
2420                         inst->register_handle = nh;
2421                 }
2422                 break;
2423         case nua_i_register:
2424                 if (!inst->register_handle) {
2425                         PDEBUG(DEBUG_SIP, "New register instance\n");
2426                         inst->register_handle = nh;
2427                 }
2428                 break;
2429         case nua_i_invite:
2430                 if (!psip) {
2431                         char name[64];
2432                         struct interface *interface = interface_first;
2433
2434                         PDEBUG(DEBUG_SIP, "New psip instance\n");
2435
2436                         /* create call instance */
2437                         SPRINT(name, "%s-%d-in", inst->interface_name, 0);
2438                         while (interface) {
2439                                 if (!strcmp(interface->name, inst->interface_name))
2440                                         break;
2441                                 interface = interface->next;
2442                         }
2443                         if (!interface)
2444                                 FATAL("Cannot find interface %s.\n", inst->interface_name);
2445                         if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
2446                                 FATAL("Cannot create Port instance.\n");
2447                 }
2448                 break;
2449         default:
2450                 if (!psip && !inst->register_handle) {
2451                         PDEBUG(DEBUG_SIP, "Destroying unknown instance\n");
2452                         nua_handle_destroy(nh);
2453                         return;
2454                 }
2455         }
2456
2457         /* handle register process */
2458         if (inst->register_handle == nh) {
2459                 switch (event) {
2460                 case nua_i_options:
2461                         i_options(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2462                         break;
2463                 case nua_i_register:
2464                         i_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2465                         break;
2466                 case nua_r_register:
2467                         r_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2468                         break;
2469                 default:
2470                         PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2471                 }
2472                 return;
2473         }
2474
2475         /* handle port process */
2476         if (!psip) {
2477                 PERROR("no SIP Port found for handel %p\n", nh);
2478                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2479                 nua_handle_destroy(nh);
2480                 return;
2481         }
2482
2483         switch (status) {
2484         case 401:
2485         case 407:
2486                 rc = challenge(inst, psip, status, phrase, nua, magic, nh, hmagic, sip, tags);
2487                 if (rc >= 0)
2488                         return;
2489         }
2490
2491         switch (event) {
2492         case nua_r_set_params:
2493                 PDEBUG(DEBUG_SIP, "setparam response\n");
2494                 break;
2495         case nua_r_options:
2496                 psip->r_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2497                 break;
2498         case nua_i_error:
2499                 PDEBUG(DEBUG_SIP, "error received\n");
2500                 break;
2501         case nua_i_state:
2502                 psip->i_state(status, phrase, nua, magic, nh, hmagic, sip, tags);
2503                 break;
2504         case nua_i_invite:
2505                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2506                 break;
2507         case nua_i_ack:
2508                 PDEBUG(DEBUG_SIP, "ack received\n");
2509                 break;
2510         case nua_i_active:
2511                 PDEBUG(DEBUG_SIP, "active received\n");
2512                 break;
2513         case nua_i_options:
2514                 psip->i_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2515                 break;
2516         case nua_i_bye:
2517                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2518                 break;
2519         case nua_i_cancel:
2520                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2521                 break;
2522         case nua_r_bye:
2523                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2524                 break;
2525         case nua_r_cancel:
2526                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2527                 break;
2528         case nua_r_invite:
2529                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2530                 break;
2531         case nua_i_terminated:
2532                 PDEBUG(DEBUG_SIP, "terminated received\n");
2533                 break;
2534         default:
2535                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2536         }
2537 }
2538
2539 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)
2540 {
2541         struct sip_inst *inst = (struct sip_inst *) magic;
2542         su_sockaddr_t sa;
2543         socklen_t addrlen;
2544
2545         PDEBUG(DEBUG_SIP, "Event %d from STUN stack received\n", event);
2546
2547         switch (event) {
2548         case stun_discovery_done:
2549                 addrlen = sizeof(sa);
2550                 memset(&sa, 0, addrlen);
2551                 if (stun_discovery_get_address(sd, &sa, &addrlen) < 0) {
2552                         PDEBUG(DEBUG_SIP, "stun_discovery_get_address failed\n");
2553                         goto failed;
2554                 }
2555                 su_inet_ntop(sa.su_family, SU_ADDR(&sa), inst->public_ip, sizeof(inst->public_ip));
2556                 inst->stun_state = STUN_STATE_RESOLVED;
2557                 /* start timer for next stun request with inst->stun_interval */
2558                 schedule_timer(&inst->stun_retry_timer, inst->stun_interval, 0);
2559                 sip_trace_header(NULL, inst->interface_name, "STUN resolved", DIRECTION_OUT);
2560                 add_trace("ip", "addr", "%s", inst->public_ip);
2561                 end_trace();
2562                 break;
2563         default:
2564 failed:
2565                 PDEBUG(DEBUG_SIP, "STUN failed, starting timer\n");
2566                 inst->stun_state = STUN_STATE_FAILED;
2567                 /* start timer for next stun request (after failing) with STUN_RETRY_TIMER */
2568                 schedule_timer(&inst->stun_retry_timer, STUN_RETRY_TIMER);
2569                 sip_trace_header(NULL, inst->interface_name, "STUN failed", DIRECTION_OUT);
2570                 end_trace();
2571         }
2572 }
2573
2574 /* received shutdown due to termination of RTP */
2575 void Psip::rtp_shutdown(void)
2576 {
2577         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2578         struct lcr_msg *message;
2579
2580         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
2581
2582         sip_trace_header(this, inst->interface_name, "RTP terminated", DIRECTION_IN);
2583         end_trace();
2584
2585         nua_handle_destroy(p_s_handle);
2586         p_s_handle = NULL;
2587
2588         while(p_epointlist) {
2589                 /* send setup message to endpoit */
2590                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2591                 message->param.disconnectinfo.cause = 16;
2592                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2593                 message_put(message);
2594                 /* remove epoint */
2595                 free_epointlist(p_epointlist);
2596         }
2597         new_state(PORT_STATE_RELEASE);
2598         trigger_work(&p_s_delete);
2599 }
2600
2601 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index)
2602 {
2603         class Psip *psip = (class Psip *)instance;
2604         struct sip_inst *inst = (struct sip_inst *) psip->p_s_sip_inst;
2605
2606         sip_trace_header(psip, inst->interface_name, "OPTIONS", psip->p_s_invite_direction);
2607         end_trace();
2608
2609         nua_options(psip->p_s_handle,
2610                 TAG_END());
2611
2612         return 0;
2613 }
2614
2615 static int stun_retry_timer(struct lcr_timer *timer, void *instance, int index)
2616 {
2617         struct sip_inst *inst = (struct sip_inst *)instance;
2618
2619         PDEBUG(DEBUG_SIP, "timeout, restart stun lookup\n");
2620         inst->stun_state = STUN_STATE_UNRESOLVED;
2621
2622         return 0;
2623 }
2624
2625 static int register_retry_timer(struct lcr_timer *timer, void *instance, int index)
2626 {
2627         struct sip_inst *inst = (struct sip_inst *)instance;
2628
2629         PDEBUG(DEBUG_SIP, "timeout, restart register\n");
2630         /* if we have a handle, destroy it and becom unregistered, so registration is
2631          * triggered next */
2632         if (inst->register_handle) {
2633                 /* stop option timer */
2634                 unsched_timer(&inst->register_option_timer);
2635                 nua_handle_destroy(inst->register_handle);
2636                 inst->register_handle = NULL;
2637         }
2638         inst->register_state = REGISTER_STATE_UNREGISTERED;
2639
2640         return 0;
2641 }
2642
2643 static int register_option_timer(struct lcr_timer *timer, void *instance, int index)
2644 {
2645         struct sip_inst *inst = (struct sip_inst *)instance;
2646         sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_OUT);
2647         end_trace();
2648
2649         nua_options(inst->register_handle,
2650                 TAG_END());
2651
2652         return 0;
2653 }
2654
2655 int sip_init_inst(struct interface *interface)
2656 {
2657         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
2658         char local[256];
2659
2660         interface->sip_inst = inst;
2661         SCPY(inst->interface_name, interface->name);
2662         SCPY(inst->local_peer, interface->sip_local_peer);
2663         SCPY(inst->remote_peer, interface->sip_remote_peer);
2664         if (!inst->remote_peer[0])
2665                 inst->allow_register = 1;
2666         SCPY(inst->asserted_id, interface->sip_asserted_id);
2667         if (interface->sip_register) {
2668                 inst->register_state = REGISTER_STATE_UNREGISTERED;
2669                 SCPY(inst->register_user, interface->sip_register_user);
2670                 SCPY(inst->register_host, interface->sip_register_host);
2671         }
2672         SCPY(inst->auth_user, interface->sip_auth_user);
2673         SCPY(inst->auth_password, interface->sip_auth_password);
2674         SCPY(inst->auth_realm, interface->sip_auth_realm);
2675         inst->register_interval = interface->sip_register_interval;
2676         inst->options_interval = interface->sip_options_interval;
2677
2678         inst->rtp_port_from = interface->rtp_port_from;
2679         inst->rtp_port_to = interface->rtp_port_to;
2680         if (!inst->rtp_port_from || !inst->rtp_port_to) {
2681                 inst->rtp_port_from = RTP_PORT_BASE;
2682                 inst->rtp_port_to = RTP_PORT_MAX;
2683         }
2684         inst->next_rtp_port = inst->rtp_port_from;
2685
2686         /* create timers */
2687         memset(&inst->stun_retry_timer, 0, sizeof(inst->stun_retry_timer));
2688         add_timer(&inst->stun_retry_timer, stun_retry_timer, inst, 0);
2689         memset(&inst->register_retry_timer, 0, sizeof(inst->register_retry_timer));
2690         add_timer(&inst->register_retry_timer, register_retry_timer, inst, 0);
2691         memset(&inst->register_option_timer, 0, sizeof(inst->register_option_timer));
2692         add_timer(&inst->register_option_timer, register_option_timer, inst, 0);
2693
2694         /* init root object */
2695         inst->root = su_root_create(inst);
2696         if (!inst->root) {
2697                 PERROR("Failed to create SIP root\n");
2698                 sip_exit_inst(interface);
2699                 return -EINVAL;
2700         }
2701
2702         SPRINT(local, "sip:%s",inst->local_peer);
2703         if (!strchr(inst->local_peer, ':'))
2704                 SCAT(local, ":5060");
2705         inst->nua = nua_create(inst->root, sip_callback, inst, NUTAG_URL(local), TAG_END());
2706         if (!inst->nua) {
2707                 PERROR("Failed to create SIP stack object\n");
2708                 sip_exit_inst(interface);
2709                 return -EINVAL;
2710         }
2711         nua_set_params(inst->nua,
2712                 SIPTAG_ALLOW_STR("REGISTER,INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
2713                 NUTAG_APPL_METHOD("REGISTER"),
2714                 NUTAG_APPL_METHOD("INVITE"),
2715                 NUTAG_APPL_METHOD("ACK"),
2716 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
2717                 NUTAG_APPL_METHOD("CANCEL"),
2718                 NUTAG_APPL_METHOD("OPTIONS"),
2719                 NUTAG_APPL_METHOD("NOTIFY"),
2720                 NUTAG_APPL_METHOD("INFO"),
2721                 NUTAG_AUTOACK(0),
2722 #ifdef NUTAG_AUTO100
2723                 NUTAG_AUTO100(0),
2724 #endif
2725                 NUTAG_AUTOALERT(0),
2726                 NUTAG_AUTOANSWER(0),
2727                 TAG_NULL());
2728
2729         SCPY(inst->public_ip, interface->sip_public_ip);
2730         if (interface->sip_stun_server[0]) {
2731                 SCPY(inst->stun_server, interface->sip_stun_server);
2732                 inst->stun_interval = interface->sip_stun_interval;
2733                 inst->stun_handle = stun_handle_init(inst->root,
2734                         STUNTAG_SERVER(inst->stun_server),
2735                         TAG_NULL());
2736                 if (!inst->stun_handle) {
2737                         PERROR("Failed to create STUN handle\n");
2738                         sip_exit_inst(interface);
2739                         return -EINVAL;
2740                 }
2741                 inst->stun_socket = su_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
2742                 if (inst->stun_socket < 0) {
2743                         PERROR("Failed to create STUN socket\n");
2744                         sip_exit_inst(interface);
2745                         return -EINVAL;
2746                 }
2747                 inst->stun_state = STUN_STATE_UNRESOLVED;
2748         }
2749
2750         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
2751
2752         any_sip_interface = 1;
2753
2754         return 0;
2755 }
2756
2757 void sip_exit_inst(struct interface *interface)
2758 {
2759         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
2760
2761         if (!inst)
2762                 return;
2763         del_timer(&inst->stun_retry_timer);
2764         del_timer(&inst->register_retry_timer);
2765         del_timer(&inst->register_option_timer);
2766         if (inst->stun_socket)
2767                 su_close(inst->stun_socket);
2768         if (inst->stun_handle)
2769                 stun_handle_destroy(inst->stun_handle);
2770         if (inst->register_handle)
2771                 nua_handle_destroy(inst->register_handle);
2772         if (inst->root)
2773                 su_root_destroy(inst->root);
2774         if (inst->nua)
2775                 nua_destroy(inst->nua);
2776         FREE(inst, sizeof(*inst));
2777         interface->sip_inst = NULL;
2778
2779         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
2780
2781         /* check if there is any other SIP interface left */
2782         interface = interface_first;
2783         while (interface) {
2784                 if (interface->sip_inst)
2785                         break;
2786                 interface = interface->next;
2787         }
2788         if (!interface)
2789                 any_sip_interface = 0;
2790 }
2791
2792 extern su_log_t su_log_default[];
2793 extern su_log_t nua_log[];
2794
2795 int sip_init(void)
2796 {
2797         int i;
2798
2799         /* init SOFIA lib */
2800         su_init();
2801         su_home_init(sip_home);
2802
2803         if (options.deb & DEBUG_SIP) {
2804                 su_log_set_level(su_log_default, 9);
2805                 su_log_set_level(nua_log, 9);
2806                 //su_log_set_level(soa_log, 9);
2807         }
2808
2809         for (i = 0; i < 256; i++)
2810                 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);
2811
2812         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
2813
2814         return 0;
2815 }
2816
2817 void sip_exit(void)
2818 {
2819         su_home_deinit(sip_home);
2820         su_deinit();
2821
2822         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
2823 }
2824
2825 static void sip_handle_stun(struct sip_inst *inst)
2826 {
2827         int rc;
2828
2829         switch (inst->stun_state) {
2830         case STUN_STATE_UNRESOLVED:
2831                 PDEBUG(DEBUG_SIP, "Trying to to get local IP from stun server\n");
2832                 rc = stun_bind(inst->stun_handle, stun_bind_cb, (stun_discovery_magic_t *)inst,
2833                         STUNTAG_SOCKET(inst->stun_socket),
2834                         STUNTAG_REGISTER_EVENTS(1),
2835                         TAG_NULL());
2836                 if (rc < 0) {
2837                         PERROR("Failed to call stun_bind()\n");
2838                         inst->stun_state = STUN_STATE_FAILED;
2839                         break;
2840                 }
2841                 inst->stun_state = STUN_STATE_RESOLVING;
2842                 sip_trace_header(NULL, inst->interface_name, "STUN resolving", DIRECTION_OUT);
2843                 add_trace("server", "addr", "%s", inst->stun_server);
2844                 end_trace();
2845                 break;
2846         }
2847 }
2848
2849 static void sip_handle_register(struct sip_inst *inst)
2850 {
2851         char from[128] = "";
2852         char to[128] = "";
2853         char contact[128] = "";
2854
2855         switch (inst->register_state) {
2856         case REGISTER_STATE_UNREGISTERED:
2857                 /* wait for resoved stun */
2858                 if (inst->stun_handle && inst->stun_state != STUN_STATE_RESOLVED)
2859                         return;
2860
2861                 PDEBUG(DEBUG_SIP, "Registering to peer\n");
2862                 inst->register_handle = nua_handle(inst->nua, NULL, TAG_END());
2863                 if (!inst->register_handle) {
2864                         PERROR("Failed to create handle\n");
2865                         inst->register_state = REGISTER_STATE_FAILED;
2866                         break;
2867                 }
2868                 /* apply handle to trace */
2869 //              sip_trace_header(NULL, inst->interface_name, "NEW handle", DIRECTION_NONE);
2870 //              add_trace("handle", "new", "0x%x", inst->register_handle);
2871 //              end_trace();
2872
2873                 SPRINT(from, "sip:%s@%s", inst->register_user, inst->register_host);
2874                 SPRINT(to, "sip:%s@%s", inst->register_user, inst->register_host);
2875                 if (inst->public_ip[0]) {
2876                         char *p;
2877                         SPRINT(contact, "sip:%s@%s", inst->register_user, inst->public_ip);
2878                         p = strchr(inst->local_peer, ':');
2879                         if (p)
2880                                 SCAT(contact, p);
2881                 }
2882
2883                 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_OUT);
2884                 add_trace("from", "uri", "%s", from);
2885                 add_trace("to", "uri", "%s", to);
2886                 end_trace();
2887
2888                 nua_register(inst->register_handle,
2889                         TAG_IF(from[0], SIPTAG_FROM_STR(from)),
2890                         TAG_IF(to[0], SIPTAG_TO_STR(to)),
2891                         TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
2892                         TAG_END());
2893
2894                 inst->register_state = REGISTER_STATE_REGISTERING;
2895
2896                 break;
2897         }
2898         
2899 }
2900
2901 void sip_handle(void)
2902 {
2903         struct interface *interface = interface_first;
2904         struct sip_inst *inst;
2905
2906         while (interface) {
2907                 if (interface->sip_inst) {
2908                         inst = (struct sip_inst *) interface->sip_inst;
2909                         su_root_step(inst->root, 0);
2910                         sip_handle_stun(inst);
2911                         sip_handle_register(inst);
2912                 }
2913                 interface = interface->next;
2914         }
2915 }
2916
2917 /* deletes when back in event loop */
2918 static int delete_event(struct lcr_work *work, void *instance, int index)
2919 {
2920         class Psip *psip = (class Psip *)instance;
2921
2922         delete psip;
2923
2924         return 0;
2925 }
2926
2927
2928 /*
2929  * generate audio, if no data is received from bridge
2930  */
2931
2932 void Psip::set_tone(const char *dir, const char *tone)
2933 {
2934         Port::set_tone(dir, tone);
2935
2936         update_load();
2937 }
2938
2939 void Psip::update_load(void)
2940 {
2941         /* don't trigger load event if event already active */
2942         if (p_s_load_timer.active)
2943                 return;
2944
2945         /* don't start timer if ... */
2946         if (!p_tone_name[0] && !p_dov_tx)
2947                 return;
2948
2949         p_s_next_tv_sec = 0;
2950         schedule_timer(&p_s_load_timer, 0, 0); /* no delay the first time */
2951 }
2952
2953 static int load_timer(struct lcr_timer *timer, void *instance, int index)
2954 {
2955         class Psip *psip = (class Psip *)instance;
2956
2957         /* stop timer if ... */
2958         if (!psip->p_tone_name[0] && !psip->p_dov_tx)
2959                 return 0;
2960
2961         psip->load_tx();
2962
2963         return 0;
2964 }
2965
2966 #define SEND_SIP_LEN 160
2967
2968 void Psip::load_tx(void)
2969 {
2970         int diff;
2971         struct timeval current_time;
2972         int tosend = SEND_SIP_LEN, i;
2973         unsigned char buf[SEND_SIP_LEN], *p = buf;
2974
2975         /* get elapsed */
2976         gettimeofday(&current_time, NULL);
2977         if (!p_s_next_tv_sec) {
2978                 /* if timer expired the first time, set next expected timeout 160 samples in advance */
2979                 p_s_next_tv_sec = current_time.tv_sec;
2980                 p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2981                 if (p_s_next_tv_usec >= 1000000) {
2982                         p_s_next_tv_usec -= 1000000;
2983                         p_s_next_tv_sec++;
2984                 }
2985                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125);
2986         } else {
2987                 diff = 1000000 * (current_time.tv_sec - p_s_next_tv_sec)
2988                         + (current_time.tv_usec - p_s_next_tv_usec);
2989                 if (diff < -SEND_SIP_LEN * 125 || diff > SEND_SIP_LEN * 125) {
2990                         /* if clock drifts too much, set next timeout event to current timer + 160 */
2991                         diff = 0;
2992                         p_s_next_tv_sec = current_time.tv_sec;
2993                         p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2994                         if (p_s_next_tv_usec >= 1000000) {
2995                                 p_s_next_tv_usec -= 1000000;
2996                                 p_s_next_tv_sec++;
2997                         }
2998                 } else {
2999                         /* if diff is positive, it took too long, so next timeout will be earlier */
3000                         p_s_next_tv_usec += SEND_SIP_LEN * 125;
3001                         if (p_s_next_tv_usec >= 1000000) {
3002                                 p_s_next_tv_usec -= 1000000;
3003                                 p_s_next_tv_sec++;
3004                         }
3005                 }
3006                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125 - diff);
3007         }
3008
3009         /* copy tones */
3010         if (p_tone_name[0]) {
3011                 tosend -= read_audio(p, tosend);
3012         } else
3013         if (p_dov_tx) {
3014                 tosend -= dov_tx(p, tosend);
3015         }
3016         if (tosend) {
3017                 PERROR("buffer is not completely filled\n");
3018                 return;
3019         }
3020
3021         p = buf;
3022         for (i = 0; i < SEND_SIP_LEN; i++) {
3023                 *p = flip[*p];
3024                 p++;
3025         }
3026         /* transmit data via rtp */
3027         rtp_send_frame(buf, SEND_SIP_LEN, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
3028 }
3029