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