1 /*****************************************************************************\
3 ** Linux Call Router **
5 **---------------------------------------------------------------------------**
6 ** Copyright: Andreas Eversberg **
10 \*****************************************************************************/
13 #include <sofia-sip/sip_status.h>
14 #include <sofia-sip/su_log.h>
15 #include <sofia-sip/sdp.h>
16 #include <sofia-sip/sip_header.h>
17 #include <sofia-sip/stun.h>
18 #include <sofia-sip/stun_tag.h>
19 #include <sofia-sip/su_md5.h>
21 #ifndef SOFIA_SIP_GCC_4_8_PATCH_APLLIED
22 #warning ********************************************************
23 #warning Please apply the sofia-sip-gcc-4.8.patch !
24 #warning If this issue is already fixed, just remove this check.
25 #warning ********************************************************
31 unsigned char flip[256];
33 int any_sip_interface = 0;
35 //pthread_mutex_t mutex_msg;
36 su_home_t sip_home[1];
38 #define REGISTER_STATE_UNREGISTERED 1
39 #define REGISTER_STATE_REGISTERING 2
40 #define REGISTER_STATE_REGISTERED 3
41 #define REGISTER_STATE_FAILED 4
43 #define STUN_RETRY_TIMER 10, 0
44 #define REGISTER_RETRY_TIMER 10, 0
46 #define STUN_STATE_UNRESOLVED 1
47 #define STUN_STATE_RESOLVING 2
48 #define STUN_STATE_RESOLVED 3
49 #define STUN_STATE_FAILED 4
51 #define RTP_PORT_BASE 30000
52 #define RTP_PORT_MAX 39998
55 char interface_name[64];
57 char remote_peer[128];
58 char asserted_id[128];
61 char register_user[128];
62 char register_host[128];
63 nua_handle_t *register_handle;
64 struct lcr_timer register_retry_timer;
65 struct lcr_timer register_option_timer;
66 int register_interval;
69 char auth_password[128];
77 char stun_server[128];
78 stun_handle_t *stun_handle;
79 su_socket_t stun_socket;
80 struct lcr_timer stun_retry_timer;
83 unsigned short rtp_port_from;
84 unsigned short rtp_port_to;
85 unsigned short next_rtp_port;
89 static int delete_event(struct lcr_work *work, void *instance, int index);
90 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index);
91 static int load_timer(struct lcr_timer *timer, void *instance, int index);
96 Psip::Psip(int type, char *portname, struct port_settings *settings, struct interface *interface) : Port(type, portname, settings, interface)
99 if (interface->rtp_bridge)
101 p_s_sip_inst = interface->sip_inst;
102 memset(&p_s_delete, 0, sizeof(p_s_delete));
103 add_work(&p_s_delete, delete_event, this, 0);
106 memset(&p_s_rtp_fd, 0, sizeof(p_s_rtp_fd));
107 memset(&p_s_rtcp_fd, 0, sizeof(p_s_rtcp_fd));
108 memset(&p_s_rtp_sin_local, 0, sizeof(p_s_rtp_sin_local));
109 memset(&p_s_rtcp_sin_local, 0, sizeof(p_s_rtcp_sin_local));
110 memset(&p_s_rtp_sin_remote, 0, sizeof(p_s_rtp_sin_remote));
111 memset(&p_s_rtcp_sin_remote, 0, sizeof(p_s_rtcp_sin_remote));
112 p_s_rtp_ip_local = 0;
113 p_s_rtp_ip_remote = 0;
114 p_s_rtp_port_local = 0;
115 p_s_rtp_port_remote = 0;
120 p_s_rtp_tx_action = 0;
121 p_s_rtp_is_connected = 0;
123 /* create option timer */
124 memset(&p_s_invite_option_timer, 0, sizeof(p_s_invite_option_timer));
125 add_timer(&p_s_invite_option_timer, invite_option_timer, this, 0);
126 p_s_invite_direction = 0;
129 memset(&p_s_load_timer, 0, sizeof(p_s_load_timer));
130 add_timer(&p_s_load_timer, load_timer, this, 0);
133 PDEBUG(DEBUG_SIP, "Created new Psip(%s).\n", portname);
135 FATAL("No SIP instance for interface\n");
144 PDEBUG(DEBUG_SIP, "Destroyed SIP process(%s).\n", p_name);
146 del_timer(&p_s_invite_option_timer);
147 del_timer(&p_s_load_timer);
148 del_work(&p_s_delete);
153 static const char *media_type2name(uint8_t media_type) {
154 switch (media_type) {
155 case MEDIA_TYPE_ULAW:
157 case MEDIA_TYPE_ALAW:
161 case MEDIA_TYPE_GSM_HR:
163 case MEDIA_TYPE_GSM_EFR:
172 static void sip_trace_header(class Psip *sip, const char *interface_name, const char *message, int direction)
174 struct interface *interface = NULL;
177 interface = getinterfacebyname(interface_name);
179 /* init trace with given values */
182 sip?numberrize_callerinfo(sip->p_callerinfo.id, sip->p_callerinfo.ntype, options.national, options.international):NULL,
183 sip?sip->p_dialinginfo.id:NULL,
194 /* according to RFC 3550 */
196 #if __BYTE_ORDER == __LITTLE_ENDIAN
197 uint8_t csrc_count:4,
201 uint8_t payload_type:7,
203 #elif __BYTE_ORDER == __BIG_ENDIAN
214 } __attribute__((packed));
219 } __attribute__((packed));
221 #define RTP_VERSION 2
223 #define PAYLOAD_TYPE_ULAW 0
224 #define PAYLOAD_TYPE_ALAW 8
225 #define PAYLOAD_TYPE_GSM 3
227 /* decode an rtp frame */
228 static int rtp_decode(class Psip *psip, unsigned char *data, int len)
230 struct rtp_hdr *rtph = (struct rtp_hdr *)data;
231 struct rtp_x_hdr *rtpxh;
235 unsigned char *from, *to;
239 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d)\n", len);
242 if (rtph->version != RTP_VERSION) {
243 PDEBUG(DEBUG_SIP, "received RTP version %d not supported.\n", rtph->version);
246 payload = data + sizeof(struct rtp_hdr) + (rtph->csrc_count << 2);
247 payload_len = len - sizeof(struct rtp_hdr) - (rtph->csrc_count << 2);
248 if (payload_len < 0) {
249 PDEBUG(DEBUG_SIP, "received RTP frame too short (len = %d, "
250 "csrc count = %d)\n", len, rtph->csrc_count);
253 if (rtph->extension) {
254 if (payload_len < (int)sizeof(struct rtp_x_hdr)) {
255 PDEBUG(DEBUG_SIP, "received RTP frame too short for "
256 "extension header\n");
259 rtpxh = (struct rtp_x_hdr *)payload;
260 x_len = ntohs(rtpxh->length) * 4 + sizeof(struct rtp_x_hdr);
262 payload_len -= x_len;
263 if (payload_len < 0) {
264 PDEBUG(DEBUG_SIP, "received RTP frame too short, "
265 "extension header exceeds frame length\n");
270 if (payload_len < 0) {
271 PDEBUG(DEBUG_SIP, "received RTP frame too short for "
275 payload_len -= payload[payload_len - 1];
276 if (payload_len < 0) {
277 PDEBUG(DEBUG_SIP, "received RTP frame with padding "
278 "greater than payload\n");
283 switch (rtph->payload_type) {
285 we only support alaw and ulaw!
286 case RTP_PT_GSM_FULL:
287 if (payload_len != 33) {
288 PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
289 "payload length != 33 (len = %d)\n",
295 if (payload_len != 31) {
296 PDEBUG(DEBUG_SIP, "received RTP full rate frame with "
297 "payload length != 31 (len = %d)\n",
302 case RTP_PT_GSM_HALF:
303 if (payload_len != 14) {
304 PDEBUG(DEBUG_SIP, "received RTP half rate frame with "
305 "payload length != 14 (len = %d)\n",
311 case PAYLOAD_TYPE_ALAW:
312 if (options.law != 'a') {
313 PDEBUG(DEBUG_SIP, "received Alaw, but we don't do Alaw\n");
317 case PAYLOAD_TYPE_ULAW:
318 if (options.law == 'a') {
319 PDEBUG(DEBUG_SIP, "received Ulaw, but we don't do Ulaw\n");
324 PDEBUG(DEBUG_SIP, "received RTP frame with unknown payload "
325 "type %d\n", rtph->payload_type);
329 if (payload_len <= 0) {
330 PDEBUG(DEBUG_SIP, "received RTP payload is too small: %d\n", payload_len);
336 psip->record(payload, payload_len, 0); // from down
338 psip->tap(payload, payload_len, 0); // from down
343 if (psip->p_echotest) {
344 /* echo rtp data we just received */
345 psip->rtp_send_frame(from, n, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
349 *to++ = flip[*from++];
351 psip->dov_rx(payload, payload_len);
352 psip->bridge_tx(payload, payload_len);
357 static int rtp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
359 class Psip *psip = (class Psip *) instance;
361 unsigned char buffer[256];
364 if ((what & LCR_FD_READ)) {
365 len = read(fd->fd, &buffer, sizeof(buffer));
367 PDEBUG(DEBUG_SIP, "read result=%d\n", len);
368 // psip->rtp_close();
369 // psip->rtp_shutdown();
372 if (psip->p_s_rtp_is_connected)
373 rc = rtp_decode(psip, buffer, len);
379 static int rtcp_sock_callback(struct lcr_fd *fd, unsigned int what, void *instance, int index)
381 // class Psip *psip = (class Psip *) instance;
383 unsigned char buffer[256];
385 if ((what & LCR_FD_READ)) {
386 len = read(fd->fd, &buffer, sizeof(buffer));
388 PDEBUG(DEBUG_SIP, "read result=%d\n", len);
389 // psip->rtp_close();
390 // psip->rtp_shutdown();
393 PDEBUG(DEBUG_SIP, "rtcp!\n");
399 static int rtp_sub_socket_bind(int fd, struct sockaddr_in *sin_local, uint32_t ip, uint16_t port)
402 socklen_t alen = sizeof(*sin_local);
404 sin_local->sin_family = AF_INET;
405 sin_local->sin_addr.s_addr = htonl(ip);
406 sin_local->sin_port = htons(port);
408 rc = bind(fd, (struct sockaddr *) sin_local, sizeof(*sin_local));
412 /* retrieve the address we actually bound to, in case we
413 * passed INADDR_ANY as IP address */
414 return getsockname(fd, (struct sockaddr *) sin_local, &alen);
417 static int rtp_sub_socket_connect(int fd, struct sockaddr_in *sin_local, struct sockaddr_in *sin_remote, uint32_t ip, uint16_t port)
420 socklen_t alen = sizeof(*sin_local);
422 sin_remote->sin_family = AF_INET;
423 sin_remote->sin_addr.s_addr = htonl(ip);
424 sin_remote->sin_port = htons(port);
426 rc = connect(fd, (struct sockaddr *) sin_remote, sizeof(*sin_remote));
428 PERROR("failed to connect to ip %08x port %d rc=%d\n", ip, port, rc);
432 return getsockname(fd, (struct sockaddr *) sin_local, &alen);
435 int Psip::rtp_open(void)
437 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
439 // struct in_addr ia;
441 unsigned short start_port;
443 PDEBUG(DEBUG_SIP, "rtp_open\n");
446 rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
452 register_fd(&p_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
454 rc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
460 register_fd(&p_s_rtcp_fd, LCR_FD_READ, rtcp_sock_callback, this, 0);
463 ip = htonl(INADDR_ANY);
464 start_port = inst->next_rtp_port;
466 rc = rtp_sub_socket_bind(p_s_rtp_fd.fd, &p_s_rtp_sin_local, ip, inst->next_rtp_port);
470 rc = rtp_sub_socket_bind(p_s_rtcp_fd.fd, &p_s_rtcp_sin_local, ip, inst->next_rtp_port + 1);
472 p_s_rtp_port_local = inst->next_rtp_port;
473 inst->next_rtp_port = (inst->next_rtp_port + 2 > inst->rtp_port_to) ? inst->rtp_port_from : inst->next_rtp_port + 2;
476 /* reopen rtp socket and try again with next udp port */
477 unregister_fd(&p_s_rtp_fd);
478 close(p_s_rtp_fd.fd);
480 rc2 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
486 register_fd(&p_s_rtp_fd, LCR_FD_READ, rtp_sock_callback, this, 0);
489 inst->next_rtp_port = (inst->next_rtp_port + 2 > inst->rtp_port_to) ? inst->rtp_port_from : inst->next_rtp_port + 2;
490 if (inst->next_rtp_port == start_port)
492 /* we must use rc2, in order to preserve rc */
495 PDEBUG(DEBUG_SIP, "failed to find port\n");
499 p_s_rtp_ip_local = ntohl(p_s_rtp_sin_local.sin_addr.s_addr);
500 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
501 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
503 return p_s_rtp_port_local;
506 int Psip::rtp_connect(void)
511 ia.s_addr = htonl(p_s_rtp_ip_remote);
512 if (p_s_rtp_is_connected)
513 PDEBUG(DEBUG_SIP, "reconnecting existing RTP connection to new/same destination\n");
514 PDEBUG(DEBUG_SIP, "rtp_connect(ip=%s, port=%u)\n", inet_ntoa(ia), p_s_rtp_port_remote);
516 rc = rtp_sub_socket_connect(p_s_rtp_fd.fd, &p_s_rtp_sin_local, &p_s_rtp_sin_remote, p_s_rtp_ip_remote, p_s_rtp_port_remote);
520 rc = rtp_sub_socket_connect(p_s_rtcp_fd.fd, &p_s_rtcp_sin_local, &p_s_rtcp_sin_remote, p_s_rtp_ip_remote, p_s_rtp_port_remote + 1);
524 p_s_rtp_ip_local = ntohl(p_s_rtp_sin_local.sin_addr.s_addr);
525 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
526 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
527 p_s_rtp_is_connected = 1;
531 void Psip::rtp_close(void)
533 if (p_s_rtp_fd.fd > 0) {
534 unregister_fd(&p_s_rtp_fd);
535 close(p_s_rtp_fd.fd);
538 if (p_s_rtcp_fd.fd > 0) {
539 unregister_fd(&p_s_rtcp_fd);
540 close(p_s_rtcp_fd.fd);
543 if (p_s_rtp_is_connected) {
544 PDEBUG(DEBUG_SIP, "rtp closed\n");
545 p_s_rtp_is_connected = 0;
550 void tv_difference(struct timeval *diff, const struct timeval *from,
551 const struct timeval *__to)
553 struct timeval _to = *__to, *to = &_to;
555 if (to->tv_usec < from->tv_usec) {
557 to->tv_usec += 1000000;
560 diff->tv_usec = to->tv_usec - from->tv_usec;
561 diff->tv_sec = to->tv_sec - from->tv_sec;
564 /* encode and send a rtp frame */
565 int Psip::rtp_send_frame(unsigned char *data, unsigned int len, uint8_t payload_type)
567 struct rtp_hdr *rtph;
569 int duration; /* in samples */
570 unsigned char buffer[256];
574 record(data, len, 1); // from up
576 tap(data, len, 1); // from up
578 if (!p_s_rtp_is_connected) {
583 if (!p_s_rtp_tx_action) {
584 /* initialize sequences */
585 p_s_rtp_tx_action = 1;
586 p_s_rtp_tx_ssrc = rand();
587 p_s_rtp_tx_sequence = random();
588 p_s_rtp_tx_timestamp = random();
589 memset(&p_s_rtp_tx_last_tv, 0, sizeof(p_s_rtp_tx_last_tv));
592 switch (payload_type) {
594 we only support alaw and ulaw!
595 case RTP_PT_GSM_FULL:
603 case RTP_PT_GSM_HALF:
608 case PAYLOAD_TYPE_ALAW:
609 case PAYLOAD_TYPE_ULAW:
614 PERROR("unsupported message type %d\n", payload_type);
620 struct timeval tv, tv_diff;
621 long int usec_diff, frame_diff;
623 gettimeofday(&tv, NULL);
624 tv_difference(&tv_diff, &p_s_rtp_tx_last_tv, &tv);
625 p_s_rtp_tx_last_tv = tv;
627 usec_diff = tv_diff.tv_sec * 1000000 + tv_diff.tv_usec;
628 frame_diff = (usec_diff / 20000);
630 if (abs(frame_diff) > 1) {
631 long int frame_diff_excess = frame_diff - 1;
633 PDEBUG(DEBUG_SIP, "Correcting frame difference of %ld frames\n", frame_diff_excess);
634 p_s_rtp_tx_sequence += frame_diff_excess;
635 p_s_rtp_tx_timestamp += frame_diff_excess * duration;
640 rtph = (struct rtp_hdr *) buffer;
641 rtph->version = RTP_VERSION;
644 rtph->csrc_count = 0;
646 rtph->payload_type = payload_type;
647 rtph->sequence = htons(p_s_rtp_tx_sequence++);
648 rtph->timestamp = htonl(p_s_rtp_tx_timestamp);
649 p_s_rtp_tx_timestamp += duration;
650 rtph->ssrc = htonl(p_s_rtp_tx_ssrc);
651 memcpy(buffer + sizeof(struct rtp_hdr), data, payload_len);
653 if (p_s_rtp_fd.fd > 0) {
654 len = write(p_s_rtp_fd.fd, &buffer, sizeof(struct rtp_hdr) + payload_len);
655 if (len != sizeof(struct rtp_hdr) + payload_len) {
656 PDEBUG(DEBUG_SIP, "write result=%d\n", len);
666 /* receive from remote */
667 int Psip::bridge_rx(unsigned char *data, int len)
671 /* don't bridge, if tones are provided */
672 if (p_tone_name[0] || p_dov_tx)
678 if ((ret = Port::bridge_rx(data, len)))
681 /* write to rx buffer */
683 p_s_rxdata[p_s_rxpos++] = flip[*data++];
684 if (p_s_rxpos == 160) {
687 /* transmit data via rtp */
688 rtp_send_frame(p_s_rxdata, 160, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);
695 /* taken from freeswitch */
696 /* map sip responses to QSIG cause codes ala RFC4497 section 8.4.4 */
697 static int status2cause(int status)
701 return 16; //SWITCH_CAUSE_NORMAL_CLEARING;
707 return 21; //SWITCH_CAUSE_CALL_REJECTED;
709 return 1; //SWITCH_CAUSE_UNALLOCATED_NUMBER;
712 return 3; //SWITCH_CAUSE_NO_ROUTE_DESTINATION;
715 return 102; //SWITCH_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
717 return 22; //SWITCH_CAUSE_NUMBER_CHANGED;
726 return 127; //SWITCH_CAUSE_INTERWORKING;
728 return 180; //SWITCH_CAUSE_NO_USER_RESPONSE;
733 return 41; //SWITCH_CAUSE_NORMAL_TEMPORARY_FAILURE;
736 return 17; //SWITCH_CAUSE_USER_BUSY;
738 return 28; //SWITCH_CAUSE_INVALID_NUMBER_FORMAT;
741 return 88; //SWITCH_CAUSE_INCOMPATIBLE_DESTINATION;
743 return 38; //SWITCH_CAUSE_NETWORK_OUT_OF_ORDER;
745 return 63; //SWITCH_CAUSE_SERVICE_UNAVAILABLE;
749 return 79; //SWITCH_CAUSE_SERVICE_NOT_IMPLEMENTED;
752 return 25; //SWITCH_CAUSE_EXCHANGE_ROUTING_ERROR;
754 return 31; //??? SWITCH_CAUSE_ORIGINATOR_CANCEL;
756 return 31; //SWITCH_CAUSE_NORMAL_UNSPECIFIED;
760 static int cause2status(int cause, int location, const char **st)
766 s = 404; *st = sip_404_Not_found;
769 s = 404; *st = sip_404_Not_found;
772 s = 404; *st = sip_404_Not_found;
775 s = 486; *st = sip_486_Busy_here;
778 s = 408; *st = sip_408_Request_timeout;
781 s = 480; *st = sip_480_Temporarily_unavailable;
784 s = 480; *st = sip_480_Temporarily_unavailable;
787 if (location == LOCATION_USER) {
788 s = 603; *st = sip_603_Decline;
790 s = 403; *st = sip_403_Forbidden;
794 //s = 301; *st = sip_301_Moved_permanently;
795 s = 410; *st = sip_410_Gone;
798 s = 410; *st = sip_410_Gone;
801 s = 404; *st = sip_404_Not_found;
804 s = 502; *st = sip_502_Bad_gateway;
807 s = 484; *st = sip_484_Address_incomplete;
810 s = 501; *st = sip_501_Not_implemented;
813 s = 480; *st = sip_480_Temporarily_unavailable;
816 s = 503; *st = sip_503_Service_unavailable;
819 s = 503; *st = sip_503_Service_unavailable;
822 s = 503; *st = sip_503_Service_unavailable;
825 s = 503; *st = sip_503_Service_unavailable;
828 s = 503; *st = sip_503_Service_unavailable;
831 s = 403; *st = sip_403_Forbidden;
834 s = 403; *st = sip_403_Forbidden;
837 s = 503; *st = sip_503_Service_unavailable;
840 s = 488; *st = sip_488_Not_acceptable;
843 s = 501; *st = sip_501_Not_implemented;
846 s = 488; *st = sip_488_Not_acceptable;
849 s = 501; *st = sip_501_Not_implemented;
852 s = 403; *st = sip_403_Forbidden;
855 s = 503; *st = sip_503_Service_unavailable;
858 s = 504; *st = sip_504_Gateway_time_out;
861 s = 500; *st = sip_500_Internal_server_error;
864 s = 500; *st = sip_500_Internal_server_error;
867 s = 468; *st = sip_486_Busy_here;
873 /* use STUN ip, or return the ip without change */
874 unsigned int Psip::get_local_ip(unsigned int ip)
876 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
878 if (inst->public_ip[0]) {
879 PDEBUG(DEBUG_SIP, "RTP local IP is replaced by STUN ip %s\n", inst->public_ip);
880 inet_pton(AF_INET, inst->public_ip, &ip);
886 /* some simple nonce generator */
887 static void generate_nonce(char *result)
889 UPRINT(result, "%08x", (unsigned int)random());
891 UPRINT(result, "%08x", (unsigned int)random());
893 UPRINT(result, "%08x", (unsigned int)random());
895 UPRINT(result, "%08x", (unsigned int)random());
898 /* check authorization */
899 static int check_authorization(sip_authorization_t const *authorization, const char *regstr, const char *check_user, const char *check_pass, const char *check_realm, const char *check_nonce, const char **auth_text)
902 *auth_text = "Internal Server Error";
904 char *username = NULL;
911 char *response = NULL;
916 char temp[256], first_digest[2 * SU_MD5_DIGEST_SIZE + 1], second_digest[2 * SU_MD5_DIGEST_SIZE + 1], third_digest[2 * SU_MD5_DIGEST_SIZE + 1];
919 if (!check_nonce || !check_nonce[0] || !authorization || !authorization->au_params) {
920 if (!strcmp(regstr, "REGISTER")) {
921 *auth_text = "Unauthorized";
924 *auth_text = "Proxy Authentication Required";
930 /* parse header (stolen from freeswitch) */
931 for (indexnum = 0; (cur = authorization->au_params[indexnum]); indexnum++) {
932 char *var, *val, *p, *work;
933 var = val = work = NULL;
934 if ((work = strdup(cur))) {
936 if ((val = strchr(var, '='))) {
938 while (*val == '"') {
941 if ((p = strchr(val, '"'))) {
945 PDEBUG(DEBUG_SIP, "Found in Auth header: %s = %s\n", var, val);
946 if (!strcasecmp(var, "username")) {
947 username = strdup(val);
948 } else if (!strcasecmp(var, "realm")) {
950 } else if (!strcasecmp(var, "nonce")) {
952 } else if (!strcasecmp(var, "uri")) {
954 } else if (!strcasecmp(var, "qop")) {
956 } else if (!strcasecmp(var, "cnonce")) {
957 cnonce = strdup(val);
958 } else if (!strcasecmp(var, "response")) {
959 response = strdup(val);
960 } else if (!strcasecmp(var, "nc")) {
969 if (!username || !realm || !nonce || ! uri || !response) {
970 *auth_text = "Authorization header incomplete";
975 if (!!strcmp(username, check_user)) {
976 *auth_text = "Authorization Username Missmatch";
980 if (!!strcmp(realm, check_realm)) {
981 *auth_text = "Authorization Realm Missmatch";
985 if (!!strcmp(nonce, check_nonce)) {
986 *auth_text = "Authorization Nonce Missmatch";
992 SPRINT(temp, "%s:%s:%s", check_user, realm, check_pass);
993 PDEBUG(DEBUG_SIP, "First hash: %s\n", temp);
994 su_md5_init(&md5_ctx);
995 su_md5_strupdate(&md5_ctx, temp);
996 su_md5_hexdigest(&md5_ctx, first_digest);
997 su_md5_deinit(&md5_ctx);
999 SPRINT(temp, "%s:%s", regstr, uri);
1000 PDEBUG(DEBUG_SIP, "Second hash: %s\n", temp);
1001 su_md5_init(&md5_ctx);
1002 su_md5_strupdate(&md5_ctx, temp);
1003 su_md5_hexdigest(&md5_ctx, second_digest);
1004 su_md5_deinit(&md5_ctx);
1006 if (nc && cnonce && qop)
1007 SPRINT(temp, "%s:%s:%s:%s:%s:%s", first_digest, nonce, nc, cnonce, qop, second_digest);
1009 SPRINT(temp, "%s:%s:%s", first_digest, nonce, second_digest);
1010 PDEBUG(DEBUG_SIP, "Third hash: %s\n", temp);
1011 su_md5_init(&md5_ctx);
1012 su_md5_strupdate(&md5_ctx, temp);
1013 su_md5_hexdigest(&md5_ctx, third_digest);
1014 su_md5_deinit(&md5_ctx);
1016 if (!!strcmp(response, third_digest)) {
1017 *auth_text = "Authorization Failed";
1022 *auth_text = "Authorization Success";
1039 * endpoint sends messages to the SIP port
1042 int Psip::message_connect(unsigned int epoint_id, int message_id, union parameter *param)
1044 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1045 const char *sdp_str = NULL;
1046 struct lcr_msg *message;
1047 struct interface *interface;
1049 unsigned char payload_type;
1051 interface = getinterfacebyname(inst->interface_name);
1053 PERROR("Cannot find interface %s.\n", inst->interface_name);
1057 if (param->connectinfo.rtpinfo.port) {
1058 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1060 media_type = param->connectinfo.rtpinfo.media_types[0];
1061 payload_type = param->connectinfo.rtpinfo.payload_types[0];
1062 p_s_rtp_ip_local = param->connectinfo.rtpinfo.ip;
1063 p_s_rtp_port_local = param->connectinfo.rtpinfo.port;
1064 PDEBUG(DEBUG_SIP, "payload type %d\n", payload_type);
1065 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
1066 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
1068 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
1069 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1070 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1071 /* open local RTP peer (if not bridging) */
1072 if (rtp_connect() < 0) {
1073 nua_cancel(p_s_handle, TAG_END());
1074 nua_handle_destroy(p_s_handle);
1076 sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
1077 add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
1079 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1080 message->param.disconnectinfo.cause = 41;
1081 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1082 message_put(message);
1083 new_state(PORT_STATE_RELEASE);
1084 trigger_work(&p_s_delete);
1089 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1090 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1093 * If this response causes corrupt messages, like SDP body inside or
1094 * before header, check if the sofia-sip-gcc-4.8.patch was applied.
1095 * If it is still corrupted, try to disable optimization when compiling
1098 nua_respond(p_s_handle, SIP_200_OK,
1099 NUTAG_MEDIA_ENABLE(0),
1100 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1101 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1103 new_state(PORT_STATE_CONNECT);
1104 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1105 add_trace("respond", "value", "200 OK");
1106 add_trace("reason", NULL, "call connected");
1108 memset(&ia, 0, sizeof(ia));
1109 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1110 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1111 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1112 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
1118 int Psip::message_release(unsigned int epoint_id, int message_id, union parameter *param)
1120 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1121 struct lcr_msg *message;
1122 char cause_str[128] = "";
1123 int cause = param->disconnectinfo.cause;
1124 int location = param->disconnectinfo.cause;
1126 const char *status_text;
1128 if (cause > 0 && cause <= 127) {
1129 SPRINT(cause_str, "Q.850;cause=%d;text=\"%s\"", cause, isdn_cause[cause].english);
1133 case PORT_STATE_OUT_SETUP:
1134 case PORT_STATE_OUT_PROCEEDING:
1135 case PORT_STATE_OUT_ALERTING:
1136 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will cancel\n");
1137 sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
1139 add_trace("cause", "value", "%d", cause);
1141 nua_cancel(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
1143 case PORT_STATE_IN_SETUP:
1144 case PORT_STATE_IN_PROCEEDING:
1145 case PORT_STATE_IN_ALERTING:
1146 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will respond\n");
1147 status = cause2status(cause, location, &status_text);
1148 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1150 add_trace("cause", "value", "%d", cause);
1151 add_trace("respond", "value", "%d %s", status, status_text);
1153 nua_respond(p_s_handle, status, status_text, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
1154 nua_handle_destroy(p_s_handle);
1156 trigger_work(&p_s_delete);
1159 PDEBUG(DEBUG_SIP, "RELEASE/DISCONNECT will perform nua_bye\n");
1160 sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_OUT);
1162 add_trace("cause", "value", "%d", cause);
1164 nua_bye(p_s_handle, TAG_IF(cause_str[0], SIPTAG_REASON_STR(cause_str)), TAG_END());
1167 if (message_id == MESSAGE_DISCONNECT) {
1168 while(p_epointlist) {
1169 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1170 message->param.disconnectinfo.cause = CAUSE_NORMAL;
1171 message->param.disconnectinfo.location = LOCATION_BEYOND;
1172 message_put(message);
1174 free_epointlist(p_epointlist);
1178 new_state(PORT_STATE_RELEASE);
1183 int Psip::message_setup(unsigned int epoint_id, int message_id, union parameter *param)
1185 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1186 char from[128] = "";
1187 char asserted_id[128] = "", asserted_msg[256] = "";
1189 char contact[128] = "";
1190 const char *local = inst->local_peer;
1192 const char *remote = inst->remote_peer;
1193 const char *sdp_str = NULL;
1194 struct epoint_list *epointlist;
1195 sip_cseq_t *cseq = NULL;
1196 struct lcr_msg *message;
1197 int lcr_media = { (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW };
1198 unsigned char lcr_payload = { (options.law=='a') ? (unsigned char )PAYLOAD_TYPE_ALAW : (unsigned char )PAYLOAD_TYPE_ULAW };
1200 unsigned char *payload_types;
1205 sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_OUT);
1206 add_trace("failed", "reason", "No remote peer set or no peer has registered to us.");
1208 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1209 message->param.disconnectinfo.cause = 27;
1210 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1211 message_put(message);
1212 new_state(PORT_STATE_RELEASE);
1213 trigger_work(&p_s_delete);
1217 PDEBUG(DEBUG_SIP, "Doing Setup (inst %p)\n", inst);
1219 memcpy(&p_dialinginfo, ¶m->setup.dialinginfo, sizeof(p_dialinginfo));
1220 memcpy(&p_callerinfo, ¶m->setup.callerinfo, sizeof(p_callerinfo));
1221 // memcpy(&p_redirinfo, ¶m->setup.redirinfo, sizeof(p_redirinfo));
1222 do_screen(1, p_callerinfo.id, sizeof(p_callerinfo.id), &p_callerinfo.ntype, &p_callerinfo.present, inst->interface_name);
1223 // do_screen(1, p_redirinfo.id, sizeof(p_redirinfo.id), &p_redirinfo.ntype, &p_redirinfo.present, inst->interface_name);
1225 if (param->setup.rtpinfo.port) {
1226 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1228 media_types = param->setup.rtpinfo.media_types;
1229 payload_types = param->setup.rtpinfo.payload_types;
1230 payloads = param->setup.rtpinfo.payloads;
1231 p_s_rtp_ip_local = param->setup.rtpinfo.ip;
1232 p_s_rtp_port_local = param->setup.rtpinfo.port;
1233 PDEBUG(DEBUG_SIP, "local ip %08x port %d\n", p_s_rtp_ip_local, p_s_rtp_port_local);
1234 PDEBUG(DEBUG_SIP, "remote ip %08x port %d\n", p_s_rtp_ip_remote, p_s_rtp_port_remote);
1236 PDEBUG(DEBUG_SIP, "RTP info not given by remote, so we do our own RTP\n");
1238 media_types = &lcr_media;
1239 payload_types = &lcr_payload;
1242 /* open local RTP peer (if not bridging) */
1243 if (rtp_open() < 0) {
1244 PERROR("Failed to open RTP sockets\n");
1245 /* send release message to endpoit */
1246 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1247 message->param.disconnectinfo.cause = 41;
1248 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1249 message_put(message);
1250 new_state(PORT_STATE_RELEASE);
1251 trigger_work(&p_s_delete);
1254 if (!p_s_rtp_ip_local) {
1257 /* extract IP from local peer */
1258 SCPY(local_ip, local);
1259 p = strchr(local_ip, ':');
1262 PDEBUG(DEBUG_SIP, "RTP local IP not known, so we use our local SIP ip %s\n", local_ip);
1263 inet_pton(AF_INET, local_ip, &p_s_rtp_ip_local);
1264 p_s_rtp_ip_local = ntohl(p_s_rtp_ip_local);
1268 p_s_handle = nua_handle(inst->nua, NULL, TAG_END());
1270 PERROR("Failed to create handle\n");
1271 /* send release message to endpoit */
1272 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
1273 message->param.disconnectinfo.cause = 41;
1274 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1275 message_put(message);
1276 new_state(PORT_STATE_RELEASE);
1277 trigger_work(&p_s_delete);
1280 /* apply handle to trace */
1281 // sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1282 // add_trace("handle", "new", "0x%x", p_s_handle);
1285 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, payloads, payload_types, media_types);
1286 PDEBUG(DEBUG_SIP, "Using SDP for invite: %s\n", sdp_str);
1288 SPRINT(from, "sip:%s@%s", p_callerinfo.id, remote);
1289 SPRINT(to, "sip:%s@%s", p_dialinginfo.id, remote);
1290 if (inst->asserted_id[0]) {
1291 SPRINT(asserted_id, "sip:%s@%s", inst->asserted_id, remote);
1292 SPRINT(asserted_msg, "P-Asserted-Identity: <%s>", asserted_id);
1294 if (inst->public_ip[0]) {
1296 SPRINT(contact, "sip:%s@%s", p_callerinfo.id, inst->public_ip);
1297 p = strchr(inst->local_peer, ':');
1302 sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_OUT);
1303 add_trace("from", "uri", "%s", from);
1304 add_trace("to", "uri", "%s", to);
1306 add_trace("assert-id", "uri", "%s", asserted_id);
1308 memset(&ia, 0, sizeof(ia));
1309 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1310 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
1311 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
1312 for (i = 0; i < payloads; i++)
1313 add_trace("rtp", "payload", "%s:%d", media_type2name(media_types[i]), payload_types[i]);
1316 // cseq = sip_cseq_create(sip_home, 123, SIP_METHOD_INVITE);
1318 nua_invite(p_s_handle,
1319 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1320 TAG_IF(to[0], SIPTAG_TO_STR(to)),
1321 TAG_IF(asserted_msg[0], SIPTAG_HEADER_STR(asserted_msg)),
1322 TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
1323 TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1324 NUTAG_MEDIA_ENABLE(0),
1325 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1326 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1327 new_state(PORT_STATE_OUT_SETUP);
1329 p_s_invite_direction = DIRECTION_OUT;
1332 PDEBUG(DEBUG_SIP, "do overlap\n");
1333 new_state(PORT_STATE_OUT_OVERLAP);
1334 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_OVERLAP);
1335 message_put(message);
1337 PDEBUG(DEBUG_SIP, "do proceeding\n");
1338 new_state(PORT_STATE_OUT_PROCEEDING);
1339 message = message_create(p_serial, epoint_id, PORT_TO_EPOINT, MESSAGE_PROCEEDING);
1340 message_put(message);
1343 /* attach only if not already */
1344 epointlist = p_epointlist;
1346 if (epointlist->epoint_id == epoint_id)
1348 epointlist = epointlist->next;
1351 epointlist_new(epoint_id);
1356 int Psip::message_notify(unsigned int epoint_id, int message_id, union parameter *param)
1359 // struct in_addr ia;
1361 switch (param->notifyinfo.notify) {
1362 case INFO_NOTIFY_REMOTE_HOLD:
1364 sdp_str = generate_sdp(0, 0, 0, NULL, NULL);
1367 "o=LCR-Sofia-SIP 0 0 IN IP4 0.0.0.0\r\n"
1369 "c=IN IP4 0.0.0.0\r\n"
1372 PDEBUG(DEBUG_SIP, "Using SDP for hold: %s\n", sdp_str);
1373 nua_info(p_s_handle,
1374 // TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1375 // TAG_IF(to[0], SIPTAG_TO_STR(to)),
1376 // TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1377 NUTAG_MEDIA_ENABLE(0),
1378 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1379 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1382 case INFO_NOTIFY_REMOTE_RETRIEVAL:
1384 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1385 PDEBUG(DEBUG_SIP, "Using SDP for rertieve: %s\n", sdp_str);
1386 nua_info(p_s_handle,
1387 // TAG_IF(from[0], SIPTAG_FROM_STR(from)),
1388 // TAG_IF(to[0], SIPTAG_TO_STR(to)),
1389 // TAG_IF(cseq, SIPTAG_CSEQ(cseq)),
1390 NUTAG_MEDIA_ENABLE(0),
1391 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1392 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1400 int Psip::message_dtmf(unsigned int epoint_id, int message_id, union parameter *param)
1404 /* prepare DTMF info payload */
1410 /* start invite to handle DTMF */
1411 nua_info(p_s_handle,
1412 NUTAG_MEDIA_ENABLE(0),
1413 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1414 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1419 /* NOTE: incomplete and not working */
1420 int Psip::message_information(unsigned int epoint_id, int message_id, union parameter *param)
1424 /* prepare DTMF info payload */
1428 , param->information.id);
1430 /* start invite to handle DTMF */
1431 nua_info(p_s_handle,
1432 NUTAG_MEDIA_ENABLE(0),
1433 SIPTAG_CONTENT_TYPE_STR("application/dtmf-relay"),
1434 SIPTAG_PAYLOAD_STR(dtmf_str), TAG_END());
1439 int Psip::message_epoint(unsigned int epoint_id, int message_id, union parameter *param)
1441 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1443 if (Port::message_epoint(epoint_id, message_id, param))
1446 switch(message_id) {
1447 case MESSAGE_ALERTING: /* call is ringing on LCR side */
1448 if (p_state != PORT_STATE_IN_SETUP
1449 && p_state != PORT_STATE_IN_PROCEEDING)
1451 nua_respond(p_s_handle, SIP_180_RINGING, TAG_END());
1452 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1453 add_trace("respond", "value", "180 Ringing");
1455 new_state(PORT_STATE_IN_ALERTING);
1458 case MESSAGE_CONNECT: /* call is connected on LCR side */
1459 if (p_state != PORT_STATE_IN_SETUP
1460 && p_state != PORT_STATE_IN_PROCEEDING
1461 && p_state != PORT_STATE_IN_ALERTING)
1463 message_connect(epoint_id, message_id, param);
1466 case MESSAGE_DISCONNECT: /* call has been disconnected */
1467 case MESSAGE_RELEASE: /* call has been released */
1468 message_release(epoint_id, message_id, param);
1471 case MESSAGE_SETUP: /* dial-out command received from epoint */
1472 message_setup(epoint_id, message_id, param);
1475 case MESSAGE_INFORMATION: /* overlap dialing */
1476 if (p_state != PORT_STATE_OUT_OVERLAP)
1478 message_information(epoint_id, message_id, param);
1481 case MESSAGE_DTMF: /* DTMF info to be transmitted via INFO transaction */
1482 if (p_state == PORT_STATE_CONNECT)
1483 message_dtmf(epoint_id, message_id, param);
1484 case MESSAGE_NOTIFY: /* notification about remote hold/retrieve */
1485 if (p_state == PORT_STATE_CONNECT)
1486 message_notify(epoint_id, message_id, param);
1490 PDEBUG(DEBUG_SIP, "PORT(%s) SIP port with (caller id %s) received an unsupported message: %d\n", p_name, p_callerinfo.id, message_id);
1496 int Psip::parse_sdp(sip_t const *sip, unsigned int *ip, unsigned short *port, uint8_t *payload_types, int *media_types, int *payloads, int max_payloads)
1500 if (!sip->sip_payload) {
1501 PDEBUG(DEBUG_SIP, "no payload given\n");
1505 sdp_parser_t *parser;
1508 sdp_attribute_t *attr;
1510 sdp_connection_t *conn;
1512 PDEBUG(DEBUG_SIP, "payload given: %s\n", sip->sip_payload->pl_data);
1514 parser = sdp_parse(NULL, sip->sip_payload->pl_data, (int) strlen(sip->sip_payload->pl_data), 0);
1518 if (!(sdp = sdp_session(parser))) {
1519 sdp_parser_free(parser);
1522 for (m = sdp->sdp_media; m; m = m->m_next) {
1523 if (m->m_proto != sdp_proto_rtp)
1525 if (m->m_type != sdp_media_audio)
1527 PDEBUG(DEBUG_SIP, "RTP port:'%u'\n", m->m_port);
1529 for (attr = m->m_attributes; attr; attr = attr->a_next) {
1530 PDEBUG(DEBUG_SIP, "ATTR: name:'%s' value='%s'\n", attr->a_name, attr->a_value);
1532 if (m->m_connections) {
1533 conn = m->m_connections;
1534 PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", conn->c_address);
1535 inet_pton(AF_INET, conn->c_address, ip);
1536 *ip = ntohl(p_s_rtp_ip_remote);
1538 char *p = sip->sip_payload->pl_data;
1541 PDEBUG(DEBUG_SIP, "sofia cannot find connection tag, so we try ourself\n");
1542 p = strstr(p, "c=IN IP4 ");
1544 PDEBUG(DEBUG_SIP, "missing c-tag with internet address\n");
1545 sdp_parser_free(parser);
1549 if ((p = strchr(addr, '\n'))) *p = '\0';
1550 if ((p = strchr(addr, '\r'))) *p = '\0';
1551 PDEBUG(DEBUG_SIP, "CONN: address:'%s'\n", addr);
1552 inet_pton(AF_INET, addr, ip);
1553 *ip = ntohl(p_s_rtp_ip_remote);
1555 for (map = m->m_rtpmaps; map; map = map->rm_next) {
1558 PDEBUG(DEBUG_SIP, "RTPMAP: coding:'%s' rate='%d' pt='%d'\n", map->rm_encoding, map->rm_rate, map->rm_pt);
1559 /* append to payload list, if there is space */
1560 add_trace("rtp", "payload", "%s:%d", map->rm_encoding, map->rm_pt);
1561 if (map->rm_pt == PAYLOAD_TYPE_ALAW)
1562 media_type = MEDIA_TYPE_ALAW;
1563 else if (map->rm_pt == PAYLOAD_TYPE_ULAW)
1564 media_type = MEDIA_TYPE_ULAW;
1565 else if (map->rm_pt == PAYLOAD_TYPE_GSM)
1566 media_type = MEDIA_TYPE_GSM;
1567 else if (!strcmp(map->rm_encoding, "GSM-EFR"))
1568 media_type = MEDIA_TYPE_GSM_EFR;
1569 else if (!strcmp(map->rm_encoding, "AMR"))
1570 media_type = MEDIA_TYPE_AMR;
1571 else if (!strcmp(map->rm_encoding, "GSM-HR"))
1572 media_type = MEDIA_TYPE_GSM_HR;
1573 if (media_type && *payloads <= max_payloads) {
1574 *payload_types++ = map->rm_pt;
1575 *media_types++ = media_type;
1581 sdp_parser_free(parser);
1586 const char *Psip::generate_sdp(unsigned int rtp_ip_local, unsigned short rtp_port_local, int payloads, unsigned char *payload_types, int *media_types)
1589 static char sdp_str[256], sub_str[128];
1592 memset(&ia, 0, sizeof(ia));
1593 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
1596 "o=LCR-Sofia-SIP 0 0 IN IP4 %s\r\n"
1599 "t=0 0\r\n", inet_ntoa(ia), inet_ntoa(ia));
1601 SPRINT(sub_str, "m=audio %d RTP/AVP", p_s_rtp_port_local);
1602 SCAT(sdp_str, sub_str);
1603 for (i = 0; i < payloads; i++) {
1604 SPRINT(sub_str, " %d", payload_types[i]);
1605 SCAT(sdp_str, sub_str);
1607 SCAT(sdp_str, "\r\n");
1608 for (i = 0; i < payloads; i++) {
1609 SPRINT(sub_str, "a=rtpmap:%d %s/8000\r\n", payload_types[i], media_type2name(media_types[i]));
1610 SCAT(sdp_str, sub_str);
1617 static int challenge(struct sip_inst *inst, class Psip *psip, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1619 sip_www_authenticate_t const *authenticate = NULL;
1620 char const *realm = NULL;
1621 char const *scheme = NULL;
1624 char authentication[256] = "";
1625 PDEBUG(DEBUG_SIP, "challenge order received\n");
1627 if (!inst->auth_user[0]) {
1628 PDEBUG(DEBUG_SIP, "No credentials available\n");
1629 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1630 add_trace("error", NULL, "There are no credentials given for interface");
1635 if (sip->sip_www_authenticate) {
1636 authenticate = sip->sip_www_authenticate;
1637 } else if (sip->sip_proxy_authenticate) {
1638 authenticate = sip->sip_proxy_authenticate;
1640 PDEBUG(DEBUG_SIP, "No authentication header found\n");
1641 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1642 add_trace("error", NULL, "Authentication method unknwon");
1647 scheme = (char const *) authenticate->au_scheme;
1648 if (authenticate->au_params) {
1649 for (i = 0; (cur = (char *) authenticate->au_params[i]); i++) {
1650 if ((realm = strstr(cur, "realm="))) {
1657 if (!scheme || !realm) {
1658 PDEBUG(DEBUG_SIP, "No scheme or no realm in authentication header found\n");
1659 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1660 add_trace("error", NULL, "Authentication header has no realm or scheme");
1665 SPRINT(authentication, "%s:%s:%s:%s", scheme, realm, inst->auth_user, inst->auth_password);
1666 PDEBUG(DEBUG_SIP, "auth: '%s'\n", authentication);
1668 sip_trace_header(psip, inst->interface_name, "AUTHENTICATE", DIRECTION_OUT);
1669 add_trace("scheme", NULL, "%s", scheme);
1670 add_trace("realm", NULL, "%s", realm);
1671 add_trace("user", NULL, "%s", inst->auth_user);
1672 add_trace("pass", NULL, "%s", inst->auth_password);
1675 nua_authenticate(nh, /*SIPTAG_EXPIRES_STR("3600"),*/ NUTAG_AUTH(authentication), TAG_END());
1680 static void i_options(struct sip_inst *inst, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1682 #define NUTAG_WITH_THIS_MSG(msg) nutag_with, tag_ptr_v(msg)
1683 nua_saved_event_t saved[1];
1684 nua_save_event(nua, saved);
1685 nua_event_data_t const *data = nua_event_data(saved);
1687 sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_IN);
1690 sip_trace_header(NULL, inst->interface_name, "RESPOND", DIRECTION_OUT);
1691 add_trace("respond", "value", "200 OK");
1694 nua_respond(nh, SIP_200_OK, NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1695 nua_handle_destroy(nh);
1696 inst->register_handle = NULL;
1699 static void i_register(struct sip_inst *inst, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1701 #define NUTAG_WITH_THIS_MSG(msg) nutag_with, tag_ptr_v(msg)
1702 nua_saved_event_t saved[1];
1703 sip_contact_t const *contact = NULL;
1704 contact = sip->sip_contact;
1705 nua_save_event(nua, saved);
1706 nua_event_data_t const *data = nua_event_data(saved);
1707 sip_authorization_t const *authorization;
1709 const char *auth_text = NULL;
1710 char auth_str[256] = "";
1712 if (contact->m_url->url_host)
1713 SCPY(uri, contact->m_url->url_host);
1714 if (contact->m_url->url_port && contact->m_url->url_port[0]) {
1716 SCAT(uri, contact->m_url->url_port);
1719 if (!inst->allow_register) {
1720 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_IN);
1721 add_trace("error", NULL, "forbidden, because we don't accept registration");
1723 nua_respond(nh, SIP_403_FORBIDDEN, NUTAG_WITH_THIS_MSG(data->e_msg), TAG_END());
1724 nua_handle_destroy(nh);
1725 inst->register_handle = NULL;
1729 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_IN);
1730 add_trace("contact", "uri", "%s", uri);
1733 sip_trace_header(NULL, inst->interface_name, "Authorization", DIRECTION_IN);
1734 if (inst->auth_realm[0]) {
1735 authorization = sip->sip_authorization;
1736 status = check_authorization(authorization, "REGISTER", inst->auth_user, inst->auth_password, inst->auth_realm, inst->auth_nonce, &auth_text);
1737 if (status == 401) {
1738 if (!inst->auth_nonce[0])
1739 generate_nonce(inst->auth_nonce);
1740 SPRINT(auth_str, "Digest realm=\"%s\", nonce=\"%s\", algorithm=MD5, qop=\"auth\"", inst->auth_realm, inst->auth_nonce);
1744 auth_text = "Authentication not required";
1746 add_trace("result", NULL, "%s", auth_text);
1749 if (status == 200) {
1750 SCPY(inst->remote_peer, uri);
1753 sip_trace_header(NULL, inst->interface_name, "RESPOND", DIRECTION_OUT);
1754 add_trace("respond", "value", "%d", status);
1755 add_trace("reason", NULL, "peer registers");
1758 nua_respond(nh, status, auth_text, SIPTAG_CONTACT(sip->sip_contact), NUTAG_WITH_THIS_MSG(data->e_msg), TAG_IF(auth_str[0], SIPTAG_WWW_AUTHENTICATE_STR(auth_str)), TAG_END());
1759 nua_handle_destroy(nh);
1760 inst->register_handle = NULL;
1763 static void r_register(struct sip_inst *inst, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1767 sip_trace_header(NULL, inst->interface_name, "STATUS", DIRECTION_IN);
1768 add_trace("value", NULL, "%d", status);
1769 add_trace("phrase", NULL, "%s", phrase);
1775 /* if not registered, become registered and start register interval timer */
1776 if (inst->register_state != REGISTER_STATE_REGISTERED) {
1777 if (inst->register_interval)
1778 schedule_timer(&inst->register_retry_timer, inst->register_interval, 0);
1779 inst->register_state = REGISTER_STATE_REGISTERED;
1781 /* start option timer */
1782 if (inst->options_interval)
1783 PDEBUG(DEBUG_SIP, "register ok, scheduling option timer with %d seconds\n", inst->options_interval);
1784 schedule_timer(&inst->register_option_timer, inst->options_interval, 0);
1788 PDEBUG(DEBUG_SIP, "Register challenge received\n");
1789 rc = challenge(inst, NULL, status, phrase, nua, magic, nh, hmagic, sip, tags);
1794 if (status >= 200 && status <= 299)
1799 PDEBUG(DEBUG_SIP, "Register failed, starting register timer\n");
1800 inst->register_state = REGISTER_STATE_FAILED;
1801 nua_handle_destroy(nh);
1802 inst->register_handle = NULL;
1803 /* stop option timer */
1804 unsched_timer(&inst->register_option_timer);
1805 /* if failed, start register interval timer with REGISTER_RETRY_TIMER */
1806 schedule_timer(&inst->register_retry_timer, REGISTER_RETRY_TIMER);
1810 void Psip::i_invite(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
1812 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
1813 const char *from = "", *to = "", *name = "";
1816 class Endpoint *epoint;
1817 struct lcr_msg *message;
1818 struct interface *interface;
1819 const char *sdp_str = NULL;
1820 int media_types[32];
1821 uint8_t payload_types[32];
1823 unsigned char payload_type;
1825 sip_authorization_t const *authorization;
1826 const char *auth_text = NULL;
1827 char auth_str[256] = "";
1829 interface = getinterfacebyname(inst->interface_name);
1831 PERROR("Cannot find interface %s.\n", inst->interface_name);
1835 if (sip->sip_from) {
1836 if (sip->sip_from->a_url)
1837 from = sip->sip_from->a_url->url_user;
1838 if (sip->sip_from->a_display) {
1839 name = sip->sip_from->a_display;
1840 if (!strncmp(name, "\"IMSI", 5)) {
1841 strncpy(imsi, name + 5, 15);
1848 if (sip->sip_to->a_url)
1849 to = sip->sip_to->a_url->url_user;
1851 PDEBUG(DEBUG_SIP, "invite received (%s->%s)\n", from, to);
1853 sip_trace_header(this, inst->interface_name, "Authorization", DIRECTION_IN);
1854 if (inst->auth_realm[0] && p_state == PORT_STATE_IDLE) {
1855 /* only authenticate remote, if we have a realm set and we don't have re-invite */
1856 authorization = sip->sip_proxy_authorization;
1857 status = check_authorization(authorization, "INVITE", inst->auth_user, inst->auth_password, inst->auth_realm, inst->auth_nonce, &auth_text);
1858 if (status == 407) {
1859 if (!inst->auth_nonce[0])
1860 generate_nonce(inst->auth_nonce);
1861 SPRINT(auth_str, "Digest realm=\"%s\", nonce=\"%s\", algorithm=MD5, qop=\"auth\"", inst->auth_realm, inst->auth_nonce);
1865 auth_text = "Authentication not required";
1867 add_trace("result", NULL, "%s", auth_text);
1870 if (status == 200) {
1872 sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_IN);
1875 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1876 add_trace("respond", "value", "%d", status);
1877 add_trace("reason", NULL, "peer invited");
1880 nua_respond(nh, status, auth_text, SIPTAG_CONTACT(sip->sip_contact), TAG_IF(auth_str[0], SIPTAG_PROXY_AUTHENTICATE_STR(auth_str)), TAG_END());
1881 new_state(PORT_STATE_RELEASE);
1882 trigger_work(&p_s_delete);
1886 sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
1887 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
1889 /* if no RTP bridge, we must support LAW codec, otherwise we forward what we have */
1890 if (!p_s_rtp_bridge) {
1893 /* check if supported payload type exists */
1894 for (i = 0; i < payloads; i++) {
1895 if (media_types[i] == ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW))
1898 if (i == payloads) {
1899 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
1907 nua_respond(nh, SIP_400_BAD_REQUEST, TAG_END());
1909 nua_respond(nh, SIP_415_UNSUPPORTED_MEDIA, TAG_END());
1910 nua_handle_destroy(nh);
1912 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1914 add_trace("respond", "value", "415 Unsupported Media");
1916 add_trace("respond", "value", "400 Bad Request");
1917 add_trace("reason", NULL, "offered codec does not match");
1919 if (p_state != PORT_STATE_IDLE) {
1920 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
1921 message->param.disconnectinfo.cause = 41;
1922 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
1923 message_put(message);
1925 new_state(PORT_STATE_RELEASE);
1926 trigger_work(&p_s_delete);
1930 /* handle re-invite */
1931 if (p_state != PORT_STATE_IDLE) {
1932 sip_trace_header(this, inst->interface_name, "RE-INVITE", DIRECTION_IN);
1934 if (p_s_rtp_bridge) {
1935 PDEBUG(DEBUG_SIP, "RE-INVITE not implemented for RTP forwarding\n");
1936 nua_respond(nh, SIP_501_NOT_IMPLEMENTED, TAG_END());
1937 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1938 add_trace("respond", "value", "501 NOT IMPLEMENTED");
1939 add_trace("reason", NULL, "RE-INVITE not implemented for RTP forwarding");
1942 PDEBUG(DEBUG_SIP, "RTP info given by remote, forward that\n");
1943 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
1944 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
1945 if (rtp_connect() < 0) {
1948 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
1949 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
1950 nua_respond(p_s_handle, SIP_200_OK,
1951 NUTAG_MEDIA_ENABLE(0),
1952 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
1953 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
1958 /* open local RTP peer (if not bridging) */
1959 if (!p_s_rtp_bridge && rtp_open() < 0) {
1960 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
1961 nua_handle_destroy(nh);
1963 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
1964 add_trace("respond", "value", "500 Internal Server Error");
1965 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
1967 new_state(PORT_STATE_RELEASE);
1968 trigger_work(&p_s_delete);
1973 // sip_trace_header(this, inst->interface_name, "NEW handle", DIRECTION_IN);
1974 // add_trace("handle", "new", "0x%x", nh);
1979 sip_trace_header(this, inst->interface_name, "INVITE", DIRECTION_IN);
1980 add_trace("rtp", "port", "%d", p_s_rtp_port_remote);
1981 /* caller information */
1983 p_callerinfo.present = INFO_PRESENT_NOTAVAIL;
1984 p_callerinfo.ntype = INFO_NTYPE_NOTPRESENT;
1985 add_trace("calling", "present", "unavailable");
1987 p_callerinfo.present = INFO_PRESENT_ALLOWED;
1988 add_trace("calling", "present", "allowed");
1989 p_callerinfo.screen = INFO_SCREEN_NETWORK;
1990 p_callerinfo.ntype = INFO_NTYPE_UNKNOWN;
1991 SCPY(p_callerinfo.id, from);
1992 add_trace("calling", "number", "%s", from);
1993 SCPY(p_callerinfo.name, name);
1995 add_trace("calling", "name", "%s", name);
1996 SCPY(p_callerinfo.imsi, imsi);
1998 add_trace("calling", "imsi", "%s", imsi);
2000 SCPY(p_callerinfo.interface, inst->interface_name);
2001 /* dialing information */
2003 p_dialinginfo.ntype = INFO_NTYPE_UNKNOWN;
2004 SCAT(p_dialinginfo.id, to);
2005 add_trace("dialing", "number", "%s", to);
2008 /* bearer capability */
2009 p_capainfo.bearer_capa = INFO_BC_SPEECH;
2010 p_capainfo.bearer_info1 = (options.law=='a')?3:2;
2011 p_capainfo.bearer_mode = INFO_BMODE_CIRCUIT;
2012 add_trace("bearer", "capa", "speech");
2013 add_trace("bearer", "mode", "circuit");
2014 /* if packet mode works some day, see dss1.cpp for conditions */
2015 p_capainfo.source_mode = B_MODE_TRANSPARENT;
2019 /* create endpoint */
2021 FATAL("Incoming call but already got an endpoint.\n");
2022 if (!(epoint = new Endpoint(p_serial, 0)))
2023 FATAL("No memory for Endpoint instance\n");
2024 epoint->ep_app = new_endpointapp(epoint, 0, interface->app); //incoming
2025 epointlist_new(epoint->ep_serial);
2027 #ifdef NUTAG_AUTO100
2028 /* send trying (proceeding) */
2029 nua_respond(nh, SIP_100_TRYING, TAG_END());
2030 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2031 add_trace("respond", "value", "100 Trying");
2035 new_state(PORT_STATE_IN_PROCEEDING);
2037 /* send setup message to endpoit */
2038 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_SETUP);
2039 message->param.setup.port_type = p_type;
2040 // message->param.setup.dtmf = 0;
2041 memcpy(&message->param.setup.dialinginfo, &p_dialinginfo, sizeof(struct dialing_info));
2042 memcpy(&message->param.setup.callerinfo, &p_callerinfo, sizeof(struct caller_info));
2043 memcpy(&message->param.setup.capainfo, &p_capainfo, sizeof(struct capa_info));
2044 // SCPY((char *)message->param.setup.useruser.data, useruser.info);
2045 // message->param.setup.useruser.len = strlen(mncc->useruser.info);
2046 // message->param.setup.useruser.protocol = mncc->useruser.proto;
2047 if (p_s_rtp_bridge) {
2050 PDEBUG(DEBUG_SIP, "sending setup with RTP info\n");
2051 message->param.setup.rtpinfo.ip = p_s_rtp_ip_remote;
2052 message->param.setup.rtpinfo.port = p_s_rtp_port_remote;
2053 /* add codecs to setup message */
2054 for (i = 0; i < payloads; i++) {
2055 message->param.setup.rtpinfo.media_types[i] = media_types[i];
2056 message->param.setup.rtpinfo.payload_types[i] = payload_types[i];
2057 if (i == sizeof(message->param.setup.rtpinfo.payload_types))
2060 message->param.setup.rtpinfo.payloads = i;
2062 message_put(message);
2064 /* start option timer */
2065 if (inst->options_interval) {
2066 PDEBUG(DEBUG_SIP, "Invite received, scheduling option timer with %d seconds\n", inst->options_interval);
2067 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2070 p_s_invite_direction = DIRECTION_IN;
2072 /* send progress, if tones are available and if we don't bridge */
2073 if (!p_s_rtp_bridge && interface->is_tones == IS_YES) {
2074 PDEBUG(DEBUG_SIP, "Connecting audio, since we have tones available\n");
2075 media_type = (options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW;
2076 payload_type = (options.law=='a') ? PAYLOAD_TYPE_ALAW : PAYLOAD_TYPE_ULAW;
2077 /* open local RTP peer (if not bridging) */
2078 if (rtp_connect() < 0) {
2080 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2081 nua_handle_destroy(nh);
2083 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2084 add_trace("respond", "value", "500 Internal Server Error");
2085 add_trace("reason", NULL, "failed to connect RTP/RTCP sockts");
2087 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_RELEASE);
2088 message->param.disconnectinfo.cause = 41;
2089 message->param.disconnectinfo.location = LOCATION_PRIVATE_LOCAL;
2090 message_put(message);
2091 new_state(PORT_STATE_RELEASE);
2092 trigger_work(&p_s_delete);
2096 sdp_str = generate_sdp(p_s_rtp_ip_local, p_s_rtp_port_local, 1, &payload_type, &media_type);
2097 PDEBUG(DEBUG_SIP, "Using SDP response: %s\n", sdp_str);
2099 nua_respond(p_s_handle, SIP_183_SESSION_PROGRESS,
2100 NUTAG_MEDIA_ENABLE(0),
2101 SIPTAG_CONTENT_TYPE_STR("application/sdp"),
2102 SIPTAG_PAYLOAD_STR(sdp_str), TAG_END());
2103 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2104 add_trace("respond", "value", "183 SESSION PROGRESS");
2105 add_trace("reason", NULL, "audio available");
2107 memset(&ia, 0, sizeof(ia));
2108 ia.s_addr = htonl(get_local_ip(p_s_rtp_ip_local));
2109 add_trace("rtp", "ip", "%s", inet_ntoa(ia));
2110 add_trace("rtp", "port", "%d,%d", p_s_rtp_port_local, p_s_rtp_port_local + 1);
2111 add_trace("rtp", "payload", "%s:%d", media_type2name(media_type), payload_type);
2116 void Psip::i_options(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2118 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2120 PDEBUG(DEBUG_SIP, "options received\n");
2122 sip_trace_header(this, inst->interface_name, "OPTIONS", DIRECTION_IN);
2125 nua_respond(nh, SIP_200_OK, TAG_END());
2128 void Psip::i_bye(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2130 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2131 struct lcr_msg *message;
2134 PDEBUG(DEBUG_SIP, "bye received\n");
2136 sip_trace_header(this, inst->interface_name, "BYE", DIRECTION_IN);
2137 if (sip->sip_reason && sip->sip_reason->re_protocol && !strcasecmp(sip->sip_reason->re_protocol, "Q.850") && sip->sip_reason->re_cause) {
2138 cause = atoi(sip->sip_reason->re_cause);
2139 add_trace("cause", "value", "%d", cause);
2143 // let stack do bye automaticall, since it will not accept our response for some reason
2144 // nua_respond(nh, SIP_200_OK, TAG_END());
2145 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2146 add_trace("respond", "value", "200 OK");
2148 // nua_handle_destroy(nh);
2153 while(p_epointlist) {
2154 /* send setup message to endpoit */
2155 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2156 message->param.disconnectinfo.cause = cause ? : 16;
2157 message->param.disconnectinfo.location = LOCATION_BEYOND;
2158 message_put(message);
2160 free_epointlist(p_epointlist);
2162 new_state(PORT_STATE_RELEASE);
2163 trigger_work(&p_s_delete);
2166 void Psip::i_cancel(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2168 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2169 struct lcr_msg *message;
2171 PDEBUG(DEBUG_SIP, "cancel received\n");
2173 sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_IN);
2176 nua_handle_destroy(nh);
2181 while(p_epointlist) {
2182 /* send setup message to endpoit */
2183 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2184 message->param.disconnectinfo.cause = 16;
2185 message->param.disconnectinfo.location = LOCATION_BEYOND;
2186 message_put(message);
2188 free_epointlist(p_epointlist);
2190 new_state(PORT_STATE_RELEASE);
2191 trigger_work(&p_s_delete);
2194 void Psip::r_bye(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2196 PDEBUG(DEBUG_SIP, "bye response received\n");
2198 nua_handle_destroy(nh);
2203 trigger_work(&p_s_delete);
2206 void Psip::r_cancel(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2208 PDEBUG(DEBUG_SIP, "cancel response received\n");
2210 nua_handle_destroy(nh);
2215 trigger_work(&p_s_delete);
2218 void Psip::r_invite(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2220 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2221 struct lcr_msg *message;
2222 int cause = 0, location = 0;
2223 int media_types[32];
2224 uint8_t payload_types[32];
2227 PDEBUG(DEBUG_SIP, "response to invite received (status = %d)\n", status);
2229 sip_trace_header(this, inst->interface_name, "RESPOND", DIRECTION_OUT);
2230 add_trace("respond", "value", "%d", status);
2233 if (status == 401 || status == 407) {
2234 PDEBUG(DEBUG_SIP, "Invite challenge received\n");
2235 challenge(inst, this, status, phrase, nua, magic, nh, hmagic, sip, tags);
2240 if (status == 183 || (status >= 200 && status <= 299)) {
2243 sip_trace_header(this, inst->interface_name, "Payload received", DIRECTION_NONE);
2244 ret = parse_sdp(sip, &p_s_rtp_ip_remote, &p_s_rtp_port_remote, payload_types, media_types, &payloads, sizeof(payload_types));
2248 else if (!p_s_rtp_bridge) {
2249 if (media_types[0] != ((options.law=='a') ? MEDIA_TYPE_ALAW : MEDIA_TYPE_ULAW)) {
2250 add_trace("error", NULL, "Expected LAW payload type (not bridged)");
2257 nua_cancel(nh, TAG_END());
2258 sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2259 add_trace("reason", NULL, "accepted codec does not match");
2262 location = LOCATION_PRIVATE_LOCAL;
2263 goto release_with_cause;
2266 /* connect to remote RTP (if not bridging) */
2267 if (!p_s_rtp_bridge && rtp_connect() < 0) {
2268 nua_cancel(nh, TAG_END());
2269 sip_trace_header(this, inst->interface_name, "CANCEL", DIRECTION_OUT);
2270 add_trace("reason", NULL, "failed to open RTP/RTCP sockts");
2273 location = LOCATION_PRIVATE_LOCAL;
2274 goto release_with_cause;
2278 /* start option timer */
2279 if (inst->options_interval) {
2280 PDEBUG(DEBUG_SIP, "Invite response, scheduling option timer with %d seconds\n", inst->options_interval);
2281 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2287 PDEBUG(DEBUG_SIP, "do proceeding\n");
2288 new_state(PORT_STATE_OUT_PROCEEDING);
2289 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROCEEDING);
2290 message_put(message);
2294 PDEBUG(DEBUG_SIP, "do alerting\n");
2295 new_state(PORT_STATE_OUT_ALERTING);
2296 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_ALERTING);
2297 message_put(message);
2300 PDEBUG(DEBUG_SIP, "do progress\n");
2301 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_PROGRESS);
2302 message->param.progressinfo.progress = 8;
2303 message->param.progressinfo.location = 10;
2304 if (p_s_rtp_bridge) {
2305 message->param.progressinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2306 message->param.progressinfo.rtpinfo.port = p_s_rtp_port_remote;
2307 message->param.progressinfo.rtpinfo.media_types[0] = media_types[0];
2308 message->param.progressinfo.rtpinfo.payload_types[0] = payload_types[0];
2309 message->param.progressinfo.rtpinfo.payloads = 1;
2311 message_put(message);
2315 PDEBUG(DEBUG_SIP, "do connect\n");
2316 nua_ack(nh, TAG_END());
2317 new_state(PORT_STATE_CONNECT);
2318 message = message_create(p_serial, ACTIVE_EPOINT(p_epointlist), PORT_TO_EPOINT, MESSAGE_CONNECT);
2319 if (p_s_rtp_bridge) {
2320 message->param.connectinfo.rtpinfo.ip = p_s_rtp_ip_remote;
2321 message->param.connectinfo.rtpinfo.port = p_s_rtp_port_remote;
2322 message->param.connectinfo.rtpinfo.media_types[0] = media_types[0];
2323 message->param.connectinfo.rtpinfo.payload_types[0] = payload_types[0];
2324 message->param.connectinfo.rtpinfo.payloads = 1;
2326 message_put(message);
2329 if (status >= 200 && status <= 299)
2331 if (status < 100 || status > 199)
2333 PDEBUG(DEBUG_SIP, "skipping 1xx message\n");
2338 cause = status2cause(status);
2339 location = LOCATION_BEYOND;
2342 PDEBUG(DEBUG_SIP, "do release (cause %d)\n", cause);
2344 while(p_epointlist) {
2345 /* send setup message to endpoit */
2346 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2347 message->param.disconnectinfo.cause = cause;
2348 message->param.disconnectinfo.location = location;
2349 message_put(message);
2351 free_epointlist(p_epointlist);
2354 new_state(PORT_STATE_RELEASE);
2358 trigger_work(&p_s_delete);
2361 void Psip::r_options(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2363 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2364 int cause = 0, location = 0;
2365 struct lcr_msg *message;
2367 PDEBUG(DEBUG_SIP, "options result %d received\n", status);
2369 if (status >= 200 && status <= 299) {
2370 PDEBUG(DEBUG_SIP, "options ok, scheduling option timer with %d seconds\n", inst->options_interval);
2371 /* restart option timer */
2372 schedule_timer(&p_s_invite_option_timer, inst->options_interval, 0);
2376 nua_handle_destroy(nh);
2381 cause = status2cause(status);
2382 location = LOCATION_BEYOND;
2384 while(p_epointlist) {
2385 /* send setup message to endpoit */
2386 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2387 message->param.disconnectinfo.cause = cause;
2388 message->param.disconnectinfo.location = location;
2389 message_put(message);
2391 free_epointlist(p_epointlist);
2393 new_state(PORT_STATE_RELEASE);
2394 trigger_work(&p_s_delete);
2397 void Psip::i_state(int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2399 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2401 PDEBUG(DEBUG_SIP, "state change received\n");
2402 sip_trace_header(this, inst->interface_name, "STATUS", DIRECTION_OUT);
2403 add_trace("value", NULL, "%d", status);
2404 add_trace("phrase", NULL, "%s", phrase);
2408 static void sip_callback(nua_event_t event, int status, char const *phrase, nua_t *nua, nua_magic_t *magic, nua_handle_t *nh, nua_hmagic_t *hmagic, sip_t const *sip, tagi_t tags[])
2410 struct sip_inst *inst = (struct sip_inst *) magic;
2412 class Psip *psip = NULL;
2414 PDEBUG(DEBUG_SIP, "Event %d from SIP stack received (handle=%p)\n", event, nh);
2418 /* hunt for existing handles */
2421 if ((port->p_type & PORT_CLASS_mISDN_MASK) == PORT_CLASS_SIP) {
2422 psip = (class Psip *)port;
2423 if (psip->p_s_handle == nh) {
2424 PDEBUG(DEBUG_SIP, "Event found for port %s\n", psip->p_name);
2436 if (!inst->register_handle) {
2437 PDEBUG(DEBUG_SIP, "New options instance\n");
2438 inst->register_handle = nh;
2441 case nua_i_register:
2442 if (!inst->register_handle) {
2443 PDEBUG(DEBUG_SIP, "New register instance\n");
2444 inst->register_handle = nh;
2450 struct interface *interface = interface_first;
2452 PDEBUG(DEBUG_SIP, "New psip instance\n");
2454 /* create call instance */
2455 SPRINT(name, "%s-%d-in", inst->interface_name, 0);
2457 if (!strcmp(interface->name, inst->interface_name))
2459 interface = interface->next;
2462 FATAL("Cannot find interface %s.\n", inst->interface_name);
2463 if (!(psip = new Psip(PORT_TYPE_SIP_IN, name, NULL, interface)))
2464 FATAL("Cannot create Port instance.\n");
2468 if (!psip && !inst->register_handle) {
2469 PDEBUG(DEBUG_SIP, "Destroying unknown instance\n");
2470 nua_handle_destroy(nh);
2475 /* handle register process */
2476 if (inst->register_handle == nh) {
2479 i_options(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2481 case nua_i_register:
2482 i_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2484 case nua_r_register:
2485 r_register(inst, status, phrase, nua, magic, nh, hmagic, sip, tags);
2488 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2493 /* handle port process */
2495 PERROR("no SIP Port found for handel %p\n", nh);
2496 nua_respond(nh, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
2497 nua_handle_destroy(nh);
2502 case nua_r_set_params:
2503 PDEBUG(DEBUG_SIP, "setparam response\n");
2506 psip->r_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2509 PDEBUG(DEBUG_SIP, "error received\n");
2512 psip->i_state(status, phrase, nua, magic, nh, hmagic, sip, tags);
2515 psip->i_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2518 PDEBUG(DEBUG_SIP, "ack received\n");
2521 PDEBUG(DEBUG_SIP, "active received\n");
2524 psip->i_options(status, phrase, nua, magic, nh, hmagic, sip, tags);
2527 psip->i_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2530 psip->i_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2533 psip->r_bye(status, phrase, nua, magic, nh, hmagic, sip, tags);
2536 psip->r_cancel(status, phrase, nua, magic, nh, hmagic, sip, tags);
2539 psip->r_invite(status, phrase, nua, magic, nh, hmagic, sip, tags);
2541 case nua_i_terminated:
2542 PDEBUG(DEBUG_SIP, "terminated received\n");
2545 PDEBUG(DEBUG_SIP, "Event %d not handled\n", event);
2549 static void stun_bind_cb(stun_discovery_magic_t *magic, stun_handle_t *sh, stun_discovery_t *sd, stun_action_t action, stun_state_t event)
2551 struct sip_inst *inst = (struct sip_inst *) magic;
2555 PDEBUG(DEBUG_SIP, "Event %d from STUN stack received\n", event);
2558 case stun_discovery_done:
2559 addrlen = sizeof(sa);
2560 memset(&sa, 0, addrlen);
2561 if (stun_discovery_get_address(sd, &sa, &addrlen) < 0) {
2562 PDEBUG(DEBUG_SIP, "stun_discovery_get_address failed\n");
2565 su_inet_ntop(sa.su_family, SU_ADDR(&sa), inst->public_ip, sizeof(inst->public_ip));
2566 inst->stun_state = STUN_STATE_RESOLVED;
2567 /* start timer for next stun request with inst->stun_interval */
2568 schedule_timer(&inst->stun_retry_timer, inst->stun_interval, 0);
2569 sip_trace_header(NULL, inst->interface_name, "STUN resolved", DIRECTION_OUT);
2570 add_trace("ip", "addr", "%s", inst->public_ip);
2575 PDEBUG(DEBUG_SIP, "STUN failed, starting timer\n");
2576 inst->stun_state = STUN_STATE_FAILED;
2577 /* start timer for next stun request (after failing) with STUN_RETRY_TIMER */
2578 schedule_timer(&inst->stun_retry_timer, STUN_RETRY_TIMER);
2579 sip_trace_header(NULL, inst->interface_name, "STUN failed", DIRECTION_OUT);
2584 /* received shutdown due to termination of RTP */
2585 void Psip::rtp_shutdown(void)
2587 struct sip_inst *inst = (struct sip_inst *) p_s_sip_inst;
2588 struct lcr_msg *message;
2590 PDEBUG(DEBUG_SIP, "RTP stream terminated\n");
2592 sip_trace_header(this, inst->interface_name, "RTP terminated", DIRECTION_IN);
2595 nua_handle_destroy(p_s_handle);
2598 while(p_epointlist) {
2599 /* send setup message to endpoit */
2600 message = message_create(p_serial, p_epointlist->epoint_id, PORT_TO_EPOINT, MESSAGE_RELEASE);
2601 message->param.disconnectinfo.cause = 16;
2602 message->param.disconnectinfo.location = LOCATION_BEYOND;
2603 message_put(message);
2605 free_epointlist(p_epointlist);
2607 new_state(PORT_STATE_RELEASE);
2608 trigger_work(&p_s_delete);
2611 static int invite_option_timer(struct lcr_timer *timer, void *instance, int index)
2613 class Psip *psip = (class Psip *)instance;
2614 struct sip_inst *inst = (struct sip_inst *) psip->p_s_sip_inst;
2616 sip_trace_header(psip, inst->interface_name, "OPTIONS", psip->p_s_invite_direction);
2619 nua_options(psip->p_s_handle,
2625 static int stun_retry_timer(struct lcr_timer *timer, void *instance, int index)
2627 struct sip_inst *inst = (struct sip_inst *)instance;
2629 PDEBUG(DEBUG_SIP, "timeout, restart stun lookup\n");
2630 inst->stun_state = STUN_STATE_UNRESOLVED;
2635 static int register_retry_timer(struct lcr_timer *timer, void *instance, int index)
2637 struct sip_inst *inst = (struct sip_inst *)instance;
2639 PDEBUG(DEBUG_SIP, "timeout, restart register\n");
2640 /* if we have a handle, destroy it and becom unregistered, so registration is
2642 if (inst->register_handle) {
2643 /* stop option timer */
2644 unsched_timer(&inst->register_option_timer);
2645 nua_handle_destroy(inst->register_handle);
2646 inst->register_handle = NULL;
2648 inst->register_state = REGISTER_STATE_UNREGISTERED;
2653 static int register_option_timer(struct lcr_timer *timer, void *instance, int index)
2655 struct sip_inst *inst = (struct sip_inst *)instance;
2656 sip_trace_header(NULL, inst->interface_name, "OPTIONS", DIRECTION_OUT);
2659 nua_options(inst->register_handle,
2665 int sip_init_inst(struct interface *interface)
2667 struct sip_inst *inst = (struct sip_inst *) MALLOC(sizeof(*inst));
2670 interface->sip_inst = inst;
2671 SCPY(inst->interface_name, interface->name);
2672 SCPY(inst->local_peer, interface->sip_local_peer);
2673 SCPY(inst->remote_peer, interface->sip_remote_peer);
2674 if (!inst->remote_peer[0])
2675 inst->allow_register = 1;
2676 SCPY(inst->asserted_id, interface->sip_asserted_id);
2677 if (interface->sip_register) {
2678 inst->register_state = REGISTER_STATE_UNREGISTERED;
2679 SCPY(inst->register_user, interface->sip_register_user);
2680 SCPY(inst->register_host, interface->sip_register_host);
2682 SCPY(inst->auth_user, interface->sip_auth_user);
2683 SCPY(inst->auth_password, interface->sip_auth_password);
2684 SCPY(inst->auth_realm, interface->sip_auth_realm);
2685 inst->register_interval = interface->sip_register_interval;
2686 inst->options_interval = interface->sip_options_interval;
2688 inst->rtp_port_from = interface->rtp_port_from;
2689 inst->rtp_port_to = interface->rtp_port_to;
2690 if (!inst->rtp_port_from || !inst->rtp_port_to) {
2691 inst->rtp_port_from = RTP_PORT_BASE;
2692 inst->rtp_port_to = RTP_PORT_MAX;
2694 inst->next_rtp_port = inst->rtp_port_from;
2697 memset(&inst->stun_retry_timer, 0, sizeof(inst->stun_retry_timer));
2698 add_timer(&inst->stun_retry_timer, stun_retry_timer, inst, 0);
2699 memset(&inst->register_retry_timer, 0, sizeof(inst->register_retry_timer));
2700 add_timer(&inst->register_retry_timer, register_retry_timer, inst, 0);
2701 memset(&inst->register_option_timer, 0, sizeof(inst->register_option_timer));
2702 add_timer(&inst->register_option_timer, register_option_timer, inst, 0);
2704 /* init root object */
2705 inst->root = su_root_create(inst);
2707 PERROR("Failed to create SIP root\n");
2708 sip_exit_inst(interface);
2712 SPRINT(local, "sip:%s",inst->local_peer);
2713 if (!strchr(inst->local_peer, ':'))
2714 SCAT(local, ":5060");
2715 inst->nua = nua_create(inst->root, sip_callback, inst, NUTAG_URL(local), TAG_END());
2717 PERROR("Failed to create SIP stack object\n");
2718 sip_exit_inst(interface);
2721 nua_set_params(inst->nua,
2722 SIPTAG_ALLOW_STR("REGISTER,INVITE,ACK,BYE,CANCEL,OPTIONS,NOTIFY,INFO"),
2723 NUTAG_APPL_METHOD("REGISTER"),
2724 NUTAG_APPL_METHOD("INVITE"),
2725 NUTAG_APPL_METHOD("ACK"),
2726 // NUTAG_APPL_METHOD("BYE"), /* we must reply to BYE */
2727 NUTAG_APPL_METHOD("CANCEL"),
2728 NUTAG_APPL_METHOD("OPTIONS"),
2729 NUTAG_APPL_METHOD("NOTIFY"),
2730 NUTAG_APPL_METHOD("INFO"),
2732 #ifdef NUTAG_AUTO100
2736 NUTAG_AUTOANSWER(0),
2739 SCPY(inst->public_ip, interface->sip_public_ip);
2740 if (interface->sip_stun_server[0]) {
2741 SCPY(inst->stun_server, interface->sip_stun_server);
2742 inst->stun_interval = interface->sip_stun_interval;
2743 inst->stun_handle = stun_handle_init(inst->root,
2744 STUNTAG_SERVER(inst->stun_server),
2746 if (!inst->stun_handle) {
2747 PERROR("Failed to create STUN handle\n");
2748 sip_exit_inst(interface);
2751 inst->stun_socket = su_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
2752 if (inst->stun_socket < 0) {
2753 PERROR("Failed to create STUN socket\n");
2754 sip_exit_inst(interface);
2757 inst->stun_state = STUN_STATE_UNRESOLVED;
2760 PDEBUG(DEBUG_SIP, "SIP interface created (inst=%p)\n", inst);
2762 any_sip_interface = 1;
2767 void sip_exit_inst(struct interface *interface)
2769 struct sip_inst *inst = (struct sip_inst *) interface->sip_inst;
2773 del_timer(&inst->stun_retry_timer);
2774 del_timer(&inst->register_retry_timer);
2775 del_timer(&inst->register_option_timer);
2776 if (inst->stun_socket)
2777 su_close(inst->stun_socket);
2778 if (inst->stun_handle)
2779 stun_handle_destroy(inst->stun_handle);
2780 if (inst->register_handle)
2781 nua_handle_destroy(inst->register_handle);
2783 su_root_destroy(inst->root);
2785 nua_destroy(inst->nua);
2786 FREE(inst, sizeof(*inst));
2787 interface->sip_inst = NULL;
2789 PDEBUG(DEBUG_SIP, "SIP interface removed\n");
2791 /* check if there is any other SIP interface left */
2792 interface = interface_first;
2794 if (interface->sip_inst)
2796 interface = interface->next;
2799 any_sip_interface = 0;
2802 extern su_log_t su_log_default[];
2803 extern su_log_t nua_log[];
2809 /* init SOFIA lib */
2811 su_home_init(sip_home);
2813 if (options.deb & DEBUG_SIP) {
2814 su_log_set_level(su_log_default, 9);
2815 su_log_set_level(nua_log, 9);
2816 //su_log_set_level(soa_log, 9);
2819 for (i = 0; i < 256; i++)
2820 flip[i] = ((i & 1) << 7) + ((i & 2) << 5) + ((i & 4) << 3) + ((i & 8) << 1) + ((i & 16) >> 1) + ((i & 32) >> 3) + ((i & 64) >> 5) + ((i & 128) >> 7);
2822 PDEBUG(DEBUG_SIP, "SIP globals initialized\n");
2829 su_home_deinit(sip_home);
2832 PDEBUG(DEBUG_SIP, "SIP globals de-initialized\n");
2835 static void sip_handle_stun(struct sip_inst *inst)
2839 switch (inst->stun_state) {
2840 case STUN_STATE_UNRESOLVED:
2841 PDEBUG(DEBUG_SIP, "Trying to to get local IP from stun server\n");
2842 rc = stun_bind(inst->stun_handle, stun_bind_cb, (stun_discovery_magic_t *)inst,
2843 STUNTAG_SOCKET(inst->stun_socket),
2844 STUNTAG_REGISTER_EVENTS(1),
2847 PERROR("Failed to call stun_bind()\n");
2848 inst->stun_state = STUN_STATE_FAILED;
2851 inst->stun_state = STUN_STATE_RESOLVING;
2852 sip_trace_header(NULL, inst->interface_name, "STUN resolving", DIRECTION_OUT);
2853 add_trace("server", "addr", "%s", inst->stun_server);
2859 static void sip_handle_register(struct sip_inst *inst)
2861 char from[128] = "";
2863 char contact[128] = "";
2865 switch (inst->register_state) {
2866 case REGISTER_STATE_UNREGISTERED:
2867 /* wait for resoved stun */
2868 if (inst->stun_handle && inst->stun_state != STUN_STATE_RESOLVED)
2871 PDEBUG(DEBUG_SIP, "Registering to peer\n");
2872 inst->register_handle = nua_handle(inst->nua, NULL, TAG_END());
2873 if (!inst->register_handle) {
2874 PERROR("Failed to create handle\n");
2875 inst->register_state = REGISTER_STATE_FAILED;
2878 /* apply handle to trace */
2879 // sip_trace_header(NULL, inst->interface_name, "NEW handle", DIRECTION_NONE);
2880 // add_trace("handle", "new", "0x%x", inst->register_handle);
2883 SPRINT(from, "sip:%s@%s", inst->register_user, inst->register_host);
2884 SPRINT(to, "sip:%s@%s", inst->register_user, inst->register_host);
2885 if (inst->public_ip[0]) {
2887 SPRINT(contact, "sip:%s@%s", inst->register_user, inst->public_ip);
2888 p = strchr(inst->local_peer, ':');
2893 sip_trace_header(NULL, inst->interface_name, "REGISTER", DIRECTION_OUT);
2894 add_trace("from", "uri", "%s", from);
2895 add_trace("to", "uri", "%s", to);
2898 nua_register(inst->register_handle,
2899 TAG_IF(from[0], SIPTAG_FROM_STR(from)),
2900 TAG_IF(to[0], SIPTAG_TO_STR(to)),
2901 TAG_IF(contact[0], SIPTAG_CONTACT_STR(contact)),
2904 inst->register_state = REGISTER_STATE_REGISTERING;
2911 void sip_handle(void)
2913 struct interface *interface = interface_first;
2914 struct sip_inst *inst;
2917 if (interface->sip_inst) {
2918 inst = (struct sip_inst *) interface->sip_inst;
2919 su_root_step(inst->root, 0);
2920 sip_handle_stun(inst);
2921 sip_handle_register(inst);
2923 interface = interface->next;
2927 /* deletes when back in event loop */
2928 static int delete_event(struct lcr_work *work, void *instance, int index)
2930 class Psip *psip = (class Psip *)instance;
2939 * generate audio, if no data is received from bridge
2942 void Psip::set_tone(const char *dir, const char *tone)
2944 Port::set_tone(dir, tone);
2949 void Psip::update_load(void)
2951 /* don't trigger load event if event already active */
2952 if (p_s_load_timer.active)
2955 /* don't start timer if ... */
2956 if (!p_tone_name[0] && !p_dov_tx)
2959 p_s_next_tv_sec = 0;
2960 schedule_timer(&p_s_load_timer, 0, 0); /* no delay the first time */
2963 static int load_timer(struct lcr_timer *timer, void *instance, int index)
2965 class Psip *psip = (class Psip *)instance;
2967 /* stop timer if ... */
2968 if (!psip->p_tone_name[0] && !psip->p_dov_tx)
2976 #define SEND_SIP_LEN 160
2978 void Psip::load_tx(void)
2981 struct timeval current_time;
2982 int tosend = SEND_SIP_LEN, i;
2983 unsigned char buf[SEND_SIP_LEN], *p = buf;
2986 gettimeofday(¤t_time, NULL);
2987 if (!p_s_next_tv_sec) {
2988 /* if timer expired the first time, set next expected timeout 160 samples in advance */
2989 p_s_next_tv_sec = current_time.tv_sec;
2990 p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
2991 if (p_s_next_tv_usec >= 1000000) {
2992 p_s_next_tv_usec -= 1000000;
2995 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125);
2997 diff = 1000000 * (current_time.tv_sec - p_s_next_tv_sec)
2998 + (current_time.tv_usec - p_s_next_tv_usec);
2999 if (diff < -SEND_SIP_LEN * 125 || diff > SEND_SIP_LEN * 125) {
3000 /* if clock drifts too much, set next timeout event to current timer + 160 */
3002 p_s_next_tv_sec = current_time.tv_sec;
3003 p_s_next_tv_usec = current_time.tv_usec + SEND_SIP_LEN * 125;
3004 if (p_s_next_tv_usec >= 1000000) {
3005 p_s_next_tv_usec -= 1000000;
3009 /* if diff is positive, it took too long, so next timeout will be earlier */
3010 p_s_next_tv_usec += SEND_SIP_LEN * 125;
3011 if (p_s_next_tv_usec >= 1000000) {
3012 p_s_next_tv_usec -= 1000000;
3016 schedule_timer(&p_s_load_timer, 0, SEND_SIP_LEN * 125 - diff);
3020 if (p_tone_name[0]) {
3021 tosend -= read_audio(p, tosend);
3024 tosend -= dov_tx(p, tosend);
3027 PERROR("buffer is not completely filled\n");
3032 for (i = 0; i < SEND_SIP_LEN; i++) {
3036 /* transmit data via rtp */
3037 rtp_send_frame(buf, SEND_SIP_LEN, (options.law=='a')?PAYLOAD_TYPE_ALAW:PAYLOAD_TYPE_ULAW);