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