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