fixup
[lcr.git] / sip.cpp
1 /*****************************************************************************\
2 **                                                                           **
3 ** Linux Call Router                                                         **
4 **                                                                           **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg                                              **
7 **                                                                           **
8 ** SIP port                                                                  **
9 **                                                                           **
10 \*****************************************************************************/ 
11
12 #include "main.h"
13 #include <sofia-sip/sip_status.h>
14 #include <sofia-sip/su_log.h>
15 #include <sofia-sip/sdp.h>
16 #include <sofia-sip/sip_header.h>
17 #include <sofia-sip/stun.h>
18 #include <sofia-sip/stun_tag.h>
19 #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 == 407) {
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         } else {
1872                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1873                 add_trace("respond", "value", "%d", status);
1874                 add_trace("reason", NULL, "peer registers");
1875                 end_trace();
1876
1877                 nua_respond(nh, status, auth_text, SIPTAG_CONTACT(sip->sip_contact), TAG_IF(auth_str[0], SIPTAG_WWW_AUTHENTICATE_STR(auth_str)), TAG_END());
1878 //              nua_handle_destroy(nh);
1879 //              inst->register_handle = NULL;
1880                 return;
1881         }
1882
1883         sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
1884         ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1885         if (!ret) {
1886                 /* if no RTP bridge, we must support LAW codec, otherwise we forward what we have */
1887                 if (!p_s_rtp_bridge) {
1888                         int i;
1889
1890                         /* check if supported payload type exists */
1891                         for (i = 0; i < payloads; i++) {
1892                                 if (media_types[i] == ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW))
1893                                         break;
1894                         }
1895                         if (i == payloads) {
1896                                 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1897                                 ret = 415;
1898                         }
1899                 }
1900         }
1901         end_trace();
1902         if (ret) {
1903                 if (ret == 400)
1904                         nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1905                 else
1906                         nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1907                 nua_handle_destroy(nh);
1908                 p_s_handle = NULL;
1909                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1910                 if (ret == 400)
1911                         add_trace("respond", "value", "415 Unsupported Media");
1912                 else
1913                         add_trace("respond", "value", "400 Bad Request");
1914                 add_trace("reason", NULL, "offered codec does not match");
1915                 end_trace();
1916                 if (p_state != PORT_STATE_IDLE) {
1917                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1918                         message->param.disconnectinfo.cause = 41;
1919                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1920                         message_put(message);
1921                 }
1922                 new_state(PORT_STATE_RELEASE);
1923                 trigger_work(&p_s_delete);
1924                 return;
1925         }
1926
1927         /* handle re-invite */
1928         if (p_state != PORT_STATE_IDLE) {
1929                 sip_trace_header(this, inst->interface_name, "RE-INVITE", DIRECTION_IN);
1930                 end_trace();
1931                 if (p_s_rtp_bridge) {
1932                         PDEBUG(DEBUG_SIP, "RE-INVITE not implemented for RTP forwarding\n");
1933                         nua_respond(nh, SIP_501_NOT_IMPLEMENTED, TAG_END());
1934                         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1935                         add_trace("respond", "value", "501 NOT IMPLEMENTED");
1936                         add_trace("reason", NULL, "RE-INVITE not implemented for RTP forwarding");
1937                         end_trace();
1938                 } else {
1939                         PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1940                         media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1941                         payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1942                         if (rtp_connect() < 0) {
1943                                 goto rtp_failed;
1944                         }
1945                         sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1946                         PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1947                         nua_respond(p_s_handle, SIP_200_OK,
1948                                 NUTAG_MEDIA_ENABLE(0),
1949                                 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1950                                 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1951                 }
1952                 return;
1953         }
1954
1955         /* open local RTP peer (if not bridging) */
1956         if (!p_s_rtp_bridge && rtp_open() < 0) {
1957                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1958                 nua_handle_destroy(nh);
1959                 p_s_handle = NULL;
1960                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1961                 add_trace("respond", "value", "500 Internal Server Error");
1962                 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1963                 end_trace();
1964                 new_state(PORT_STATE_RELEASE);
1965                 trigger_work(&p_s_delete);
1966                 return;
1967         }
1968
1969         /* apply handle */
1970 //      sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1971 //      add_trace("handle", "new", "0x%x", nh);
1972 //      end_trace();
1973 //
1974         p_s_handle = nh;
1975
1976         sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_IN);
1977         add_trace("rtp", "port", "%d", p_s_rtp_port_remote);
1978         /* caller information */
1979         if (!from[0]) {
1980                 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1981                 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1982                 add_trace("calling", "present", "unavailable");
1983         } else {
1984                 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1985                 add_trace("calling", "present", "allowed");
1986                 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1987                 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1988                 SCPY(p_callerinfo.id, from);
1989                 add_trace("calling", "number", "%s", from);
1990                 SCPY(p_callerinfo.name, name);
1991                 if (name[0])
1992                         add_trace("calling", "name", "%s", name);
1993                 SCPY(p_callerinfo.imsi, imsi);
1994                 if (imsi[0])
1995                         add_trace("calling", "imsi", "%s", imsi);
1996         }
1997         SCPY(p_callerinfo.interface, inst->interface_name);
1998         /* dialing information */
1999         if (to[0]) {
2000                 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
2001                 SCAT(p_dialinginfo.id, to);
2002                 add_trace("dialing", "number", "%s", to);
2003         }
2004         /* redir info */
2005         /* bearer capability */
2006         p_capainfo.bearer_capa = INFO_BC_SPEECH;
2007         p_capainfo.bearer_info1 = (options.law=='a')?3:2;
2008         p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
2009         add_trace("bearer", "capa", "speech");
2010         add_trace("bearer", "mode", "circuit");
2011         /* if packet mode works some day, see dss1.cpp for conditions */
2012         p_capainfo.source_mode = B_MODE_TRANSPARENT;
2013
2014         end_trace();
2015
2016         /* create endpoint */
2017         if (p_epointlist)
2018                 FATAL("Incoming call but already got an endpoint.\n");
2019         if (!(epoint = new Endpoint(p_serial, 0)))
2020                 FATAL("No memory for Endpoint instance\n");
2021         epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
2022         epointlist_new(epoint->ep_serial);
2023
2024 #ifdef NUTAG_AUTO100
2025         /* send trying (proceeding) */
2026         nua_respond(nh, SIP_100_TRYING, TAG_END());
2027         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2028         add_trace("respond", "value", "100 Trying");
2029         end_trace();
2030 #endif
2031
2032         new_state(PORT_STATE_IN_PROCEEDING);
2033
2034         /* send setup message to endpoit */
2035         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
2036         message->param.setup.port_type = p_type;
2037 //      message->param.setup.dtmf = 0;
2038         memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
2039         memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
2040         memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
2041 //      SCPY((char *)message->param.setup.useruser.data, useruser.info);
2042 //      message->param.setup.useruser.len = strlen(mncc->useruser.info);
2043 //      message->param.setup.useruser.protocol = mncc->useruser.proto;
2044         if (p_s_rtp_bridge) {
2045                 int i;
2046
2047                 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
2048                 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
2049                 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
2050                 /* add codecs to setup message */
2051                 for (i = 0; i < payloads; i++) {
2052                         message->param.setup.rtpinfo.media_types[i] = media_types[i];
2053                         message->param.setup.rtpinfo.payload_types[i] = payload_types[i];
2054                         if (i == sizeof(message->param.setup.rtpinfo.payload_types))
2055                                 break;
2056                 }
2057                 message->param.setup.rtpinfo.payloads = i;
2058         }
2059         message_put(message);
2060
2061         /* start option timer */
2062         if (inst->options_interval) {
2063                 PDEBUG(DEBUG_SIP, "Invite received, scheduling option timer with %d seconds\n", inst->options_interval);
2064                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2065         }
2066
2067         p_s_invite_direction = DIRECTION_IN;
2068
2069         /* send progress, if tones are available and if we don't bridge */
2070         if (!p_s_rtp_bridge && interface->is_tones == IS_YES) {
2071                 PDEBUG(DEBUG_SIP, "Connecting audio, since we have tones available\n");
2072                 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
2073                 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
2074                 /* open local RTP peer (if not bridging) */
2075                 if (rtp_connect() < 0) {
2076 rtp_failed:
2077                         nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2078                         nua_handle_destroy(nh);
2079                         p_s_handle = NULL;
2080                         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2081                         add_trace("respond", "value", "500 Internal Server Error");
2082                         add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
2083                         end_trace();
2084                         message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
2085                         message->param.disconnectinfo.cause = 41;
2086                         message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2087                         message_put(message);
2088                         new_state(PORT_STATE_RELEASE);
2089                         trigger_work(&p_s_delete);
2090                         return;
2091                 }
2092
2093                 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
2094                 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
2095
2096                 nua_respond(p_s_handle, SIP_183_SESSION_PROGRESS,
2097                         NUTAG_MEDIA_ENABLE(0),
2098                         SIPTAG_CONTENT_TYPE_STR("application/sdp"),
2099                         SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
2100                 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2101                 add_trace("respond", "value", "183 SESSION PROGRESS");
2102                 add_trace("reason", NULL, "audio available");
2103                 struct in_addr ia;
2104                 memset(&ia, 0, sizeof(ia));
2105                 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
2106                 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
2107                 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
2108                 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
2109                 end_trace();
2110         }
2111 }
2112
2113 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[])
2114 {
2115         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2116
2117         PDEBUG(DEBUG_SIP, "options received\n");
2118
2119         sip_trace_header(this, inst->interface_name, "OPTIONS", DIRECTION_IN);
2120         end_trace();
2121
2122         nua_respond(nh, SIP_200_OK, TAG_END());
2123 }
2124
2125 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[])
2126 {
2127         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2128         struct lcr_msg *message;
2129         int cause = 0;
2130
2131         PDEBUG(DEBUG_SIP, "bye received\n");
2132
2133         sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_IN);
2134         if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
2135                 cause = atoi(sip->sip_reason->re_cause);
2136                 add_trace("cause", "value", "%d", cause);
2137         }
2138         end_trace();
2139
2140 // let stack do bye automaticall, since it will not accept our response for some reason
2141 //      nua_respond(nh, SIP_200_OK, TAG_END());
2142         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2143         add_trace("respond", "value", "200 OK");
2144         end_trace();
2145 //      nua_handle_destroy(nh);
2146         p_s_handle = NULL;
2147
2148         rtp_close();
2149
2150         while(p_epointlist) {
2151                 /* send setup message to endpoit */
2152                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2153                 message->param.disconnectinfo.cause = cause ? : 16;
2154                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2155                 message_put(message);
2156                 /* remove epoint */
2157                 free_epointlist(p_epointlist);
2158         }
2159         new_state(PORT_STATE_RELEASE);
2160         trigger_work(&p_s_delete);
2161 }
2162
2163 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[])
2164 {
2165         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2166         struct lcr_msg *message;
2167
2168         PDEBUG(DEBUG_SIP, "cancel received\n");
2169
2170         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_IN);
2171         end_trace();
2172
2173         nua_handle_destroy(nh);
2174         p_s_handle = NULL;
2175
2176         rtp_close();
2177
2178         while(p_epointlist) {
2179                 /* send setup message to endpoit */
2180                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2181                 message->param.disconnectinfo.cause = 16;
2182                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2183                 message_put(message);
2184                 /* remove epoint */
2185                 free_epointlist(p_epointlist);
2186         }
2187         new_state(PORT_STATE_RELEASE);
2188         trigger_work(&p_s_delete);
2189 }
2190
2191 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[])
2192 {
2193         PDEBUG(DEBUG_SIP, "bye response received\n");
2194
2195         nua_handle_destroy(nh);
2196         p_s_handle = NULL;
2197
2198         rtp_close();
2199
2200         trigger_work(&p_s_delete);
2201 }
2202
2203 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[])
2204 {
2205         PDEBUG(DEBUG_SIP, "cancel response received\n");
2206
2207         nua_handle_destroy(nh);
2208         p_s_handle = NULL;
2209
2210         rtp_close();
2211
2212         trigger_work(&p_s_delete);
2213 }
2214
2215 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[])
2216 {
2217         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2218         struct lcr_msg *message;
2219         int cause = 0, location = 0;
2220         int media_types[32];
2221         uint8_t payload_types[32];
2222         int payloads = 0;
2223
2224         PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
2225
2226         sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2227         add_trace("respond", "value", "%d", status);
2228         end_trace();
2229
2230         if (status == 401 || status == 407) {
2231                 PDEBUG(DEBUG_SIP, "Invite challenge received\n");
2232                 challenge(inst, this, status, phrase, nua, magic, nh, hmagic, sip, tags);
2233                 return;
2234         }
2235
2236         /* connect audio */
2237         if (status == 183 || (status >= 200 && status <= 299)) {
2238                 int ret;
2239
2240                 sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
2241                 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
2242                 if (!ret) {
2243                         if (payloads != 1)
2244                                 ret = 415;
2245                         else if (!p_s_rtp_bridge) {
2246                                 if (media_types[0] != ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW)) {
2247                                         add_trace("error", NULL, "Expected LAW payload type (not bridged)");
2248                                         ret = 415;
2249                                 }
2250                         }
2251                 }
2252                 end_trace();
2253                 if (ret) {
2254                         nua_cancel(nh, TAG_END());
2255                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2256                         add_trace("reason", NULL, "accepted codec does not match");
2257                         end_trace();
2258                         cause = 88;
2259                         location = LOCATION_PRIVATE_LOCAL;
2260                         goto release_with_cause;
2261                 }
2262
2263                 /* connect to remote RTP (if not bridging) */
2264                 if (!p_s_rtp_bridge && rtp_connect() < 0) {
2265                         nua_cancel(nh, TAG_END());
2266                         sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2267                         add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
2268                         end_trace();
2269                         cause = 31;
2270                         location = LOCATION_PRIVATE_LOCAL;
2271                         goto release_with_cause;
2272                 }
2273         }
2274
2275         /* start option timer */
2276         if (inst->options_interval) {
2277                 PDEBUG(DEBUG_SIP, "Invite response, scheduling option timer with %d seconds\n", inst->options_interval);
2278                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2279         }
2280
2281         switch (status) {
2282         case 100:
2283 #if 0
2284                 PDEBUG(DEBUG_SIP, "do proceeding\n");
2285                 new_state(PORT_STATE_OUT_PROCEEDING);
2286                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
2287                 message_put(message);
2288 #endif
2289                 return;
2290         case 180:
2291                 PDEBUG(DEBUG_SIP, "do alerting\n");
2292                 new_state(PORT_STATE_OUT_ALERTING);
2293                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
2294                 message_put(message);
2295                 return;
2296         case 183:
2297                 PDEBUG(DEBUG_SIP, "do progress\n");
2298                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
2299                 message->param.progressinfo.progress = 8;
2300                 message->param.progressinfo.location = 10;
2301                 if (p_s_rtp_bridge) {
2302                         message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2303                         message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
2304                         message->param.progressinfo.rtpinfo.media_types[0] = media_types[0];
2305                         message->param.progressinfo.rtpinfo.payload_types[0] = payload_types[0];
2306                         message->param.progressinfo.rtpinfo.payloads = 1;
2307                 }
2308                 message_put(message);
2309                 return;
2310         case 200:
2311                 status_200:
2312                 PDEBUG(DEBUG_SIP, "do connect\n");
2313                 nua_ack(nh, TAG_END());
2314                 new_state(PORT_STATE_CONNECT);
2315                 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
2316                 if (p_s_rtp_bridge) {
2317                         message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2318                         message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
2319                         message->param.connectinfo.rtpinfo.media_types[0] = media_types[0];
2320                         message->param.connectinfo.rtpinfo.payload_types[0] = payload_types[0];
2321                         message->param.connectinfo.rtpinfo.payloads = 1;
2322                 }
2323                 message_put(message);
2324                 return;
2325         default:
2326                 if (status >= 200 && status <= 299)
2327                         goto status_200;
2328                 if (status < 100 || status > 199)
2329                         break;
2330                 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
2331
2332                 return;
2333         }
2334
2335         cause = status2cause(status);
2336         location = LOCATION_BEYOND;
2337
2338 release_with_cause:
2339         PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
2340
2341         while(p_epointlist) {
2342                 /* send setup message to endpoit */
2343                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2344                 message->param.disconnectinfo.cause = cause;
2345                 message->param.disconnectinfo.location = location;
2346                 message_put(message);
2347                 /* remove epoint */
2348                 free_epointlist(p_epointlist);
2349         }
2350
2351         new_state(PORT_STATE_RELEASE);
2352
2353         rtp_close();
2354
2355         trigger_work(&p_s_delete);
2356 }
2357
2358 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[])
2359 {
2360         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2361         int cause = 0, location = 0;
2362         struct lcr_msg *message;
2363
2364         PDEBUG(DEBUG_SIP, "options result %d received\n", status);
2365
2366         if (status >= 200 && status <= 299) {
2367                 PDEBUG(DEBUG_SIP, "options ok, scheduling option timer with %d seconds\n", inst->options_interval);
2368                 /* restart option timer */
2369                 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2370                 return;
2371         }
2372
2373         nua_handle_destroy(nh);
2374         p_s_handle = NULL;
2375
2376         rtp_close();
2377
2378         cause = status2cause(status);
2379         location = LOCATION_BEYOND;
2380
2381         while(p_epointlist) {
2382                 /* send setup message to endpoit */
2383                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2384                 message->param.disconnectinfo.cause = cause;
2385                 message->param.disconnectinfo.location = location;
2386                 message_put(message);
2387                 /* remove epoint */
2388                 free_epointlist(p_epointlist);
2389         }
2390         new_state(PORT_STATE_RELEASE);
2391         trigger_work(&p_s_delete);
2392 }
2393
2394 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[])
2395 {
2396         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2397
2398         PDEBUG(DEBUG_SIP, "state change received\n");
2399         sip_trace_header(this, inst->interface_name, "STATUS", DIRECTION_OUT);
2400         add_trace("value", NULL, "%d", status);
2401         add_trace("phrase", NULL, "%s", phrase);
2402         end_trace();
2403 }
2404
2405 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[])
2406 {
2407         struct sip_inst *inst = (struct sip_inst *) magic;
2408         class Port *port;
2409         class Psip *psip = NULL;
2410
2411         PDEBUG(DEBUG_SIP, "Event %d from SIP stack received (handle=%p)\n", event, nh);
2412         if (!nh)
2413                 return;
2414
2415         /* hunt for existing handles */
2416         port = port_first;
2417         while(port) {
2418                 if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
2419                         psip = (class Psip *)port;
2420                         if (psip->p_s_handle == nh) {
2421                                 PDEBUG(DEBUG_SIP, "Event found for port %s\n", psip->p_name);
2422                                 break;
2423                         }
2424                 }
2425                 port = port->next;
2426         }
2427         if (!port)
2428                 psip = NULL;
2429
2430         /* new handle */
2431         switch (event) {
2432         case nua_i_options:
2433                 if (!inst->register_handle) {
2434                         PDEBUG(DEBUG_SIP, "New options instance\n");
2435                         inst->register_handle = nh;
2436                 }
2437                 break;
2438         case nua_i_register:
2439                 if (!inst->register_handle) {
2440                         PDEBUG(DEBUG_SIP, "New register instance\n");
2441                         inst->register_handle = nh;
2442                 }
2443                 break;
2444         case nua_i_invite:
2445                 if (!psip) {
2446                         char name[64];
2447                         struct interface *interface = interface_first;
2448
2449                         PDEBUG(DEBUG_SIP, "New psip instance\n");
2450
2451                         /* create call instance */
2452                         SPRINT(name, "%s-%d-in", inst->interface_name, 0);
2453                         while (interface) {
2454                                 if (!strcmp(interface->name, inst->interface_name))
2455                                         break;
2456                                 interface = interface->next;
2457                         }
2458                         if (!interface)
2459                                 FATAL("Cannot find interface %s.\n", inst->interface_name);
2460                         if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
2461                                 FATAL("Cannot create Port instance.\n");
2462                 }
2463                 break;
2464         default:
2465                 if (!psip && !inst->register_handle) {
2466                         PDEBUG(DEBUG_SIP, "Destroying unknown instance\n");
2467                         nua_handle_destroy(nh);
2468                         return;
2469                 }
2470         }
2471
2472         /* handle register process */
2473         if (inst->register_handle == nh) {
2474                 switch (event) {
2475                 case nua_i_options:
2476                         i_options(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2477                         break;
2478                 case nua_i_register:
2479                         i_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2480                         break;
2481                 case nua_r_register:
2482                         r_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2483                         break;
2484                 default:
2485                         PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2486                 }
2487                 return;
2488         }
2489
2490         /* handle port process */
2491         if (!psip) {
2492                 PERROR("no SIP Port found for handel %p\n", nh);
2493                 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2494                 nua_handle_destroy(nh);
2495                 return;
2496         }
2497
2498         switch (event) {
2499         case nua_r_set_params:
2500                 PDEBUG(DEBUG_SIP, "setparam response\n");
2501                 break;
2502         case nua_r_options:
2503                 psip->r_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2504                 break;
2505         case nua_i_error:
2506                 PDEBUG(DEBUG_SIP, "error received\n");
2507                 break;
2508         case nua_i_state:
2509                 psip->i_state(status, phrase, nua, magic, nh, hmagic, sip, tags);
2510                 break;
2511         case nua_i_invite:
2512                 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2513                 break;
2514         case nua_i_ack:
2515                 PDEBUG(DEBUG_SIP, "ack received\n");
2516                 break;
2517         case nua_i_active:
2518                 PDEBUG(DEBUG_SIP, "active received\n");
2519                 break;
2520         case nua_i_options:
2521                 psip->i_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2522                 break;
2523         case nua_i_bye:
2524                 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2525                 break;
2526         case nua_i_cancel:
2527                 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2528                 break;
2529         case nua_r_bye:
2530                 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2531                 break;
2532         case nua_r_cancel:
2533                 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2534                 break;
2535         case nua_r_invite:
2536                 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2537                 break;
2538         case nua_i_terminated:
2539                 PDEBUG(DEBUG_SIP, "terminated received\n");
2540                 break;
2541         default:
2542                 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2543         }
2544 }
2545
2546 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)
2547 {
2548         struct sip_inst *inst = (struct sip_inst *) magic;
2549         su_sockaddr_t sa;
2550         socklen_t addrlen;
2551
2552         PDEBUG(DEBUG_SIP, "Event %d from STUN stack received\n", event);
2553
2554         switch (event) {
2555         case stun_discovery_done:
2556                 addrlen = sizeof(sa);
2557                 memset(&sa, 0, addrlen);
2558                 if (stun_discovery_get_address(sd, &sa, &addrlen) < 0) {
2559                         PDEBUG(DEBUG_SIP, "stun_discovery_get_address failed\n");
2560                         goto failed;
2561                 }
2562                 su_inet_ntop(sa.su_family, SU_ADDR(&sa), inst->public_ip, sizeof(inst->public_ip));
2563                 inst->stun_state = STUN_STATE_RESOLVED;
2564                 /* start timer for next stun request with inst->stun_interval */
2565                 schedule_timer(&inst->stun_retry_timer, inst->stun_interval, 0);
2566                 sip_trace_header(NULL, inst->interface_name, "STUN resolved", DIRECTION_OUT);
2567                 add_trace("ip", "addr", "%s", inst->public_ip);
2568                 end_trace();
2569                 break;
2570         default:
2571 failed:
2572                 PDEBUG(DEBUG_SIP, "STUN failed, starting timer\n");
2573                 inst->stun_state = STUN_STATE_FAILED;
2574                 /* start timer for next stun request (after failing) with STUN_RETRY_TIMER */
2575                 schedule_timer(&inst->stun_retry_timer, STUN_RETRY_TIMER);
2576                 sip_trace_header(NULL, inst->interface_name, "STUN failed", DIRECTION_OUT);
2577                 end_trace();
2578         }
2579 }
2580
2581 /* received shutdown due to termination of RTP */
2582 void Psip::rtp_shutdown(void)
2583 {
2584         struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2585         struct lcr_msg *message;
2586
2587         PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
2588
2589         sip_trace_header(this, inst->interface_name, "RTP terminated", DIRECTION_IN);
2590         end_trace();
2591
2592         nua_handle_destroy(p_s_handle);
2593         p_s_handle = NULL;
2594
2595         while(p_epointlist) {
2596                 /* send setup message to endpoit */
2597                 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2598                 message->param.disconnectinfo.cause = 16;
2599                 message->param.disconnectinfo.location = LOCATION_BEYOND;
2600                 message_put(message);
2601                 /* remove epoint */
2602                 free_epointlist(p_epointlist);
2603         }
2604         new_state(PORT_STATE_RELEASE);
2605         trigger_work(&p_s_delete);
2606 }
2607
2608 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index)
2609 {
2610         class Psip *psip = (class Psip *)instance;
2611         struct sip_inst *inst = (struct sip_inst *) psip->p_s_sip_inst;
2612
2613         sip_trace_header(psip, inst->interface_name, "OPTIONS", psip->p_s_invite_direction);
2614         end_trace();
2615
2616         nua_options(psip->p_s_handle,
2617                 TAG_END());
2618
2619         return 0;
2620 }
2621
2622 static int stun_retry_timer(struct lcr_timer *timer, void *instance, int index)
2623 {
2624         struct sip_inst *inst = (struct sip_inst *)instance;
2625
2626         PDEBUG(DEBUG_SIP, "timeout, restart stun lookup\n");
2627         inst->stun_state = STUN_STATE_UNRESOLVED;
2628
2629         return 0;
2630 }
2631
2632 static int register_retry_timer(struct lcr_timer *timer, void *instance, int index)
2633 {
2634         struct sip_inst *inst = (struct sip_inst *)instance;
2635
2636         PDEBUG(DEBUG_SIP, "timeout, restart register\n");
2637         /* if we have a handle, destroy it and becom unregistered, so registration is
2638          * triggered next */
2639         if (inst->register_handle) {
2640                 /* stop option timer */
2641                 unsched_timer(&inst->register_option_timer);
2642                 nua_handle_destroy(inst->register_handle);
2643                 inst->register_handle = NULL;
2644         }
2645         inst->register_state = REGISTER_STATE_UNREGISTERED;
2646
2647         return 0;
2648 }
2649
2650 static int register_option_timer(struct lcr_timer *timer, void *instance, int index)
2651 {
2652         struct sip_inst *inst = (struct sip_inst *)instance;
2653         sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_OUT);
2654         end_trace();
2655
2656         nua_options(inst->register_handle,
2657                 TAG_END());
2658
2659         return 0;
2660 }
2661
2662 int sip_init_inst(struct interface *interface)
2663 {
2664         struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
2665         char local[256];
2666
2667         interface->sip_inst = inst;
2668         SCPY(inst->interface_name, interface->name);
2669         SCPY(inst->local_peer, interface->sip_local_peer);
2670         SCPY(inst->remote_peer, interface->sip_remote_peer);
2671         if (!inst->remote_peer[0])
2672                 inst->allow_register = 1;
2673         SCPY(inst->asserted_id, interface->sip_asserted_id);
2674         if (interface->sip_register) {
2675                 inst->register_state = REGISTER_STATE_UNREGISTERED;
2676                 SCPY(inst->register_user, interface->sip_register_user);
2677                 SCPY(inst->register_host, interface->sip_register_host);
2678         }
2679         SCPY(inst->auth_user, interface->sip_auth_user);
2680         SCPY(inst->auth_password, interface->sip_auth_password);
2681         SCPY(inst->auth_realm, interface->sip_auth_realm);
2682         inst->register_interval = interface->sip_register_interval;
2683         inst->options_interval = interface->sip_options_interval;
2684
2685         inst->rtp_port_from = interface->rtp_port_from;
2686         inst->rtp_port_to = interface->rtp_port_to;
2687         if (!inst->rtp_port_from || !inst->rtp_port_to) {
2688                 inst->rtp_port_from = RTP_PORT_BASE;
2689                 inst->rtp_port_to = RTP_PORT_MAX;
2690         }
2691         inst->next_rtp_port = inst->rtp_port_from;
2692
2693         /* create timers */
2694         memset(&inst->stun_retry_timer, 0, sizeof(inst->stun_retry_timer));
2695         add_timer(&inst->stun_retry_timer, stun_retry_timer, inst, 0);
2696         memset(&inst->register_retry_timer, 0, sizeof(inst->register_retry_timer));
2697         add_timer(&inst->register_retry_timer, register_retry_timer, inst, 0);
2698         memset(&inst->register_option_timer, 0, sizeof(inst->register_option_timer));
2699         add_timer(&inst->register_option_timer, register_option_timer, inst, 0);
2700
2701         /* init root object */
2702         inst->root = su_root_create(inst);
2703         if (!inst->root) {
2704                 PERROR("Failed to create SIP root\n");
2705                 sip_exit_inst(interface);
2706                 return -EINVAL;
2707         }
2708
2709         SPRINT(local, "sip:%s",inst->local_peer);
2710         if (!strchr(inst->local_peer, ':'))
2711                 SCAT(local, ":5060");
2712         inst->nua = nua_create(inst->root, sip_callback, inst, NUTAG_URL(local), TAG_END());
2713         if (!inst->nua) {
2714                 PERROR("Failed to create SIP stack object\n");
2715                 sip_exit_inst(interface);
2716                 return -EINVAL;
2717         }
2718         nua_set_params(inst->nua,
2719                 SIPTAG_ALLOW_STR("REGISTER,INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
2720                 NUTAG_APPL_METHOD("REGISTER"),
2721                 NUTAG_APPL_METHOD("INVITE"),
2722                 NUTAG_APPL_METHOD("ACK"),
2723 //              NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
2724                 NUTAG_APPL_METHOD("CANCEL"),
2725                 NUTAG_APPL_METHOD("OPTIONS"),
2726                 NUTAG_APPL_METHOD("NOTIFY"),
2727                 NUTAG_APPL_METHOD("INFO"),
2728                 NUTAG_AUTOACK(0),
2729 #ifdef NUTAG_AUTO100
2730                 NUTAG_AUTO100(0),
2731 #endif
2732                 NUTAG_AUTOALERT(0),
2733                 NUTAG_AUTOANSWER(0),
2734                 TAG_NULL());
2735
2736         SCPY(inst->public_ip, interface->sip_public_ip);
2737         if (interface->sip_stun_server[0]) {
2738                 SCPY(inst->stun_server, interface->sip_stun_server);
2739                 inst->stun_interval = interface->sip_stun_interval;
2740                 inst->stun_handle = stun_handle_init(inst->root,
2741                         STUNTAG_SERVER(inst->stun_server),
2742                         TAG_NULL());
2743                 if (!inst->stun_handle) {
2744                         PERROR("Failed to create STUN handle\n");
2745                         sip_exit_inst(interface);
2746                         return -EINVAL;
2747                 }
2748                 inst->stun_socket = su_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
2749                 if (inst->stun_socket < 0) {
2750                         PERROR("Failed to create STUN socket\n");
2751                         sip_exit_inst(interface);
2752                         return -EINVAL;
2753                 }
2754                 inst->stun_state = STUN_STATE_UNRESOLVED;
2755         }
2756
2757         PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
2758
2759         any_sip_interface = 1;
2760
2761         return 0;
2762 }
2763
2764 void sip_exit_inst(struct interface *interface)
2765 {
2766         struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
2767
2768         if (!inst)
2769                 return;
2770         del_timer(&inst->stun_retry_timer);
2771         del_timer(&inst->register_retry_timer);
2772         del_timer(&inst->register_option_timer);
2773         if (inst->stun_socket)
2774                 su_close(inst->stun_socket);
2775         if (inst->stun_handle)
2776                 stun_handle_destroy(inst->stun_handle);
2777         if (inst->register_handle)
2778                 nua_handle_destroy(inst->register_handle);
2779         if (inst->root)
2780                 su_root_destroy(inst->root);
2781         if (inst->nua)
2782                 nua_destroy(inst->nua);
2783         FREE(inst, sizeof(*inst));
2784         interface->sip_inst = NULL;
2785
2786         PDEBUG(DEBUG_SIP, "SIP interface removed\n");
2787
2788         /* check if there is any other SIP interface left */
2789         interface = interface_first;
2790         while (interface) {
2791                 if (interface->sip_inst)
2792                         break;
2793                 interface = interface->next;
2794         }
2795         if (!interface)
2796                 any_sip_interface = 0;
2797 }
2798
2799 extern su_log_t su_log_default[];
2800 extern su_log_t nua_log[];
2801
2802 int sip_init(void)
2803 {
2804         int i;
2805
2806         /* init SOFIA lib */
2807         su_init();
2808         su_home_init(sip_home);
2809
2810         if (options.deb & DEBUG_SIP) {
2811                 su_log_set_level(su_log_default, 9);
2812                 su_log_set_level(nua_log, 9);
2813                 //su_log_set_level(soa_log, 9);
2814         }
2815
2816         for (i = 0; i < 256; i++)
2817                 flip[i] = ((i & 1) << 7) + ((i & 2) << 5) + ((i & 4) << 3) + ((i & 8) << 1) + ((i & 16) >> 1) + ((i & 32) >> 3) + ((i & 64) >> 5) + ((i & 128) >> 7);
2818
2819         PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
2820
2821         return 0;
2822 }
2823
2824 void sip_exit(void)
2825 {
2826         su_home_deinit(sip_home);
2827         su_deinit();
2828
2829         PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
2830 }
2831
2832 static void sip_handle_stun(struct sip_inst *inst)
2833 {
2834         int rc;
2835
2836         switch (inst->stun_state) {
2837         case STUN_STATE_UNRESOLVED:
2838                 PDEBUG(DEBUG_SIP, "Trying to to get local IP from stun server\n");
2839                 rc = stun_bind(inst->stun_handle, stun_bind_cb, (stun_discovery_magic_t *)inst,
2840                         STUNTAG_SOCKET(inst->stun_socket),
2841                         STUNTAG_REGISTER_EVENTS(1),
2842                         TAG_NULL());
2843                 if (rc < 0) {
2844                         PERROR("Failed to call stun_bind()\n");
2845                         inst->stun_state = STUN_STATE_FAILED;
2846                         break;
2847                 }
2848                 inst->stun_state = STUN_STATE_RESOLVING;
2849                 sip_trace_header(NULL, inst->interface_name, "STUN resolving", DIRECTION_OUT);
2850                 add_trace("server", "addr", "%s", inst->stun_server);
2851                 end_trace();
2852                 break;
2853         }
2854 }
2855
2856 static void sip_handle_register(struct sip_inst *inst)
2857 {
2858         char from[128] = "";
2859         char to[128] = "";
2860         char contact[128] = "";
2861
2862         switch (inst->register_state) {
2863         case REGISTER_STATE_UNREGISTERED:
2864                 /* wait for resoved stun */
2865                 if (inst->stun_handle && inst->stun_state != STUN_STATE_RESOLVED)
2866                         return;
2867
2868                 PDEBUG(DEBUG_SIP, "Registering to peer\n");
2869                 inst->register_handle = nua_handle(inst->nua, NULL, TAG_END());
2870                 if (!inst->register_handle) {
2871                         PERROR("Failed to create handle\n");
2872                         inst->register_state = REGISTER_STATE_FAILED;
2873                         break;
2874                 }
2875                 /* apply handle to trace */
2876 //              sip_trace_header(NULL, inst->interface_name, "NEW handle", DIRECTION_NONE);
2877 //              add_trace("handle", "new", "0x%x", inst->register_handle);
2878 //              end_trace();
2879
2880                 SPRINT(from, "sip:%s@%s", inst->register_user, inst->register_host);
2881                 SPRINT(to, "sip:%s@%s", inst->register_user, inst->register_host);
2882                 if (inst->public_ip[0]) {
2883                         char *p;
2884                         SPRINT(contact, "sip:%s@%s", inst->register_user, inst->public_ip);
2885                         p = strchr(inst->local_peer, ':');
2886                         if (p)
2887                                 SCAT(contact, p);
2888                 }
2889
2890                 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_OUT);
2891                 add_trace("from", "uri", "%s", from);
2892                 add_trace("to", "uri", "%s", to);
2893                 end_trace();
2894
2895                 nua_register(inst->register_handle,
2896                         TAG_IF(from[0], SIPTAG_FROM_STR(from)),
2897                         TAG_IF(to[0], SIPTAG_TO_STR(to)),
2898                         TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
2899                         TAG_END());
2900
2901                 inst->register_state = REGISTER_STATE_REGISTERING;
2902
2903                 break;
2904         }
2905         
2906 }
2907
2908 void sip_handle(void)
2909 {
2910         struct interface *interface = interface_first;
2911         struct sip_inst *inst;
2912
2913         while (interface) {
2914                 if (interface->sip_inst) {
2915                         inst = (struct sip_inst *) interface->sip_inst;
2916                         su_root_step(inst->root, 0);
2917                         sip_handle_stun(inst);
2918                         sip_handle_register(inst);
2919                 }
2920                 interface = interface->next;
2921         }
2922 }
2923
2924 /* deletes when back in event loop */
2925 static int delete_event(struct lcr_work *work, void *instance, int index)
2926 {
2927         class Psip *psip = (class Psip *)instance;
2928
2929         delete psip;
2930
2931         return 0;
2932 }
2933
2934
2935 /*
2936  * generate audio, if no data is received from bridge
2937  */
2938
2939 void Psip::set_tone(const char *dir, const char *tone)
2940 {
2941         Port::set_tone(dir, tone);
2942
2943         update_load();
2944 }
2945
2946 void Psip::update_load(void)
2947 {
2948         /* don't trigger load event if event already active */
2949         if (p_s_load_timer.active)
2950                 return;
2951
2952         /* don't start timer if ... */
2953         if (!p_tone_name[0] && !p_dov_tx)
2954                 return;
2955
2956         p_s_next_tv_sec = 0;
2957         schedule_timer(&p_s_load_timer, 0, 0); /* no delay the first time */
2958 }
2959
2960 static int load_timer(struct lcr_timer *timer, void *instance, int index)
2961 {
2962         class Psip *psip = (class Psip *)instance;
2963
2964         /* stop timer if ... */
2965         if (!psip->p_tone_name[0] && !psip->p_dov_tx)
2966                 return 0;
2967
2968         psip->load_tx();
2969
2970         return 0;
2971 }
2972
2973 #define SEND_SIP_LEN 160
2974
2975 void Psip::load_tx(void)
2976 {
2977         int diff;
2978         struct timeval current_time;
2979         int tosend = SEND_SIP_LEN, i;
2980         unsigned char buf[SEND_SIP_LEN], *p = buf;
2981
2982         /* get elapsed */
2983         gettimeofday(&current_time, NULL);
2984         if (!p_s_next_tv_sec) {
2985                 /* if timer expired the first time, set next expected timeout 160 samples in advance */
2986                 p_s_next_tv_sec = current_time.tv_sec;
2987                 p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2988                 if (p_s_next_tv_usec >= 1000000) {
2989                         p_s_next_tv_usec -= 1000000;
2990                         p_s_next_tv_sec++;
2991                 }
2992                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125);
2993         } else {
2994                 diff = 1000000 * (current_time.tv_sec - p_s_next_tv_sec)
2995                         + (current_time.tv_usec - p_s_next_tv_usec);
2996                 if (diff < -SEND_SIP_LEN * 125 || diff > SEND_SIP_LEN * 125) {
2997                         /* if clock drifts too much, set next timeout event to current timer + 160 */
2998                         diff = 0;
2999                         p_s_next_tv_sec = current_time.tv_sec;
3000                         p_s_next_tv_usec = current_time.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                 } else {
3006                         /* if diff is positive, it took too long, so next timeout will be earlier */
3007                         p_s_next_tv_usec += SEND_SIP_LEN * 125;
3008                         if (p_s_next_tv_usec >= 1000000) {
3009                                 p_s_next_tv_usec -= 1000000;
3010                                 p_s_next_tv_sec++;
3011                         }
3012                 }
3013                 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125 - diff);
3014         }
3015
3016         /* copy tones */
3017         if (p_tone_name[0]) {
3018                 tosend -= read_audio(p, tosend);
3019         } else
3020         if (p_dov_tx) {
3021                 tosend -= dov_tx(p, tosend);
3022         }
3023         if (tosend) {
3024                 PERROR("buffer is not completely filled\n");
3025                 return;
3026         }
3027
3028         p = buf;
3029         for (i = 0; i < SEND_SIP_LEN; i++) {
3030                 *p = flip[*p];
3031                 p++;
3032         }
3033         /* transmit data via rtp */
3034         rtp_send_frame(buf, SEND_SIP_LEN, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
3035 }
3036