Add the InsertBraces command for clang-format to ensure that all conditionals always have braces (#1408)

- Why? Because code where conditionals lack braces is much harder to read, and prone to indentation confusion.
- How? Just added an extra flag to .clang-format and re-ran clang-format on all the files.

I also moved .clang-format up to the top level of the repo so that it can be applied to the fuzz targets as well.
This commit is contained in:
Michael Jones 2024-01-27 18:38:40 -06:00 committed by GitHub
parent 168305494d
commit da332ed9e7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
45 changed files with 2702 additions and 1518 deletions

View File

@ -133,5 +133,6 @@ StatementMacros:
TabWidth: 8 TabWidth: 8
UseCRLF: false UseCRLF: false
UseTab: Never UseTab: Never
InsertBraces: true
... ...

View File

@ -13,17 +13,23 @@ jobs:
steps: steps:
- name: Install dependencies - name: Install dependencies
run: | run: |
sudo apt-get update sudo apt update
sudo apt-get install -y \ sudo apt install -y clang-format-15
sudo apt install -y \
libevent-dev \ libevent-dev \
libssl-dev \ libssl-dev \
libpq-dev libmariadb-dev libsqlite3-dev \ libpq-dev libmariadb-dev libsqlite3-dev \
libhiredis-dev \ libhiredis-dev \
libmongoc-dev \ libmongoc-dev \
libmicrohttpd-dev \ libmicrohttpd-dev \
clang-format
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: configure - name: configure
run: ./configure run: ./configure
- name: lint - name: lint
run: clang-format --version && make lint run: |
if which clang-format-15 2>&1 >/dev/null
then
sudo cp $(which clang-format-15) $(which clang-format)
fi
clang-format --version
make lint

View File

@ -24,7 +24,6 @@ extern int LLVMFuzzerTestOneInput(const uint8_t *Data,
uint8_t realm[33]; uint8_t realm[33];
uint8_t upwd[33]; uint8_t upwd[33];
strcpy((char *)upwd, "VOkJxbRl1RmTxUk/WvJxBt"); strcpy((char *)upwd, "VOkJxbRl1RmTxUk/WvJxBt");
stun_check_message_integrity_str(TURN_CREDENTIALS_SHORT_TERM, (uint8_t *)Data, stun_check_message_integrity_str(TURN_CREDENTIALS_SHORT_TERM, (uint8_t *)Data, Size, uname, realm, upwd, shatype);
Size, uname, realm, upwd, shatype);
return 0; return 0;
} }

View File

@ -183,9 +183,9 @@ int socket_tcp_set_keepalive(evutil_socket_t fd, SOCKET_TYPE st) {
int socket_set_reusable(evutil_socket_t fd, int flag, SOCKET_TYPE st) { int socket_set_reusable(evutil_socket_t fd, int flag, SOCKET_TYPE st) {
UNUSED_ARG(st); UNUSED_ARG(st);
if (fd < 0) if (fd < 0) {
return -1; return -1;
else { } else {
#if defined(WINDOWS) #if defined(WINDOWS)
int use_reuseaddr = IS_TURN_SERVER; int use_reuseaddr = IS_TURN_SERVER;
@ -197,8 +197,9 @@ int socket_set_reusable(evutil_socket_t fd, int flag, SOCKET_TYPE st) {
if (use_reuseaddr) { if (use_reuseaddr) {
int on = flag; int on = flag;
int ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, (socklen_t)sizeof(on)); int ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, (socklen_t)sizeof(on));
if (ret < 0) if (ret < 0) {
perror("SO_REUSEADDR"); perror("SO_REUSEADDR");
}
} }
#endif #endif
@ -208,8 +209,9 @@ int socket_set_reusable(evutil_socket_t fd, int flag, SOCKET_TYPE st) {
if (is_sctp_socket(st)) { if (is_sctp_socket(st)) {
int on = flag; int on = flag;
int ret = setsockopt(fd, IPPROTO_SCTP, SCTP_REUSE_PORT, (const void *)&on, (socklen_t)sizeof(on)); int ret = setsockopt(fd, IPPROTO_SCTP, SCTP_REUSE_PORT, (const void *)&on, (socklen_t)sizeof(on));
if (ret < 0) if (ret < 0) {
perror("SCTP_REUSE_PORT"); perror("SCTP_REUSE_PORT");
}
} }
} }
#endif #endif
@ -238,10 +240,11 @@ int sock_bind_to_device(evutil_socket_t fd, const unsigned char *ifname) {
strncpy(ifr.ifr_name, (const char *)ifname, sizeof(ifr.ifr_name)); strncpy(ifr.ifr_name, (const char *)ifname, sizeof(ifr.ifr_name));
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) { if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
if (socket_eperm()) if (socket_eperm()) {
perror("You must obtain superuser privileges to bind a socket to device"); perror("You must obtain superuser privileges to bind a socket to device");
else } else {
perror("Cannot bind socket to device"); perror("Cannot bind socket to device");
}
return -1; return -1;
} }
@ -255,9 +258,9 @@ int sock_bind_to_device(evutil_socket_t fd, const unsigned char *ifname) {
} }
int addr_connect(evutil_socket_t fd, const ioa_addr *addr, int *out_errno) { int addr_connect(evutil_socket_t fd, const ioa_addr *addr, int *out_errno) {
if (!addr || fd < 0) if (!addr || fd < 0) {
return -1; return -1;
else { } else {
int err = 0; int err = 0;
do { do {
if (addr->ss.sa_family == AF_INET) { if (addr->ss.sa_family == AF_INET) {
@ -269,11 +272,13 @@ int addr_connect(evutil_socket_t fd, const ioa_addr *addr, int *out_errno) {
} }
} while (err < 0 && socket_eintr()); } while (err < 0 && socket_eintr());
if (out_errno) if (out_errno) {
*out_errno = socket_errno(); *out_errno = socket_errno();
}
if (err < 0 && !socket_einprogress()) if (err < 0 && !socket_einprogress()) {
perror("Connect"); perror("Connect");
}
return err; return err;
} }
@ -318,9 +323,9 @@ int addr_bind(evutil_socket_t fd, const ioa_addr *addr, int reusable, int debug,
int addr_get_from_sock(evutil_socket_t fd, ioa_addr *addr) { int addr_get_from_sock(evutil_socket_t fd, ioa_addr *addr) {
if (fd < 0 || !addr) if (fd < 0 || !addr) {
return -1; return -1;
else { } else {
ioa_addr a; ioa_addr a;
a.ss.sa_family = AF_INET6; a.ss.sa_family = AF_INET6;
@ -559,14 +564,16 @@ int set_socket_df(evutil_socket_t fd, int family, int value) {
/* kernel sets DF bit on outgoing IP packets */ /* kernel sets DF bit on outgoing IP packets */
if (family == AF_INET) { if (family == AF_INET) {
int val = IP_PMTUDISC_DO; int val = IP_PMTUDISC_DO;
if (!value) if (!value) {
val = IP_PMTUDISC_DONT; val = IP_PMTUDISC_DONT;
}
ret = setsockopt(fd, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)); ret = setsockopt(fd, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
} else { } else {
#if defined(IPPROTO_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT) #if defined(IPPROTO_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
int val = IPV6_PMTUDISC_DO; int val = IPV6_PMTUDISC_DO;
if (!value) if (!value) {
val = IPV6_PMTUDISC_DONT; val = IPV6_PMTUDISC_DONT;
}
ret = setsockopt(fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val, sizeof(val)); ret = setsockopt(fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val, sizeof(val));
#else #else
#error CANNOT SET IPV6 SOCKET DF FLAG (2) #error CANNOT SET IPV6 SOCKET DF FLAG (2)
@ -590,8 +597,9 @@ int set_socket_df(evutil_socket_t fd, int family, int value) {
static int get_mtu_from_ssl(SSL *ssl) { static int get_mtu_from_ssl(SSL *ssl) {
int ret = SOSO_MTU; int ret = SOSO_MTU;
#if DTLS_SUPPORTED #if DTLS_SUPPORTED
if (ssl) if (ssl) {
ret = BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); ret = BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
}
#else #else
UNUSED_ARG(ssl); UNUSED_ARG(ssl);
#endif #endif
@ -610,29 +618,35 @@ static void set_query_mtu(SSL *ssl) {
int decrease_mtu(SSL *ssl, int mtu, int verbose) { int decrease_mtu(SSL *ssl, int mtu, int verbose) {
if (!ssl) if (!ssl) {
return mtu; return mtu;
}
int new_mtu = get_mtu_from_ssl(ssl); int new_mtu = get_mtu_from_ssl(ssl);
if (new_mtu < 1) if (new_mtu < 1) {
new_mtu = mtu; new_mtu = mtu;
}
if (new_mtu > MAX_MTU) if (new_mtu > MAX_MTU) {
mtu = MAX_MTU; mtu = MAX_MTU;
if (new_mtu > 0 && new_mtu < MIN_MTU) }
if (new_mtu > 0 && new_mtu < MIN_MTU) {
mtu = MIN_MTU; mtu = MIN_MTU;
else if (new_mtu < mtu) } else if (new_mtu < mtu) {
mtu = new_mtu; mtu = new_mtu;
else } else {
mtu -= MTU_STEP; mtu -= MTU_STEP;
}
if (mtu < MIN_MTU) if (mtu < MIN_MTU) {
mtu = MIN_MTU; mtu = MIN_MTU;
}
set_query_mtu(ssl); set_query_mtu(ssl);
if (verbose) if (verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "1. mtu to use: %d\n", mtu); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "1. mtu to use: %d\n", mtu);
}
#if DTLS_SUPPORTED #if DTLS_SUPPORTED
SSL_set_mtu(ssl, mtu); SSL_set_mtu(ssl, mtu);
@ -644,21 +658,24 @@ int decrease_mtu(SSL *ssl, int mtu, int verbose) {
int set_mtu_df(SSL *ssl, evutil_socket_t fd, int family, int mtu, int df_value, int verbose) { int set_mtu_df(SSL *ssl, evutil_socket_t fd, int family, int mtu, int df_value, int verbose) {
if (!ssl || fd < 0) if (!ssl || fd < 0) {
return 0; return 0;
}
int ret = set_socket_df(fd, family, df_value); int ret = set_socket_df(fd, family, df_value);
if (!mtu) if (!mtu) {
mtu = SOSO_MTU; mtu = SOSO_MTU;
else if (mtu < MIN_MTU) } else if (mtu < MIN_MTU) {
mtu = MIN_MTU; mtu = MIN_MTU;
else if (mtu > MAX_MTU) } else if (mtu > MAX_MTU) {
mtu = MAX_MTU; mtu = MAX_MTU;
}
set_query_mtu(ssl); set_query_mtu(ssl);
if (verbose) if (verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "3. mtu to use: %d\n", mtu); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "3. mtu to use: %d\n", mtu);
}
#if DTLS_SUPPORTED #if DTLS_SUPPORTED
@ -668,8 +685,9 @@ int set_mtu_df(SSL *ssl, evutil_socket_t fd, int family, int mtu, int df_value,
#endif #endif
if (verbose) if (verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "4. new mtu: %d\n", get_mtu_from_ssl(ssl)); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "4. new mtu: %d\n", get_mtu_from_ssl(ssl));
}
return ret; return ret;
} }
@ -697,8 +715,9 @@ int get_socket_mtu(evutil_socket_t fd, int family, int verbose) {
ret = val; ret = val;
#endif #endif
if (verbose) if (verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: final=%d\n", __FUNCTION__, ret); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: final=%d\n", __FUNCTION__, ret);
}
return ret; return ret;
} }
@ -762,8 +781,9 @@ int handle_socket_error(void) {
//////////////////// Misc utils ////////////////////////////// //////////////////// Misc utils //////////////////////////////
char *skip_blanks(char *s) { char *skip_blanks(char *s) {
while (*s == ' ' || *s == '\t' || *s == '\n') while (*s == ' ' || *s == '\t' || *s == '\n') {
++s; ++s;
}
return s; return s;
} }
@ -810,9 +830,9 @@ int clock_gettime(int X, struct timeval *tv) {
frequencyToMicroseconds = 10.; frequencyToMicroseconds = 10.;
} }
} }
if (usePerformanceCounter) if (usePerformanceCounter) {
QueryPerformanceCounter(&t); QueryPerformanceCounter(&t);
else { } else {
GetSystemTimeAsFileTime(&f); GetSystemTimeAsFileTime(&f);
t.QuadPart = f.dwHighDateTime; t.QuadPart = f.dwHighDateTime;
t.QuadPart <<= 32; t.QuadPart <<= 32;
@ -858,10 +878,11 @@ char *dirname(char *path) {
} }
int n = strlen(drive) + strlen(dir); int n = strlen(drive) + strlen(dir);
if (n > 0) if (n > 0) {
path[n] = 0; path[n] = 0;
else } else {
return NULL; return NULL;
}
return path; return path;
} }
#endif #endif
@ -889,8 +910,9 @@ int getdomainname(char *name, size_t len) {
strncpy(name, pszOut, n); strncpy(name, pszOut, n);
name[n] = 0; name[n] = 0;
TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "DomainForestName: %s\n", pszOut); TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "DomainForestName: %s\n", pszOut);
} else } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "wchar convert to char fail"); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "wchar convert to char fail");
}
free(pszOut); free(pszOut);
break; break;
@ -909,8 +931,9 @@ int getdomainname(char *name, size_t len) {
strncpy(name, pszOut, n); strncpy(name, pszOut, n);
name[n] = 0; name[n] = 0;
TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "DomainNameDns: %s\n", pszOut); TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "DomainNameDns: %s\n", pszOut);
} else } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "wchar convert to char fail"); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "wchar convert to char fail");
}
free(pszOut); free(pszOut);
break; break;
@ -929,8 +952,9 @@ int getdomainname(char *name, size_t len) {
strncpy(name, pszOut, n); strncpy(name, pszOut, n);
name[n] = 0; name[n] = 0;
TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "DomainNameFlat: %s\n", pszOut); TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "DomainNameFlat: %s\n", pszOut);
} else } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "wchar convert to char fail"); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "wchar convert to char fail");
}
free(pszOut); free(pszOut);
} else { } else {
@ -953,20 +977,23 @@ int getdomainname(char *name, size_t len) {
* \return * \return
*/ */
wchar_t *_ATW(__in char *pszInBuf, __in int nInSize, __out wchar_t **pszOutBuf, __out int *pnOutSize) { wchar_t *_ATW(__in char *pszInBuf, __in int nInSize, __out wchar_t **pszOutBuf, __out int *pnOutSize) {
if (!pszInBuf || !pszOutBuf || !pnOutSize || nInSize <= 0) if (!pszInBuf || !pszOutBuf || !pnOutSize || nInSize <= 0) {
return NULL; return NULL;
}
// Get buffer size // Get buffer size
*pnOutSize = MultiByteToWideChar(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, 0); *pnOutSize = MultiByteToWideChar(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, 0);
if (*pnOutSize == 0) if (*pnOutSize == 0) {
return NULL; return NULL;
}
(*pnOutSize)++; (*pnOutSize)++;
*pszOutBuf = malloc((*pnOutSize) * sizeof(wchar_t)); *pszOutBuf = malloc((*pnOutSize) * sizeof(wchar_t));
memset((void *)*pszOutBuf, 0, sizeof(wchar_t) * (*pnOutSize)); memset((void *)*pszOutBuf, 0, sizeof(wchar_t) * (*pnOutSize));
if (MultiByteToWideChar(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, *pnOutSize) == 0) { if (MultiByteToWideChar(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, *pnOutSize) == 0) {
free(*pszOutBuf); free(*pszOutBuf);
return NULL; return NULL;
} else } else {
return *pszOutBuf; return *pszOutBuf;
}
} }
/*! /*!
@ -979,19 +1006,22 @@ wchar_t *_ATW(__in char *pszInBuf, __in int nInSize, __out wchar_t **pszOutBuf,
* \return * \return
*/ */
char *_WTA(__in wchar_t *pszInBuf, __in int nInSize, __out char **pszOutBuf, __out int *pnOutSize) { char *_WTA(__in wchar_t *pszInBuf, __in int nInSize, __out char **pszOutBuf, __out int *pnOutSize) {
if (!pszInBuf || !pszOutBuf || !pnOutSize || nInSize <= 0) if (!pszInBuf || !pszOutBuf || !pnOutSize || nInSize <= 0) {
return NULL; return NULL;
}
*pnOutSize = WideCharToMultiByte(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, 0, NULL, NULL); *pnOutSize = WideCharToMultiByte(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, 0, NULL, NULL);
if (*pnOutSize == 0) if (*pnOutSize == 0) {
return NULL; return NULL;
}
(*pnOutSize)++; (*pnOutSize)++;
*pszOutBuf = malloc(*pnOutSize * sizeof(char)); *pszOutBuf = malloc(*pnOutSize * sizeof(char));
memset((void *)*pszOutBuf, 0, sizeof(char) * (*pnOutSize)); memset((void *)*pszOutBuf, 0, sizeof(char) * (*pnOutSize));
if (WideCharToMultiByte(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, *pnOutSize, NULL, NULL) == 0) { if (WideCharToMultiByte(NULL, NULL, pszInBuf, nInSize, *pszOutBuf, *pnOutSize, NULL, NULL) == 0) {
free(*pszOutBuf); free(*pszOutBuf);
return NULL; return NULL;
} else } else {
return *pszOutBuf; return *pszOutBuf;
}
} }
#endif #endif
@ -1047,14 +1077,17 @@ void set_execdir(void) {
if (_var && *_var) { if (_var && *_var) {
_var = strdup(_var); _var = strdup(_var);
char *edir = _var; char *edir = _var;
if (edir[0] != '.') if (edir[0] != '.') {
edir = strstr(edir, "/"); edir = strstr(edir, "/");
if (edir && *edir) }
if (edir && *edir) {
edir = dirname(edir); edir = dirname(edir);
else } else {
edir = dirname(_var); edir = dirname(_var);
if (c_execdir) }
if (c_execdir) {
free(c_execdir); free(c_execdir);
}
c_execdir = strdup(edir); c_execdir = strdup(edir);
free(_var); free(_var);
} }
@ -1065,16 +1098,19 @@ void print_abs_file_name(const char *msg1, const char *msg2, const char *fn) {
absfn[0] = 0; absfn[0] = 0;
if (fn) { if (fn) {
while (fn[0] && fn[0] == ' ') while (fn[0] && fn[0] == ' ') {
++fn; ++fn;
}
if (fn[0]) { if (fn[0]) {
if (fn[0] == '/') { if (fn[0] == '/') {
STRCPY(absfn, fn); STRCPY(absfn, fn);
} else { } else {
if (fn[0] == '.' && fn[1] && fn[1] == '/') if (fn[0] == '.' && fn[1] && fn[1] == '/') {
fn += 2; fn += 2;
if (!getcwd(absfn, sizeof(absfn) - 1)) }
if (!getcwd(absfn, sizeof(absfn) - 1)) {
absfn[0] = 0; absfn[0] = 0;
}
size_t blen = strlen(absfn); size_t blen = strlen(absfn);
if (blen < sizeof(absfn) - 1) { if (blen < sizeof(absfn) - 1) {
strncpy(absfn + blen, "/", sizeof(absfn) - blen); strncpy(absfn + blen, "/", sizeof(absfn) - blen);
@ -1286,8 +1322,9 @@ char *base64_encode(const unsigned char *data, size_t input_length, size_t *outp
*output_length = 4 * ((input_length + 2) / 3); *output_length = 4 * ((input_length + 2) / 3);
char *encoded_data = (char *)malloc(*output_length + 1); char *encoded_data = (char *)malloc(*output_length + 1);
if (encoded_data == NULL) if (encoded_data == NULL) {
return NULL; return NULL;
}
size_t i, j; size_t i, j;
for (i = 0, j = 0; i < input_length;) { for (i = 0, j = 0; i < input_length;) {
@ -1304,8 +1341,9 @@ char *base64_encode(const unsigned char *data, size_t input_length, size_t *outp
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
} }
for (i = 0; i < mod_table[input_length % 3]; i++) for (i = 0; i < mod_table[input_length % 3]; i++) {
encoded_data[*output_length - 1 - i] = '='; encoded_data[*output_length - 1 - i] = '=';
}
encoded_data[*output_length] = 0; encoded_data[*output_length] = 0;
@ -1318,27 +1356,33 @@ void build_base64_decoding_table(void) {
memset(decoding_table, 0, 256); memset(decoding_table, 0, 256);
int i; int i;
for (i = 0; i < 64; i++) for (i = 0; i < 64; i++) {
decoding_table[(unsigned char)encoding_table[i]] = (char)i; decoding_table[(unsigned char)encoding_table[i]] = (char)i;
}
} }
unsigned char *base64_decode(const char *data, size_t input_length, size_t *output_length) { unsigned char *base64_decode(const char *data, size_t input_length, size_t *output_length) {
if (decoding_table == NULL) if (decoding_table == NULL) {
build_base64_decoding_table(); build_base64_decoding_table();
}
if (input_length % 4 != 0) if (input_length % 4 != 0) {
return NULL; return NULL;
}
*output_length = input_length / 4 * 3; *output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') if (data[input_length - 1] == '=') {
(*output_length)--; (*output_length)--;
if (data[input_length - 2] == '=') }
if (data[input_length - 2] == '=') {
(*output_length)--; (*output_length)--;
}
unsigned char *decoded_data = (unsigned char *)malloc(*output_length); unsigned char *decoded_data = (unsigned char *)malloc(*output_length);
if (decoded_data == NULL) if (decoded_data == NULL) {
return NULL; return NULL;
}
int i; int i;
size_t j; size_t j;
@ -1351,12 +1395,15 @@ unsigned char *base64_decode(const char *data, size_t input_length, size_t *outp
uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6);
if (j < *output_length) if (j < *output_length) {
decoded_data[j++] = (triple >> 2 * 8) & 0xFF; decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < *output_length) }
if (j < *output_length) {
decoded_data[j++] = (triple >> 1 * 8) & 0xFF; decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < *output_length) }
if (j < *output_length) {
decoded_data[j++] = (triple >> 0 * 8) & 0xFF; decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
} }
return decoded_data; return decoded_data;

View File

@ -143,15 +143,17 @@ static void redisLibeventCleanup(void *privdata) {
struct redisLibeventEvents *e = (struct redisLibeventEvents *)privdata; struct redisLibeventEvents *e = (struct redisLibeventEvents *)privdata;
if (e->allocated) { if (e->allocated) {
if (e->rev) { if (e->rev) {
if (e->rev_set) if (e->rev_set) {
event_del(e->rev); event_del(e->rev);
}
event_free(e->rev); event_free(e->rev);
e->rev = NULL; e->rev = NULL;
} }
e->rev_set = 0; e->rev_set = 0;
if (e->wev) { if (e->wev) {
if (e->wev_set) if (e->wev_set) {
event_del(e->wev); event_del(e->wev);
}
event_free(e->wev); event_free(e->wev);
e->wev = NULL; e->wev = NULL;
} }
@ -166,8 +168,9 @@ static void redisLibeventCleanup(void *privdata) {
int is_redis_asyncconn_good(redis_context_handle rch) { int is_redis_asyncconn_good(redis_context_handle rch) {
if (rch) { if (rch) {
struct redisLibeventEvents *e = (struct redisLibeventEvents *)rch; struct redisLibeventEvents *e = (struct redisLibeventEvents *)rch;
if (redis_le_valid(e)) if (redis_le_valid(e)) {
return 1; return 1;
}
} }
return 0; return 0;
} }
@ -216,14 +219,16 @@ redis_context_handle redisLibeventAttach(struct event_base *base, char *ip0, int
redisAsyncContext *ac = NULL; redisAsyncContext *ac = NULL;
char ip[256]; char ip[256];
if (ip0 && ip0[0]) if (ip0 && ip0[0]) {
STRCPY(ip, ip0); STRCPY(ip, ip0);
else } else {
strncpy(ip, "127.0.0.1", sizeof(ip)); strncpy(ip, "127.0.0.1", sizeof(ip));
}
int port = DEFAULT_REDIS_PORT; int port = DEFAULT_REDIS_PORT;
if (port0 > 0) if (port0 > 0) {
port = port0; port = port0;
}
ac = redisAsyncConnect(ip, port); ac = redisAsyncConnect(ip, port);
if (!ac) { if (!ac) {
@ -243,8 +248,9 @@ redis_context_handle redisLibeventAttach(struct event_base *base, char *ip0, int
e->base = base; e->base = base;
e->ip = strdup(ip); e->ip = strdup(ip);
e->port = port; e->port = port;
if (pwd) if (pwd) {
e->pwd = strdup(pwd); e->pwd = strdup(pwd);
}
e->db = db; e->db = db;
/* Register functions to start/stop listening for events */ /* Register functions to start/stop listening for events */
@ -286,20 +292,23 @@ redis_context_handle redisLibeventAttach(struct event_base *base, char *ip0, int
} }
static void redis_reconnect(struct redisLibeventEvents *e) { static void redis_reconnect(struct redisLibeventEvents *e) {
if (!e || !(e->allocated)) if (!e || !(e->allocated)) {
return; return;
}
if (e->rev) { if (e->rev) {
if (e->rev_set) if (e->rev_set) {
event_del(e->rev); event_del(e->rev);
}
event_free(e->rev); event_free(e->rev);
e->rev = NULL; e->rev = NULL;
} }
e->rev_set = 0; e->rev_set = 0;
if (e->wev) { if (e->wev) {
if (e->wev_set) if (e->wev_set) {
event_del(e->wev); event_del(e->wev);
}
event_free(e->wev); event_free(e->wev);
e->wev = NULL; e->wev = NULL;
} }

View File

@ -66,11 +66,13 @@ volatile int _log_time_value_set = 0;
volatile turn_time_t _log_time_value = 0; volatile turn_time_t _log_time_value = 0;
static inline turn_time_t log_time(void) { static inline turn_time_t log_time(void) {
if (!log_start_time) if (!log_start_time) {
log_start_time = turn_time(); log_start_time = turn_time();
}
if (_log_time_value_set) if (_log_time_value_set) {
return (_log_time_value - log_start_time); return (_log_time_value - log_start_time);
}
return (turn_time() - log_start_time); return (turn_time() - log_start_time);
} }
@ -175,8 +177,9 @@ static int syslog_facility = 0;
static int str_to_syslog_facility(char *s) { static int str_to_syslog_facility(char *s) {
int i; int i;
for (i = 0; str_fac[i]; i++) { for (i = 0; str_fac[i]; i++) {
if (!strcasecmp(s, str_fac[i])) if (!strcasecmp(s, str_fac[i])) {
return int_fac[i]; return int_fac[i];
}
} }
return -1; return -1;
} }
@ -218,8 +221,9 @@ void addr_debug_print(int verbose, const ioa_addr *addr, const char *s) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: EMPTY\n", s); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: EMPTY\n", s);
} else { } else {
char addrbuf[INET6_ADDRSTRLEN]; char addrbuf[INET6_ADDRSTRLEN];
if (!s) if (!s) {
s = ""; s = "";
}
if (addr->ss.sa_family == AF_INET) { if (addr->ss.sa_family == AF_INET) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "IPv4. %s: %s:%d\n", s, TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "IPv4. %s: %s:%d\n", s,
inet_ntop(AF_INET, &addr->s4.sin_addr, addrbuf, INET6_ADDRSTRLEN), nswap16(addr->s4.sin_port)); inet_ntop(AF_INET, &addr->s4.sin_addr, addrbuf, INET6_ADDRSTRLEN), nswap16(addr->s4.sin_port));
@ -287,8 +291,9 @@ void set_log_file_line(int set) { _log_file_line_set = set; }
void reset_rtpprintf(void) { void reset_rtpprintf(void) {
log_lock(); log_lock();
if (_rtpfile) { if (_rtpfile) {
if (_rtpfile != stdout) if (_rtpfile != stdout) {
fclose(_rtpfile); fclose(_rtpfile);
}
_rtpfile = NULL; _rtpfile = NULL;
} }
log_unlock(); log_unlock();
@ -323,9 +328,9 @@ static void set_log_file_name_func(char *base, char *f, size_t fsz) {
len = (int)strlen(base1); len = (int)strlen(base1);
while (len >= 0) { while (len >= 0) {
if (base1[len] == '/') if (base1[len] == '/') {
break; break;
else if (base1[len] == '.') { } else if (base1[len] == '.') {
free(tail); free(tail);
tail = strdup(base1 + len); tail = strdup(base1 + len);
base1[len] = 0; base1[len] = 0;
@ -382,8 +387,9 @@ static void set_rtpfile(void) {
} else { } else {
set_log_file_name(log_fn_base, log_fn); set_log_file_name(log_fn_base, log_fn);
_rtpfile = fopen(log_fn, "a"); _rtpfile = fopen(log_fn, "a");
if (_rtpfile) if (_rtpfile) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", log_fn); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", log_fn);
}
} }
if (!_rtpfile) { if (!_rtpfile) {
fprintf(stderr, "ERROR: Cannot open log file for writing: %s\n", log_fn); fprintf(stderr, "ERROR: Cannot open log file for writing: %s\n", log_fn);
@ -399,49 +405,54 @@ static void set_rtpfile(void) {
char logtail[FILE_STR_LEN]; char logtail[FILE_STR_LEN];
char logf[FILE_STR_LEN]; char logf[FILE_STR_LEN];
if (simple_log) if (simple_log) {
snprintf(logtail, FILE_STR_LEN, "turn.log"); snprintf(logtail, FILE_STR_LEN, "turn.log");
else } else {
snprintf(logtail, FILE_STR_LEN, "turn_%d_", (int)getpid()); snprintf(logtail, FILE_STR_LEN, "turn_%d_", (int)getpid());
}
if (snprintf(logbase, FILE_STR_LEN, "/var/log/turnserver/%s", logtail) < 0) if (snprintf(logbase, FILE_STR_LEN, "/var/log/turnserver/%s", logtail) < 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n");
}
set_log_file_name(logbase, logf); set_log_file_name(logbase, logf);
_rtpfile = fopen(logf, "a"); _rtpfile = fopen(logf, "a");
if (_rtpfile) if (_rtpfile) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf);
else { } else {
if (snprintf(logbase, FILE_STR_LEN, "/var/log/%s", logtail) < 0) if (snprintf(logbase, FILE_STR_LEN, "/var/log/%s", logtail) < 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n");
}
set_log_file_name(logbase, logf); set_log_file_name(logbase, logf);
_rtpfile = fopen(logf, "a"); _rtpfile = fopen(logf, "a");
if (_rtpfile) if (_rtpfile) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf);
else { } else {
if (snprintf(logbase, FILE_STR_LEN, "/var/tmp/%s", logtail) < 0) if (snprintf(logbase, FILE_STR_LEN, "/var/tmp/%s", logtail) < 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n");
}
set_log_file_name(logbase, logf); set_log_file_name(logbase, logf);
_rtpfile = fopen(logf, "a"); _rtpfile = fopen(logf, "a");
if (_rtpfile) if (_rtpfile) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf);
else { } else {
if (snprintf(logbase, FILE_STR_LEN, "/tmp/%s", logtail) < 0) if (snprintf(logbase, FILE_STR_LEN, "/tmp/%s", logtail) < 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "String truncation occured.\n");
}
set_log_file_name(logbase, logf); set_log_file_name(logbase, logf);
_rtpfile = fopen(logf, "a"); _rtpfile = fopen(logf, "a");
if (_rtpfile) if (_rtpfile) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf);
else { } else {
snprintf(logbase, FILE_STR_LEN, "%s", logtail); snprintf(logbase, FILE_STR_LEN, "%s", logtail);
set_log_file_name(logbase, logf); set_log_file_name(logbase, logf);
_rtpfile = fopen(logf, "a"); _rtpfile = fopen(logf, "a");
if (_rtpfile) if (_rtpfile) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "log file opened: %s\n", logf);
else { } else {
_rtpfile = stdout; _rtpfile = stdout;
return; return;
} }
@ -463,8 +474,9 @@ void set_simple_log(int val) { simple_log = val; }
#define QUOTE(x) Q(x) #define QUOTE(x) Q(x)
void rollover_logfile(void) { void rollover_logfile(void) {
if (to_syslog || !(log_fn[0])) if (to_syslog || !(log_fn[0])) {
return; return;
}
{ {
FILE *f = fopen(log_fn, "r"); FILE *f = fopen(log_fn, "r");
@ -478,8 +490,9 @@ void rollover_logfile(void) {
} }
} }
if (simple_log) if (simple_log) {
return; return;
}
log_lock(); log_lock();
if (_rtpfile && log_fn[0] && (_rtpfile != stdout)) { if (_rtpfile && log_fn[0] && (_rtpfile != stdout)) {
@ -547,8 +560,9 @@ void turn_log_func_default(char *file, int line, TURN_LOG_LEVEL level, const cha
so_far += snprintf(s + so_far, MAX_RTPPRINTF_BUFFER_SIZE - (so_far + 1), "(%lu): ", (unsigned long)gettid()); so_far += snprintf(s + so_far, MAX_RTPPRINTF_BUFFER_SIZE - (so_far + 1), "(%lu): ", (unsigned long)gettid());
#endif #endif
if (_log_file_line_set) if (_log_file_line_set) {
so_far += snprintf(s + so_far, MAX_RTPPRINTF_BUFFER_SIZE - (so_far + 1), "%s(%d):", file, line); so_far += snprintf(s + so_far, MAX_RTPPRINTF_BUFFER_SIZE - (so_far + 1), "%s(%d):", file, line);
}
switch (level) { switch (level) {
case TURN_LOG_LEVEL_DEBUG: case TURN_LOG_LEVEL_DEBUG:
@ -572,8 +586,9 @@ void turn_log_func_default(char *file, int line, TURN_LOG_LEVEL level, const cha
if (so_far > MAX_RTPPRINTF_BUFFER_SIZE + 1) { if (so_far > MAX_RTPPRINTF_BUFFER_SIZE + 1) {
so_far = MAX_RTPPRINTF_BUFFER_SIZE + 1; so_far = MAX_RTPPRINTF_BUFFER_SIZE + 1;
} }
if (!no_stdout_log) if (!no_stdout_log) {
fwrite(s, so_far, 1, stdout); fwrite(s, so_far, 1, stdout);
}
/* write to syslog or to log file */ /* write to syslog or to log file */
if (to_syslog) { if (to_syslog) {
@ -605,46 +620,62 @@ int get_default_protocol_port(const char *scheme, size_t slen) {
if (scheme && (slen > 0)) { if (scheme && (slen > 0)) {
switch (slen) { switch (slen) {
case 3: case 3:
if (!memcmp("ftp", scheme, 3)) if (!memcmp("ftp", scheme, 3)) {
return 21; return 21;
if (!memcmp("svn", scheme, 3)) }
if (!memcmp("svn", scheme, 3)) {
return 3690; return 3690;
if (!memcmp("ssh", scheme, 3)) }
if (!memcmp("ssh", scheme, 3)) {
return 22; return 22;
if (!memcmp("sip", scheme, 3)) }
if (!memcmp("sip", scheme, 3)) {
return 5060; return 5060;
}
break; break;
case 4: case 4:
if (!memcmp("http", scheme, 4)) if (!memcmp("http", scheme, 4)) {
return 80; return 80;
if (!memcmp("ldap", scheme, 4)) }
if (!memcmp("ldap", scheme, 4)) {
return 389; return 389;
if (!memcmp("sips", scheme, 4)) }
if (!memcmp("sips", scheme, 4)) {
return 5061; return 5061;
if (!memcmp("turn", scheme, 4)) }
if (!memcmp("turn", scheme, 4)) {
return 3478; return 3478;
if (!memcmp("stun", scheme, 4)) }
if (!memcmp("stun", scheme, 4)) {
return 3478; return 3478;
}
break; break;
case 5: case 5:
if (!memcmp("https", scheme, 5)) if (!memcmp("https", scheme, 5)) {
return 443; return 443;
if (!memcmp("ldaps", scheme, 5)) }
if (!memcmp("ldaps", scheme, 5)) {
return 636; return 636;
if (!memcmp("turns", scheme, 5)) }
if (!memcmp("turns", scheme, 5)) {
return 5349; return 5349;
if (!memcmp("stuns", scheme, 5)) }
if (!memcmp("stuns", scheme, 5)) {
return 5349; return 5349;
}
break; break;
case 6: case 6:
if (!memcmp("telnet", scheme, 6)) if (!memcmp("telnet", scheme, 6)) {
return 23; return 23;
if (!memcmp("radius", scheme, 6)) }
if (!memcmp("radius", scheme, 6)) {
return 1645; return 1645;
}
break; break;
case 7: case 7:
if (!memcmp("svn+ssh", scheme, 7)) if (!memcmp("svn+ssh", scheme, 7)) {
return 22; return 22;
}
break; break;
default: default:
return 0; return 0;
@ -682,10 +713,11 @@ int get_canonic_origin(const char *o, char *co, int sz) {
if (port < 1) { if (port < 1) {
port = get_default_protocol_port(otmp, schlen); port = get_default_protocol_port(otmp, schlen);
} }
if (port > 0) if (port > 0) {
snprintf(otmp + schlen, sizeof(otmp) - schlen - 1, "://%s:%d", host, port); snprintf(otmp + schlen, sizeof(otmp) - schlen - 1, "://%s:%d", host, port);
else } else {
snprintf(otmp + schlen, sizeof(otmp) - schlen - 1, "://%s", host); snprintf(otmp + schlen, sizeof(otmp) - schlen - 1, "://%s", host);
}
{ {
unsigned char *s = (unsigned char *)otmp + schlen + 3; unsigned char *s = (unsigned char *)otmp + schlen + 3;

View File

@ -33,8 +33,9 @@
////////////////////// BUFFERS /////////////////////////// ////////////////////// BUFFERS ///////////////////////////
int stun_init_buffer(stun_buffer *buf) { int stun_init_buffer(stun_buffer *buf) {
if (!buf) if (!buf) {
return -1; return -1;
}
memset(buf->buf, 0, sizeof(buf->buf)); memset(buf->buf, 0, sizeof(buf->buf));
buf->len = 0; buf->len = 0;
buf->offset = 0; buf->offset = 0;
@ -43,8 +44,9 @@ int stun_init_buffer(stun_buffer *buf) {
} }
int stun_get_size(const stun_buffer *buf) { int stun_get_size(const stun_buffer *buf) {
if (!buf) if (!buf) {
return 0; return 0;
}
return sizeof(buf->buf); return sizeof(buf->buf);
} }
@ -70,10 +72,11 @@ static inline int is_channel_msg(const stun_buffer *buf) {
} }
int stun_is_command_message(const stun_buffer *buf) { int stun_is_command_message(const stun_buffer *buf) {
if (!buf || buf->len <= 0) if (!buf || buf->len <= 0) {
return 0; return 0;
else } else {
return stun_is_command_message_str(buf->buf, (size_t)(buf->len)); return stun_is_command_message_str(buf->buf, (size_t)(buf->len));
}
} }
int stun_is_request(const stun_buffer *buf) { return stun_is_request_str(buf->buf, (size_t)buf->len); } int stun_is_request(const stun_buffer *buf) { return stun_is_request_str(buf->buf, (size_t)buf->len); }
@ -89,16 +92,18 @@ int stun_is_error_response(const stun_buffer *buf, int *err_code, uint8_t *err_m
int stun_is_response(const stun_buffer *buf) { return stun_is_response_str(buf->buf, (size_t)(buf->len)); } int stun_is_response(const stun_buffer *buf) { return stun_is_response_str(buf->buf, (size_t)(buf->len)); }
int stun_is_indication(const stun_buffer *buf) { int stun_is_indication(const stun_buffer *buf) {
if (is_channel_msg(buf)) if (is_channel_msg(buf)) {
return 0; return 0;
}
return IS_STUN_INDICATION(stun_get_msg_type(buf)); return IS_STUN_INDICATION(stun_get_msg_type(buf));
} }
uint16_t stun_get_method(const stun_buffer *buf) { return stun_get_method_str(buf->buf, (size_t)(buf->len)); } uint16_t stun_get_method(const stun_buffer *buf) { return stun_get_method_str(buf->buf, (size_t)(buf->len)); }
uint16_t stun_get_msg_type(const stun_buffer *buf) { uint16_t stun_get_msg_type(const stun_buffer *buf) {
if (!buf) if (!buf) {
return (uint16_t)-1; return (uint16_t)-1;
}
return stun_get_msg_type_str(buf->buf, (size_t)buf->len); return stun_get_msg_type_str(buf->buf, (size_t)buf->len);
} }
@ -137,8 +142,9 @@ int stun_init_channel_message(uint16_t chnumber, stun_buffer *buf, int length, i
} }
int stun_is_channel_message(stun_buffer *buf, uint16_t *chnumber, int is_padding_mandatory) { int stun_is_channel_message(stun_buffer *buf, uint16_t *chnumber, int is_padding_mandatory) {
if (!buf) if (!buf) {
return 0; return 0;
}
size_t blen = (size_t)buf->len; size_t blen = (size_t)buf->len;
int ret = stun_is_channel_message_str(buf->buf, &blen, chnumber, is_padding_mandatory); int ret = stun_is_channel_message_str(buf->buf, &blen, chnumber, is_padding_mandatory);
if (ret) { if (ret) {
@ -209,8 +215,9 @@ int stun_attr_get_first_addr(const stun_buffer *buf, uint16_t attr_type, ioa_add
} }
int stun_attr_add_even_port(stun_buffer *buf, uint8_t value) { int stun_attr_add_even_port(stun_buffer *buf, uint8_t value) {
if (value) if (value) {
value = 0x80; value = 0x80;
}
return stun_attr_add(buf, STUN_ATTRIBUTE_EVEN_PORT, (const char *)&value, 1); return stun_attr_add(buf, STUN_ATTRIBUTE_EVEN_PORT, (const char *)&value, 1);
} }

View File

@ -113,8 +113,9 @@ static const char illoptstring[] = "unknown option -- %s";
static void _vwarnx(const char *fmt, va_list ap) { static void _vwarnx(const char *fmt, va_list ap) {
(void)fprintf(stderr, "%s: ", __progname); (void)fprintf(stderr, "%s: ", __progname);
if (fmt != NULL) if (fmt != NULL) {
(void)vfprintf(stderr, fmt, ap); (void)vfprintf(stderr, fmt, ap);
}
(void)fprintf(stderr, "\n"); (void)fprintf(stderr, "\n");
} }
@ -162,10 +163,11 @@ static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char
cstart = panonopt_end + i; cstart = panonopt_end + i;
pos = cstart; pos = cstart;
for (j = 0; j < cyclelen; j++) { for (j = 0; j < cyclelen; j++) {
if (pos >= panonopt_end) if (pos >= panonopt_end) {
pos -= nnonopts; pos -= nnonopts;
else } else {
pos += nopts; pos += nopts;
}
swap = nargv[pos]; swap = nargv[pos];
/* LINTED const cast */ /* LINTED const cast */
((char **)nargv)[pos] = nargv[cstart]; ((char **)nargv)[pos] = nargv[cstart];
@ -200,13 +202,15 @@ static int parse_long_options(char *const *nargv, const char *options, const str
/* argument found (--option=arg) */ /* argument found (--option=arg) */
current_argv_len = has_equal - current_argv; current_argv_len = has_equal - current_argv;
has_equal++; has_equal++;
} else } else {
current_argv_len = strlen(current_argv); current_argv_len = strlen(current_argv);
}
for (i = 0; long_options[i].name; i++) { for (i = 0; long_options[i].name; i++) {
/* find matching long option */ /* find matching long option */
if (strncmp(current_argv, long_options[i].name, current_argv_len)) if (strncmp(current_argv, long_options[i].name, current_argv_len)) {
continue; continue;
}
if (strlen(long_options[i].name) == current_argv_len) { if (strlen(long_options[i].name) == current_argv_len) {
/* exact match */ /* exact match */
@ -218,38 +222,43 @@ static int parse_long_options(char *const *nargv, const char *options, const str
* If this is a known short option, don't allow * If this is a known short option, don't allow
* a partial match of a single character. * a partial match of a single character.
*/ */
if (short_too && current_argv_len == 1) if (short_too && current_argv_len == 1) {
continue; continue;
}
if (match == -1) /* partial match */ if (match == -1) { /* partial match */
match = i; match = i;
else if (!IDENTICAL_INTERPRETATION(i, match)) } else if (!IDENTICAL_INTERPRETATION(i, match)) {
ambiguous = 1; ambiguous = 1;
}
} }
if (ambiguous) { if (ambiguous) {
/* ambiguous abbreviation */ /* ambiguous abbreviation */
if (PRINT_ERROR) if (PRINT_ERROR) {
warnx(ambig, (int)current_argv_len, current_argv); warnx(ambig, (int)current_argv_len, current_argv);
}
optopt = 0; optopt = 0;
return (BADCH); return (BADCH);
} }
if (match != -1) { /* option found */ if (match != -1) { /* option found */
if (long_options[match].has_arg == no_argument && has_equal) { if (long_options[match].has_arg == no_argument && has_equal) {
if (PRINT_ERROR) if (PRINT_ERROR) {
warnx(noarg, (int)current_argv_len, current_argv); warnx(noarg, (int)current_argv_len, current_argv);
}
/* /*
* XXX: GNU sets optopt to val regardless of flag * XXX: GNU sets optopt to val regardless of flag
*/ */
if (long_options[match].flag == NULL) if (long_options[match].flag == NULL) {
optopt = long_options[match].val; optopt = long_options[match].val;
else } else {
optopt = 0; optopt = 0;
}
return (BADARG); return (BADARG);
} }
if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) { if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) {
if (has_equal) if (has_equal) {
optarg = has_equal; optarg = has_equal;
else if (long_options[match].has_arg == required_argument) { } else if (long_options[match].has_arg == required_argument) {
/* /*
* optional argument doesn't use next nargv * optional argument doesn't use next nargv
*/ */
@ -261,15 +270,17 @@ static int parse_long_options(char *const *nargv, const char *options, const str
* Missing argument; leading ':' indicates no error * Missing argument; leading ':' indicates no error
* should be generated. * should be generated.
*/ */
if (PRINT_ERROR) if (PRINT_ERROR) {
warnx(recargstring, current_argv); warnx(recargstring, current_argv);
}
/* /*
* XXX: GNU sets optopt to val regardless of flag * XXX: GNU sets optopt to val regardless of flag
*/ */
if (long_options[match].flag == NULL) if (long_options[match].flag == NULL) {
optopt = long_options[match].val; optopt = long_options[match].val;
else } else {
optopt = 0; optopt = 0;
}
--optind; --optind;
return (BADARG); return (BADARG);
} }
@ -278,18 +289,21 @@ static int parse_long_options(char *const *nargv, const char *options, const str
--optind; --optind;
return (-1); return (-1);
} }
if (PRINT_ERROR) if (PRINT_ERROR) {
warnx(illoptstring, current_argv); warnx(illoptstring, current_argv);
}
optopt = 0; optopt = 0;
return (BADCH); return (BADCH);
} }
if (idx) if (idx) {
*idx = match; *idx = match;
}
if (long_options[match].flag) { if (long_options[match].flag) {
*long_options[match].flag = long_options[match].val; *long_options[match].flag = long_options[match].val;
return (0); return (0);
} else } else {
return (long_options[match].val); return (long_options[match].val);
}
#undef IDENTICAL_INTERPRETATION #undef IDENTICAL_INTERPRETATION
} }
@ -303,15 +317,17 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, c
int optchar, short_too; int optchar, short_too;
static int posixly_correct = -1; static int posixly_correct = -1;
if (options == NULL) if (options == NULL) {
return (-1); return (-1);
}
/* /*
* XXX Some GNU programs (like cvs) set optind to 0 instead of * XXX Some GNU programs (like cvs) set optind to 0 instead of
* XXX using optreset. Work around this braindamage. * XXX using optreset. Work around this braindamage.
*/ */
if (optind == 0) if (optind == 0) {
optind = optreset = 1; optind = optreset = 1;
}
/* /*
* Disable GNU extensions if POSIXLY_CORRECT is set or options * Disable GNU extensions if POSIXLY_CORRECT is set or options
@ -320,18 +336,22 @@ static int getopt_internal(int nargc, char *const *nargv, const char *options, c
* CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
* optreset != 0 for GNU compatibility. * optreset != 0 for GNU compatibility.
*/ */
if (posixly_correct == -1 || optreset != 0) if (posixly_correct == -1 || optreset != 0) {
posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
if (*options == '-') }
if (*options == '-') {
flags |= FLAG_ALLARGS; flags |= FLAG_ALLARGS;
else if (posixly_correct || *options == '+') } else if (posixly_correct || *options == '+') {
flags &= ~FLAG_PERMUTE; flags &= ~FLAG_PERMUTE;
if (*options == '+' || *options == '-') }
if (*options == '+' || *options == '-') {
options++; options++;
}
optarg = NULL; optarg = NULL;
if (optreset) if (optreset) {
nonopt_start = nonopt_end = -1; nonopt_start = nonopt_end = -1;
}
start: start:
if (optreset || !*place) { /* update scanning pointer */ if (optreset || !*place) { /* update scanning pointer */
optreset = 0; optreset = 0;
@ -369,9 +389,9 @@ start:
return (-1); return (-1);
} }
/* do permutation */ /* do permutation */
if (nonopt_start == -1) if (nonopt_start == -1) {
nonopt_start = optind; nonopt_start = optind;
else if (nonopt_end != -1) { } else if (nonopt_end != -1) {
permute_args(nonopt_start, nonopt_end, optind, nargv); permute_args(nonopt_start, nonopt_end, optind, nargv);
nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_start = optind - (nonopt_end - nonopt_start);
nonopt_end = -1; nonopt_end = -1;
@ -380,8 +400,9 @@ start:
/* process next argument */ /* process next argument */
goto start; goto start;
} }
if (nonopt_start != -1 && nonopt_end == -1) if (nonopt_start != -1 && nonopt_end == -1) {
nonopt_end = optind; nonopt_end = optind;
}
/* /*
* If we have "-" do nothing, if "--" we are done. * If we have "-" do nothing, if "--" we are done.
@ -410,10 +431,11 @@ start:
*/ */
if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) { if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) {
short_too = 0; short_too = 0;
if (*place == '-') if (*place == '-') {
place++; /* --foo long option */ place++; /* --foo long option */
else if (*place != ':' && strchr(options, *place) != NULL) } else if (*place != ':' && strchr(options, *place) != NULL) {
short_too = 1; /* could be short option too */ short_too = 1; /* could be short option too */
}
optchar = parse_long_options(nargv, options, long_options, idx, short_too); optchar = parse_long_options(nargv, options, long_options, idx, short_too);
if (optchar != -1) { if (optchar != -1) {
@ -429,47 +451,55 @@ start:
* options, return -1 (non-option) as per POSIX. * options, return -1 (non-option) as per POSIX.
* Otherwise, it is an unknown option character (or ':'). * Otherwise, it is an unknown option character (or ':').
*/ */
if (optchar == (int)'-' && *place == '\0') if (optchar == (int)'-' && *place == '\0') {
return (-1); return (-1);
if (!*place) }
if (!*place) {
++optind; ++optind;
if (PRINT_ERROR) }
if (PRINT_ERROR) {
warnx(illoptchar, optchar); warnx(illoptchar, optchar);
}
optopt = optchar; optopt = optchar;
return (BADCH); return (BADCH);
} }
if (long_options != NULL && optchar == 'W' && oli[1] == ';') { if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
/* -W long-option */ /* -W long-option */
if (*place) /* no space */ if (*place) /* no space */ {
/* NOTHING */; /* NOTHING */;
else if (++optind >= nargc) { /* no arg */ } else if (++optind >= nargc) { /* no arg */
place = EMSG; place = EMSG;
if (PRINT_ERROR) if (PRINT_ERROR) {
warnx(recargchar, optchar); warnx(recargchar, optchar);
}
optopt = optchar; optopt = optchar;
return (BADARG); return (BADARG);
} else /* white space */ } else { /* white space */
place = nargv[optind]; place = nargv[optind];
}
optchar = parse_long_options(nargv, options, long_options, idx, 0); optchar = parse_long_options(nargv, options, long_options, idx, 0);
place = EMSG; place = EMSG;
return (optchar); return (optchar);
} }
if (*++oli != ':') { /* doesn't take argument */ if (*++oli != ':') { /* doesn't take argument */
if (!*place) if (!*place) {
++optind; ++optind;
}
} else { /* takes (optional) argument */ } else { /* takes (optional) argument */
optarg = NULL; optarg = NULL;
if (*place) /* no white space */ if (*place) { /* no white space */
optarg = place; optarg = place;
else if (oli[1] != ':') { /* arg not optional */ } else if (oli[1] != ':') { /* arg not optional */
if (++optind >= nargc) { /* no arg */ if (++optind >= nargc) { /* no arg */
place = EMSG; place = EMSG;
if (PRINT_ERROR) if (PRINT_ERROR) {
warnx(recargchar, optchar); warnx(recargchar, optchar);
}
optopt = optchar; optopt = optchar;
return (BADARG); return (BADARG);
} else } else {
optarg = nargv[optind]; optarg = nargv[optind];
}
} }
place = EMSG; place = EMSG;
++optind; ++optind;

View File

@ -63,12 +63,14 @@ static int init_socket(int *socketfd, ioa_addr *local_addr, int local_port, ioa_
} }
*socketfd = socket(remote_addr->ss.sa_family, SOCK_DGRAM, 0); *socketfd = socket(remote_addr->ss.sa_family, SOCK_DGRAM, 0);
if (udp_fd < 0) if (udp_fd < 0) {
err(-1, NULL); err(-1, NULL);
}
if (!addr_any(local_addr)) { if (!addr_any(local_addr)) {
if (addr_bind(*socketfd, local_addr, 0, 1, UDP_SOCKET) < 0) if (addr_bind(*socketfd, local_addr, 0, 1, UDP_SOCKET) < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
return ret; return ret;
@ -140,8 +142,9 @@ static int stunclient_send(int sockfd, ioa_addr *local_addr, int *local_port, io
len = sendto(sockfd, req.getRawBuffer(), req.getSize(), 0, (struct sockaddr *)remote_addr, (socklen_t)slen); len = sendto(sockfd, req.getRawBuffer(), req.getSize(), 0, (struct sockaddr *)remote_addr, (socklen_t)slen);
} while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain())); } while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain()));
if (len < 0) if (len < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
if (addr_get_from_sock(sockfd, local_addr) < 0) { if (addr_get_from_sock(sockfd, local_addr) < 0) {
@ -184,8 +187,9 @@ static int stunclient_receive(int sockfd, ioa_addr *local_addr, ioa_addr *reflex
ret = 1; ret = 1;
return ret; return ret;
} }
if (recvd > 0) if (recvd > 0) {
len = recvd; len = recvd;
}
buf.len = len; buf.len = len;
try { try {
@ -336,8 +340,9 @@ static int init_socket(int *socketfd, ioa_addr *local_addr, int local_port, ioa_
int ret = 0; int ret = 0;
*socketfd = socket(remote_addr->ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL); *socketfd = socket(remote_addr->ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL);
if (udp_fd < 0) if (udp_fd < 0) {
err(-1, NULL); err(-1, NULL);
}
if (local_port >= 0) { if (local_port >= 0) {
addr_set_port(local_addr, local_port); addr_set_port(local_addr, local_port);
@ -377,8 +382,9 @@ static int stunclient_send(stun_buffer *buf, int sockfd, ioa_addr *local_addr, i
len = sendto(sockfd, buf->buf, buf->len, 0, (struct sockaddr *)remote_addr, (socklen_t)slen); len = sendto(sockfd, buf->buf, buf->len, 0, (struct sockaddr *)remote_addr, (socklen_t)slen);
} while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain())); } while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain()));
if (len < 0) if (len < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
if (addr_get_from_sock(sockfd, local_addr) < 0) { if (addr_get_from_sock(sockfd, local_addr) < 0) {
@ -415,8 +421,9 @@ static int stunclient_receive(stun_buffer *buf, int sockfd, ioa_addr *local_addr
} }
} while (len < 0 && socket_eintr()); } while (len < 0 && socket_eintr());
if (recvd > 0) if (recvd > 0) {
len = recvd; len = recvd;
}
buf->len = len; buf->len = len;
if (stun_is_command_message(buf)) { if (stun_is_command_message(buf)) {
@ -601,12 +608,14 @@ static void init(int first, ioa_addr *local_addr, ioa_addr *remote_addr, int *lo
err(-1, NULL); err(-1, NULL);
} }
} }
if (!first) if (!first) {
*local_port = -1; *local_port = -1;
}
*rfc5780 = 0; *rfc5780 = 0;
if (make_ioa_addr((const uint8_t *)remote_param, port, remote_addr) < 0) if (make_ioa_addr((const uint8_t *)remote_param, port, remote_addr) < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
static void discoveryresult(const char *decision) { static void discoveryresult(const char *decision) {
@ -632,8 +641,9 @@ int main(int argc, char **argv) {
int first = 1; int first = 1;
ioa_addr other_addr, reflexive_addr, tmp_addr, remote_addr, local_addr, local2_addr; ioa_addr other_addr, reflexive_addr, tmp_addr, remote_addr, local_addr, local2_addr;
if (socket_init()) if (socket_init()) {
return -1; return -1;
}
set_logfile("stdout"); set_logfile("stdout");
set_no_stdout_log(1); set_no_stdout_log(1);

View File

@ -105,8 +105,9 @@ static int encode_token(const char *server_name, const char *gcm_nonce, const ch
memset(&etoken, 0, sizeof(etoken)); memset(&etoken, 0, sizeof(etoken));
// TODO: avoid this hack // TODO: avoid this hack
if (!*gcm_nonce) if (!*gcm_nonce) {
gcm_nonce = NULL; gcm_nonce = NULL;
}
if (encode_oauth_token((const uint8_t *)server_name, &etoken, &key, &ot, (const uint8_t *)gcm_nonce) < 0) { if (encode_oauth_token((const uint8_t *)server_name, &etoken, &key, &ot, (const uint8_t *)gcm_nonce) < 0) {
fprintf(stderr, "%s: cannot encode oauth token\n", __FUNCTION__); fprintf(stderr, "%s: cannot encode oauth token\n", __FUNCTION__);
@ -370,8 +371,9 @@ int main(int argc, char **argv) {
} }
} }
for (i = optind; i < argc; i++) for (i = optind; i < argc; i++) {
printf("Non-option argument %s\n", argv[i]); printf("Non-option argument %s\n", argv[i]);
}
if (optind > argc) { if (optind > argc) {
fprintf(stderr, "%s\n", Usage); fprintf(stderr, "%s\n", Usage);
@ -456,8 +458,9 @@ int main(int argc, char **argv) {
oauth_token dot; oauth_token dot;
if (validate_decode_token(server_name, key, base64encoded_etoken, &dot) == 0) { if (validate_decode_token(server_name, key, base64encoded_etoken, &dot) == 0) {
printf("-=Valid token!=-\n"); printf("-=Valid token!=-\n");
if (verbose_flag) if (verbose_flag) {
print_token_body(&dot); print_token_body(&dot);
}
} else { } else {
fprintf(stderr, "Error during token validation and decoding\n"); fprintf(stderr, "Error during token validation and decoding\n");
exit(-1); exit(-1);

View File

@ -61,8 +61,9 @@ int main(int argc, char **argv) {
int c; int c;
char ifname[1025] = "\0"; char ifname[1025] = "\0";
if (socket_init()) if (socket_init()) {
return -1; return -1;
}
IS_TURN_SERVER = 1; IS_TURN_SERVER = 1;
@ -70,7 +71,7 @@ int main(int argc, char **argv) {
set_no_stdout_log(1); set_no_stdout_log(1);
set_system_parameters(0); set_system_parameters(0);
while ((c = getopt(argc, argv, "d:p:L:v")) != -1) while ((c = getopt(argc, argv, "d:p:L:v")) != -1) {
switch (c) { switch (c) {
case 'd': case 'd':
STRCPY(ifname, optarg); STRCPY(ifname, optarg);
@ -89,6 +90,7 @@ int main(int argc, char **argv) {
fprintf(stderr, "%s\n", Usage); fprintf(stderr, "%s\n", Usage);
exit(1); exit(1);
} }
}
if (las < 1) { if (las < 1) {
local_addr_list = (char **)realloc(local_addr_list, ++las * sizeof(char *)); local_addr_list = (char **)realloc(local_addr_list, ++las * sizeof(char *));

View File

@ -36,8 +36,9 @@
static void udp_server_input_handler(evutil_socket_t fd, short what, void *arg) { static void udp_server_input_handler(evutil_socket_t fd, short what, void *arg) {
if (!(what & EV_READ)) if (!(what & EV_READ)) {
return; return;
}
ioa_addr *addr = (ioa_addr *)arg; ioa_addr *addr = (ioa_addr *)arg;
@ -63,19 +64,22 @@ static void udp_server_input_handler(evutil_socket_t fd, short what, void *arg)
static int udp_create_server_socket(server_type *server, const char *ifname, const char *local_address, int port) { static int udp_create_server_socket(server_type *server, const char *ifname, const char *local_address, int port) {
if (server && server->verbose) if (server && server->verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Start\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Start\n");
}
if (!server) if (!server) {
return -1; return -1;
}
evutil_socket_t udp_fd = -1; evutil_socket_t udp_fd = -1;
ioa_addr *server_addr = (ioa_addr *)malloc(sizeof(ioa_addr)); ioa_addr *server_addr = (ioa_addr *)malloc(sizeof(ioa_addr));
STRCPY(server->ifname, ifname); STRCPY(server->ifname, ifname);
if (make_ioa_addr((const uint8_t *)local_address, port, server_addr) < 0) if (make_ioa_addr((const uint8_t *)local_address, port, server_addr) < 0) {
return -1; return -1;
}
udp_fd = socket(server_addr->ss.sa_family, RELAY_DGRAM_SOCKET_TYPE, RELAY_DGRAM_SOCKET_PROTOCOL); udp_fd = socket(server_addr->ss.sa_family, RELAY_DGRAM_SOCKET_TYPE, RELAY_DGRAM_SOCKET_PROTOCOL);
if (udp_fd < 0) { if (udp_fd < 0) {
@ -90,8 +94,9 @@ static int udp_create_server_socket(server_type *server, const char *ifname, con
set_sock_buf_size(udp_fd, UR_SERVER_SOCK_BUF_SIZE); set_sock_buf_size(udp_fd, UR_SERVER_SOCK_BUF_SIZE);
if (addr_bind(udp_fd, server_addr, 1, 1, UDP_SOCKET) < 0) if (addr_bind(udp_fd, server_addr, 1, 1, UDP_SOCKET) < 0) {
return -1; return -1;
}
socket_set_nonblocking(udp_fd); socket_set_nonblocking(udp_fd);
@ -100,8 +105,9 @@ static int udp_create_server_socket(server_type *server, const char *ifname, con
event_add(udp_ev, NULL); event_add(udp_ev, NULL);
if (server && server->verbose) if (server && server->verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "End\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "End\n");
}
return 0; return 0;
} }
@ -110,8 +116,9 @@ static server_type *init_server(int verbose, const char *ifname, char **local_ad
server_type *server = (server_type *)malloc(sizeof(server_type)); server_type *server = (server_type *)malloc(sizeof(server_type));
if (!server) if (!server) {
return server; return server;
}
memset(server, 0, sizeof(server_type)); memset(server, 0, sizeof(server_type));
@ -129,8 +136,9 @@ static server_type *init_server(int verbose, const char *ifname, char **local_ad
static int clean_server(server_type *server) { static int clean_server(server_type *server) {
if (server) { if (server) {
if (server->event_base) if (server->event_base) {
event_base_free(server->event_base); event_base_free(server->event_base);
}
free(server); free(server);
} }
return 0; return 0;
@ -140,8 +148,9 @@ static int clean_server(server_type *server) {
static void run_events(server_type *server) { static void run_events(server_type *server) {
if (!server) if (!server) {
return; return;
}
struct timeval timeout; struct timeval timeout;
@ -174,8 +183,9 @@ void run_udp_server(server_type *server) {
} }
void clean_udp_server(server_type *server) { void clean_udp_server(server_type *server) {
if (server) if (server) {
clean_server(server); clean_server(server);
}
} }
////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////

View File

@ -17,26 +17,31 @@ static int is_acme_req(char *req, size_t len) {
int c, i, k; int c, i, k;
// Check first request line. Should be like: GET path HTTP/1.x // Check first request line. Should be like: GET path HTTP/1.x
if (strncmp(req, GET_ACME_PREFIX, GET_ACME_PREFIX_LEN)) if (strncmp(req, GET_ACME_PREFIX, GET_ACME_PREFIX_LEN)) {
return -1; return -1;
}
// Usually (for LE) the "method path" is 32 + 43 = 55 chars. But other // Usually (for LE) the "method path" is 32 + 43 = 55 chars. But other
// implementations may choose longer pathes. We define PATHMAX = 127 chars // implementations may choose longer pathes. We define PATHMAX = 127 chars
// to be prepared for "DoS" attacks (STUN msg size max. is ~ 64K). // to be prepared for "DoS" attacks (STUN msg size max. is ~ 64K).
len -= 21; // min size of trailing headers len -= 21; // min size of trailing headers
if (len > 131) if (len > 131) {
len = 131; len = 131;
}
for (i = GET_ACME_PREFIX_LEN; i < (int)len; i++) { for (i = GET_ACME_PREFIX_LEN; i < (int)len; i++) {
// find the end of the path // find the end of the path
if (req[i] != ' ') if (req[i] != ' ') {
continue; continue;
}
// consider path < 10 chars invalid. Also we wanna see a "trailer". // consider path < 10 chars invalid. Also we wanna see a "trailer".
if (i < (GET_ACME_PREFIX_LEN + 10) || strncmp(req + i, " HTTP/1.", 8)) if (i < (GET_ACME_PREFIX_LEN + 10) || strncmp(req + i, " HTTP/1.", 8)) {
return -2; return -2;
}
// finally check for allowed chars // finally check for allowed chars
for (k = GET_ACME_PREFIX_LEN; k < i; k++) { for (k = GET_ACME_PREFIX_LEN; k < i; k++) {
c = req[k]; c = req[k];
if ((c > 127) || (A[c] == ' ')) if ((c > 127) || (A[c] == ' ')) {
return -3; return -3;
}
} }
// all checks passed: sufficient for us to answer with a redirect // all checks passed: sufficient for us to answer with a redirect
return i; return i;
@ -50,11 +55,13 @@ int try_acme_redirect(char *req, size_t len, const char *url, ioa_socket_handle
char http_response[1024]; char http_response[1024];
size_t plen, rlen; size_t plen, rlen;
if (url == NULL || url[0] == '\0' || req == NULL || s == 0) if (url == NULL || url[0] == '\0' || req == NULL || s == 0) {
return 1; return 1;
}
if (len < (GET_ACME_PREFIX_LEN + 32) || len > (512 - GET_ACME_PREFIX_LEN) || if (len < (GET_ACME_PREFIX_LEN + 32) || len > (512 - GET_ACME_PREFIX_LEN) ||
(plen = is_acme_req(req, len)) < (GET_ACME_PREFIX_LEN + 1)) (plen = is_acme_req(req, len)) < (GET_ACME_PREFIX_LEN + 1)) {
return 2; return 2;
}
req[plen] = '\0'; req[plen] = '\0';

View File

@ -72,10 +72,12 @@ static void mongo_logger(mongoc_log_level_t log_level, const char *log_domain, c
static void MongoFree(MONGO *info) { static void MongoFree(MONGO *info) {
if (info) { if (info) {
if (info->uri) if (info->uri) {
mongoc_uri_destroy(info->uri); mongoc_uri_destroy(info->uri);
if (info->client) }
if (info->client) {
mongoc_client_destroy(info->client); mongoc_client_destroy(info->client);
}
free(info); free(info);
} }
} }
@ -108,8 +110,9 @@ static MONGO *get_mongodb_connection(void) {
mydbconnection = NULL; mydbconnection = NULL;
} else { } else {
mydbconnection->database = mongoc_uri_get_database(mydbconnection->uri); mydbconnection->database = mongoc_uri_get_database(mydbconnection->uri);
if (!mydbconnection->database) if (!mydbconnection->database) {
mydbconnection->database = MONGO_DEFAULT_DB; mydbconnection->database = MONGO_DEFAULT_DB;
}
if (mydbconnection) { if (mydbconnection) {
(void)pthread_setspecific(connection_key, mydbconnection); (void)pthread_setspecific(connection_key, mydbconnection);
} }
@ -143,8 +146,9 @@ static mongoc_collection_t *mongo_get_collection(const char *name) {
static int mongo_get_auth_secrets(secrets_list_t *sl, uint8_t *realm) { static int mongo_get_auth_secrets(secrets_list_t *sl, uint8_t *realm) {
mongoc_collection_t *collection = mongo_get_collection("turn_secret"); mongoc_collection_t *collection = mongo_get_collection("turn_secret");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -185,8 +189,9 @@ static int mongo_get_auth_secrets(secrets_list_t *sl, uint8_t *realm) {
static int mongo_get_user_key(uint8_t *usname, uint8_t *realm, hmackey_t key) { static int mongo_get_user_key(uint8_t *usname, uint8_t *realm, hmackey_t key) {
mongoc_collection_t *collection = mongo_get_collection("turnusers_lt"); mongoc_collection_t *collection = mongo_get_collection("turnusers_lt");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -240,8 +245,9 @@ static int mongo_get_oauth_key(const uint8_t *kid, oauth_key_data_raw *key) {
mongoc_collection_t *collection = mongo_get_collection("oauth_key"); mongoc_collection_t *collection = mongo_get_collection("oauth_key");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -298,8 +304,9 @@ static int mongo_get_oauth_key(const uint8_t *kid, oauth_key_data_raw *key) {
static int mongo_set_user_key(uint8_t *usname, uint8_t *realm, const char *key) { static int mongo_set_user_key(uint8_t *usname, uint8_t *realm, const char *key) {
mongoc_collection_t *collection = mongo_get_collection("turnusers_lt"); mongoc_collection_t *collection = mongo_get_collection("turnusers_lt");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -329,8 +336,9 @@ static int mongo_set_oauth_key(oauth_key_data_raw *key) {
mongoc_collection_t *collection = mongo_get_collection("oauth_key"); mongoc_collection_t *collection = mongo_get_collection("oauth_key");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -361,8 +369,9 @@ static int mongo_set_oauth_key(oauth_key_data_raw *key) {
static int mongo_del_user(uint8_t *usname, uint8_t *realm) { static int mongo_del_user(uint8_t *usname, uint8_t *realm) {
mongoc_collection_t *collection = mongo_get_collection("turnusers_lt"); mongoc_collection_t *collection = mongo_get_collection("turnusers_lt");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -385,8 +394,9 @@ static int mongo_del_oauth_key(const uint8_t *kid) {
mongoc_collection_t *collection = mongo_get_collection("oauth_key"); mongoc_collection_t *collection = mongo_get_collection("oauth_key");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -409,11 +419,13 @@ static int mongo_list_users(uint8_t *realm, secrets_list_t *users, secrets_list_
mongoc_collection_t *collection = mongo_get_collection(collection_name); mongoc_collection_t *collection = mongo_get_collection(collection_name);
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query, child; bson_t query, child;
bson_init(&query); bson_init(&query);
@ -484,8 +496,9 @@ static int mongo_list_oauth_keys(secrets_list_t *kids, secrets_list_t *teas, sec
const char *collection_name = "oauth_key"; const char *collection_name = "oauth_key";
mongoc_collection_t *collection = mongo_get_collection(collection_name); mongoc_collection_t *collection = mongo_get_collection(collection_name);
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -572,11 +585,13 @@ static int mongo_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
mongoc_collection_t *collection = mongo_get_collection("turn_secret"); mongoc_collection_t *collection = mongo_get_collection("turn_secret");
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query, child; bson_t query, child;
bson_init(&query); bson_init(&query);
@ -644,8 +659,9 @@ static int mongo_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
static int mongo_del_secret(uint8_t *secret, uint8_t *realm) { static int mongo_del_secret(uint8_t *secret, uint8_t *realm) {
mongoc_collection_t *collection = mongo_get_collection("turn_secret"); mongoc_collection_t *collection = mongo_get_collection("turn_secret");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -663,8 +679,9 @@ static int mongo_del_secret(uint8_t *secret, uint8_t *realm) {
static int mongo_set_secret(uint8_t *secret, uint8_t *realm) { static int mongo_set_secret(uint8_t *secret, uint8_t *realm) {
mongoc_collection_t *collection = mongo_get_collection("turn_secret"); mongoc_collection_t *collection = mongo_get_collection("turn_secret");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -689,14 +706,16 @@ static int mongo_set_permission_ip(const char *kind, uint8_t *realm, const char
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return -1; return -1;
}
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
bson_t query, doc, child; bson_t query, doc, child;
bson_init(&query); bson_init(&query);
@ -732,14 +751,16 @@ static int mongo_set_permission_ip(const char *kind, uint8_t *realm, const char
static int mongo_add_origin(uint8_t *origin, uint8_t *realm) { static int mongo_add_origin(uint8_t *origin, uint8_t *realm) {
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return -1; return -1;
}
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
bson_t query, doc, child; bson_t query, doc, child;
bson_init(&query); bson_init(&query);
@ -763,8 +784,9 @@ static int mongo_add_origin(uint8_t *origin, uint8_t *realm) {
static int mongo_del_origin(uint8_t *origin) { static int mongo_del_origin(uint8_t *origin) {
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return -1; return -1;
}
int ret = -1; int ret = -1;
@ -789,12 +811,14 @@ static int mongo_del_origin(uint8_t *origin) {
static int mongo_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_list_t *realms) { static int mongo_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_list_t *realms) {
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return -1; return -1;
}
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
bson_t query, child; bson_t query, child;
bson_init(&query); bson_init(&query);
@ -867,8 +891,9 @@ static int mongo_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_l
static int mongo_set_realm_option_one(uint8_t *realm, unsigned long value, const char *opt) { static int mongo_set_realm_option_one(uint8_t *realm, unsigned long value, const char *opt) {
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query, doc, child; bson_t query, doc, child;
bson_init(&query); bson_init(&query);
@ -907,8 +932,9 @@ static int mongo_set_realm_option_one(uint8_t *realm, unsigned long value, const
static int mongo_list_realm_options(uint8_t *realm) { static int mongo_list_realm_options(uint8_t *realm) {
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query, child; bson_t query, child;
bson_init(&query); bson_init(&query);
@ -991,8 +1017,9 @@ static int mongo_read_realms_ip_lists(const char *kind, ip_range_list_t *list) {
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return ret; return ret;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -1057,8 +1084,9 @@ static void mongo_reread_realms(secrets_list_t *realms_list) {
mongoc_collection_t *collection = mongo_get_collection("realm"); mongoc_collection_t *collection = mongo_get_collection("realm");
if (!collection) if (!collection) {
return; return;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -1139,13 +1167,13 @@ static void mongo_reread_realms(secrets_list_t *realms_list) {
_v = (uint64_t)bson_iter_int64(&options_iter); _v = (uint64_t)bson_iter_int64(&options_iter);
} }
if (_v) { if (_v) {
if (!strcmp(_k, "max-bps")) if (!strcmp(_k, "max-bps")) {
rp->options.perf_options.max_bps = (band_limit_t)_v; rp->options.perf_options.max_bps = (band_limit_t)_v;
else if (!strcmp(_k, "total-quota")) } else if (!strcmp(_k, "total-quota")) {
rp->options.perf_options.total_quota = (vint)_v; rp->options.perf_options.total_quota = (vint)_v;
else if (!strcmp(_k, "user-quota")) } else if (!strcmp(_k, "user-quota")) {
rp->options.perf_options.user_quota = (vint)_v; rp->options.perf_options.user_quota = (vint)_v;
else { } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", _k); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", _k);
} }
} }
@ -1168,8 +1196,9 @@ static void mongo_reread_realms(secrets_list_t *realms_list) {
static int mongo_get_admin_user(const uint8_t *usname, uint8_t *realm, password_t pwd) { static int mongo_get_admin_user(const uint8_t *usname, uint8_t *realm, password_t pwd) {
mongoc_collection_t *collection = mongo_get_collection("admin_user"); mongoc_collection_t *collection = mongo_get_collection("admin_user");
if (!collection) if (!collection) {
return -1; return -1;
}
realm[0] = 0; realm[0] = 0;
pwd[0] = 0; pwd[0] = 0;
@ -1215,8 +1244,9 @@ static int mongo_get_admin_user(const uint8_t *usname, uint8_t *realm, password_
static int mongo_set_admin_user(const uint8_t *usname, const uint8_t *realm, const password_t pwd) { static int mongo_set_admin_user(const uint8_t *usname, const uint8_t *realm, const password_t pwd) {
mongoc_collection_t *collection = mongo_get_collection("admin_user"); mongoc_collection_t *collection = mongo_get_collection("admin_user");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -1244,8 +1274,9 @@ static int mongo_set_admin_user(const uint8_t *usname, const uint8_t *realm, con
static int mongo_del_admin_user(const uint8_t *usname) { static int mongo_del_admin_user(const uint8_t *usname) {
mongoc_collection_t *collection = mongo_get_collection("admin_user"); mongoc_collection_t *collection = mongo_get_collection("admin_user");
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query; bson_t query;
bson_init(&query); bson_init(&query);
@ -1267,8 +1298,9 @@ static int mongo_list_admin_users(int no_print) {
const char *collection_name = "admin_user"; const char *collection_name = "admin_user";
mongoc_collection_t *collection = mongo_get_collection(collection_name); mongoc_collection_t *collection = mongo_get_collection(collection_name);
if (!collection) if (!collection) {
return -1; return -1;
}
bson_t query, child; bson_t query, child;
bson_init(&query); bson_init(&query);

View File

@ -60,24 +60,33 @@ typedef struct _Myconninfo Myconninfo;
static void MyconninfoFree(Myconninfo *co) { static void MyconninfoFree(Myconninfo *co) {
if (co) { if (co) {
if (co->host) if (co->host) {
free(co->host); free(co->host);
if (co->dbname) }
if (co->dbname) {
free(co->dbname); free(co->dbname);
if (co->user) }
if (co->user) {
free(co->user); free(co->user);
if (co->password) }
if (co->password) {
free(co->password); free(co->password);
if (co->key) }
if (co->key) {
free(co->key); free(co->key);
if (co->ca) }
if (co->ca) {
free(co->ca); free(co->ca);
if (co->cert) }
if (co->cert) {
free(co->cert); free(co->cert);
if (co->capath) }
if (co->capath) {
free(co->capath); free(co->capath);
if (co->cipher) }
if (co->cipher) {
free(co->cipher); free(co->cipher);
}
memset(co, 0, sizeof(Myconninfo)); memset(co, 0, sizeof(Myconninfo));
free(co); free(co);
} }
@ -120,8 +129,9 @@ static Myconninfo *MyconninfoParse(char *userdb, char **errmsg) {
while (s && *s) { while (s && *s) {
while (*s && (*s == ' ')) while (*s && (*s == ' ')) {
++s; ++s;
}
char *snext = strstr(s, " "); char *snext = strstr(s, " ");
if (snext) { if (snext) {
*snext = 0; *snext = 0;
@ -139,69 +149,69 @@ static Myconninfo *MyconninfoParse(char *userdb, char **errmsg) {
} }
*seq = 0; *seq = 0;
if (!strcmp(s, "host")) if (!strcmp(s, "host")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "ip")) } else if (!strcmp(s, "ip")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "addr")) } else if (!strcmp(s, "addr")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "ipaddr")) } else if (!strcmp(s, "ipaddr")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "hostaddr")) } else if (!strcmp(s, "hostaddr")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "dbname")) } else if (!strcmp(s, "dbname")) {
co->dbname = strdup(seq + 1); co->dbname = strdup(seq + 1);
else if (!strcmp(s, "db")) } else if (!strcmp(s, "db")) {
co->dbname = strdup(seq + 1); co->dbname = strdup(seq + 1);
else if (!strcmp(s, "database")) } else if (!strcmp(s, "database")) {
co->dbname = strdup(seq + 1); co->dbname = strdup(seq + 1);
else if (!strcmp(s, "user")) } else if (!strcmp(s, "user")) {
co->user = strdup(seq + 1); co->user = strdup(seq + 1);
else if (!strcmp(s, "uname")) } else if (!strcmp(s, "uname")) {
co->user = strdup(seq + 1); co->user = strdup(seq + 1);
else if (!strcmp(s, "name")) } else if (!strcmp(s, "name")) {
co->user = strdup(seq + 1); co->user = strdup(seq + 1);
else if (!strcmp(s, "username")) } else if (!strcmp(s, "username")) {
co->user = strdup(seq + 1); co->user = strdup(seq + 1);
else if (!strcmp(s, "password")) } else if (!strcmp(s, "password")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "pwd")) } else if (!strcmp(s, "pwd")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "passwd")) } else if (!strcmp(s, "passwd")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "secret")) } else if (!strcmp(s, "secret")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "port")) } else if (!strcmp(s, "port")) {
co->port = (unsigned int)atoi(seq + 1); co->port = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "p")) } else if (!strcmp(s, "p")) {
co->port = (unsigned int)atoi(seq + 1); co->port = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "connect_timeout")) } else if (!strcmp(s, "connect_timeout")) {
co->connect_timeout = (unsigned int)atoi(seq + 1); co->connect_timeout = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "timeout")) } else if (!strcmp(s, "timeout")) {
co->connect_timeout = (unsigned int)atoi(seq + 1); co->connect_timeout = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "read_timeout")) } else if (!strcmp(s, "read_timeout")) {
co->read_timeout = (unsigned int)atoi(seq + 1); co->read_timeout = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "key")) } else if (!strcmp(s, "key")) {
co->key = strdup(seq + 1); co->key = strdup(seq + 1);
else if (!strcmp(s, "ssl-key")) } else if (!strcmp(s, "ssl-key")) {
co->key = strdup(seq + 1); co->key = strdup(seq + 1);
else if (!strcmp(s, "ca")) } else if (!strcmp(s, "ca")) {
co->ca = strdup(seq + 1); co->ca = strdup(seq + 1);
else if (!strcmp(s, "ssl-ca")) } else if (!strcmp(s, "ssl-ca")) {
co->ca = strdup(seq + 1); co->ca = strdup(seq + 1);
else if (!strcmp(s, "capath")) } else if (!strcmp(s, "capath")) {
co->capath = strdup(seq + 1); co->capath = strdup(seq + 1);
else if (!strcmp(s, "ssl-capath")) } else if (!strcmp(s, "ssl-capath")) {
co->capath = strdup(seq + 1); co->capath = strdup(seq + 1);
else if (!strcmp(s, "cert")) } else if (!strcmp(s, "cert")) {
co->cert = strdup(seq + 1); co->cert = strdup(seq + 1);
else if (!strcmp(s, "ssl-cert")) } else if (!strcmp(s, "ssl-cert")) {
co->cert = strdup(seq + 1); co->cert = strdup(seq + 1);
else if (!strcmp(s, "cipher")) } else if (!strcmp(s, "cipher")) {
co->cipher = strdup(seq + 1); co->cipher = strdup(seq + 1);
else if (!strcmp(s, "ssl-cipher")) } else if (!strcmp(s, "ssl-cipher")) {
co->cipher = strdup(seq + 1); co->cipher = strdup(seq + 1);
else { } else {
MyconninfoFree(co); MyconninfoFree(co);
co = NULL; co = NULL;
if (errmsg) { if (errmsg) {
@ -217,14 +227,18 @@ static Myconninfo *MyconninfoParse(char *userdb, char **errmsg) {
} }
if (co) { if (co) {
if (!(co->dbname)) if (!(co->dbname)) {
co->dbname = strdup("0"); co->dbname = strdup("0");
if (!(co->host)) }
if (!(co->host)) {
co->host = strdup("127.0.0.1"); co->host = strdup("127.0.0.1");
if (!(co->user)) }
if (!(co->user)) {
co->user = strdup(""); co->user = strdup("");
if (!(co->password)) }
if (!(co->password)) {
co->password = strdup(""); co->password = strdup("");
}
} }
return co; return co;
@ -270,10 +284,12 @@ static MYSQL *get_mydb_connection(void) {
if (!mydbconnection) { if (!mydbconnection) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot initialize MySQL DB connection\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot initialize MySQL DB connection\n");
} else { } else {
if (co->connect_timeout) if (co->connect_timeout) {
mysql_options(mydbconnection, MYSQL_OPT_CONNECT_TIMEOUT, &(co->connect_timeout)); mysql_options(mydbconnection, MYSQL_OPT_CONNECT_TIMEOUT, &(co->connect_timeout));
if (co->read_timeout) }
if (co->read_timeout) {
mysql_options(mydbconnection, MYSQL_OPT_READ_TIMEOUT, &(co->read_timeout)); mysql_options(mydbconnection, MYSQL_OPT_READ_TIMEOUT, &(co->read_timeout));
}
if (co->ca || co->capath || co->cert || co->cipher || co->key) { if (co->ca || co->capath || co->cert || co->cipher || co->key) {
mysql_ssl_set(mydbconnection, co->key, co->cert, co->ca, co->capath, co->cipher); mysql_ssl_set(mydbconnection, co->key, co->cert, co->ca, co->capath, co->cipher);
} }
@ -298,8 +314,9 @@ static MYSQL *get_mydb_connection(void) {
if (turn_params.secret_key_file[0]) { if (turn_params.secret_key_file[0]) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Encryption with AES is activated.\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Encryption with AES is activated.\n");
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Connection is secure.\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Connection is secure.\n");
} else } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Connection is not secure.\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Connection is not secure.\n");
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
} }
} }
@ -348,8 +365,9 @@ static int mysql_get_auth_secrets(secrets_list_t *sl, uint8_t *realm) {
ret = 0; ret = 0;
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -395,8 +413,9 @@ static int mysql_get_user_key(uint8_t *usname, uint8_t *realm, hmackey_t key) {
} }
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -451,8 +470,9 @@ static int mysql_get_oauth_key(const uint8_t *kid, oauth_key_data_raw *key) {
} }
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -531,8 +551,9 @@ static int mysql_list_oauth_keys(secrets_list_t *kids, secrets_list_t *teas, sec
} }
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
@ -630,8 +651,9 @@ static int mysql_list_users(uint8_t *realm, secrets_list_t *users, secrets_list_
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
MYSQL *myc = get_mydb_connection(); MYSQL *myc = get_mydb_connection();
if (myc) { if (myc) {
@ -675,8 +697,9 @@ static int mysql_list_users(uint8_t *realm, secrets_list_t *users, secrets_list_
ret = 0; ret = 0;
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -686,8 +709,9 @@ static int mysql_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
if (realm[0]) { if (realm[0]) {
@ -737,8 +761,9 @@ static int mysql_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
ret = 0; ret = 0;
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -750,10 +775,11 @@ static int mysql_del_secret(uint8_t *secret, uint8_t *realm) {
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
MYSQL *myc = get_mydb_connection(); MYSQL *myc = get_mydb_connection();
if (myc) { if (myc) {
if (!secret || (secret[0] == 0)) if (!secret || (secret[0] == 0)) {
snprintf(statement, sizeof(statement), "delete from turn_secret where realm='%s'", realm); snprintf(statement, sizeof(statement), "delete from turn_secret where realm='%s'", realm);
else } else {
snprintf(statement, sizeof(statement), "delete from turn_secret where value='%s' and realm='%s'", secret, realm); snprintf(statement, sizeof(statement), "delete from turn_secret where value='%s' and realm='%s'", secret, realm);
}
mysql_query(myc, statement); mysql_query(myc, statement);
ret = 0; ret = 0;
} }
@ -781,8 +807,9 @@ static int mysql_set_permission_ip(const char *kind, uint8_t *realm, const char
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -844,8 +871,9 @@ static int mysql_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_l
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -894,8 +922,9 @@ static int mysql_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_l
ret = 0; ret = 0;
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -959,8 +988,9 @@ static int mysql_list_realm_options(uint8_t *realm) {
ret = 0; ret = 0;
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -1033,8 +1063,9 @@ static int mysql_get_ip_list(const char *kind, ip_range_list_t *list) {
ret = 0; ret = 0;
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -1077,8 +1108,9 @@ static void mysql_reread_realms(secrets_list_t *realms_list) {
update_o_to_realm(o_to_realm_new); update_o_to_realm(o_to_realm_new);
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
{ {
@ -1136,13 +1168,13 @@ static void mysql_reread_realms(secrets_list_t *realms_list) {
memcpy(vval, row[2], sz); memcpy(vval, row[2], sz);
vval[sz] = 0; vval[sz] = 0;
realm_params_t *rp = get_realm(rval); realm_params_t *rp = get_realm(rval);
if (!strcmp(oval, "max-bps")) if (!strcmp(oval, "max-bps")) {
rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval, NULL, 10); rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval, NULL, 10);
else if (!strcmp(oval, "total-quota")) } else if (!strcmp(oval, "total-quota")) {
rp->options.perf_options.total_quota = (vint)atoi(vval); rp->options.perf_options.total_quota = (vint)atoi(vval);
else if (!strcmp(oval, "user-quota")) } else if (!strcmp(oval, "user-quota")) {
rp->options.perf_options.user_quota = (vint)atoi(vval); rp->options.perf_options.user_quota = (vint)atoi(vval);
else { } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval);
} }
} }
@ -1151,8 +1183,9 @@ static void mysql_reread_realms(secrets_list_t *realms_list) {
} }
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
} }
@ -1187,8 +1220,9 @@ static int mysql_get_admin_user(const uint8_t *usname, uint8_t *realm, password_
} }
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;
@ -1271,8 +1305,9 @@ static int mysql_list_admin_users(int no_print) {
} }
} }
if (mres) if (mres) {
mysql_free_result(mres); mysql_free_result(mres);
}
} }
} }
return ret; return ret;

View File

@ -68,8 +68,9 @@ static PGconn *get_pqdb_connection(void) {
} }
} else { } else {
PQconninfoFree(co); PQconninfoFree(co);
if (errmsg) if (errmsg) {
free(errmsg); free(errmsg);
}
pqdbconnection = PQconnectdb(pud->userdb); pqdbconnection = PQconnectdb(pud->userdb);
if (!pqdbconnection) { if (!pqdbconnection) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, runtime error\n", TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot open PostgreSQL DB connection: <%s>, runtime error\n",
@ -154,8 +155,9 @@ static int pgsql_get_user_key(uint8_t *usname, uint8_t *realm, hmackey_t key) {
} }
} }
if (res) if (res) {
PQclear(res); PQclear(res);
}
} }
return ret; return ret;
} }
@ -363,8 +365,9 @@ static int pgsql_list_users(uint8_t *realm, secrets_list_t *users, secrets_list_
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
PGconn *pqc = get_pqdb_connection(); PGconn *pqc = get_pqdb_connection();
if (pqc) { if (pqc) {
@ -412,8 +415,9 @@ static int pgsql_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
if (realm[0]) { if (realm[0]) {
@ -465,10 +469,11 @@ static int pgsql_del_secret(uint8_t *secret, uint8_t *realm) {
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
PGconn *pqc = get_pqdb_connection(); PGconn *pqc = get_pqdb_connection();
if (pqc) { if (pqc) {
if (!secret || (secret[0] == 0)) if (!secret || (secret[0] == 0)) {
snprintf(statement, sizeof(statement), "delete from turn_secret where realm='%s'", realm); snprintf(statement, sizeof(statement), "delete from turn_secret where realm='%s'", realm);
else } else {
snprintf(statement, sizeof(statement), "delete from turn_secret where value='%s' and realm='%s'", secret, realm); snprintf(statement, sizeof(statement), "delete from turn_secret where value='%s' and realm='%s'", secret, realm);
}
PGresult *res = PQexec(pqc, statement); PGresult *res = PQexec(pqc, statement);
if (res) { if (res) {
@ -504,8 +509,9 @@ static int pgsql_set_permission_ip(const char *kind, uint8_t *realm, const char
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -580,8 +586,9 @@ static int pgsql_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_l
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -834,13 +841,13 @@ static void pgsql_reread_realms(secrets_list_t *realms_list) {
char *vval = PQgetvalue(res, i, 2); char *vval = PQgetvalue(res, i, 2);
if (rval && oval && vval) { if (rval && oval && vval) {
realm_params_t *rp = get_realm(rval); realm_params_t *rp = get_realm(rval);
if (!strcmp(oval, "max-bps")) if (!strcmp(oval, "max-bps")) {
rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval, NULL, 10); rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval, NULL, 10);
else if (!strcmp(oval, "total-quota")) } else if (!strcmp(oval, "total-quota")) {
rp->options.perf_options.total_quota = (vint)atoi(vval); rp->options.perf_options.total_quota = (vint)atoi(vval);
else if (!strcmp(oval, "user-quota")) } else if (!strcmp(oval, "user-quota")) {
rp->options.perf_options.user_quota = (vint)atoi(vval); rp->options.perf_options.user_quota = (vint)atoi(vval);
else { } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval);
} }
} }
@ -882,8 +889,9 @@ static int pgsql_get_admin_user(const uint8_t *usname, uint8_t *realm, password_
ret = 0; ret = 0;
} }
if (res) if (res) {
PQclear(res); PQclear(res);
}
} }
return ret; return ret;
} }

View File

@ -58,12 +58,15 @@ typedef struct _Ryconninfo Ryconninfo;
static void RyconninfoFree(Ryconninfo *co) { static void RyconninfoFree(Ryconninfo *co) {
if (co) { if (co) {
if (co->host) if (co->host) {
free(co->host); free(co->host);
if (co->dbname) }
if (co->dbname) {
free(co->dbname); free(co->dbname);
if (co->password) }
if (co->password) {
free(co->password); free(co->password);
}
memset(co, 0, sizeof(Ryconninfo)); memset(co, 0, sizeof(Ryconninfo));
free(co); free(co);
} }
@ -78,8 +81,9 @@ static Ryconninfo *RyconninfoParse(const char *userdb, char **errmsg) {
while (s && *s) { while (s && *s) {
while (*s && (*s == ' ')) while (*s && (*s == ' ')) {
++s; ++s;
}
char *snext = strstr(s, " "); char *snext = strstr(s, " ");
if (snext) { if (snext) {
*snext = 0; *snext = 0;
@ -97,47 +101,47 @@ static Ryconninfo *RyconninfoParse(const char *userdb, char **errmsg) {
} }
*seq = 0; *seq = 0;
if (!strcmp(s, "host")) if (!strcmp(s, "host")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "ip")) } else if (!strcmp(s, "ip")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "addr")) } else if (!strcmp(s, "addr")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "ipaddr")) } else if (!strcmp(s, "ipaddr")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "hostaddr")) } else if (!strcmp(s, "hostaddr")) {
co->host = strdup(seq + 1); co->host = strdup(seq + 1);
else if (!strcmp(s, "dbname")) } else if (!strcmp(s, "dbname")) {
co->dbname = strdup(seq + 1); co->dbname = strdup(seq + 1);
else if (!strcmp(s, "db")) } else if (!strcmp(s, "db")) {
co->dbname = strdup(seq + 1); co->dbname = strdup(seq + 1);
else if (!strcmp(s, "database")) } else if (!strcmp(s, "database")) {
co->dbname = strdup(seq + 1); co->dbname = strdup(seq + 1);
else if (!strcmp(s, "user")) } else if (!strcmp(s, "user")) {
; ;
else if (!strcmp(s, "uname")) } else if (!strcmp(s, "uname")) {
; ;
else if (!strcmp(s, "name")) } else if (!strcmp(s, "name")) {
; ;
else if (!strcmp(s, "username")) } else if (!strcmp(s, "username")) {
; ;
else if (!strcmp(s, "password")) } else if (!strcmp(s, "password")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "pwd")) } else if (!strcmp(s, "pwd")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "passwd")) } else if (!strcmp(s, "passwd")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "secret")) } else if (!strcmp(s, "secret")) {
co->password = strdup(seq + 1); co->password = strdup(seq + 1);
else if (!strcmp(s, "port")) } else if (!strcmp(s, "port")) {
co->port = (unsigned int)atoi(seq + 1); co->port = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "p")) } else if (!strcmp(s, "p")) {
co->port = (unsigned int)atoi(seq + 1); co->port = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "connect_timeout")) } else if (!strcmp(s, "connect_timeout")) {
co->connect_timeout = (unsigned int)atoi(seq + 1); co->connect_timeout = (unsigned int)atoi(seq + 1);
else if (!strcmp(s, "timeout")) } else if (!strcmp(s, "timeout")) {
co->connect_timeout = (unsigned int)atoi(seq + 1); co->connect_timeout = (unsigned int)atoi(seq + 1);
else { } else {
RyconninfoFree(co); RyconninfoFree(co);
co = NULL; co = NULL;
if (errmsg) { if (errmsg) {
@ -153,12 +157,15 @@ static Ryconninfo *RyconninfoParse(const char *userdb, char **errmsg) {
} }
if (co) { if (co) {
if (!(co->dbname)) if (!(co->dbname)) {
co->dbname = strdup("0"); co->dbname = strdup("0");
if (!(co->host)) }
if (!(co->host)) {
co->host = strdup("127.0.0.1"); co->host = strdup("127.0.0.1");
if (!(co->password)) }
if (!(co->password)) {
co->password = strdup(""); co->password = strdup("");
}
} }
return co; return co;
@ -195,13 +202,16 @@ redis_context_handle get_redis_async_connection(struct event_base *base, redis_s
char ip[256] = "\0"; char ip[256] = "\0";
int port = DEFAULT_REDIS_PORT; int port = DEFAULT_REDIS_PORT;
if (co->host) if (co->host) {
STRCPY(ip, co->host); STRCPY(ip, co->host);
if (!ip[0]) }
if (!ip[0]) {
strncpy(ip, "127.0.0.1", sizeof(ip)); strncpy(ip, "127.0.0.1", sizeof(ip));
}
if (co->port) if (co->port) {
port = (int)(co->port); port = (int)(co->port);
}
if (co->connect_timeout) { if (co->connect_timeout) {
struct timeval tv; struct timeval tv;
@ -233,8 +243,9 @@ redis_context_handle get_redis_async_connection(struct event_base *base, redis_s
if (reply->type == REDIS_REPLY_ERROR) { if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
} else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < reply->elements; ++i) { for (i = 0; i < reply->elements; ++i) {
@ -310,13 +321,16 @@ static redisContext *get_redis_connection(void) {
} else { } else {
char ip[256] = "\0"; char ip[256] = "\0";
int port = DEFAULT_REDIS_PORT; int port = DEFAULT_REDIS_PORT;
if (co->host) if (co->host) {
STRCPY(ip, co->host); STRCPY(ip, co->host);
if (!ip[0]) }
if (!ip[0]) {
strncpy(ip, "127.0.0.1", sizeof(ip)); strncpy(ip, "127.0.0.1", sizeof(ip));
}
if (co->port) if (co->port) {
port = (int)(co->port); port = (int)(co->port);
}
if (co->connect_timeout) { if (co->connect_timeout) {
struct timeval tv; struct timeval tv;
@ -391,11 +405,12 @@ static int set_redis_realm_opt(char *realm, const char *key, unsigned long *valu
rget = (redisReply *)redisCommand(rc, s); rget = (redisReply *)redisCommand(rc, s);
if (rget) { if (rget) {
if (rget->type == REDIS_REPLY_ERROR) if (rget->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", rget->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", rget->str);
else if (rget->type != REDIS_REPLY_STRING) { } else if (rget->type != REDIS_REPLY_STRING) {
if (rget->type != REDIS_REPLY_NIL) if (rget->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type);
}
} else { } else {
lock_realms(); lock_realms();
*value = (unsigned long)atol(rget->str); *value = (unsigned long)atol(rget->str);
@ -418,11 +433,12 @@ static int redis_get_auth_secrets(secrets_list_t *sl, uint8_t *realm) {
redisReply *reply = (redisReply *)redisCommand(rc, "smembers turn/realm/%s/secret", (char *)realm); redisReply *reply = (redisReply *)redisCommand(rc, "smembers turn/realm/%s/secret", (char *)realm);
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < reply->elements; ++i) { for (i = 0; i < reply->elements; ++i) {
@ -446,11 +462,12 @@ static int redis_get_user_key(uint8_t *usname, uint8_t *realm, hmackey_t key) {
snprintf(s, sizeof(s), "get turn/realm/%s/user/%s/key", (char *)realm, usname); snprintf(s, sizeof(s), "get turn/realm/%s/user/%s/key", (char *)realm, usname);
redisReply *rget = (redisReply *)redisCommand(rc, s); redisReply *rget = (redisReply *)redisCommand(rc, s);
if (rget) { if (rget) {
if (rget->type == REDIS_REPLY_ERROR) if (rget->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", rget->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", rget->str);
else if (rget->type != REDIS_REPLY_STRING) { } else if (rget->type != REDIS_REPLY_STRING) {
if (rget->type != REDIS_REPLY_NIL) if (rget->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type);
}
} else { } else {
size_t sz = get_hmackey_size(SHATYPE_DEFAULT); size_t sz = get_hmackey_size(SHATYPE_DEFAULT);
if (strlen(rget->str) < sz * 2) { if (strlen(rget->str) < sz * 2) {
@ -477,11 +494,12 @@ static int redis_get_oauth_key(const uint8_t *kid, oauth_key_data_raw *key) {
snprintf(s, sizeof(s), "hgetall turn/oauth/kid/%s", (const char *)kid); snprintf(s, sizeof(s), "hgetall turn/oauth/kid/%s", (const char *)kid);
redisReply *reply = (redisReply *)redisCommand(rc, s); redisReply *reply = (redisReply *)redisCommand(rc, s);
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else if (reply->elements > 1) { } else if (reply->elements > 1) {
size_t i; size_t i;
for (i = 0; i < (reply->elements) / 2; ++i) { for (i = 0; i < (reply->elements) / 2; ++i) {
@ -572,8 +590,9 @@ static int redis_list_users(uint8_t *realm, secrets_list_t *users, secrets_list_
redisContext *rc = get_redis_connection(); redisContext *rc = get_redis_connection();
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
if (rc) { if (rc) {
secrets_list_t keys; secrets_list_t keys;
@ -592,11 +611,12 @@ static int redis_list_users(uint8_t *realm, secrets_list_t *users, secrets_list_
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < reply->elements; ++i) { for (i = 0; i < reply->elements; ++i) {
@ -614,23 +634,27 @@ static int redis_list_users(uint8_t *realm, secrets_list_t *users, secrets_list_
char *s = keys.secrets[isz]; char *s = keys.secrets[isz];
char *sh = strstr(s, "turn/realm/"); char *sh = strstr(s, "turn/realm/");
if (sh != s) if (sh != s) {
continue; continue;
}
sh += rhsz; sh += rhsz;
char *st = strchr(sh, '/'); char *st = strchr(sh, '/');
if (!st) if (!st) {
continue; continue;
}
*st = 0; *st = 0;
char *sr = sh; char *sr = sh;
++st; ++st;
sh = strstr(st, "user/"); sh = strstr(st, "user/");
if (sh != st) if (sh != st) {
continue; continue;
}
sh += uhsz; sh += uhsz;
st = strchr(sh, '/'); st = strchr(sh, '/');
if (!st) if (!st) {
continue; continue;
}
*st = 0; *st = 0;
char *su = sh; char *su = sh;
@ -718,8 +742,9 @@ static int redis_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
redisContext *rc = get_redis_connection(); redisContext *rc = get_redis_connection();
@ -737,11 +762,12 @@ static int redis_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
init_secrets_list(&keys); init_secrets_list(&keys);
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < reply->elements; ++i) { for (i = 0; i < reply->elements; ++i) {
@ -760,19 +786,22 @@ static int redis_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_l
} else if (rget->type == REDIS_REPLY_STRING) { } else if (rget->type == REDIS_REPLY_STRING) {
printf("%s\n", rget->str); printf("%s\n", rget->str);
} else if (rget->type != REDIS_REPLY_ARRAY) { } else if (rget->type != REDIS_REPLY_ARRAY) {
if (rget->type != REDIS_REPLY_NIL) if (rget->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type);
}
} else { } else {
char *s = keys.secrets[isz]; char *s = keys.secrets[isz];
char *sh = strstr(s, "turn/realm/"); char *sh = strstr(s, "turn/realm/");
if (sh != s) if (sh != s) {
continue; continue;
}
sh += rhsz; sh += rhsz;
char *st = strchr(sh, '/'); char *st = strchr(sh, '/');
if (!st) if (!st) {
continue; continue;
}
*st = 0; *st = 0;
const char *rval = sh; const char *rval = sh;
@ -840,8 +869,9 @@ static int redis_set_permission_ip(const char *kind, uint8_t *realm, const char
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -896,8 +926,9 @@ static int redis_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_l
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -914,11 +945,12 @@ static int redis_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_l
reply = (redisReply *)redisCommand(rc, "keys turn/origin/*"); reply = (redisReply *)redisCommand(rc, "keys turn/origin/*");
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
size_t offset = strlen("turn/origin/"); size_t offset = strlen("turn/origin/");
@ -937,11 +969,12 @@ static int redis_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_l
reply = (redisReply *)redisCommand(rc, "get turn/origin/%s", o); reply = (redisReply *)redisCommand(rc, "get turn/origin/%s", o);
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_STRING) { } else if (reply->type != REDIS_REPLY_STRING) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
if (!(realm && realm[0] && strcmp((char *)realm, reply->str))) { if (!(realm && realm[0] && strcmp((char *)realm, reply->str))) {
if (origins) { if (origins) {
@ -970,10 +1003,11 @@ static int redis_set_realm_option_one(uint8_t *realm, unsigned long value, const
if (rc) { if (rc) {
char s[TURN_LONG_STRING_SIZE]; char s[TURN_LONG_STRING_SIZE];
if (value > 0) if (value > 0) {
snprintf(s, sizeof(s), "set turn/realm/%s/%s %lu", (char *)realm, opt, (unsigned long)value); snprintf(s, sizeof(s), "set turn/realm/%s/%s %lu", (char *)realm, opt, (unsigned long)value);
else } else {
snprintf(s, sizeof(s), "del turn/realm/%s/%s", (char *)realm, opt); snprintf(s, sizeof(s), "del turn/realm/%s/%s", (char *)realm, opt);
}
turnFreeRedisReply(redisCommand(rc, s)); turnFreeRedisReply(redisCommand(rc, s));
turnFreeRedisReply(redisCommand(rc, "save")); turnFreeRedisReply(redisCommand(rc, "save"));
@ -1002,11 +1036,12 @@ static int redis_list_realm_options(uint8_t *realm) {
} }
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < reply->elements; ++i) { for (i = 0; i < reply->elements; ++i) {
@ -1028,11 +1063,12 @@ static int redis_list_realm_options(uint8_t *realm) {
reply = (redisReply *)redisCommand(rc, "get %s", o); reply = (redisReply *)redisCommand(rc, "get %s", o);
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_STRING) { } else if (reply->type != REDIS_REPLY_STRING) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
printf("%s = %s\n", o + offset, reply->str); printf("%s = %s\n", o + offset, reply->str);
} }
@ -1070,11 +1106,12 @@ static int redis_get_ip_list(const char *kind, ip_range_list_t *list) {
init_secrets_list(&keys); init_secrets_list(&keys);
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < reply->elements; ++i) { for (i = 0; i < reply->elements; ++i) {
@ -1103,8 +1140,9 @@ static int redis_get_ip_list(const char *kind, ip_range_list_t *list) {
} else if (rget->type == REDIS_REPLY_STRING) { } else if (rget->type == REDIS_REPLY_STRING) {
add_ip_list_range(rget->str, realm, list); add_ip_list_range(rget->str, realm, list);
} else if (rget->type != REDIS_REPLY_ARRAY) { } else if (rget->type != REDIS_REPLY_ARRAY) {
if (rget->type != REDIS_REPLY_NIL) if (rget->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < rget->elements; ++i) { for (i = 0; i < rget->elements; ++i) {
@ -1145,11 +1183,12 @@ static void redis_reread_realms(secrets_list_t *realms_list) {
char s[1025]; char s[1025];
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else { } else {
size_t i; size_t i;
for (i = 0; i < reply->elements; ++i) { for (i = 0; i < reply->elements; ++i) {
@ -1164,11 +1203,12 @@ static void redis_reread_realms(secrets_list_t *realms_list) {
snprintf(s, sizeof(s), "get %s", keys.secrets[isz]); snprintf(s, sizeof(s), "get %s", keys.secrets[isz]);
redisReply *rget = (redisReply *)redisCommand(rc, s); redisReply *rget = (redisReply *)redisCommand(rc, s);
if (rget) { if (rget) {
if (rget->type == REDIS_REPLY_ERROR) if (rget->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", rget->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", rget->str);
else if (rget->type != REDIS_REPLY_STRING) { } else if (rget->type != REDIS_REPLY_STRING) {
if (rget->type != REDIS_REPLY_NIL) if (rget->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", rget->type);
}
} else { } else {
get_realm(rget->str); get_realm(rget->str);
ur_string_map_value_type value = strdup(rget->str); ur_string_map_value_type value = strdup(rget->str);
@ -1243,11 +1283,12 @@ static int redis_get_admin_user(const uint8_t *usname, uint8_t *realm, password_
snprintf(s, sizeof(s), "hgetall turn/admin_user/%s", (const char *)usname); snprintf(s, sizeof(s), "hgetall turn/admin_user/%s", (const char *)usname);
redisReply *reply = (redisReply *)redisCommand(rc, s); redisReply *reply = (redisReply *)redisCommand(rc, s);
if (reply) { if (reply) {
if (reply->type == REDIS_REPLY_ERROR) if (reply->type == REDIS_REPLY_ERROR) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Error: %s\n", reply->str);
else if (reply->type != REDIS_REPLY_ARRAY) { } else if (reply->type != REDIS_REPLY_ARRAY) {
if (reply->type != REDIS_REPLY_NIL) if (reply->type != REDIS_REPLY_NIL) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unexpected type: %d\n", reply->type);
}
} else if (reply->elements > 1) { } else if (reply->elements > 1) {
size_t i; size_t i;
for (i = 0; i < (reply->elements) / 2; ++i) { for (i = 0; i < (reply->elements) / 2; ++i) {

View File

@ -147,8 +147,9 @@ static int donot_print_connection_success = 0;
static void fix_user_directory(char *dir0) { static void fix_user_directory(char *dir0) {
char *dir = dir0; char *dir = dir0;
while (*dir == ' ') while (*dir == ' ') {
++dir; ++dir;
}
#if defined(__unix__) || defined(unix) || defined(__APPLE__) #if defined(__unix__) || defined(unix) || defined(__APPLE__)
if (*dir == '~') { if (*dir == '~') {
char *home = getenv("HOME"); char *home = getenv("HOME");
@ -268,8 +269,9 @@ static int sqlite_get_auth_secrets(secrets_list_t *sl, uint8_t *realm) {
if (res == SQLITE_ROW) { if (res == SQLITE_ROW) {
int type = sqlite3_column_type(st, 0); int type = sqlite3_column_type(st, 0);
if (type != SQLITE_NULL) if (type != SQLITE_NULL) {
add_to_secrets_list(sl, (const char *)sqlite3_column_text(st, 0)); add_to_secrets_list(sl, (const char *)sqlite3_column_text(st, 0));
}
} else if (res == SQLITE_DONE) { } else if (res == SQLITE_DONE) {
break; break;
@ -574,8 +576,9 @@ static int sqlite_list_users(uint8_t *realm, secrets_list_t *users, secrets_list
int rc = 0; int rc = 0;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -638,8 +641,9 @@ static int sqlite_list_secrets(uint8_t *realm, secrets_list_t *secrets, secrets_
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
sqlite3_stmt *st = NULL; sqlite3_stmt *st = NULL;
int rc = 0; int rc = 0;
@ -707,10 +711,11 @@ static int sqlite_del_secret(uint8_t *secret, uint8_t *realm) {
sqlite3 *sqliteconnection = get_sqlite_connection(); sqlite3 *sqliteconnection = get_sqlite_connection();
if (sqliteconnection) { if (sqliteconnection) {
if (!secret || (secret[0] == 0)) if (!secret || (secret[0] == 0)) {
snprintf(statement, sizeof(statement), "delete from turn_secret where realm='%s'", realm); snprintf(statement, sizeof(statement), "delete from turn_secret where realm='%s'", realm);
else } else {
snprintf(statement, sizeof(statement), "delete from turn_secret where value='%s' and realm='%s'", secret, realm); snprintf(statement, sizeof(statement), "delete from turn_secret where value='%s' and realm='%s'", secret, realm);
}
sqlite_lock(1); sqlite_lock(1);
@ -816,8 +821,9 @@ static int sqlite_list_origins(uint8_t *realm, secrets_list_t *origins, secrets_
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
donot_print_connection_success = 1; donot_print_connection_success = 1;
@ -1012,8 +1018,9 @@ static int sqlite_set_permission_ip(const char *kind, uint8_t *realm, const char
int ret = -1; int ret = -1;
uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0"; uint8_t realm0[STUN_MAX_REALM_SIZE + 1] = "\0";
if (!realm) if (!realm) {
realm = realm0; realm = realm0;
}
char statement[TURN_LONG_STRING_SIZE]; char statement[TURN_LONG_STRING_SIZE];
@ -1140,13 +1147,13 @@ static void sqlite_reread_realms(secrets_list_t *realms_list) {
const char *vval = (const char *)sqlite3_column_text(st, 2); const char *vval = (const char *)sqlite3_column_text(st, 2);
realm_params_t *rp = get_realm(rval); realm_params_t *rp = get_realm(rval);
if (!strcmp(oval, "max-bps")) if (!strcmp(oval, "max-bps")) {
rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval, NULL, 10); rp->options.perf_options.max_bps = (band_limit_t)strtoul(vval, NULL, 10);
else if (!strcmp(oval, "total-quota")) } else if (!strcmp(oval, "total-quota")) {
rp->options.perf_options.total_quota = (vint)atoi(vval); rp->options.perf_options.total_quota = (vint)atoi(vval);
else if (!strcmp(oval, "user-quota")) } else if (!strcmp(oval, "user-quota")) {
rp->options.perf_options.user_quota = (vint)atoi(vval); rp->options.perf_options.user_quota = (vint)atoi(vval);
else { } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown realm option: %s\n", oval);
} }

View File

@ -62,8 +62,9 @@ int convert_string_key_to_binary(char *keysource, hmackey_t key, size_t sz) {
persistent_users_db_t *get_persistent_users_db(void) { return &(turn_params.default_users_db.persistent_users_db); } persistent_users_db_t *get_persistent_users_db(void) { return &(turn_params.default_users_db.persistent_users_db); }
const turn_dbdriver_t *get_dbdriver(void) { const turn_dbdriver_t *get_dbdriver(void) {
if (turn_params.default_users_db.userdb_type == TURN_USERDB_TYPE_UNKNOWN) if (turn_params.default_users_db.userdb_type == TURN_USERDB_TYPE_UNKNOWN) {
return NULL; return NULL;
}
(void)pthread_once(&connection_key_once, make_connection_key); (void)pthread_once(&connection_key_once, make_connection_key);

View File

@ -120,8 +120,9 @@ int is_dtls_message(const unsigned char *buf, int len) {
/* 0 - 1.0, 1 - 1.2 */ /* 0 - 1.0, 1 - 1.2 */
int get_dtls_version(const unsigned char *buf, int len) { int get_dtls_version(const unsigned char *buf, int len) {
if (buf && (len > 3) && (buf[2] == 0xfd)) if (buf && (len > 3) && (buf[2] == 0xfd)) {
return 1; return 1;
}
return 0; return 0;
} }
@ -134,8 +135,9 @@ static void calculate_cookie(SSL *ssl, unsigned char *cookie_secret, unsigned in
long inum = (cookie_length - (((long)cookie_secret) % sizeof(long))) / sizeof(long); long inum = (cookie_length - (((long)cookie_secret) % sizeof(long))) / sizeof(long);
long i = 0; long i = 0;
long *ip = (long *)cookie_secret; long *ip = (long *)cookie_secret;
for (i = 0; i < inum; ++i, ++ip) for (i = 0; i < inum; ++i, ++ip) {
*ip = rv; *ip = rv;
}
} }
static int generate_cookie(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) { static int generate_cookie(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) {
@ -226,13 +228,15 @@ static ioa_socket_handle dtls_accept_client_connection(dtls_listener_relay_serve
ioa_network_buffer_handle nbh) { ioa_network_buffer_handle nbh) {
FUNCSTART; FUNCSTART;
if (!ssl) if (!ssl) {
return NULL; return NULL;
}
int rc = ssl_read(sock->fd, ssl, nbh, server->verbose); int rc = ssl_read(sock->fd, ssl, nbh, server->verbose);
if (rc < 0) if (rc < 0) {
return NULL; return NULL;
}
addr_debug_print(server->verbose, remote_addr, "Accepted connection from"); addr_debug_print(server->verbose, remote_addr, "Accepted connection from");
@ -730,8 +734,9 @@ start_udp_cycle:
ioa_network_buffer_delete(server->e, server->sm.m.sm.nd.nbh); ioa_network_buffer_delete(server->e, server->sm.m.sm.nd.nbh);
server->sm.m.sm.nd.nbh = NULL; server->sm.m.sm.nd.nbh = NULL;
if ((bsize > 0) && (cycle++ < MAX_SINGLE_UDP_BATCH)) if ((bsize > 0) && (cycle++ < MAX_SINGLE_UDP_BATCH)) {
goto start_udp_cycle; goto start_udp_cycle;
}
FUNCEND; FUNCEND;
} }
@ -742,8 +747,9 @@ static int create_server_socket(dtls_listener_relay_server_type *server, int rep
FUNCSTART; FUNCSTART;
if (!server) if (!server) {
return -1; return -1;
}
clean_server(server); clean_server(server);
@ -796,12 +802,13 @@ static int create_server_socket(dtls_listener_relay_server_type *server, int rep
} }
if (report_creation) { if (report_creation) {
if (!turn_params.no_udp && !turn_params.no_dtls) if (!turn_params.no_udp && !turn_params.no_dtls) {
addr_debug_print(server->verbose, &server->addr, "DTLS/UDP listener opened on"); addr_debug_print(server->verbose, &server->addr, "DTLS/UDP listener opened on");
else if (!turn_params.no_dtls) } else if (!turn_params.no_dtls) {
addr_debug_print(server->verbose, &server->addr, "DTLS listener opened on"); addr_debug_print(server->verbose, &server->addr, "DTLS listener opened on");
else if (!turn_params.no_udp) } else if (!turn_params.no_udp) {
addr_debug_print(server->verbose, &server->addr, "UDP listener opened on"); addr_debug_print(server->verbose, &server->addr, "UDP listener opened on");
}
} }
FUNCEND; FUNCEND;
@ -812,8 +819,9 @@ static int create_server_socket(dtls_listener_relay_server_type *server, int rep
static int reopen_server_socket(dtls_listener_relay_server_type *server, evutil_socket_t fd) { static int reopen_server_socket(dtls_listener_relay_server_type *server, evutil_socket_t fd) {
UNUSED_ARG(fd); UNUSED_ARG(fd);
if (!server) if (!server) {
return 0; return 0;
}
FUNCSTART; FUNCSTART;
@ -863,12 +871,13 @@ static int reopen_server_socket(dtls_listener_relay_server_type *server, evutil_
event_add(server->udp_listen_ev, NULL); event_add(server->udp_listen_ev, NULL);
} }
if (!turn_params.no_udp && !turn_params.no_dtls) if (!turn_params.no_udp && !turn_params.no_dtls) {
addr_debug_print(server->verbose, &server->addr, "DTLS/UDP listener opened on "); addr_debug_print(server->verbose, &server->addr, "DTLS/UDP listener opened on ");
else if (!turn_params.no_dtls) } else if (!turn_params.no_dtls) {
addr_debug_print(server->verbose, &server->addr, "DTLS listener opened on "); addr_debug_print(server->verbose, &server->addr, "DTLS listener opened on ");
else if (!turn_params.no_udp) } else if (!turn_params.no_udp) {
addr_debug_print(server->verbose, &server->addr, "UDP listener opened on "); addr_debug_print(server->verbose, &server->addr, "UDP listener opened on ");
}
FUNCEND; FUNCEND;
@ -882,8 +891,9 @@ static int dtls_verify_callback(int ok, X509_STORE_CTX *ctx) {
* if he trusts the received certificate. * if he trusts the received certificate.
* Here we always trust. * Here we always trust.
*/ */
if (ok && ctx) if (ok && ctx) {
return 1; return 1;
}
return -1; return -1;
} }
@ -893,14 +903,16 @@ static int init_server(dtls_listener_relay_server_type *server, const char *ifna
int verbose, ioa_engine_handle e, turn_turnserver *ts, int report_creation, int verbose, ioa_engine_handle e, turn_turnserver *ts, int report_creation,
ioa_engine_new_connection_event_handler send_socket) { ioa_engine_new_connection_event_handler send_socket) {
if (!server) if (!server) {
return -1; return -1;
}
server->ts = ts; server->ts = ts;
server->connect_cb = send_socket; server->connect_cb = send_socket;
if (ifname) if (ifname) {
STRCPY(server->ifname, ifname); STRCPY(server->ifname, ifname);
}
if (make_ioa_addr((const uint8_t *)local_address, port, &server->addr) < 0) { if (make_ioa_addr((const uint8_t *)local_address, port, &server->addr) < 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot create a DTLS/UDP listener for address: %s\n", local_address); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot create a DTLS/UDP listener for address: %s\n", local_address);
@ -929,8 +941,9 @@ static int clean_server(dtls_listener_relay_server_type *server) {
#if DTLS_SUPPORTED #if DTLS_SUPPORTED
void setup_dtls_callbacks(SSL_CTX *ctx) { void setup_dtls_callbacks(SSL_CTX *ctx) {
if (!ctx) if (!ctx) {
return; return;
}
#if defined(REQUEST_CLIENT_CERT) #if defined(REQUEST_CLIENT_CERT)
/* If client has to authenticate, then */ /* If client has to authenticate, then */
@ -958,16 +971,18 @@ dtls_listener_relay_server_type *create_dtls_listener_server(const char *ifname,
} }
ioa_engine_handle get_engine(dtls_listener_relay_server_type *server) { ioa_engine_handle get_engine(dtls_listener_relay_server_type *server) {
if (server) if (server) {
return server->e; return server->e;
}
return NULL; return NULL;
} }
//////////// UDP send //////////////// //////////// UDP send ////////////////
void udp_send_message(dtls_listener_relay_server_type *server, ioa_network_buffer_handle nbh, ioa_addr *dest) { void udp_send_message(dtls_listener_relay_server_type *server, ioa_network_buffer_handle nbh, ioa_addr *dest) {
if (server && dest && nbh && (server->udp_listen_s)) if (server && dest && nbh && (server->udp_listen_s)) {
udp_send(server->udp_listen_s, dest, (char *)ioa_network_buffer_data(nbh), (int)ioa_network_buffer_get_size(nbh)); udp_send(server->udp_listen_s, dest, (char *)ioa_network_buffer_data(nbh), (int)ioa_network_buffer_get_size(nbh));
}
} }
////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////

View File

@ -119,9 +119,9 @@ static struct headers_list *post_parse(char *data, size_t data_len) {
while (fsplit != NULL) { while (fsplit != NULL) {
char *vmarker = NULL; char *vmarker = NULL;
char *key = strtok_r(fsplit, "=", &vmarker); char *key = strtok_r(fsplit, "=", &vmarker);
if (key == NULL) if (key == NULL) {
break; break;
else { } else {
char *value = strtok_r(NULL, "=", &vmarker); char *value = strtok_r(NULL, "=", &vmarker);
char empty[1]; char empty[1];
empty[0] = 0; empty[0] = 0;
@ -129,8 +129,9 @@ static struct headers_list *post_parse(char *data, size_t data_len) {
value = evhttp_decode_uri(value); value = evhttp_decode_uri(value);
char *p = value; char *p = value;
while (*p) { while (*p) {
if (*p == '+') if (*p == '+') {
*p = ' '; *p = ' ';
}
p++; p++;
} }
list->keys = (char **)realloc(list->keys, sizeof(char *) * (list->n + 1)); list->keys = (char **)realloc(list->keys, sizeof(char *) * (list->n + 1));
@ -178,8 +179,9 @@ static struct http_request *parse_http_request_1(struct http_request *ret, char
} }
const char *path = evhttp_uri_get_path(uri); const char *path = evhttp_uri_get_path(uri);
if (path && ret) if (path && ret) {
ret->path = strdup(path); ret->path = strdup(path);
}
evhttp_uri_free(uri); evhttp_uri_free(uri);

View File

@ -170,12 +170,14 @@ telnet_error_t _init_zlib(telnet_t *telnet, int deflate, int err_fatal) {
int rs; int rs;
/* if compression is already enabled, fail loudly */ /* if compression is already enabled, fail loudly */
if (telnet->z != 0) if (telnet->z != 0) {
return telnet_error(telnet, __LINE__, __func__, TELNET_EBADVAL, err_fatal, "cannot initialize compression twice"); return telnet_error(telnet, __LINE__, __func__, TELNET_EBADVAL, err_fatal, "cannot initialize compression twice");
}
/* allocate zstream box */ /* allocate zstream box */
if ((z = (z_stream *)calloc(1, sizeof(z_stream))) == 0) if ((z = (z_stream *)calloc(1, sizeof(z_stream))) == 0) {
return telnet_error(telnet, __LINE__, __func__, TELNET_ENOMEM, err_fatal, "malloc() failed: %s", strerror(errno)); return telnet_error(telnet, __LINE__, __func__, TELNET_ENOMEM, err_fatal, "malloc() failed: %s", strerror(errno));
}
/* initialize */ /* initialize */
if (deflate) { if (deflate) {
@ -260,18 +262,20 @@ static INLINE int _check_telopt(telnet_t *telnet, unsigned char telopt, int us)
int i; int i;
/* if we have no telopts table, we obviously don't support it */ /* if we have no telopts table, we obviously don't support it */
if (telnet->telopts == 0) if (telnet->telopts == 0) {
return 0; return 0;
}
/* loop until found or end marker (us and him both 0) */ /* loop until found or end marker (us and him both 0) */
for (i = 0; telnet->telopts[i].telopt != -1; ++i) { for (i = 0; telnet->telopts[i].telopt != -1; ++i) {
if (telnet->telopts[i].telopt == telopt) { if (telnet->telopts[i].telopt == telopt) {
if (us && telnet->telopts[i].us == TELNET_WILL) if (us && telnet->telopts[i].us == TELNET_WILL) {
return 1; return 1;
else if (!us && telnet->telopts[i].him == TELNET_DO) } else if (!us && telnet->telopts[i].him == TELNET_DO) {
return 1; return 1;
else } else {
return 0; return 0;
}
} }
} }
@ -306,13 +310,16 @@ static INLINE void _set_rfc1143(telnet_t *telnet, unsigned char telopt, char us,
for (i = 0; i != telnet->q_cnt; ++i) { for (i = 0; i != telnet->q_cnt; ++i) {
if (telnet->q[i].telopt == telopt) { if (telnet->q[i].telopt == telopt) {
telnet->q[i].state = Q_MAKE(us, him); telnet->q[i].state = Q_MAKE(us, him);
if (telopt != TELNET_TELOPT_BINARY) if (telopt != TELNET_TELOPT_BINARY) {
return; return;
}
telnet->flags &= ~(TELNET_FLAG_TRANSMIT_BINARY | TELNET_FLAG_RECEIVE_BINARY); telnet->flags &= ~(TELNET_FLAG_TRANSMIT_BINARY | TELNET_FLAG_RECEIVE_BINARY);
if (us == Q_YES) if (us == Q_YES) {
telnet->flags |= TELNET_FLAG_TRANSMIT_BINARY; telnet->flags |= TELNET_FLAG_TRANSMIT_BINARY;
if (him == Q_YES) }
if (him == Q_YES) {
telnet->flags |= TELNET_FLAG_RECEIVE_BINARY; telnet->flags |= TELNET_FLAG_RECEIVE_BINARY;
}
return; return;
} }
} }
@ -388,8 +395,9 @@ static void _negotiate(telnet_t *telnet, unsigned char telopt) {
_set_rfc1143(telnet, telopt, Q_US(q), Q_YES); _set_rfc1143(telnet, telopt, Q_US(q), Q_YES);
_send_negotiate(telnet, TELNET_DO, telopt); _send_negotiate(telnet, TELNET_DO, telopt);
NEGOTIATE_EVENT(telnet, TELNET_EV_WILL, telopt); NEGOTIATE_EVENT(telnet, TELNET_EV_WILL, telopt);
} else } else {
_send_negotiate(telnet, TELNET_DONT, telopt); _send_negotiate(telnet, TELNET_DONT, telopt);
}
break; break;
case Q_WANTNO: case Q_WANTNO:
_set_rfc1143(telnet, telopt, Q_US(q), Q_NO); _set_rfc1143(telnet, telopt, Q_US(q), Q_NO);
@ -444,8 +452,9 @@ static void _negotiate(telnet_t *telnet, unsigned char telopt) {
_set_rfc1143(telnet, telopt, Q_YES, Q_HIM(q)); _set_rfc1143(telnet, telopt, Q_YES, Q_HIM(q));
_send_negotiate(telnet, TELNET_WILL, telopt); _send_negotiate(telnet, TELNET_WILL, telopt);
NEGOTIATE_EVENT(telnet, TELNET_EV_DO, telopt); NEGOTIATE_EVENT(telnet, TELNET_EV_DO, telopt);
} else } else {
_send_negotiate(telnet, TELNET_WONT, telopt); _send_negotiate(telnet, TELNET_WONT, telopt);
}
break; break;
case Q_WANTNO: case Q_WANTNO:
_set_rfc1143(telnet, telopt, Q_NO, Q_HIM(q)); _set_rfc1143(telnet, telopt, Q_NO, Q_HIM(q));
@ -726,8 +735,9 @@ static int _zmp_telnet(telnet_t *telnet, const char *buffer, size_t size) {
} }
/* count arguments */ /* count arguments */
for (argc = 0, c = buffer; c != buffer + size; ++argc) for (argc = 0, c = buffer; c != buffer + size; ++argc) {
c += strlen(c) + 1; c += strlen(c) + 1;
}
/* allocate argument array, bail on error */ /* allocate argument array, bail on error */
if ((argv = (const char **)calloc(argc, sizeof(const char *))) == 0) { if ((argv = (const char **)calloc(argc, sizeof(const char *))) == 0) {
@ -817,8 +827,9 @@ static int _subnegotiate(telnet_t *telnet) {
*/ */
case TELNET_TELOPT_COMPRESS2: case TELNET_TELOPT_COMPRESS2:
if (telnet->sb_telopt == TELNET_TELOPT_COMPRESS2) { if (telnet->sb_telopt == TELNET_TELOPT_COMPRESS2) {
if (_init_zlib(telnet, 0, 1) != TELNET_EOK) if (_init_zlib(telnet, 0, 1) != TELNET_EOK) {
return 0; return 0;
}
/* notify app that compression was enabled */ /* notify app that compression was enabled */
ev.type = TELNET_EV_COMPRESS; ev.type = TELNET_EV_COMPRESS;
@ -848,8 +859,9 @@ static int _subnegotiate(telnet_t *telnet) {
telnet_t *telnet_init(const telnet_telopt_t *telopts, telnet_event_handler_t eh, unsigned char flags, void *user_data) { telnet_t *telnet_init(const telnet_telopt_t *telopts, telnet_event_handler_t eh, unsigned char flags, void *user_data) {
/* allocate structure */ /* allocate structure */
struct telnet_t *telnet = (telnet_t *)calloc(1, sizeof(telnet_t)); struct telnet_t *telnet = (telnet_t *)calloc(1, sizeof(telnet_t));
if (telnet == 0) if (telnet == 0) {
return 0; return 0;
}
/* initialize data */ /* initialize data */
telnet->ud = user_data; telnet->ud = user_data;
@ -873,10 +885,11 @@ void telnet_free(telnet_t *telnet) {
#if defined(HAVE_ZLIB) #if defined(HAVE_ZLIB)
/* free zlib box */ /* free zlib box */
if (telnet->z != 0) { if (telnet->z != 0) {
if (telnet->flags & TELNET_PFLAG_DEFLATE) if (telnet->flags & TELNET_PFLAG_DEFLATE) {
deflateEnd(telnet->z); deflateEnd(telnet->z);
else } else {
inflateEnd(telnet->z); inflateEnd(telnet->z);
}
free(telnet->z); free(telnet->z);
telnet->z = 0; telnet->z = 0;
} }
@ -974,8 +987,9 @@ static void _process(telnet_t *telnet, const char *buffer, size_t size) {
// any byte following '\r' other than '\n' or '\0' is invalid, // any byte following '\r' other than '\n' or '\0' is invalid,
// so pass both \r and the byte // so pass both \r and the byte
start = i; start = i;
if (byte == '\0') if (byte == '\0') {
++start; ++start;
}
/* state update */ /* state update */
telnet->state = TELNET_STATE_DATA; telnet->state = TELNET_STATE_DATA;
break; break;
@ -1155,10 +1169,11 @@ void telnet_recv(telnet_t *telnet, const char *buffer, size_t size) {
rs = inflate(telnet->z, Z_SYNC_FLUSH); rs = inflate(telnet->z, Z_SYNC_FLUSH);
/* process the decompressed bytes on success */ /* process the decompressed bytes on success */
if (rs == Z_OK || rs == Z_STREAM_END) if (rs == Z_OK || rs == Z_STREAM_END) {
_process(telnet, inflate_buffer, sizeof(inflate_buffer) - telnet->z->avail_out); _process(telnet, inflate_buffer, sizeof(inflate_buffer) - telnet->z->avail_out);
else } else {
telnet_error(telnet, __LINE__, __func__, TELNET_ECOMPRESS, 1, "inflate() failed: %s", zError(rs)); telnet_error(telnet, __LINE__, __func__, TELNET_ECOMPRESS, 1, "inflate() failed: %s", zError(rs));
}
/* prepare output buffer for next run */ /* prepare output buffer for next run */
telnet->z->next_out = (unsigned char *)inflate_buffer; telnet->z->next_out = (unsigned char *)inflate_buffer;
@ -1374,8 +1389,9 @@ void telnet_subnegotiation(telnet_t *telnet, unsigned char telopt, const char *b
if (telnet->flags & TELNET_FLAG_PROXY && telopt == TELNET_TELOPT_COMPRESS2) { if (telnet->flags & TELNET_FLAG_PROXY && telopt == TELNET_TELOPT_COMPRESS2) {
telnet_event_t ev; telnet_event_t ev;
if (_init_zlib(telnet, 1, 1) != TELNET_EOK) if (_init_zlib(telnet, 1, 1) != TELNET_EOK) {
return; return;
}
/* notify app that compression was enabled */ /* notify app that compression was enabled */
ev.type = TELNET_EV_COMPRESS; ev.type = TELNET_EV_COMPRESS;
@ -1392,8 +1408,9 @@ void telnet_begin_compress2(telnet_t *telnet) {
telnet_event_t ev; telnet_event_t ev;
/* attempt to create output stream first, bail if we can't */ /* attempt to create output stream first, bail if we can't */
if (_init_zlib(telnet, 1, 0) != TELNET_EOK) if (_init_zlib(telnet, 1, 0) != TELNET_EOK) {
return; return;
}
/* send compression marker. we send directly to the event handler /* send compression marker. we send directly to the event handler
* instead of passing through _send because _send would result in * instead of passing through _send because _send would result in
@ -1439,19 +1456,23 @@ int telnet_vprintf(telnet_t *telnet, const char *fmt, va_list va) {
/* special characters */ /* special characters */
if (output[i] == (char)TELNET_IAC || output[i] == '\r' || output[i] == '\n') { if (output[i] == (char)TELNET_IAC || output[i] == '\r' || output[i] == '\n') {
/* dump prior portion of text */ /* dump prior portion of text */
if (i != l) if (i != l) {
_send(telnet, output + l, i - l); _send(telnet, output + l, i - l);
}
l = i + 1; l = i + 1;
/* IAC -> IAC IAC */ /* IAC -> IAC IAC */
if (output[i] == (char)TELNET_IAC) if (output[i] == (char)TELNET_IAC) {
telnet_iac(telnet, TELNET_IAC); telnet_iac(telnet, TELNET_IAC);
}
/* automatic translation of \r -> CRNUL */ /* automatic translation of \r -> CRNUL */
else if (output[i] == '\r') else if (output[i] == '\r') {
_send(telnet, CRNUL, 2); _send(telnet, CRNUL, 2);
}
/* automatic translation of \n -> CRLF */ /* automatic translation of \n -> CRLF */
else if (output[i] == '\n') else if (output[i] == '\n') {
_send(telnet, CRLF, 2); _send(telnet, CRLF, 2);
}
} }
} }
@ -1562,8 +1583,9 @@ void telnet_send_zmp(telnet_t *telnet, size_t argc, const char **argv) {
telnet_begin_zmp(telnet, argv[0]); telnet_begin_zmp(telnet, argv[0]);
/* send out each argument, including trailing NUL byte */ /* send out each argument, including trailing NUL byte */
for (i = 1; i != argc; ++i) for (i = 1; i != argc; ++i) {
telnet_zmp_arg(telnet, argv[i]); telnet_zmp_arg(telnet, argv[i]);
}
/* ZMP footer */ /* ZMP footer */
telnet_finish_zmp(telnet); telnet_finish_zmp(telnet);
@ -1577,8 +1599,9 @@ void telnet_send_vzmpv(telnet_t *telnet, va_list va) {
telnet_begin_sb(telnet, TELNET_TELOPT_ZMP); telnet_begin_sb(telnet, TELNET_TELOPT_ZMP);
/* send out each argument, including trailing NUL byte */ /* send out each argument, including trailing NUL byte */
while ((arg = va_arg(va, const char *)) != 0) while ((arg = va_arg(va, const char *)) != 0) {
telnet_zmp_arg(telnet, arg); telnet_zmp_arg(telnet, arg);
}
/* ZMP footer */ /* ZMP footer */
telnet_finish_zmp(telnet); telnet_finish_zmp(telnet);

View File

@ -334,30 +334,38 @@ static int make_local_listeners_list(void) {
if (AF_INET == pUnicast->Address.lpSockaddr->sa_family) // IPV4 if (AF_INET == pUnicast->Address.lpSockaddr->sa_family) // IPV4
{ {
if (!inet_ntop(PF_INET, &((struct sockaddr_in *)pUnicast->Address.lpSockaddr)->sin_addr, saddr, if (!inet_ntop(PF_INET, &((struct sockaddr_in *)pUnicast->Address.lpSockaddr)->sin_addr, saddr,
INET6_ADDRSTRLEN)) INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "169.254.") == saddr) }
if (strstr(saddr, "169.254.") == saddr) {
continue; continue;
if (!strcmp(saddr, "0.0.0.0")) }
if (!strcmp(saddr, "0.0.0.0")) {
continue; continue;
}
} else if (AF_INET6 == pUnicast->Address.lpSockaddr->sa_family) // IPV6 } else if (AF_INET6 == pUnicast->Address.lpSockaddr->sa_family) // IPV6
{ {
if (!inet_ntop(PF_INET6, &((struct sockaddr_in6 *)pUnicast->Address.lpSockaddr)->sin6_addr, saddr, if (!inet_ntop(PF_INET6, &((struct sockaddr_in6 *)pUnicast->Address.lpSockaddr)->sin6_addr, saddr,
INET6_ADDRSTRLEN)) INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "fe80") == saddr) }
if (strstr(saddr, "fe80") == saddr) {
continue; continue;
if (!strcmp(saddr, "::")) }
if (!strcmp(saddr, "::")) {
continue; continue;
} else }
} else {
continue; continue;
}
// printf("\t\tIP: %s\n", saddr); // printf("\t\tIP: %s\n", saddr);
add_listener_addr(saddr); add_listener_addr(saddr);
if (MIB_IF_TYPE_LOOPBACK != pCurrAddresses->IfType) if (MIB_IF_TYPE_LOOPBACK != pCurrAddresses->IfType) {
ret++; ret++;
}
} }
} }
/* /*
@ -456,9 +464,9 @@ static int make_local_listeners_list(void) {
} }
} else { } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Call to GetAdaptersAddresses failed with error: %d\n", dwRetVal); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Call to GetAdaptersAddresses failed with error: %d\n", dwRetVal);
if (dwRetVal == ERROR_NO_DATA) if (dwRetVal == ERROR_NO_DATA) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\tNo addresses were found for the requested parameters\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\tNo addresses were found for the requested parameters\n");
else { } else {
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
@ -466,8 +474,9 @@ static int make_local_listeners_list(void) {
(LPTSTR)&lpMsgBuf, 0, NULL)) { (LPTSTR)&lpMsgBuf, 0, NULL)) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\tError: %s", lpMsgBuf); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\tError: %s", lpMsgBuf);
LocalFree(lpMsgBuf); LocalFree(lpMsgBuf);
if (pAddresses) if (pAddresses) {
free(pAddresses); free(pAddresses);
}
return -2; return -2;
} }
} }
@ -487,34 +496,43 @@ static int make_local_listeners_list(void) {
for (ifa = ifs; ifa != NULL; ifa = ifa->ifa_next) { for (ifa = ifs; ifa != NULL; ifa = ifa->ifa_next) {
if (!(ifa->ifa_flags & IFF_UP)) if (!(ifa->ifa_flags & IFF_UP)) {
continue; continue;
}
if (!(ifa->ifa_addr)) if (!(ifa->ifa_addr)) {
continue; continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) { if (ifa->ifa_addr->sa_family == AF_INET) {
if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, saddr, INET_ADDRSTRLEN)) if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, saddr, INET_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "169.254.") == saddr) }
if (strstr(saddr, "169.254.") == saddr) {
continue; continue;
if (!strcmp(saddr, "0.0.0.0")) }
if (!strcmp(saddr, "0.0.0.0")) {
continue; continue;
}
} else if (ifa->ifa_addr->sa_family == AF_INET6) { } else if (ifa->ifa_addr->sa_family == AF_INET6) {
if (!inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, saddr, INET6_ADDRSTRLEN)) if (!inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, saddr, INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "fe80") == saddr) }
if (strstr(saddr, "fe80") == saddr) {
continue; continue;
if (!strcmp(saddr, "::")) }
if (!strcmp(saddr, "::")) {
continue; continue;
}
} else { } else {
continue; continue;
} }
add_listener_addr(saddr); add_listener_addr(saddr);
if (!(ifa->ifa_flags & IFF_LOOPBACK)) if (!(ifa->ifa_flags & IFF_LOOPBACK)) {
ret++; ret++;
}
} }
freeifaddrs(ifs); freeifaddrs(ifs);
} }
@ -581,35 +599,45 @@ static int make_local_relays_list(int allow_local, int family) {
if (pUnicast != NULL) { if (pUnicast != NULL) {
// printf("\tNumber of Unicast Addresses:\n"); // printf("\tNumber of Unicast Addresses:\n");
for (; pUnicast != NULL; pUnicast = pUnicast->Next) { for (; pUnicast != NULL; pUnicast = pUnicast->Next) {
if (!allow_local && (MIB_IF_TYPE_LOOPBACK == pCurrAddresses->IfType)) if (!allow_local && (MIB_IF_TYPE_LOOPBACK == pCurrAddresses->IfType)) {
continue; continue;
}
char saddr[INET6_ADDRSTRLEN] = ""; char saddr[INET6_ADDRSTRLEN] = "";
if (AF_INET == pUnicast->Address.lpSockaddr->sa_family) // IPV4 if (AF_INET == pUnicast->Address.lpSockaddr->sa_family) // IPV4
{ {
if (family != AF_INET) if (family != AF_INET) {
continue; continue;
}
if (!inet_ntop(PF_INET, &((struct sockaddr_in *)pUnicast->Address.lpSockaddr)->sin_addr, saddr, if (!inet_ntop(PF_INET, &((struct sockaddr_in *)pUnicast->Address.lpSockaddr)->sin_addr, saddr,
INET6_ADDRSTRLEN)) INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "169.254.") == saddr) }
if (strstr(saddr, "169.254.") == saddr) {
continue; continue;
if (!strcmp(saddr, "0.0.0.0")) }
if (!strcmp(saddr, "0.0.0.0")) {
continue; continue;
}
} else if (AF_INET6 == pUnicast->Address.lpSockaddr->sa_family) // IPV6 } else if (AF_INET6 == pUnicast->Address.lpSockaddr->sa_family) // IPV6
{ {
if (family != AF_INET6) if (family != AF_INET6) {
continue; continue;
}
if (!inet_ntop(PF_INET6, &((struct sockaddr_in6 *)pUnicast->Address.lpSockaddr)->sin6_addr, saddr, if (!inet_ntop(PF_INET6, &((struct sockaddr_in6 *)pUnicast->Address.lpSockaddr)->sin6_addr, saddr,
INET6_ADDRSTRLEN)) INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "fe80") == saddr) }
if (strstr(saddr, "fe80") == saddr) {
continue; continue;
if (!strcmp(saddr, "::")) }
if (!strcmp(saddr, "::")) {
continue; continue;
} else }
} else {
continue; continue;
}
if (add_relay_addr(saddr) > 0) { if (add_relay_addr(saddr) > 0) {
counter += 1; counter += 1;
@ -634,41 +662,54 @@ static int make_local_relays_list(int allow_local, int family) {
if (ifs) { if (ifs) {
for (ifa = ifs; ifa != NULL; ifa = ifa->ifa_next) { for (ifa = ifs; ifa != NULL; ifa = ifa->ifa_next) {
if (!(ifa->ifa_flags & IFF_UP)) if (!(ifa->ifa_flags & IFF_UP)) {
continue; continue;
}
if (!(ifa->ifa_name)) if (!(ifa->ifa_name)) {
continue; continue;
if (!(ifa->ifa_addr)) }
if (!(ifa->ifa_addr)) {
continue; continue;
}
if (!allow_local && (ifa->ifa_flags & IFF_LOOPBACK)) if (!allow_local && (ifa->ifa_flags & IFF_LOOPBACK)) {
continue; continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) { if (ifa->ifa_addr->sa_family == AF_INET) {
if (family != AF_INET) if (family != AF_INET) {
continue; continue;
}
if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, saddr, INET_ADDRSTRLEN)) if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, saddr, INET_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "169.254.") == saddr) }
if (strstr(saddr, "169.254.") == saddr) {
continue; continue;
if (!strcmp(saddr, "0.0.0.0")) }
if (!strcmp(saddr, "0.0.0.0")) {
continue; continue;
}
} else if (ifa->ifa_addr->sa_family == AF_INET6) { } else if (ifa->ifa_addr->sa_family == AF_INET6) {
if (family != AF_INET6) if (family != AF_INET6) {
continue; continue;
}
if (!inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, saddr, INET6_ADDRSTRLEN)) if (!inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, saddr, INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "fe80") == saddr) }
if (strstr(saddr, "fe80") == saddr) {
continue; continue;
if (!strcmp(saddr, "::")) }
if (!strcmp(saddr, "::")) {
continue; continue;
} else }
} else {
continue; continue;
}
if (add_relay_addr(saddr) > 0) { if (add_relay_addr(saddr) > 0) {
counter += 1; counter += 1;
@ -734,35 +775,45 @@ int get_a_local_relay(int family, ioa_addr *relay_addr) {
if (pUnicast != NULL) { if (pUnicast != NULL) {
// printf("\tNumber of Unicast Addresses:\n"); // printf("\tNumber of Unicast Addresses:\n");
for (; pUnicast != NULL; pUnicast = pUnicast->Next) { for (; pUnicast != NULL; pUnicast = pUnicast->Next) {
if (!allow_local && (MIB_IF_TYPE_LOOPBACK == pCurrAddresses->IfType)) if (!allow_local && (MIB_IF_TYPE_LOOPBACK == pCurrAddresses->IfType)) {
continue; continue;
}
char saddr[INET6_ADDRSTRLEN] = ""; char saddr[INET6_ADDRSTRLEN] = "";
if (AF_INET == pUnicast->Address.lpSockaddr->sa_family) // IPV4 if (AF_INET == pUnicast->Address.lpSockaddr->sa_family) // IPV4
{ {
if (family != AF_INET) if (family != AF_INET) {
continue; continue;
}
if (!inet_ntop(PF_INET, &((struct sockaddr_in *)pUnicast->Address.lpSockaddr)->sin_addr, saddr, if (!inet_ntop(PF_INET, &((struct sockaddr_in *)pUnicast->Address.lpSockaddr)->sin_addr, saddr,
INET6_ADDRSTRLEN)) INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "169.254.") == saddr) }
if (strstr(saddr, "169.254.") == saddr) {
continue; continue;
if (!strcmp(saddr, "0.0.0.0")) }
if (!strcmp(saddr, "0.0.0.0")) {
continue; continue;
}
} else if (AF_INET6 == pUnicast->Address.lpSockaddr->sa_family) // IPV6 } else if (AF_INET6 == pUnicast->Address.lpSockaddr->sa_family) // IPV6
{ {
if (family != AF_INET6) if (family != AF_INET6) {
continue; continue;
}
if (!inet_ntop(PF_INET6, &((struct sockaddr_in6 *)pUnicast->Address.lpSockaddr)->sin6_addr, saddr, if (!inet_ntop(PF_INET6, &((struct sockaddr_in6 *)pUnicast->Address.lpSockaddr)->sin6_addr, saddr,
INET6_ADDRSTRLEN)) INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "fe80") == saddr) }
if (strstr(saddr, "fe80") == saddr) {
continue; continue;
if (!strcmp(saddr, "::")) }
if (!strcmp(saddr, "::")) {
continue; continue;
} else }
} else {
continue; continue;
}
if (make_ioa_addr((const uint8_t *)saddr, 0, relay_addr) < 0) { if (make_ioa_addr((const uint8_t *)saddr, 0, relay_addr) < 0) {
continue; continue;
@ -793,48 +844,57 @@ int get_a_local_relay(int family, ioa_addr *relay_addr) {
if (ifs) { if (ifs) {
galr_start : galr_start:
for (struct ifaddrs *ifa = ifs; ifa != NULL; ifa = ifa->ifa_next) {
{ if (!(ifa->ifa_flags & IFF_UP)) {
struct ifaddrs *ifa = NULL;
for (ifa = ifs; ifa != NULL; ifa = ifa->ifa_next) {
if (!(ifa->ifa_flags & IFF_UP))
continue; continue;
}
if (!(ifa->ifa_name)) if (!(ifa->ifa_name)) {
continue; continue;
if (!(ifa->ifa_addr)) }
if (!(ifa->ifa_addr)) {
continue; continue;
}
if (!allow_local && (ifa->ifa_flags & IFF_LOOPBACK)) if (!allow_local && (ifa->ifa_flags & IFF_LOOPBACK)) {
continue; continue;
}
if (ifa->ifa_addr->sa_family == AF_INET) { if (ifa->ifa_addr->sa_family == AF_INET) {
if (family != AF_INET) if (family != AF_INET) {
continue; continue;
}
if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, saddr, INET_ADDRSTRLEN)) if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, saddr, INET_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "169.254.") == saddr) }
if (strstr(saddr, "169.254.") == saddr) {
continue; continue;
if (!strcmp(saddr, "0.0.0.0")) }
if (!strcmp(saddr, "0.0.0.0")) {
continue; continue;
}
} else if (ifa->ifa_addr->sa_family == AF_INET6) { } else if (ifa->ifa_addr->sa_family == AF_INET6) {
if (family != AF_INET6) if (family != AF_INET6) {
continue; continue;
}
if (!inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, saddr, INET6_ADDRSTRLEN)) if (!inet_ntop(AF_INET6, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, saddr, INET6_ADDRSTRLEN)) {
continue; continue;
if (strstr(saddr, "fe80") == saddr) }
if (strstr(saddr, "fe80") == saddr) {
continue; continue;
if (!strcmp(saddr, "::")) }
if (!strcmp(saddr, "::")) {
continue; continue;
} else }
} else {
continue; continue;
}
if (make_ioa_addr((const uint8_t *)saddr, 0, relay_addr) < 0) { if (make_ioa_addr((const uint8_t *)saddr, 0, relay_addr) < 0) {
continue; continue;
@ -843,7 +903,6 @@ int get_a_local_relay(int family, ioa_addr *relay_addr) {
break; break;
} }
} }
}
if (ret < 0 && !allow_local) { if (ret < 0 && !allow_local) {
allow_local = 1; allow_local = 1;
@ -1761,24 +1820,31 @@ void decrypt_aes_128(char *in, const unsigned char *mykey) {
} }
static int get_int_value(const char *s, int default_value) { static int get_int_value(const char *s, int default_value) {
if (!s || !(s[0])) if (!s || !(s[0])) {
return default_value; return default_value;
}
return atoi(s); return atoi(s);
} }
static int get_bool_value(const char *s) { static int get_bool_value(const char *s) {
if (!s || !(s[0])) if (!s || !(s[0])) {
return 1; return 1;
if (s[0] == '0' || s[0] == 'n' || s[0] == 'N' || s[0] == 'f' || s[0] == 'F') }
if (s[0] == '0' || s[0] == 'n' || s[0] == 'N' || s[0] == 'f' || s[0] == 'F') {
return 0; return 0;
if (s[0] == 'y' || s[0] == 'Y' || s[0] == 't' || s[0] == 'T') }
if (s[0] == 'y' || s[0] == 'Y' || s[0] == 't' || s[0] == 'T') {
return 1; return 1;
if (s[0] > '0' && s[0] <= '9') }
if (s[0] > '0' && s[0] <= '9') {
return 1; return 1;
if (!strcmp(s, "off") || !strcmp(s, "OFF") || !strcmp(s, "Off")) }
if (!strcmp(s, "off") || !strcmp(s, "OFF") || !strcmp(s, "Off")) {
return 0; return 0;
if (!strcmp(s, "on") || !strcmp(s, "ON") || !strcmp(s, "On")) }
if (!strcmp(s, "on") || !strcmp(s, "ON") || !strcmp(s, "On")) {
return 1; return 1;
}
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown boolean value: %s. You can use on/off, yes/no, 1/0, true/false.\n", s); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Unknown boolean value: %s. You can use on/off, yes/no, 1/0, true/false.\n", s);
exit(-1); exit(-1);
} }
@ -1794,13 +1860,15 @@ static void set_option(int c, char *value) {
switch (c) { switch (c) {
case 'K': case 'K':
if (get_bool_value(value)) if (get_bool_value(value)) {
turn_params.allocation_default_address_family = ALLOCATION_DEFAULT_ADDRESS_FAMILY_KEEP; turn_params.allocation_default_address_family = ALLOCATION_DEFAULT_ADDRESS_FAMILY_KEEP;
}
break; break;
case 'A': case 'A':
if (value && strlen(value) > 0) { if (value && strlen(value) > 0) {
if (*value == '=') if (*value == '=') {
++value; ++value;
}
if (!strcmp(value, "ipv6")) { if (!strcmp(value, "ipv6")) {
turn_params.allocation_default_address_family = ALLOCATION_DEFAULT_ADDRESS_FAMILY_IPV6; turn_params.allocation_default_address_family = ALLOCATION_DEFAULT_ADDRESS_FAMILY_IPV6;
} else if (!strcmp(value, "keep")) { } else if (!strcmp(value, "keep")) {
@ -1847,12 +1915,14 @@ static void set_option(int c, char *value) {
turn_params.net_engine_version = (NET_ENG_VERSION)ne; turn_params.net_engine_version = (NET_ENG_VERSION)ne;
} break; } break;
case DH566_OPT: case DH566_OPT:
if (get_bool_value(value)) if (get_bool_value(value)) {
turn_params.dh_key_size = DH_566; turn_params.dh_key_size = DH_566;
}
break; break;
case DH1066_OPT: case DH1066_OPT:
if (get_bool_value(value)) if (get_bool_value(value)) {
turn_params.dh_key_size = DH_1066; turn_params.dh_key_size = DH_1066;
}
break; break;
case EC_CURVE_NAME_OPT: case EC_CURVE_NAME_OPT:
STRCPY(turn_params.ec_curve_name, value); STRCPY(turn_params.ec_curve_name, value);
@ -2015,8 +2085,9 @@ static void set_option(int c, char *value) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "-X : Wrong address format: %s\n", div); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "-X : Wrong address format: %s\n", div);
} else { } else {
ioa_addr_add_mapping(&apub, &apriv); ioa_addr_add_mapping(&apub, &apriv);
if (add_ip_list_range((const char *)div, NULL, &turn_params.ip_whitelist) == 0) if (add_ip_list_range((const char *)div, NULL, &turn_params.ip_whitelist) == 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Whitelisting external-ip private part: %s\n", div); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Whitelisting external-ip private part: %s\n", div);
}
} }
} }
free(nval); free(nval);
@ -2234,12 +2305,14 @@ static void set_option(int c, char *value) {
add_tls_alternate_server(value); add_tls_alternate_server(value);
break; break;
case ALLOWED_PEER_IPS: case ALLOWED_PEER_IPS:
if (add_ip_list_range(value, NULL, &turn_params.ip_whitelist) == 0) if (add_ip_list_range(value, NULL, &turn_params.ip_whitelist) == 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "White listing: %s\n", value); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "White listing: %s\n", value);
}
break; break;
case DENIED_PEER_IPS: case DENIED_PEER_IPS:
if (add_ip_list_range(value, NULL, &turn_params.ip_blacklist) == 0) if (add_ip_list_range(value, NULL, &turn_params.ip_blacklist) == 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Black listing: %s\n", value); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Black listing: %s\n", value);
}
break; break;
case CIPHER_LIST_OPT: case CIPHER_LIST_OPT:
STRCPY(turn_params.cipher_list, value); STRCPY(turn_params.cipher_list, value);
@ -2375,8 +2448,9 @@ static void read_config_file(int argc, char **argv, int pass) {
char *full_path_to_config_file = NULL; char *full_path_to_config_file = NULL;
full_path_to_config_file = find_config_file(config_file, pass); full_path_to_config_file = find_config_file(config_file, pass);
if (full_path_to_config_file) if (full_path_to_config_file) {
f = fopen(full_path_to_config_file, "r"); f = fopen(full_path_to_config_file, "r");
}
if (f) { if (f) {
@ -2385,18 +2459,22 @@ static void read_config_file(int argc, char **argv, int pass) {
for (;;) { for (;;) {
char *s = fgets(sbuf, sizeof(sbuf) - 1, f); char *s = fgets(sbuf, sizeof(sbuf) - 1, f);
if (!s) if (!s) {
break; break;
}
s = skip_blanks(s); s = skip_blanks(s);
if (s[0] == '#') if (s[0] == '#') {
continue; continue;
if (!s[0]) }
if (!s[0]) {
continue; continue;
}
size_t slen = strlen(s); size_t slen = strlen(s);
// strip white-spaces from config file lines end // strip white-spaces from config file lines end
while (slen && isspace(s[slen - 1])) while (slen && isspace(s[slen - 1])) {
s[--slen] = 0; s[--slen] = 0;
}
if (slen) { if (slen) {
int c = 0; int c = 0;
char *value = NULL; char *value = NULL;
@ -2547,8 +2625,9 @@ static int adminmain(int argc, char **argv) {
break; break;
case 'X': case 'X':
ct = TA_DEL_SECRET; ct = TA_DEL_SECRET;
if (optarg) if (optarg) {
STRCPY(secret, optarg); STRCPY(secret, optarg);
}
break; break;
case DEL_ALL_AUTH_SECRETS_OPT: case DEL_ALL_AUTH_SECRETS_OPT:
ct = TA_DEL_SECRET; ct = TA_DEL_SECRET;
@ -2655,8 +2734,9 @@ static int adminmain(int argc, char **argv) {
#if !defined(TURN_NO_SQLITE) #if !defined(TURN_NO_SQLITE)
if (!strlen(turn_params.default_users_db.persistent_users_db.userdb) && if (!strlen(turn_params.default_users_db.persistent_users_db.userdb) &&
(turn_params.default_users_db.userdb_type == TURN_USERDB_TYPE_SQLITE)) (turn_params.default_users_db.userdb_type == TURN_USERDB_TYPE_SQLITE)) {
strncpy(turn_params.default_users_db.persistent_users_db.userdb, DEFAULT_USERDB_FILE, TURN_LONG_STRING_SIZE); strncpy(turn_params.default_users_db.persistent_users_db.userdb, DEFAULT_USERDB_FILE, TURN_LONG_STRING_SIZE);
}
#endif #endif
if (ct == TA_COMMAND_UNKNOWN) { if (ct == TA_COMMAND_UNKNOWN) {
@ -2682,13 +2762,15 @@ static int adminmain(int argc, char **argv) {
static void print_features(unsigned long mfn) { static void print_features(unsigned long mfn) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Coturn Version %s\n", TURN_SOFTWARE); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Coturn Version %s\n", TURN_SOFTWARE);
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Max number of open files/sockets allowed for this process: %lu\n", mfn); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Max number of open files/sockets allowed for this process: %lu\n", mfn);
if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_ENDPOINT) if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_ENDPOINT) {
mfn = mfn / 3; mfn = mfn / 3;
else } else {
mfn = mfn / 2; mfn = mfn / 2;
}
mfn = ((unsigned long)(mfn / 500)) * 500; mfn = ((unsigned long)(mfn / 500)) * 500;
if (mfn < 500) if (mfn < 500) {
mfn = 500; mfn = 500;
}
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
"Due to the open files/sockets limitation, max supported number of TURN Sessions possible is: %lu " "Due to the open files/sockets limitation, max supported number of TURN Sessions possible is: %lu "
"(approximately)\n", "(approximately)\n",
@ -2787,8 +2869,9 @@ static void print_features(unsigned long mfn) {
#endif #endif
static void set_network_engine(void) { static void set_network_engine(void) {
if (turn_params.net_engine_version != NEV_UNKNOWN) if (turn_params.net_engine_version != NEV_UNKNOWN) {
return; return;
}
turn_params.net_engine_version = NEV_UDP_SOCKET_PER_ENDPOINT; turn_params.net_engine_version = NEV_UDP_SOCKET_PER_ENDPOINT;
#if defined(SO_REUSEPORT) #if defined(SO_REUSEPORT)
#if defined(__linux__) || defined(__LINUX__) || defined(__linux) || defined(linux__) || defined(LINUX) || \ #if defined(__linux__) || defined(__LINUX__) || defined(__linux) || defined(linux__) || defined(LINUX) || \
@ -2922,12 +3005,14 @@ int main(int argc, char **argv) {
{ {
int cpus = get_system_number_of_cpus(); int cpus = get_system_number_of_cpus();
if (0 < cpus) if (0 < cpus) {
turn_params.cpus = get_system_number_of_cpus(); turn_params.cpus = get_system_number_of_cpus();
if (turn_params.cpus < DEFAULT_CPUS_NUMBER) }
if (turn_params.cpus < DEFAULT_CPUS_NUMBER) {
turn_params.cpus = DEFAULT_CPUS_NUMBER; turn_params.cpus = DEFAULT_CPUS_NUMBER;
else if (turn_params.cpus > MAX_NUMBER_OF_GENERAL_RELAY_SERVERS) } else if (turn_params.cpus > MAX_NUMBER_OF_GENERAL_RELAY_SERVERS) {
turn_params.cpus = MAX_NUMBER_OF_GENERAL_RELAY_SERVERS; turn_params.cpus = MAX_NUMBER_OF_GENERAL_RELAY_SERVERS;
}
turn_params.general_relay_servers_number = (turnserver_id)turn_params.cpus; turn_params.general_relay_servers_number = (turnserver_id)turn_params.cpus;
@ -2938,8 +3023,9 @@ int main(int argc, char **argv) {
memset(&turn_params.default_users_db, 0, sizeof(default_users_db_t)); memset(&turn_params.default_users_db, 0, sizeof(default_users_db_t));
turn_params.default_users_db.ram_db.static_accounts = ur_string_map_create(free); turn_params.default_users_db.ram_db.static_accounts = ur_string_map_create(free);
if (strstr(argv[0], "turnadmin")) if (strstr(argv[0], "turnadmin")) {
return adminmain(argc, argv); return adminmain(argc, argv);
}
// Zero pass apply the log options. // Zero pass apply the log options.
read_config_file(argc, argv, 0); read_config_file(argc, argv, 0);
// First pass read other config options // First pass read other config options
@ -2949,8 +3035,9 @@ int main(int argc, char **argv) {
uo.u.m = long_options; uo.u.m = long_options;
while (((c = getopt_long(argc, argv, OPTIONS, uo.u.o, NULL)) != -1)) { while (((c = getopt_long(argc, argv, OPTIONS, uo.u.o, NULL)) != -1)) {
if (c != 'u') if (c != 'u') {
set_option(c, optarg); set_option(c, optarg);
}
} }
// Second pass read -u options // Second pass read -u options
@ -3010,8 +3097,9 @@ int main(int argc, char **argv) {
#if !defined(TURN_NO_SQLITE) #if !defined(TURN_NO_SQLITE)
if (!strlen(turn_params.default_users_db.persistent_users_db.userdb) && if (!strlen(turn_params.default_users_db.persistent_users_db.userdb) &&
(turn_params.default_users_db.userdb_type == TURN_USERDB_TYPE_SQLITE)) (turn_params.default_users_db.userdb_type == TURN_USERDB_TYPE_SQLITE)) {
strncpy(turn_params.default_users_db.persistent_users_db.userdb, DEFAULT_USERDB_FILE, TURN_LONG_STRING_SIZE); strncpy(turn_params.default_users_db.persistent_users_db.userdb, DEFAULT_USERDB_FILE, TURN_LONG_STRING_SIZE);
}
#endif #endif
argc -= optind; argc -= optind;
@ -3152,18 +3240,20 @@ int main(int argc, char **argv) {
} }
} }
if (socket_init()) if (socket_init()) {
return -1; return -1;
}
#if defined(WINDOWS) #if defined(WINDOWS)
// TODO: implement deamon!!! use windows server // TODO: implement deamon!!! use windows server
#else #else
if (turn_params.turn_daemon) { if (turn_params.turn_daemon) {
#if !defined(TURN_HAS_DAEMON) #if !defined(TURN_HAS_DAEMON)
pid_t pid = fork(); pid_t pid = fork();
if (pid > 0) if (pid > 0) {
exit(0); exit(0);
}
if (pid < 0) { if (pid < 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot start daemon process\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot start daemon process\n");
exit(-1); exit(-1);
@ -3253,10 +3343,11 @@ void coturn_locking_function(int mode, int n, const char *file, int line) {
UNUSED_ARG(file); UNUSED_ARG(file);
UNUSED_ARG(line); UNUSED_ARG(line);
if (mutex_buf_initialized && (n < CRYPTO_num_locks())) { if (mutex_buf_initialized && (n < CRYPTO_num_locks())) {
if (mode & CRYPTO_LOCK) if (mode & CRYPTO_LOCK) {
TURN_MUTEX_LOCK(&(mutex_buf[n])); TURN_MUTEX_LOCK(&(mutex_buf[n]));
else } else {
TURN_MUTEX_UNLOCK(&(mutex_buf[n])); TURN_MUTEX_UNLOCK(&(mutex_buf[n]));
}
} }
} }
@ -3281,8 +3372,9 @@ static int THREAD_setup(void) {
int THREAD_cleanup(void) { int THREAD_cleanup(void) {
int i; int i;
if (!mutex_buf_initialized) if (!mutex_buf_initialized) {
return 0; return 0;
}
CRYPTO_THREADID_set_callback(NULL); CRYPTO_THREADID_set_callback(NULL);
CRYPTO_set_locking_callback(NULL); CRYPTO_set_locking_callback(NULL);
@ -3332,26 +3424,28 @@ static void adjust_key_file_name(char *fn, const char *file_title, int critical)
return; return;
} }
keyerr : { keyerr:
if (critical) { if (critical) {
turn_params.no_tls = 1; turn_params.no_tls = 1;
turn_params.no_dtls = 1; turn_params.no_dtls = 1;
TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "cannot start TLS and DTLS listeners because %s file is not set properly\n", TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "cannot start TLS and DTLS listeners because %s file is not set properly\n",
file_title); file_title);
} }
if (full_path_to_file) if (full_path_to_file) {
free(full_path_to_file); free(full_path_to_file);
}
return; return;
} }
}
static void adjust_key_file_names(void) { static void adjust_key_file_names(void) {
if (turn_params.ca_cert_file[0]) if (turn_params.ca_cert_file[0]) {
adjust_key_file_name(turn_params.ca_cert_file, "CA", 1); adjust_key_file_name(turn_params.ca_cert_file, "CA", 1);
}
adjust_key_file_name(turn_params.cert_file, "certificate", 1); adjust_key_file_name(turn_params.cert_file, "certificate", 1);
adjust_key_file_name(turn_params.pkey_file, "private key", 1); adjust_key_file_name(turn_params.pkey_file, "private key", 1);
if (turn_params.dh_file[0]) if (turn_params.dh_file[0]) {
adjust_key_file_name(turn_params.dh_file, "DH key", 0); adjust_key_file_name(turn_params.dh_file, "DH key", 0);
}
} }
static DH *get_dh566(void) { static DH *get_dh566(void) {
@ -3369,8 +3463,9 @@ static DH *get_dh566(void) {
unsigned char dh566_g[] = {0x05}; unsigned char dh566_g[] = {0x05};
DH *dh; DH *dh;
if ((dh = DH_new()) == NULL) if ((dh = DH_new()) == NULL) {
return (NULL); return (NULL);
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L #if OPENSSL_VERSION_NUMBER < 0x10100000L
dh->p = BN_bin2bn(dh566_p, sizeof(dh566_p), NULL); dh->p = BN_bin2bn(dh566_p, sizeof(dh566_p), NULL);
dh->g = BN_bin2bn(dh566_g, sizeof(dh566_g), NULL); dh->g = BN_bin2bn(dh566_g, sizeof(dh566_g), NULL);
@ -3405,8 +3500,9 @@ static DH *get_dh1066(void) {
unsigned char dh1066_g[] = {0x02}; unsigned char dh1066_g[] = {0x02};
DH *dh; DH *dh;
if ((dh = DH_new()) == NULL) if ((dh = DH_new()) == NULL) {
return (NULL); return (NULL);
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L #if OPENSSL_VERSION_NUMBER < 0x10100000L
dh->p = BN_bin2bn(dh1066_p, sizeof(dh1066_p), NULL); dh->p = BN_bin2bn(dh1066_p, sizeof(dh1066_p), NULL);
dh->g = BN_bin2bn(dh1066_g, sizeof(dh1066_g), NULL); dh->g = BN_bin2bn(dh1066_g, sizeof(dh1066_g), NULL);
@ -3450,8 +3546,9 @@ static DH *get_dh2066(void) {
unsigned char dh2066_g[] = {0x05}; unsigned char dh2066_g[] = {0x05};
DH *dh; DH *dh;
if ((dh = DH_new()) == NULL) if ((dh = DH_new()) == NULL) {
return (NULL); return (NULL);
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L #if OPENSSL_VERSION_NUMBER < 0x10100000L
dh->p = BN_bin2bn(dh2066_p, sizeof(dh2066_p), NULL); dh->p = BN_bin2bn(dh2066_p, sizeof(dh2066_p), NULL);
dh->g = BN_bin2bn(dh2066_g, sizeof(dh2066_g), NULL); dh->g = BN_bin2bn(dh2066_g, sizeof(dh2066_g), NULL);
@ -3490,8 +3587,9 @@ static int ServerALPNCallback(SSL *ssl, const unsigned char **out, unsigned char
const unsigned char *ptr = in; const unsigned char *ptr = in;
while (ptr < (in + inlen)) { while (ptr < (in + inlen)) {
unsigned char current_len = *ptr; unsigned char current_len = *ptr;
if (ptr + 1 + current_len > in + inlen) if (ptr + 1 + current_len > in + inlen) {
break; break;
}
if ((!turn_params.no_stun) && (current_len == sa_len) && (memcmp(ptr + 1, STUN_ALPN, sa_len) == 0)) { if ((!turn_params.no_stun) && (current_len == sa_len) && (memcmp(ptr + 1, STUN_ALPN, sa_len) == 0)) {
*out = ptr + 1; *out = ptr + 1;
*outlen = sa_len; *outlen = sa_len;
@ -3513,8 +3611,9 @@ static int ServerALPNCallback(SSL *ssl, const unsigned char **out, unsigned char
ptr += 1 + current_len; ptr += 1 + current_len;
} }
if (found_http) if (found_http) {
return SSL_TLSEXT_ERR_OK; return SSL_TLSEXT_ERR_OK;
}
return SSL_TLSEXT_ERR_NOACK; //??? return SSL_TLSEXT_ERR_NOACK; //???
} }
@ -3649,12 +3748,13 @@ static void set_ctx(SSL_CTX **out, const char *protocol, const SSL_METHOD *metho
} }
if (!dh) { if (!dh) {
if (turn_params.dh_key_size == DH_566) if (turn_params.dh_key_size == DH_566) {
dh = get_dh566(); dh = get_dh566();
else if (turn_params.dh_key_size == DH_1066) } else if (turn_params.dh_key_size == DH_1066) {
dh = get_dh1066(); dh = get_dh1066();
else } else {
dh = get_dh2066(); dh = get_dh2066();
}
} }
if (!dh) { if (!dh) {
@ -3838,8 +3938,9 @@ static void openssl_load_certificates(void) {
static void reload_ssl_certs(evutil_socket_t sock, short events, void *args) { static void reload_ssl_certs(evutil_socket_t sock, short events, void *args) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Reloading TLS certificates and keys\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Reloading TLS certificates and keys\n");
openssl_load_certificates(); openssl_load_certificates();
if (turn_params.tls_ctx_update_ev != NULL) if (turn_params.tls_ctx_update_ev != NULL) {
event_active(turn_params.tls_ctx_update_ev, EV_READ, 0); event_active(turn_params.tls_ctx_update_ev, EV_READ, 0);
}
UNUSED_ARG(sock); UNUSED_ARG(sock);
UNUSED_ARG(events); UNUSED_ARG(events);

View File

@ -338,14 +338,16 @@ extern turn_params_t turn_params;
//////////////// Listener server ///////////////// //////////////// Listener server /////////////////
static inline int get_alt_listener_port(void) { static inline int get_alt_listener_port(void) {
if (turn_params.alt_listener_port < 1) if (turn_params.alt_listener_port < 1) {
return turn_params.listener_port + 1; return turn_params.listener_port + 1;
}
return turn_params.alt_listener_port; return turn_params.alt_listener_port;
} }
static inline int get_alt_tls_listener_port(void) { static inline int get_alt_tls_listener_port(void) {
if (turn_params.alt_tls_listener_port < 1) if (turn_params.alt_tls_listener_port < 1) {
return turn_params.tls_listener_port + 1; return turn_params.tls_listener_port + 1;
}
return turn_params.alt_tls_listener_port; return turn_params.alt_tls_listener_port;
} }

View File

@ -299,11 +299,13 @@ typedef struct update_ssl_ctx_cb_args {
* Copy SSL context at "from", which may be NULL if no context in use * Copy SSL context at "from", which may be NULL if no context in use
*/ */
static void replace_one_ssl_ctx(SSL_CTX **to, SSL_CTX *from) { static void replace_one_ssl_ctx(SSL_CTX **to, SSL_CTX *from) {
if (*to) if (*to) {
SSL_CTX_free(*to); SSL_CTX_free(*to);
}
if (from != NULL) if (from != NULL) {
SSL_CTX_up_ref(from); SSL_CTX_up_ref(from);
}
*to = from; *to = from;
} }
@ -324,8 +326,9 @@ static void update_ssl_ctx(evutil_socket_t sock, short events, update_ssl_ctx_cb
struct event *next = args->next; struct event *next = args->next;
TURN_MUTEX_UNLOCK(&turn_params.tls_mutex); TURN_MUTEX_UNLOCK(&turn_params.tls_mutex);
if (next != NULL) if (next != NULL) {
event_active(next, EV_READ, 0); event_active(next, EV_READ, 0);
}
UNUSED_ARG(sock); UNUSED_ARG(sock);
UNUSED_ARG(events); UNUSED_ARG(events);
@ -459,10 +462,11 @@ static authserver_id auth_message_counter = 1;
void send_auth_message_to_auth_server(struct auth_message *am) { void send_auth_message_to_auth_server(struct auth_message *am) {
TURN_MUTEX_LOCK(&auth_message_counter_mutex); TURN_MUTEX_LOCK(&auth_message_counter_mutex);
if (auth_message_counter >= authserver_number) if (auth_message_counter >= authserver_number) {
auth_message_counter = 1; auth_message_counter = 1;
else if (auth_message_counter < 1) } else if (auth_message_counter < 1) {
auth_message_counter = 1; auth_message_counter = 1;
}
authserver_id sn = auth_message_counter++; authserver_id sn = auth_message_counter++;
TURN_MUTEX_UNLOCK(&auth_message_counter_mutex); TURN_MUTEX_UNLOCK(&auth_message_counter_mutex);
@ -504,9 +508,9 @@ static void auth_server_receive_message(struct bufferevent *bev, void *ptr) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: can't find relay for turn_server_id: %d\n", __FUNCTION__, (int)am.id); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: can't find relay for turn_server_id: %d\n", __FUNCTION__, (int)am.id);
} }
if (output) if (output) {
evbuffer_add(output, &am, sizeof(struct auth_message)); evbuffer_add(output, &am, sizeof(struct auth_message));
else { } else {
ioa_network_buffer_delete(NULL, am.in_buffer.nbh); ioa_network_buffer_delete(NULL, am.in_buffer.nbh);
am.in_buffer.nbh = NULL; am.in_buffer.nbh = NULL;
} }
@ -974,8 +978,9 @@ static void setup_listener(void) {
#endif #endif
); );
if (!turn_params.listener.ioa_eng) if (!turn_params.listener.ioa_eng) {
exit(-1); exit(-1);
}
set_ssl_ctx(turn_params.listener.ioa_eng, &turn_params); set_ssl_ctx(turn_params.listener.ioa_eng, &turn_params);
turn_params.listener.rtcpmap = rtcp_map_create(turn_params.listener.ioa_eng); turn_params.listener.rtcpmap = rtcp_map_create(turn_params.listener.ioa_eng);
@ -1046,8 +1051,9 @@ static void setup_barriers(void) {
#if !defined(TURN_NO_THREAD_BARRIERS) #if !defined(TURN_NO_THREAD_BARRIERS)
{ {
if (pthread_barrier_init(&barrier, NULL, barrier_count) < 0) if (pthread_barrier_init(&barrier, NULL, barrier_count) < 0) {
perror("barrier init"); perror("barrier init");
}
} }
#endif #endif
@ -1092,8 +1098,9 @@ static void setup_socket_per_endpoint_udp_listener_servers(void) {
int is_5780 = turn_params.rfc5780; int is_5780 = turn_params.rfc5780;
if (turn_params.general_relay_servers_number <= 1) { if (turn_params.general_relay_servers_number <= 1) {
while (!(general_relay_servers[0]->ioa_eng)) while (!(general_relay_servers[0]->ioa_eng)) {
sched_yield(); sched_yield();
}
udp_relay_servers[i] = general_relay_servers[0]; udp_relay_servers[i] = general_relay_servers[0];
continue; continue;
} else if (turn_params.general_relay_servers_number > 1) { } else if (turn_params.general_relay_servers_number > 1) {
@ -1194,8 +1201,9 @@ static void setup_socket_per_endpoint_udp_listener_servers(void) {
} }
} else { } else {
turn_params.listener.udp_services[index] = NULL; turn_params.listener.udp_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
turn_params.listener.udp_services[index + 1] = NULL; turn_params.listener.udp_services[index + 1] = NULL;
}
} }
if (!turn_params.no_dtls && (turn_params.no_udp || (turn_params.listener_port != turn_params.tls_listener_port))) { if (!turn_params.no_dtls && (turn_params.no_udp || (turn_params.listener_port != turn_params.tls_listener_port))) {
@ -1238,8 +1246,9 @@ static void setup_socket_per_endpoint_udp_listener_servers(void) {
} }
} else { } else {
turn_params.listener.dtls_services[index] = NULL; turn_params.listener.dtls_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
turn_params.listener.dtls_services[index + 1] = NULL; turn_params.listener.dtls_services[index + 1] = NULL;
}
} }
} }
} }
@ -1251,8 +1260,9 @@ static void setup_socket_per_thread_udp_listener_servers(void) {
/* Create listeners */ /* Create listeners */
for (relayindex = 0; relayindex < get_real_general_relay_servers_number(); relayindex++) { for (relayindex = 0; relayindex < get_real_general_relay_servers_number(); relayindex++) {
while (!(general_relay_servers[relayindex]->ioa_eng) || !(general_relay_servers[relayindex]->server.e)) while (!(general_relay_servers[relayindex]->ioa_eng) || !(general_relay_servers[relayindex]->server.e)) {
sched_yield(); sched_yield();
}
} }
/* Aux UDP servers */ /* Aux UDP servers */
@ -1314,8 +1324,9 @@ static void setup_socket_per_thread_udp_listener_servers(void) {
} }
} else { } else {
turn_params.listener.udp_services[index] = NULL; turn_params.listener.udp_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
turn_params.listener.udp_services[index + 1] = NULL; turn_params.listener.udp_services[index + 1] = NULL;
}
} }
if (!turn_params.no_dtls && (turn_params.no_udp || (turn_params.listener_port != turn_params.tls_listener_port))) { if (!turn_params.no_dtls && (turn_params.no_udp || (turn_params.listener_port != turn_params.tls_listener_port))) {
@ -1346,8 +1357,9 @@ static void setup_socket_per_thread_udp_listener_servers(void) {
} }
} else { } else {
turn_params.listener.dtls_services[index] = NULL; turn_params.listener.dtls_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
turn_params.listener.dtls_services[index + 1] = NULL; turn_params.listener.dtls_services[index + 1] = NULL;
}
} }
} }
} }
@ -1403,8 +1415,9 @@ static void setup_socket_per_session_udp_listener_servers(void) {
} }
} else { } else {
turn_params.listener.udp_services[index] = NULL; turn_params.listener.udp_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
turn_params.listener.udp_services[index + 1] = NULL; turn_params.listener.udp_services[index + 1] = NULL;
}
} }
if (!turn_params.no_dtls && (turn_params.no_udp || (turn_params.listener_port != turn_params.tls_listener_port))) { if (!turn_params.no_dtls && (turn_params.no_udp || (turn_params.listener_port != turn_params.tls_listener_port))) {
@ -1427,8 +1440,9 @@ static void setup_socket_per_session_udp_listener_servers(void) {
} }
} else { } else {
turn_params.listener.dtls_services[index] = NULL; turn_params.listener.dtls_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
turn_params.listener.dtls_services[index + 1] = NULL; turn_params.listener.dtls_services[index + 1] = NULL;
}
} }
} }
} }
@ -1473,54 +1487,58 @@ static void setup_tcp_listener_servers(ioa_engine_handle e, struct relay_server
create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i], create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i],
turn_params.tcp_use_proxy ? turn_params.tcp_proxy_port : turn_params.listener_port, turn_params.tcp_use_proxy ? turn_params.tcp_proxy_port : turn_params.listener_port,
turn_params.verbose, e, send_socket_to_general_relay, relay_server); turn_params.verbose, e, send_socket_to_general_relay, relay_server);
if (turn_params.rfc5780) if (turn_params.rfc5780) {
tcp_services[index + 1] = tcp_services[index + 1] =
turn_params.tcp_use_proxy turn_params.tcp_use_proxy
? NULL ? NULL
: create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i], : create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i],
get_alt_listener_port(), turn_params.verbose, e, get_alt_listener_port(), turn_params.verbose, e,
send_socket_to_general_relay, relay_server); send_socket_to_general_relay, relay_server);
}
} else { } else {
tcp_services[index] = NULL; tcp_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
tcp_services[index + 1] = NULL; tcp_services[index + 1] = NULL;
}
} }
if (!turn_params.no_tls && !turn_params.tcp_use_proxy && if (!turn_params.no_tls && !turn_params.tcp_use_proxy &&
(turn_params.no_tcp || (turn_params.listener_port != turn_params.tls_listener_port))) { (turn_params.no_tcp || (turn_params.listener_port != turn_params.tls_listener_port))) {
tls_services[index] = create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i], tls_services[index] = create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i],
turn_params.tls_listener_port, turn_params.verbose, e, turn_params.tls_listener_port, turn_params.verbose, e,
send_socket_to_general_relay, relay_server); send_socket_to_general_relay, relay_server);
if (turn_params.rfc5780) if (turn_params.rfc5780) {
tls_services[index + 1] = create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i], tls_services[index + 1] = create_tls_listener_server(turn_params.listener_ifname, turn_params.listener.addrs[i],
get_alt_tls_listener_port(), turn_params.verbose, e, get_alt_tls_listener_port(), turn_params.verbose, e,
send_socket_to_general_relay, relay_server); send_socket_to_general_relay, relay_server);
}
} else { } else {
tls_services[index] = NULL; tls_services[index] = NULL;
if (turn_params.rfc5780) if (turn_params.rfc5780) {
tls_services[index + 1] = NULL; tls_services[index + 1] = NULL;
}
} }
} }
} }
static int get_alt_addr(ioa_addr *addr, ioa_addr *alt_addr) { static int get_alt_addr(ioa_addr *addr, ioa_addr *alt_addr) {
if (!addr || !turn_params.rfc5780 || (turn_params.listener.addrs_number < 2)) if (!addr || !turn_params.rfc5780 || (turn_params.listener.addrs_number < 2)) {
; } else {
else {
size_t index = 0xffff; size_t index = 0xffff;
size_t i = 0; size_t i = 0;
int alt_port = -1; int alt_port = -1;
int port = addr_get_port(addr); int port = addr_get_port(addr);
if (port == turn_params.listener_port) if (port == turn_params.listener_port) {
alt_port = get_alt_listener_port(); alt_port = get_alt_listener_port();
else if (port == get_alt_listener_port()) } else if (port == get_alt_listener_port()) {
alt_port = turn_params.listener_port; alt_port = turn_params.listener_port;
else if (port == turn_params.tls_listener_port) } else if (port == turn_params.tls_listener_port) {
alt_port = get_alt_tls_listener_port(); alt_port = get_alt_tls_listener_port();
else if (port == get_alt_tls_listener_port()) } else if (port == get_alt_tls_listener_port()) {
alt_port = turn_params.tls_listener_port; alt_port = turn_params.tls_listener_port;
else } else {
return -1; return -1;
}
for (i = 0; i < turn_params.listener.addrs_number; i++) { for (i = 0; i < turn_params.listener.addrs_number; i++) {
if (turn_params.listener.encaddrs && turn_params.listener.encaddrs[i]) { if (turn_params.listener.encaddrs && turn_params.listener.encaddrs[i]) {
@ -1549,11 +1567,13 @@ static int get_alt_addr(ioa_addr *addr, ioa_addr *alt_addr) {
} }
static void run_events(struct event_base *eb, ioa_engine_handle e) { static void run_events(struct event_base *eb, ioa_engine_handle e) {
if (!eb && e) if (!eb && e) {
eb = e->event_base; eb = e->event_base;
}
if (!eb) if (!eb) {
return; return;
}
struct timeval timeout; struct timeval timeout;
@ -1804,8 +1824,9 @@ void setup_server(void) {
authserver_number = 1 + (authserver_id)(turn_params.cpus / 2); authserver_number = 1 + (authserver_id)(turn_params.cpus / 2);
if (authserver_number < MIN_AUTHSERVER_NUMBER) if (authserver_number < MIN_AUTHSERVER_NUMBER) {
authserver_number = MIN_AUTHSERVER_NUMBER; authserver_number = MIN_AUTHSERVER_NUMBER;
}
#if !defined(TURN_NO_THREAD_BARRIERS) #if !defined(TURN_NO_THREAD_BARRIERS)
@ -1822,12 +1843,13 @@ void setup_server(void) {
setup_general_relay_servers(); setup_general_relay_servers();
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Total General servers: %d\n", (int)get_real_general_relay_servers_number()); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Total General servers: %d\n", (int)get_real_general_relay_servers_number());
if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_THREAD) if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_THREAD) {
setup_socket_per_thread_udp_listener_servers(); setup_socket_per_thread_udp_listener_servers();
else if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_ENDPOINT) } else if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_ENDPOINT) {
setup_socket_per_endpoint_udp_listener_servers(); setup_socket_per_endpoint_udp_listener_servers();
else if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_SESSION) } else if (turn_params.net_engine_version == NEV_UDP_SOCKET_PER_SESSION) {
setup_socket_per_session_udp_listener_servers(); setup_socket_per_session_udp_listener_servers();
}
if (turn_params.net_engine_version != NEV_UDP_SOCKET_PER_THREAD) { if (turn_params.net_engine_version != NEV_UDP_SOCKET_PER_THREAD) {
setup_tcp_listener_servers(turn_params.listener.ioa_eng, NULL); setup_tcp_listener_servers(turn_params.listener.ioa_eng, NULL);

File diff suppressed because it is too large Load Diff

View File

@ -85,12 +85,13 @@ static void server_input_handler(struct evconnlistener *l, evutil_socket_t fd, s
SOCKET_TYPE st = TENTATIVE_TCP_SOCKET; SOCKET_TYPE st = TENTATIVE_TCP_SOCKET;
if (turn_params.tcp_use_proxy) if (turn_params.tcp_use_proxy) {
st = TCP_SOCKET_PROXY; st = TCP_SOCKET_PROXY;
else if (turn_params.no_tls) } else if (turn_params.no_tls) {
st = TCP_SOCKET; st = TCP_SOCKET;
else if (turn_params.no_tcp) } else if (turn_params.no_tcp) {
st = TLS_SOCKET; st = TLS_SOCKET;
}
ioa_socket_handle ioas = create_ioa_socket_from_fd(server->e, fd, NULL, st, CLIENT_SOCKET, ioa_socket_handle ioas = create_ioa_socket_from_fd(server->e, fd, NULL, st, CLIENT_SOCKET,
&(server->sm.m.sm.nd.src_addr), &(server->addr)); &(server->sm.m.sm.nd.src_addr), &(server->addr));
@ -143,10 +144,11 @@ static void sctp_server_input_handler(struct evconnlistener *l, evutil_socket_t
SOCKET_TYPE st = TENTATIVE_SCTP_SOCKET; SOCKET_TYPE st = TENTATIVE_SCTP_SOCKET;
if (turn_params.no_tls) if (turn_params.no_tls) {
st = SCTP_SOCKET; st = SCTP_SOCKET;
else if (turn_params.no_tcp) } else if (turn_params.no_tcp) {
st = TLS_SCTP_SOCKET; st = TLS_SCTP_SOCKET;
}
ioa_socket_handle ioas = create_ioa_socket_from_fd(server->e, fd, NULL, st, CLIENT_SOCKET, ioa_socket_handle ioas = create_ioa_socket_from_fd(server->e, fd, NULL, st, CLIENT_SOCKET,
&(server->sm.m.sm.nd.src_addr), &(server->addr)); &(server->sm.m.sm.nd.src_addr), &(server->addr));
@ -181,8 +183,9 @@ static int create_server_listener(tls_listener_relay_server_type *server) {
FUNCSTART; FUNCSTART;
if (!server) if (!server) {
return -1; return -1;
}
evutil_socket_t tls_listen_fd = -1; evutil_socket_t tls_listen_fd = -1;
@ -230,12 +233,13 @@ static int create_server_listener(tls_listener_relay_server_type *server) {
return -1; return -1;
} }
if (!turn_params.no_tcp && !turn_params.no_tls) if (!turn_params.no_tcp && !turn_params.no_tls) {
addr_debug_print(server->verbose, &server->addr, "TLS/TCP listener opened on "); addr_debug_print(server->verbose, &server->addr, "TLS/TCP listener opened on ");
else if (!turn_params.no_tls) } else if (!turn_params.no_tls) {
addr_debug_print(server->verbose, &server->addr, "TLS listener opened on "); addr_debug_print(server->verbose, &server->addr, "TLS listener opened on ");
else if (!turn_params.no_tcp) } else if (!turn_params.no_tcp) {
addr_debug_print(server->verbose, &server->addr, "TCP listener opened on "); addr_debug_print(server->verbose, &server->addr, "TCP listener opened on ");
}
FUNCEND; FUNCEND;
@ -248,8 +252,9 @@ static int sctp_create_server_listener(tls_listener_relay_server_type *server) {
FUNCSTART; FUNCSTART;
if (!server) if (!server) {
return -1; return -1;
}
evutil_socket_t tls_listen_fd = -1; evutil_socket_t tls_listen_fd = -1;
@ -280,10 +285,11 @@ static int sctp_create_server_listener(tls_listener_relay_server_type *server) {
return -1; return -1;
} }
if (!turn_params.no_tls) if (!turn_params.no_tls) {
addr_debug_print(server->verbose, &server->addr, "TLS/SCTP listener opened on "); addr_debug_print(server->verbose, &server->addr, "TLS/SCTP listener opened on ");
else } else {
addr_debug_print(server->verbose, &server->addr, "SCTP listener opened on "); addr_debug_print(server->verbose, &server->addr, "SCTP listener opened on ");
}
FUNCEND; FUNCEND;
@ -296,14 +302,16 @@ static int init_server(tls_listener_relay_server_type *server, const char *ifnam
int verbose, ioa_engine_handle e, ioa_engine_new_connection_event_handler send_socket, int verbose, ioa_engine_handle e, ioa_engine_new_connection_event_handler send_socket,
struct relay_server *relay_server) { struct relay_server *relay_server) {
if (!server) if (!server) {
return -1; return -1;
}
server->connect_cb = send_socket; server->connect_cb = send_socket;
server->relay_server = relay_server; server->relay_server = relay_server;
if (ifname) if (ifname) {
STRCPY(server->ifname, ifname); STRCPY(server->ifname, ifname);
}
if (make_ioa_addr((const uint8_t *)local_address, port, &server->addr) < 0) { if (make_ioa_addr((const uint8_t *)local_address, port, &server->addr) < 0) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot create a TCP/TLS listener for address: %s\n", local_address); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot create a TCP/TLS listener for address: %s\n", local_address);

View File

@ -223,16 +223,18 @@ static void print_str_array(struct cli_session *cs, const char **sa) {
} }
static const char *get_flag(int val) { static const char *get_flag(int val) {
if (val) if (val) {
return "ON"; return "ON";
}
return "OFF"; return "OFF";
} }
static void cli_print_flag(struct cli_session *cs, int flag, const char *name, int changeable) { static void cli_print_flag(struct cli_session *cs, int flag, const char *name, int changeable) {
if (cs && cs->ts && name) { if (cs && cs->ts && name) {
const char *sc = ""; const char *sc = "";
if (changeable) if (changeable) {
sc = " (*)"; sc = " (*)";
}
myprintf(cs, " %s: %s%s\n", name, get_flag(flag), sc); myprintf(cs, " %s: %s%s\n", name, get_flag(flag), sc);
} }
} }
@ -240,23 +242,26 @@ static void cli_print_flag(struct cli_session *cs, int flag, const char *name, i
static void cli_print_uint(struct cli_session *cs, unsigned long value, const char *name, int changeable) { static void cli_print_uint(struct cli_session *cs, unsigned long value, const char *name, int changeable) {
if (cs && cs->ts && name) { if (cs && cs->ts && name) {
const char *sc = ""; const char *sc = "";
if (changeable == 1) if (changeable == 1) {
sc = " (*)"; sc = " (*)";
else if (changeable == 2) } else if (changeable == 2) {
sc = " (**)"; sc = " (**)";
}
myprintf(cs, " %s: %lu%s\n", name, value, sc); myprintf(cs, " %s: %lu%s\n", name, value, sc);
} }
} }
static void cli_print_str(struct cli_session *cs, const char *value, const char *name, int changeable) { static void cli_print_str(struct cli_session *cs, const char *value, const char *name, int changeable) {
if (cs && cs->ts && name && value) { if (cs && cs->ts && name && value) {
if (value[0] == 0) if (value[0] == 0) {
value = "empty"; value = "empty";
}
const char *sc = ""; const char *sc = "";
if (changeable == 1) if (changeable == 1) {
sc = " (*)"; sc = " (*)";
else if (changeable == 2) } else if (changeable == 2) {
sc = " (**)"; sc = " (**)";
}
myprintf(cs, " %s: %s%s\n", name, value, sc); myprintf(cs, " %s: %s%s\n", name, value, sc);
} }
} }
@ -264,15 +269,17 @@ static void cli_print_str(struct cli_session *cs, const char *value, const char
static void cli_print_addr(struct cli_session *cs, ioa_addr *value, int use_port, const char *name, int changeable) { static void cli_print_addr(struct cli_session *cs, ioa_addr *value, int use_port, const char *name, int changeable) {
if (cs && cs->ts && name && value) { if (cs && cs->ts && name && value) {
const char *sc = ""; const char *sc = "";
if (changeable == 1) if (changeable == 1) {
sc = " (*)"; sc = " (*)";
else if (changeable == 2) } else if (changeable == 2) {
sc = " (**)"; sc = " (**)";
}
char s[256]; char s[256];
if (!use_port) if (!use_port) {
addr_to_string_no_port(value, (uint8_t *)s); addr_to_string_no_port(value, (uint8_t *)s);
else } else {
addr_to_string(value, (uint8_t *)s); addr_to_string(value, (uint8_t *)s);
}
myprintf(cs, " %s: %s%s\n", name, s, sc); myprintf(cs, " %s: %s%s\n", name, s, sc);
} }
} }
@ -281,17 +288,19 @@ static void cli_print_addr_list(struct cli_session *cs, turn_server_addrs_list_t
int changeable) { int changeable) {
if (cs && cs->ts && name && value && value->size && value->addrs) { if (cs && cs->ts && name && value && value->size && value->addrs) {
const char *sc = ""; const char *sc = "";
if (changeable == 1) if (changeable == 1) {
sc = " (*)"; sc = " (*)";
else if (changeable == 2) } else if (changeable == 2) {
sc = " (**)"; sc = " (**)";
}
char s[256]; char s[256];
size_t i; size_t i;
for (i = 0; i < value->size; i++) { for (i = 0; i < value->size; i++) {
if (!use_port) if (!use_port) {
addr_to_string_no_port(&(value->addrs[i]), (uint8_t *)s); addr_to_string_no_port(&(value->addrs[i]), (uint8_t *)s);
else } else {
addr_to_string(&(value->addrs[i]), (uint8_t *)s); addr_to_string(&(value->addrs[i]), (uint8_t *)s);
}
myprintf(cs, " %s: %s%s\n", name, s, sc); myprintf(cs, " %s: %s%s\n", name, s, sc);
} }
} }
@ -300,14 +309,16 @@ static void cli_print_addr_list(struct cli_session *cs, turn_server_addrs_list_t
static void cli_print_str_array(struct cli_session *cs, char **value, size_t sz, const char *name, int changeable) { static void cli_print_str_array(struct cli_session *cs, char **value, size_t sz, const char *name, int changeable) {
if (cs && cs->ts && name && value && sz) { if (cs && cs->ts && name && value && sz) {
const char *sc = ""; const char *sc = "";
if (changeable == 1) if (changeable == 1) {
sc = " (*)"; sc = " (*)";
else if (changeable == 2) } else if (changeable == 2) {
sc = " (**)"; sc = " (**)";
}
size_t i; size_t i;
for (i = 0; i < sz; i++) { for (i = 0; i < sz; i++) {
if (value[i]) if (value[i]) {
myprintf(cs, " %s: %s%s\n", name, value[i], sc); myprintf(cs, " %s: %s%s\n", name, value[i], sc);
}
} }
} }
} }
@ -315,10 +326,11 @@ static void cli_print_str_array(struct cli_session *cs, char **value, size_t sz,
static void cli_print_ip_range_list(struct cli_session *cs, ip_range_list_t *value, const char *name, int changeable) { static void cli_print_ip_range_list(struct cli_session *cs, ip_range_list_t *value, const char *name, int changeable) {
if (cs && cs->ts && name && value && value->ranges_number && value->rs) { if (cs && cs->ts && name && value && value->ranges_number && value->rs) {
const char *sc = ""; const char *sc = "";
if (changeable == 1) if (changeable == 1) {
sc = " (*)"; sc = " (*)";
else if (changeable == 2) } else if (changeable == 2) {
sc = " (**)"; sc = " (**)";
}
size_t i; size_t i;
for (i = 0; i < value->ranges_number; ++i) { for (i = 0; i < value->ranges_number; ++i) {
if (value->rs[i].realm[0]) { if (value->rs[i].realm[0]) {
@ -414,28 +426,34 @@ static int print_session(ur_map_key_type key, ur_map_value_type value, void *arg
struct cli_session *cs = csarg->cs; struct cli_session *cs = csarg->cs;
struct turn_session_info *tsi = (struct turn_session_info *)value; struct turn_session_info *tsi = (struct turn_session_info *)value;
if (cs->realm[0] && strcmp(cs->realm, tsi->realm)) if (cs->realm[0] && strcmp(cs->realm, tsi->realm)) {
return 0; return 0;
}
if (cs->origin[0] && strcmp(cs->origin, tsi->origin)) if (cs->origin[0] && strcmp(cs->origin, tsi->origin)) {
return 0; return 0;
}
if (csarg->users) { if (csarg->users) {
const char *pn = csarg->pname; const char *pn = csarg->pname;
if (pn[0]) { if (pn[0]) {
if (!strcmp(pn, "TLS") || !strcmp(pn, "tls") || !strcmp(pn, "Tls")) { if (!strcmp(pn, "TLS") || !strcmp(pn, "tls") || !strcmp(pn, "Tls")) {
if ((tsi->client_protocol != TLS_SOCKET) && (tsi->client_protocol != TLS_SCTP_SOCKET)) if ((tsi->client_protocol != TLS_SOCKET) && (tsi->client_protocol != TLS_SCTP_SOCKET)) {
return 0; return 0;
}
} else if (!strcmp(pn, "DTLS") || !strcmp(pn, "dtls") || !strcmp(pn, "Dtls")) { } else if (!strcmp(pn, "DTLS") || !strcmp(pn, "dtls") || !strcmp(pn, "Dtls")) {
if (tsi->client_protocol != DTLS_SOCKET) if (tsi->client_protocol != DTLS_SOCKET) {
return 0; return 0;
}
} else if (!strcmp(pn, "TCP") || !strcmp(pn, "tcp") || !strcmp(pn, "Tcp")) { } else if (!strcmp(pn, "TCP") || !strcmp(pn, "tcp") || !strcmp(pn, "Tcp")) {
if ((tsi->client_protocol != TCP_SOCKET) && (tsi->client_protocol != SCTP_SOCKET)) if ((tsi->client_protocol != TCP_SOCKET) && (tsi->client_protocol != SCTP_SOCKET)) {
return 0; return 0;
}
} else if (!strcmp(pn, "UDP") || !strcmp(pn, "udp") || !strcmp(pn, "Udp")) { } else if (!strcmp(pn, "UDP") || !strcmp(pn, "udp") || !strcmp(pn, "Udp")) {
if (tsi->client_protocol != UDP_SOCKET) if (tsi->client_protocol != UDP_SOCKET) {
return 0; return 0;
}
} else { } else {
return 0; return 0;
} }
@ -455,21 +473,25 @@ static int print_session(ur_map_key_type key, ur_map_value_type value, void *arg
} else { } else {
if (csarg->username[0]) { if (csarg->username[0]) {
if (csarg->exact_match) { if (csarg->exact_match) {
if (strcmp((char *)tsi->username, csarg->username)) if (strcmp((char *)tsi->username, csarg->username)) {
return 0; return 0;
}
} else { } else {
if (!strstr((char *)tsi->username, csarg->username)) if (!strstr((char *)tsi->username, csarg->username)) {
return 0; return 0;
}
} }
} }
if (cs->f || (unsigned long)csarg->counter < (unsigned long)cli_max_output_sessions) { if (cs->f || (unsigned long)csarg->counter < (unsigned long)cli_max_output_sessions) {
myprintf(cs, "\n"); myprintf(cs, "\n");
myprintf(cs, " %lu) id=%018llu, user <%s>:\n", (unsigned long)(csarg->counter + 1), myprintf(cs, " %lu) id=%018llu, user <%s>:\n", (unsigned long)(csarg->counter + 1),
(unsigned long long)tsi->id, tsi->username); (unsigned long long)tsi->id, tsi->username);
if (tsi->realm[0]) if (tsi->realm[0]) {
myprintf(cs, " realm: %s\n", tsi->realm); myprintf(cs, " realm: %s\n", tsi->realm);
if (tsi->origin[0]) }
if (tsi->origin[0]) {
myprintf(cs, " origin: %s\n", tsi->origin); myprintf(cs, " origin: %s\n", tsi->origin);
}
if (turn_time_before(csarg->ct, tsi->start_time)) { if (turn_time_before(csarg->ct, tsi->start_time)) {
myprintf(cs, " started: undefined time\n"); myprintf(cs, " started: undefined time\n");
} else { } else {
@ -483,14 +505,18 @@ static int print_session(ur_map_key_type key, ur_map_value_type value, void *arg
myprintf(cs, " client protocol %s, relay protocol %s\n", socket_type_name(tsi->client_protocol), myprintf(cs, " client protocol %s, relay protocol %s\n", socket_type_name(tsi->client_protocol),
socket_type_name(tsi->peer_protocol)); socket_type_name(tsi->peer_protocol));
{ {
if (!tsi->local_addr_data.saddr[0]) if (!tsi->local_addr_data.saddr[0]) {
addr_to_string(&(tsi->local_addr_data.addr), (uint8_t *)tsi->local_addr_data.saddr); addr_to_string(&(tsi->local_addr_data.addr), (uint8_t *)tsi->local_addr_data.saddr);
if (!tsi->remote_addr_data.saddr[0]) }
if (!tsi->remote_addr_data.saddr[0]) {
addr_to_string(&(tsi->remote_addr_data.addr), (uint8_t *)tsi->remote_addr_data.saddr); addr_to_string(&(tsi->remote_addr_data.addr), (uint8_t *)tsi->remote_addr_data.saddr);
if (!tsi->relay_addr_data_ipv4.saddr[0]) }
if (!tsi->relay_addr_data_ipv4.saddr[0]) {
addr_to_string(&(tsi->relay_addr_data_ipv4.addr), (uint8_t *)tsi->relay_addr_data_ipv4.saddr); addr_to_string(&(tsi->relay_addr_data_ipv4.addr), (uint8_t *)tsi->relay_addr_data_ipv4.saddr);
if (!tsi->relay_addr_data_ipv6.saddr[0]) }
if (!tsi->relay_addr_data_ipv6.saddr[0]) {
addr_to_string(&(tsi->relay_addr_data_ipv6.addr), (uint8_t *)tsi->relay_addr_data_ipv6.saddr); addr_to_string(&(tsi->relay_addr_data_ipv6.addr), (uint8_t *)tsi->relay_addr_data_ipv6.saddr);
}
myprintf(cs, " client addr %s, server addr %s\n", tsi->remote_addr_data.saddr, myprintf(cs, " client addr %s, server addr %s\n", tsi->remote_addr_data.saddr,
tsi->local_addr_data.saddr); tsi->local_addr_data.saddr);
if (tsi->relay_addr_data_ipv4.saddr[0]) { if (tsi->relay_addr_data_ipv4.saddr[0]) {
@ -506,8 +532,9 @@ static int print_session(ur_map_key_type key, ur_map_value_type value, void *arg
myprintf(cs, " TLS method: %s\n", tsi->tls_method); myprintf(cs, " TLS method: %s\n", tsi->tls_method);
myprintf(cs, " TLS cipher: %s\n", tsi->tls_cipher); myprintf(cs, " TLS cipher: %s\n", tsi->tls_cipher);
} }
if (tsi->bps) if (tsi->bps) {
myprintf(cs, " Max throughput: %lu bytes per second\n", (unsigned long)tsi->bps); myprintf(cs, " Max throughput: %lu bytes per second\n", (unsigned long)tsi->bps);
}
myprintf(cs, " usage: rp=%lu, rb=%lu, sp=%lu, sb=%lu\n", (unsigned long)(tsi->received_packets), myprintf(cs, " usage: rp=%lu, rb=%lu, sp=%lu, sb=%lu\n", (unsigned long)(tsi->received_packets),
(unsigned long)(tsi->received_bytes), (unsigned long)(tsi->sent_packets), (unsigned long)(tsi->received_bytes), (unsigned long)(tsi->sent_packets),
(unsigned long)(tsi->sent_bytes)); (unsigned long)(tsi->sent_bytes));
@ -517,14 +544,16 @@ static int print_session(ur_map_key_type key, ur_map_value_type value, void *arg
myprintf(cs, " peers:\n"); myprintf(cs, " peers:\n");
size_t i; size_t i;
for (i = 0; i < tsi->main_peers_size; ++i) { for (i = 0; i < tsi->main_peers_size; ++i) {
if (!(tsi->main_peers_data[i].saddr[0])) if (!(tsi->main_peers_data[i].saddr[0])) {
addr_to_string(&(tsi->main_peers_data[i].addr), (uint8_t *)tsi->main_peers_data[i].saddr); addr_to_string(&(tsi->main_peers_data[i].addr), (uint8_t *)tsi->main_peers_data[i].saddr);
}
myprintf(cs, " %s\n", tsi->main_peers_data[i].saddr); myprintf(cs, " %s\n", tsi->main_peers_data[i].saddr);
} }
if (tsi->extra_peers_size && tsi->extra_peers_data) { if (tsi->extra_peers_size && tsi->extra_peers_data) {
for (i = 0; i < tsi->extra_peers_size; ++i) { for (i = 0; i < tsi->extra_peers_size; ++i) {
if (!(tsi->extra_peers_data[i].saddr[0])) if (!(tsi->extra_peers_data[i].saddr[0])) {
addr_to_string(&(tsi->extra_peers_data[i].addr), (uint8_t *)tsi->extra_peers_data[i].saddr); addr_to_string(&(tsi->extra_peers_data[i].addr), (uint8_t *)tsi->extra_peers_data[i].saddr);
}
myprintf(cs, " %s\n", tsi->extra_peers_data[i].saddr); myprintf(cs, " %s\n", tsi->extra_peers_data[i].saddr);
} }
} }
@ -547,10 +576,12 @@ static void cancel_session(struct cli_session *cs, const char *ssid) {
static void print_sessions(struct cli_session *cs, const char *pn, int exact_match, int print_users) { static void print_sessions(struct cli_session *cs, const char *pn, int exact_match, int print_users) {
if (cs && cs->ts && pn) { if (cs && cs->ts && pn) {
while (pn[0] == ' ') while (pn[0] == ' ') {
++pn; ++pn;
if (pn[0] == '*') }
if (pn[0] == '*') {
++pn; ++pn;
}
const char *uname = ""; const char *uname = "";
if (!print_users) { if (!print_users) {
@ -590,11 +621,13 @@ static void print_sessions(struct cli_session *cs, const char *pn, int exact_mat
snprintf(ts, sizeof(ts), " Total sessions"); snprintf(ts, sizeof(ts), " Total sessions");
if (cs->realm[0]) { if (cs->realm[0]) {
snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), " for realm %s", cs->realm); snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), " for realm %s", cs->realm);
if (cs->origin[0]) if (cs->origin[0]) {
snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), " and for origin %s", cs->origin); snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), " and for origin %s", cs->origin);
}
} else { } else {
if (cs->origin[0]) if (cs->origin[0]) {
snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), " for origin %s", cs->origin); snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), " for origin %s", cs->origin);
}
} }
snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), ": %lu", (unsigned long)arg.counter); snprintf(ts + strlen(ts), sizeof(ts) - strlen(ts), ": %lu", (unsigned long)arg.counter);
myprintf(cs, "%s\n", ts); myprintf(cs, "%s\n", ts);
@ -610,18 +643,21 @@ static void print_sessions(struct cli_session *cs, const char *pn, int exact_mat
} }
} }
if (arg.user_counters) if (arg.user_counters) {
free(arg.user_counters); free(arg.user_counters);
}
if (arg.user_names) { if (arg.user_names) {
size_t i; size_t i;
for (i = 0; i < arg.users_number; ++i) { for (i = 0; i < arg.users_number; ++i) {
if (arg.user_names[i]) if (arg.user_names[i]) {
free(arg.user_names[i]); free(arg.user_names[i]);
}
} }
free(arg.user_names); free(arg.user_names);
} }
if (arg.users) if (arg.users) {
ur_string_map_free(&arg.users); ur_string_map_free(&arg.users);
}
} }
} }
@ -659,21 +695,23 @@ static void cli_print_configuration(struct cli_session *cs) {
myprintf(cs, "\n"); myprintf(cs, "\n");
if (turn_params.cipher_list[0]) if (turn_params.cipher_list[0]) {
cli_print_str(cs, turn_params.cipher_list, "cipher-list", 0); cli_print_str(cs, turn_params.cipher_list, "cipher-list", 0);
else } else {
cli_print_str(cs, DEFAULT_CIPHER_LIST, "cipher-list", 0); cli_print_str(cs, DEFAULT_CIPHER_LIST, "cipher-list", 0);
}
cli_print_str(cs, turn_params.ec_curve_name, "ec-curve-name", 0); cli_print_str(cs, turn_params.ec_curve_name, "ec-curve-name", 0);
{ {
if (turn_params.dh_key_size == DH_CUSTOM) if (turn_params.dh_key_size == DH_CUSTOM) {
cli_print_str(cs, turn_params.dh_file, "dh-file", 0); cli_print_str(cs, turn_params.dh_file, "dh-file", 0);
else { } else {
unsigned int dh_key_length = 1066; unsigned int dh_key_length = 1066;
if (turn_params.dh_key_size == DH_566) if (turn_params.dh_key_size == DH_566) {
dh_key_length = 566; dh_key_length = 566;
else if (turn_params.dh_key_size == DH_2066) } else if (turn_params.dh_key_size == DH_2066) {
dh_key_length = 2066; dh_key_length = 2066;
}
cli_print_uint(cs, (unsigned long)dh_key_length, "DH-key-length", 0); cli_print_uint(cs, (unsigned long)dh_key_length, "DH-key-length", 0);
} }
} }
@ -684,8 +722,9 @@ static void cli_print_configuration(struct cli_session *cs) {
cli_print_str_array(cs, turn_params.listener.addrs, turn_params.listener.addrs_number, "Listener addr", 0); cli_print_str_array(cs, turn_params.listener.addrs, turn_params.listener.addrs_number, "Listener addr", 0);
if (turn_params.listener_ifname[0]) if (turn_params.listener_ifname[0]) {
cli_print_str(cs, turn_params.listener_ifname, "listener-ifname", 0); cli_print_str(cs, turn_params.listener_ifname, "listener-ifname", 0);
}
cli_print_flag(cs, turn_params.no_udp, "no-udp", 0); cli_print_flag(cs, turn_params.no_udp, "no-udp", 0);
cli_print_flag(cs, turn_params.no_tcp, "no-tcp", 0); cli_print_flag(cs, turn_params.no_tcp, "no-tcp", 0);
@ -713,8 +752,9 @@ static void cli_print_configuration(struct cli_session *cs) {
cli_print_str_array(cs, turn_params.relay_addrs, turn_params.relays_number, "Relay addr", 0); cli_print_str_array(cs, turn_params.relay_addrs, turn_params.relays_number, "Relay addr", 0);
if (turn_params.relay_ifname[0]) if (turn_params.relay_ifname[0]) {
cli_print_str(cs, turn_params.relay_ifname, "relay-ifname", 0); cli_print_str(cs, turn_params.relay_ifname, "relay-ifname", 0);
}
cli_print_flag(cs, turn_params.server_relay, "server-relay", 0); cli_print_flag(cs, turn_params.server_relay, "server-relay", 0);
@ -752,30 +792,36 @@ static void cli_print_configuration(struct cli_session *cs) {
} }
#if !defined(TURN_NO_HIREDIS) #if !defined(TURN_NO_HIREDIS)
if (turn_params.use_redis_statsdb && turn_params.redis_statsdb.connection_string[0]) if (turn_params.use_redis_statsdb && turn_params.redis_statsdb.connection_string[0]) {
cli_print_str(cs, turn_params.redis_statsdb.connection_string, "Redis Statistics DB", 0); cli_print_str(cs, turn_params.redis_statsdb.connection_string, "Redis Statistics DB", 0);
}
#endif #endif
myprintf(cs, "\n"); myprintf(cs, "\n");
{ {
char *rn = get_realm(NULL)->options.name; char *rn = get_realm(NULL)->options.name;
if (rn[0]) if (rn[0]) {
cli_print_str(cs, rn, "Default realm", 0); cli_print_str(cs, rn, "Default realm", 0);
}
} }
if (cs->realm[0]) if (cs->realm[0]) {
cli_print_str(cs, cs->realm, "CLI session realm", 0); cli_print_str(cs, cs->realm, "CLI session realm", 0);
else } else {
cli_print_str(cs, get_realm(NULL)->options.name, "CLI session realm", 0); cli_print_str(cs, get_realm(NULL)->options.name, "CLI session realm", 0);
if (cs->origin[0]) }
if (cs->origin[0]) {
cli_print_str(cs, cs->origin, "CLI session origin", 0); cli_print_str(cs, cs->origin, "CLI session origin", 0);
if (turn_params.ct == TURN_CREDENTIALS_LONG_TERM) }
if (turn_params.ct == TURN_CREDENTIALS_LONG_TERM) {
cli_print_flag(cs, 1, "Long-term authorization mechanism", 0); cli_print_flag(cs, 1, "Long-term authorization mechanism", 0);
else } else {
cli_print_flag(cs, 1, "Anonymous credentials", 0); cli_print_flag(cs, 1, "Anonymous credentials", 0);
}
cli_print_flag(cs, turn_params.use_auth_secret_with_timestamp, "TURN REST API support", 0); cli_print_flag(cs, turn_params.use_auth_secret_with_timestamp, "TURN REST API support", 0);
if (turn_params.use_auth_secret_with_timestamp && turn_params.rest_api_separator) if (turn_params.use_auth_secret_with_timestamp && turn_params.rest_api_separator) {
cli_print_uint(cs, turn_params.rest_api_separator, "TURN REST API separator ASCII number", 0); cli_print_uint(cs, turn_params.rest_api_separator, "TURN REST API separator ASCII number", 0);
}
myprintf(cs, "\n"); myprintf(cs, "\n");
@ -885,8 +931,9 @@ static int run_cli_input(struct cli_session *cs, const char *buf0, unsigned int
char *cmd = buf; char *cmd = buf;
while ((cmd[0] == ' ') || (cmd[0] == '\t')) while ((cmd[0] == ' ') || (cmd[0] == '\t')) {
++cmd; ++cmd;
}
size_t sl = strlen(cmd); size_t sl = strlen(cmd);
@ -962,8 +1009,9 @@ static int run_cli_input(struct cli_session *cs, const char *buf0, unsigned int
type_cli_cursor(cs); type_cli_cursor(cs);
} else if (strstr(cmd, "psd") == cmd) { } else if (strstr(cmd, "psd") == cmd) {
cmd += 3; cmd += 3;
while (cmd[0] == ' ') while (cmd[0] == ' ') {
++cmd; ++cmd;
}
if (!(cmd[0])) { if (!(cmd[0])) {
const char *str = "You have to provide file name for ps dump\n"; const char *str = "You have to provide file name for ps dump\n";
myprintf(cs, "%s\n", str); myprintf(cs, "%s\n", str);
@ -1032,8 +1080,9 @@ static void cli_socket_input_handler_bev(struct bufferevent *bev, void *arg) {
struct cli_session *cs = (struct cli_session *)arg; struct cli_session *cs = (struct cli_session *)arg;
if (!(cs->ts)) if (!(cs->ts)) {
return; return;
}
stun_buffer buf; stun_buffer buf;
@ -1535,10 +1584,10 @@ static char *current_realm(void) {
static char *current_eff_realm(void) { static char *current_eff_realm(void) {
char *r = current_realm(); char *r = current_realm();
if (r && r[0]) if (r && r[0]) {
return r; return r;
else if (current_socket && current_socket->special_session && } else if (current_socket && current_socket->special_session &&
((struct admin_session *)current_socket->special_session)->as_ok) { ((struct admin_session *)current_socket->special_session)->as_ok) {
return ((struct admin_session *)current_socket->special_session)->as_eff_realm; return ((struct admin_session *)current_socket->special_session)->as_eff_realm;
} else { } else {
static char bad_eff_realm[1025] = "_ERROR:UNKNOWN_REALM__"; static char bad_eff_realm[1025] = "_ERROR:UNKNOWN_REALM__";
@ -1613,8 +1662,9 @@ static AS_FORM get_form(const char *path) {
if (path) { if (path) {
size_t i = 0; size_t i = 0;
while (form_names[i].name) { while (form_names[i].name) {
if (!strcmp(form_names[i].name, path)) if (!strcmp(form_names[i].name, path)) {
return form_names[i].form; return form_names[i].form;
}
++i; ++i;
} }
} }
@ -1765,8 +1815,9 @@ static void sbprintf(struct str_buffer *sb, const char *format, ...) {
static void https_print_flag(struct str_buffer *sb, int flag, const char *name, const char *param_name) { static void https_print_flag(struct str_buffer *sb, int flag, const char *name, const char *param_name) {
if (sb && name) { if (sb && name) {
if (!is_superuser()) if (!is_superuser()) {
param_name = 0; param_name = 0;
}
if (!param_name) { if (!param_name) {
sbprintf(sb, "<tr><td>%s</td><td>%s</td></tr>\r\n", name, get_flag(flag)); sbprintf(sb, "<tr><td>%s</td><td>%s</td></tr>\r\n", name, get_flag(flag));
} else { } else {
@ -1778,8 +1829,9 @@ static void https_print_flag(struct str_buffer *sb, int flag, const char *name,
static void https_print_uint(struct str_buffer *sb, unsigned long value, const char *name, const char *param_name) { static void https_print_uint(struct str_buffer *sb, unsigned long value, const char *name, const char *param_name) {
if (sb && name) { if (sb && name) {
if (!is_superuser()) if (!is_superuser()) {
param_name = 0; param_name = 0;
}
if (!param_name) { if (!param_name) {
if (value) { if (value) {
sbprintf(sb, "<tr><td>%s</td><td>%lu</td></tr>\r\n", name, value); sbprintf(sb, "<tr><td>%s</td><td>%lu</td></tr>\r\n", name, value);
@ -1804,8 +1856,9 @@ static void https_print_uint(struct str_buffer *sb, unsigned long value, const c
static void https_print_str(struct str_buffer *sb, const char *value, const char *name, const char *param_name) { static void https_print_str(struct str_buffer *sb, const char *value, const char *name, const char *param_name) {
if (sb && name && value) { if (sb && name && value) {
if (!is_superuser()) if (!is_superuser()) {
param_name = 0; param_name = 0;
}
if (!param_name) { if (!param_name) {
sbprintf(sb, "<tr><td>%s</td><td>%s</td></tr>\r\n", name, value); sbprintf(sb, "<tr><td>%s</td><td>%s</td></tr>\r\n", name, value);
} else { } else {
@ -1831,10 +1884,11 @@ static void https_print_str_array(struct str_buffer *sb, char **value, size_t sz
static void https_print_addr(struct str_buffer *sb, ioa_addr *value, int use_port, const char *name) { static void https_print_addr(struct str_buffer *sb, ioa_addr *value, int use_port, const char *name) {
if (sb && name && value) { if (sb && name && value) {
char s[256]; char s[256];
if (!use_port) if (!use_port) {
addr_to_string_no_port(value, (uint8_t *)s); addr_to_string_no_port(value, (uint8_t *)s);
else } else {
addr_to_string(value, (uint8_t *)s); addr_to_string(value, (uint8_t *)s);
}
sbprintf(sb, "<tr><td> %s</td><td> %s</td></tr>\r\n", name, s); sbprintf(sb, "<tr><td> %s</td><td> %s</td></tr>\r\n", name, s);
} }
} }
@ -1845,10 +1899,11 @@ static size_t https_print_addr_list(struct str_buffer *sb, turn_server_addrs_lis
char s[256]; char s[256];
size_t i; size_t i;
for (i = 0; i < value->size; i++) { for (i = 0; i < value->size; i++) {
if (!use_port) if (!use_port) {
addr_to_string_no_port(&(value->addrs[i]), (uint8_t *)s); addr_to_string_no_port(&(value->addrs[i]), (uint8_t *)s);
else } else {
addr_to_string(&(value->addrs[i]), (uint8_t *)s); addr_to_string(&(value->addrs[i]), (uint8_t *)s);
}
sbprintf(sb, "</tr><td> %s</td><td> %s</td></tr>\r\n", name, s); sbprintf(sb, "</tr><td> %s</td><td> %s</td></tr>\r\n", name, s);
} }
return i; return i;
@ -1864,8 +1919,9 @@ static const char *change_ip_addr_html(int dynamic, const char *kind, const char
buffer[0] = 0; buffer[0] = 0;
if (dynamic && kind && ip) { if (dynamic && kind && ip) {
if (!realm) if (!realm) {
realm = ""; realm = "";
}
if (current_realm()[0] && strcmp(current_realm(), realm)) { if (current_realm()[0] && strcmp(current_realm(), realm)) {
// delete forbidden // delete forbidden
@ -1934,8 +1990,9 @@ static void toggle_param(const char *pn) {
static void update_param(const char *pn, const char *value) { static void update_param(const char *pn, const char *value) {
if (pn) { if (pn) {
if (!value) if (!value) {
value = "0"; value = "0";
}
if (is_superuser()) { if (is_superuser()) {
if (strstr(pn, "total-quota") == pn) { if (strstr(pn, "total-quota") == pn) {
turn_params.total_quota = atoi(value); turn_params.total_quota = atoi(value);
@ -1949,8 +2006,9 @@ static void update_param(const char *pn, const char *value) {
} }
{ {
realm_params_t *rp = get_realm(current_eff_realm()); realm_params_t *rp = get_realm(current_eff_realm());
if (!rp) if (!rp) {
rp = get_realm(NULL); rp = get_realm(NULL);
}
const turn_dbdriver_t *dbd = get_dbdriver(); const turn_dbdriver_t *dbd = get_dbdriver();
if (dbd && dbd->set_realm_option_one) { if (dbd && dbd->set_realm_option_one) {
@ -2020,21 +2078,23 @@ static void write_pc_page(ioa_socket_handle s) {
https_print_empty_row(sb, 2); https_print_empty_row(sb, 2);
if (turn_params.cipher_list[0]) if (turn_params.cipher_list[0]) {
https_print_str(sb, turn_params.cipher_list, "cipher-list", 0); https_print_str(sb, turn_params.cipher_list, "cipher-list", 0);
else } else {
https_print_str(sb, DEFAULT_CIPHER_LIST, "cipher-list", 0); https_print_str(sb, DEFAULT_CIPHER_LIST, "cipher-list", 0);
}
https_print_str(sb, turn_params.ec_curve_name, "ec-curve-name", 0); https_print_str(sb, turn_params.ec_curve_name, "ec-curve-name", 0);
{ {
if (turn_params.dh_key_size == DH_CUSTOM) if (turn_params.dh_key_size == DH_CUSTOM) {
https_print_str(sb, turn_params.dh_file, "dh-file", 0); https_print_str(sb, turn_params.dh_file, "dh-file", 0);
else { } else {
unsigned int dh_key_length = 1066; unsigned int dh_key_length = 1066;
if (turn_params.dh_key_size == DH_566) if (turn_params.dh_key_size == DH_566) {
dh_key_length = 566; dh_key_length = 566;
else if (turn_params.dh_key_size == DH_2066) } else if (turn_params.dh_key_size == DH_2066) {
dh_key_length = 2066; dh_key_length = 2066;
}
https_print_uint(sb, (unsigned long)dh_key_length, "DH-key-length", 0); https_print_uint(sb, (unsigned long)dh_key_length, "DH-key-length", 0);
} }
} }
@ -2047,8 +2107,9 @@ static void write_pc_page(ioa_socket_handle s) {
https_print_str_array(sb, turn_params.listener.addrs, turn_params.listener.addrs_number, "Listener addr"); https_print_str_array(sb, turn_params.listener.addrs, turn_params.listener.addrs_number, "Listener addr");
if (turn_params.listener_ifname[0]) if (turn_params.listener_ifname[0]) {
https_print_str(sb, turn_params.listener_ifname, "listener-ifname", 0); https_print_str(sb, turn_params.listener_ifname, "listener-ifname", 0);
}
https_print_flag(sb, turn_params.no_udp, "no-udp", 0); https_print_flag(sb, turn_params.no_udp, "no-udp", 0);
https_print_flag(sb, turn_params.no_tcp, "no-tcp", 0); https_print_flag(sb, turn_params.no_tcp, "no-tcp", 0);
@ -2080,8 +2141,9 @@ static void write_pc_page(ioa_socket_handle s) {
https_print_str_array(sb, turn_params.relay_addrs, turn_params.relays_number, "Relay addr"); https_print_str_array(sb, turn_params.relay_addrs, turn_params.relays_number, "Relay addr");
if (turn_params.relay_ifname[0]) if (turn_params.relay_ifname[0]) {
https_print_str(sb, turn_params.relay_ifname, "relay-ifname", 0); https_print_str(sb, turn_params.relay_ifname, "relay-ifname", 0);
}
https_print_flag(sb, turn_params.server_relay, "server-relay", 0); https_print_flag(sb, turn_params.server_relay, "server-relay", 0);
@ -2116,10 +2178,11 @@ static void write_pc_page(ioa_socket_handle s) {
https_print_empty_row(sb, 2); https_print_empty_row(sb, 2);
if (turn_params.ct == TURN_CREDENTIALS_LONG_TERM) if (turn_params.ct == TURN_CREDENTIALS_LONG_TERM) {
https_print_flag(sb, 1, "Long-term authorization mechanism", 0); https_print_flag(sb, 1, "Long-term authorization mechanism", 0);
else } else {
https_print_flag(sb, 1, "Anonymous credentials", 0); https_print_flag(sb, 1, "Anonymous credentials", 0);
}
https_print_flag(sb, turn_params.use_auth_secret_with_timestamp, "TURN REST API support", 0); https_print_flag(sb, turn_params.use_auth_secret_with_timestamp, "TURN REST API support", 0);
if (turn_params.use_auth_secret_with_timestamp) { if (turn_params.use_auth_secret_with_timestamp) {
@ -2134,13 +2197,15 @@ static void write_pc_page(ioa_socket_handle s) {
if (is_superuser()) { if (is_superuser()) {
char *rn = get_realm(NULL)->options.name; char *rn = get_realm(NULL)->options.name;
if (rn[0]) if (rn[0]) {
https_print_str(sb, rn, "Default realm", 0); https_print_str(sb, rn, "Default realm", 0);
}
} }
realm_params_t *rp = get_realm(current_eff_realm()); realm_params_t *rp = get_realm(current_eff_realm());
if (!rp) if (!rp) {
rp = get_realm(NULL); rp = get_realm(NULL);
}
https_print_str(sb, rp->options.name, "Admin session (current) realm", 0); https_print_str(sb, rp->options.name, "Admin session (current) realm", 0);
@ -2205,8 +2270,9 @@ static int https_print_session(ur_map_key_type key, ur_map_value_type value, voi
struct str_buffer *sb = csarg->sb; struct str_buffer *sb = csarg->sb;
struct turn_session_info *tsi = (struct turn_session_info *)value; struct turn_session_info *tsi = (struct turn_session_info *)value;
if (current_eff_realm()[0] && strcmp(current_eff_realm(), tsi->realm)) if (current_eff_realm()[0] && strcmp(current_eff_realm(), tsi->realm)) {
return 0; return 0;
}
if (csarg->user_pattern[0]) { if (csarg->user_pattern[0]) {
if (!strstr((char *)tsi->username, csarg->user_pattern)) { if (!strstr((char *)tsi->username, csarg->user_pattern)) {
@ -2222,17 +2288,21 @@ static int https_print_session(ur_map_key_type key, ur_map_value_type value, voi
const char *pn = csarg->client_protocol; const char *pn = csarg->client_protocol;
if (pn[0]) { if (pn[0]) {
if (!strcmp(pn, "TLS") || !strcmp(pn, "tls") || !strcmp(pn, "Tls")) { if (!strcmp(pn, "TLS") || !strcmp(pn, "tls") || !strcmp(pn, "Tls")) {
if ((tsi->client_protocol != TLS_SOCKET) && (tsi->client_protocol != TLS_SCTP_SOCKET)) if ((tsi->client_protocol != TLS_SOCKET) && (tsi->client_protocol != TLS_SCTP_SOCKET)) {
return 0; return 0;
}
} else if (!strcmp(pn, "DTLS") || !strcmp(pn, "dtls") || !strcmp(pn, "Dtls")) { } else if (!strcmp(pn, "DTLS") || !strcmp(pn, "dtls") || !strcmp(pn, "Dtls")) {
if (tsi->client_protocol != DTLS_SOCKET) if (tsi->client_protocol != DTLS_SOCKET) {
return 0; return 0;
}
} else if (!strcmp(pn, "TCP") || !strcmp(pn, "tcp") || !strcmp(pn, "Tcp")) { } else if (!strcmp(pn, "TCP") || !strcmp(pn, "tcp") || !strcmp(pn, "Tcp")) {
if ((tsi->client_protocol != TCP_SOCKET) && (tsi->client_protocol != SCTP_SOCKET)) if ((tsi->client_protocol != TCP_SOCKET) && (tsi->client_protocol != SCTP_SOCKET)) {
return 0; return 0;
}
} else if (!strcmp(pn, "UDP") || !strcmp(pn, "udp") || !strcmp(pn, "Udp")) { } else if (!strcmp(pn, "UDP") || !strcmp(pn, "udp") || !strcmp(pn, "Udp")) {
if (tsi->client_protocol != UDP_SOCKET) if (tsi->client_protocol != UDP_SOCKET) {
return 0; return 0;
}
} else { } else {
return 0; return 0;
} }
@ -2273,14 +2343,18 @@ static int https_print_session(ur_map_key_type key, ur_map_value_type value, voi
str_buffer_append(sb, socket_type_name(tsi->peer_protocol)); str_buffer_append(sb, socket_type_name(tsi->peer_protocol));
str_buffer_append(sb, "</td><td>"); str_buffer_append(sb, "</td><td>");
{ {
if (!tsi->local_addr_data.saddr[0]) if (!tsi->local_addr_data.saddr[0]) {
addr_to_string(&(tsi->local_addr_data.addr), (uint8_t *)tsi->local_addr_data.saddr); addr_to_string(&(tsi->local_addr_data.addr), (uint8_t *)tsi->local_addr_data.saddr);
if (!tsi->remote_addr_data.saddr[0]) }
if (!tsi->remote_addr_data.saddr[0]) {
addr_to_string(&(tsi->remote_addr_data.addr), (uint8_t *)tsi->remote_addr_data.saddr); addr_to_string(&(tsi->remote_addr_data.addr), (uint8_t *)tsi->remote_addr_data.saddr);
if (!tsi->relay_addr_data_ipv4.saddr[0]) }
if (!tsi->relay_addr_data_ipv4.saddr[0]) {
addr_to_string(&(tsi->relay_addr_data_ipv4.addr), (uint8_t *)tsi->relay_addr_data_ipv4.saddr); addr_to_string(&(tsi->relay_addr_data_ipv4.addr), (uint8_t *)tsi->relay_addr_data_ipv4.saddr);
if (!tsi->relay_addr_data_ipv6.saddr[0]) }
if (!tsi->relay_addr_data_ipv6.saddr[0]) {
addr_to_string(&(tsi->relay_addr_data_ipv6.addr), (uint8_t *)tsi->relay_addr_data_ipv6.saddr); addr_to_string(&(tsi->relay_addr_data_ipv6.addr), (uint8_t *)tsi->relay_addr_data_ipv6.saddr);
}
str_buffer_append(sb, tsi->remote_addr_data.saddr); str_buffer_append(sb, tsi->remote_addr_data.saddr);
str_buffer_append(sb, "</td><td>"); str_buffer_append(sb, "</td><td>");
str_buffer_append(sb, tsi->local_addr_data.saddr); str_buffer_append(sb, tsi->local_addr_data.saddr);
@ -2319,16 +2393,18 @@ static int https_print_session(ur_map_key_type key, ur_map_value_type value, voi
if (tsi->main_peers_size) { if (tsi->main_peers_size) {
size_t i; size_t i;
for (i = 0; i < tsi->main_peers_size; ++i) { for (i = 0; i < tsi->main_peers_size; ++i) {
if (!(tsi->main_peers_data[i].saddr[0])) if (!(tsi->main_peers_data[i].saddr[0])) {
addr_to_string(&(tsi->main_peers_data[i].addr), (uint8_t *)tsi->main_peers_data[i].saddr); addr_to_string(&(tsi->main_peers_data[i].addr), (uint8_t *)tsi->main_peers_data[i].saddr);
}
str_buffer_append(sb, " "); str_buffer_append(sb, " ");
str_buffer_append(sb, tsi->main_peers_data[i].saddr); str_buffer_append(sb, tsi->main_peers_data[i].saddr);
str_buffer_append(sb, " "); str_buffer_append(sb, " ");
} }
if (tsi->extra_peers_size && tsi->extra_peers_data) { if (tsi->extra_peers_size && tsi->extra_peers_data) {
for (i = 0; i < tsi->extra_peers_size; ++i) { for (i = 0; i < tsi->extra_peers_size; ++i) {
if (!(tsi->extra_peers_data[i].saddr[0])) if (!(tsi->extra_peers_data[i].saddr[0])) {
addr_to_string(&(tsi->extra_peers_data[i].addr), (uint8_t *)tsi->extra_peers_data[i].saddr); addr_to_string(&(tsi->extra_peers_data[i].addr), (uint8_t *)tsi->extra_peers_data[i].saddr);
}
str_buffer_append(sb, " "); str_buffer_append(sb, " ");
str_buffer_append(sb, tsi->extra_peers_data[i].saddr); str_buffer_append(sb, tsi->extra_peers_data[i].saddr);
str_buffer_append(sb, " "); str_buffer_append(sb, " ");
@ -2994,8 +3070,9 @@ static void write_https_oauth_page(ioa_socket_handle s, const char *add_kid, con
str_buffer_append(sb, "<table><tr><td>"); str_buffer_append(sb, "<table><tr><td>");
{ {
if (!add_kid) if (!add_kid) {
add_kid = ""; add_kid = "";
}
str_buffer_append(sb, " <br>KID (required): <input required type=\"text\" name=\""); str_buffer_append(sb, " <br>KID (required): <input required type=\"text\" name=\"");
str_buffer_append(sb, HR_ADD_OAUTH_KID); str_buffer_append(sb, HR_ADD_OAUTH_KID);
@ -3007,8 +3084,9 @@ static void write_https_oauth_page(ioa_socket_handle s, const char *add_kid, con
str_buffer_append(sb, "</td><td>"); str_buffer_append(sb, "</td><td>");
{ {
if (!add_ts) if (!add_ts) {
add_ts = ""; add_ts = "";
}
str_buffer_append(sb, " <br>Timestamp, secs (optional): <input type=\"number\" min=\"0\" name=\""); str_buffer_append(sb, " <br>Timestamp, secs (optional): <input type=\"number\" min=\"0\" name=\"");
str_buffer_append(sb, HR_ADD_OAUTH_TS); str_buffer_append(sb, HR_ADD_OAUTH_TS);
@ -3020,8 +3098,9 @@ static void write_https_oauth_page(ioa_socket_handle s, const char *add_kid, con
str_buffer_append(sb, "</td><td>"); str_buffer_append(sb, "</td><td>");
{ {
if (!add_lt) if (!add_lt) {
add_lt = ""; add_lt = "";
}
str_buffer_append(sb, " <br>Lifetime, secs (optional): <input type=\"number\" min=\"0\" name=\""); str_buffer_append(sb, " <br>Lifetime, secs (optional): <input type=\"number\" min=\"0\" name=\"");
str_buffer_append(sb, HR_ADD_OAUTH_LT); str_buffer_append(sb, HR_ADD_OAUTH_LT);
@ -3035,8 +3114,9 @@ static void write_https_oauth_page(ioa_socket_handle s, const char *add_kid, con
str_buffer_append(sb, "<tr><td colspan=\"1\">"); str_buffer_append(sb, "<tr><td colspan=\"1\">");
{ {
if (!add_ikm) if (!add_ikm) {
add_ikm = ""; add_ikm = "";
}
str_buffer_append(sb, " <br>Base64-encoded input keying material (required):<br><textarea wrap=\"soft\" " str_buffer_append(sb, " <br>Base64-encoded input keying material (required):<br><textarea wrap=\"soft\" "
"cols=40 rows=4 name=\""); "cols=40 rows=4 name=\"");
@ -3050,8 +3130,9 @@ static void write_https_oauth_page(ioa_socket_handle s, const char *add_kid, con
str_buffer_append(sb, "</td><td>"); str_buffer_append(sb, "</td><td>");
{ {
if (!add_realm) if (!add_realm) {
add_realm = ""; add_realm = "";
}
str_buffer_append(sb, " <br>Realm (optional): <input type=\"text\" name=\""); str_buffer_append(sb, " <br>Realm (optional): <input type=\"text\" name=\"");
str_buffer_append(sb, HR_ADD_OAUTH_REALM); str_buffer_append(sb, HR_ADD_OAUTH_REALM);
@ -3065,8 +3146,9 @@ static void write_https_oauth_page(ioa_socket_handle s, const char *add_kid, con
{ {
str_buffer_append(sb, "<br>Token encryption algorithm (required):<br>\r\n"); str_buffer_append(sb, "<br>Token encryption algorithm (required):<br>\r\n");
if (!add_tea || !add_tea[0]) if (!add_tea || !add_tea[0]) {
add_tea = "A256GCM"; add_tea = "A256GCM";
}
str_buffer_append(sb, "<input type=\"radio\" name=\""); str_buffer_append(sb, "<input type=\"radio\" name=\"");
str_buffer_append(sb, HR_ADD_OAUTH_TEA); str_buffer_append(sb, HR_ADD_OAUTH_TEA);
@ -3276,8 +3358,9 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
case AS_FORM_PC: { case AS_FORM_PC: {
if (is_as_ok(s)) { if (is_as_ok(s)) {
const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm()); const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm());
if (!is_superuser()) if (!is_superuser()) {
realm0 = current_realm(); realm0 = current_realm();
}
strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE); strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE);
write_pc_page(s); write_pc_page(s);
} else { } else {
@ -3288,8 +3371,9 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
case AS_FORM_PS: { case AS_FORM_PS: {
if (is_as_ok(s)) { if (is_as_ok(s)) {
const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm()); const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm());
if (!is_superuser()) if (!is_superuser()) {
realm0 = current_realm(); realm0 = current_realm();
}
strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE); strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE);
const char *client_protocol = get_http_header_value(hr, HR_CLIENT_PROTOCOL, ""); const char *client_protocol = get_http_header_value(hr, HR_CLIENT_PROTOCOL, "");
@ -3307,13 +3391,15 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
const char *s_max_sessions = get_http_header_value(hr, HR_MAX_SESSIONS, NULL); const char *s_max_sessions = get_http_header_value(hr, HR_MAX_SESSIONS, NULL);
if (s_max_sessions) { if (s_max_sessions) {
max_sessions = strtoul(s_max_sessions, NULL, 10); max_sessions = strtoul(s_max_sessions, NULL, 10);
if (!max_sessions) if (!max_sessions) {
max_sessions = current_max_output_sessions(); max_sessions = current_max_output_sessions();
}
set_current_max_output_sessions(max_sessions); set_current_max_output_sessions(max_sessions);
} }
if (!max_sessions) if (!max_sessions) {
max_sessions = DEFAULT_CLI_MAX_OUTPUT_SESSIONS; max_sessions = DEFAULT_CLI_MAX_OUTPUT_SESSIONS;
}
write_ps_page(s, client_protocol, user_pattern, max_sessions, csid); write_ps_page(s, client_protocol, user_pattern, max_sessions, csid);
} else { } else {
@ -3325,8 +3411,9 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
if (is_as_ok(s)) { if (is_as_ok(s)) {
{ {
const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm()); const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm());
if (!is_superuser()) if (!is_superuser()) {
realm0 = current_realm(); realm0 = current_realm();
}
strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE); strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE);
} }
@ -3425,8 +3512,9 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
if (is_as_ok(s)) { if (is_as_ok(s)) {
{ {
const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm()); const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm());
if (!is_superuser()) if (!is_superuser()) {
realm0 = current_realm(); realm0 = current_realm();
}
strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE); strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE);
} }
@ -3498,8 +3586,9 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
if (is_as_ok(s)) { if (is_as_ok(s)) {
{ {
const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm()); const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm());
if (!is_superuser()) if (!is_superuser()) {
realm0 = current_realm(); realm0 = current_realm();
}
strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE); strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE);
} }
@ -3622,8 +3711,9 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
key.timestamp = (uint64_t)strtoull(add_ts, NULL, 10); key.timestamp = (uint64_t)strtoull(add_ts, NULL, 10);
} }
if (add_realm && add_realm[0]) if (add_realm && add_realm[0]) {
STRCPY(key.realm, add_realm); STRCPY(key.realm, add_realm);
}
STRCPY(key.ikm_key, add_ikm); STRCPY(key.ikm_key, add_ikm);
STRCPY(key.as_rs_alg, add_tea); STRCPY(key.as_rs_alg, add_tea);
@ -3682,8 +3772,9 @@ static void handle_https(ioa_socket_handle s, ioa_network_buffer_handle nbh) {
break; break;
default: { default: {
const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm()); const char *realm0 = get_http_header_value(hr, HR_REALM, current_realm());
if (!is_superuser()) if (!is_superuser()) {
realm0 = current_realm(); realm0 = current_realm();
}
strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE); strncpy(current_eff_realm(), realm0, STUN_MAX_REALM_SIZE);
write_https_home_page(s); write_https_home_page(s);
} }

View File

@ -137,8 +137,9 @@ static void turnports_init(turnports *tp, uint16_t start, uint16_t end) {
turnports *turnports_create(super_memory_t *sm, uint16_t start, uint16_t end) { turnports *turnports_create(super_memory_t *sm, uint16_t start, uint16_t end) {
if (start > end) if (start > end) {
return NULL; return NULL;
}
turnports *ret = (turnports *)allocate_super_memory_region(sm, sizeof(turnports)); turnports *ret = (turnports *)allocate_super_memory_region(sm, sizeof(turnports));
turnports_init(ret, start, end); turnports_init(ret, start, end);
@ -147,9 +148,9 @@ turnports *turnports_create(super_memory_t *sm, uint16_t start, uint16_t end) {
} }
uint16_t turnports_size(turnports *tp) { uint16_t turnports_size(turnports *tp) {
if (!tp) if (!tp) {
return 0; return 0;
else { } else {
TURN_MUTEX_LOCK(&tp->mutex); TURN_MUTEX_LOCK(&tp->mutex);
uint16_t ret = (uint16_t)((tp->high - tp->low)); uint16_t ret = (uint16_t)((tp->high - tp->low));
TURN_MUTEX_UNLOCK(&tp->mutex); TURN_MUTEX_UNLOCK(&tp->mutex);
@ -254,9 +255,9 @@ int turnports_allocate_even(turnports *tp, int allocate_rtcp, uint64_t *reservat
} }
int turnports_is_allocated(turnports *tp, uint16_t port) { int turnports_is_allocated(turnports *tp, uint16_t port) {
if (!tp) if (!tp) {
return 0; return 0;
else { } else {
TURN_MUTEX_LOCK(&tp->mutex); TURN_MUTEX_LOCK(&tp->mutex);
int ret = is_taken(tp->status[port]); int ret = is_taken(tp->status[port]);
TURN_MUTEX_UNLOCK(&tp->mutex); TURN_MUTEX_UNLOCK(&tp->mutex);
@ -294,8 +295,9 @@ struct _turnipports {
////////////////////////////////////////////////// //////////////////////////////////////////////////
static ur_addr_map *get_map(turnipports *tp, uint8_t transport) { static ur_addr_map *get_map(turnipports *tp, uint8_t transport) {
if (transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) if (transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) {
return &(tp->ip_to_turnports_tcp); return &(tp->ip_to_turnports_tcp);
}
return &(tp->ip_to_turnports_udp); return &(tp->ip_to_turnports_udp);
} }
////////////////////////////////////////////////// //////////////////////////////////////////////////

View File

@ -399,8 +399,9 @@ int get_user_key(int in_oauth, int *out_oauth, int *max_session_time, uint8_t *u
ioa_network_buffer_handle nbh) { ioa_network_buffer_handle nbh) {
int ret = -1; int ret = -1;
if (max_session_time) if (max_session_time) {
*max_session_time = 0; *max_session_time = 0;
}
if (in_oauth && out_oauth && usname && usname[0]) { if (in_oauth && out_oauth && usname && usname[0]) {
@ -423,11 +424,13 @@ int get_user_key(int in_oauth, int *out_oauth, int *max_session_time, uint8_t *u
memset(&rawKey, 0, sizeof(rawKey)); memset(&rawKey, 0, sizeof(rawKey));
int gres = (*(dbd->get_oauth_key))(usname, &rawKey); int gres = (*(dbd->get_oauth_key))(usname, &rawKey);
if (gres < 0) if (gres < 0) {
return ret; return ret;
}
if (!rawKey.kid[0]) if (!rawKey.kid[0]) {
return ret; return ret;
}
if (rawKey.lifetime) { if (rawKey.lifetime) {
if (!turn_time_before(turn_time(), (turn_time_t)(rawKey.timestamp + rawKey.lifetime + OAUTH_TIME_DELTA))) { if (!turn_time_before(turn_time(), (turn_time_t)(rawKey.timestamp + rawKey.lifetime + OAUTH_TIME_DELTA))) {
@ -535,8 +538,9 @@ int get_user_key(int in_oauth, int *out_oauth, int *max_session_time, uint8_t *u
init_secrets_list(&sl); init_secrets_list(&sl);
if (get_auth_secrets(&sl, realm) < 0) if (get_auth_secrets(&sl, realm) < 0) {
return ret; return ret;
}
ts = get_rest_api_timestamp((char *)usname); ts = get_rest_api_timestamp((char *)usname);
@ -550,8 +554,9 @@ int get_user_key(int in_oauth, int *out_oauth, int *max_session_time, uint8_t *u
stun_attr_ref sar = stun_attr_get_first_by_type_str( stun_attr_ref sar = stun_attr_get_first_by_type_str(
ioa_network_buffer_data(nbh), ioa_network_buffer_get_size(nbh), STUN_ATTRIBUTE_MESSAGE_INTEGRITY); ioa_network_buffer_data(nbh), ioa_network_buffer_get_size(nbh), STUN_ATTRIBUTE_MESSAGE_INTEGRITY);
if (!sar) if (!sar) {
return -1; return -1;
}
int sarlen = stun_attr_get_len(sar); int sarlen = stun_attr_get_len(sar);
switch (sarlen) { switch (sarlen) {
@ -591,8 +596,9 @@ int get_user_key(int in_oauth, int *out_oauth, int *max_session_time, uint8_t *u
} }
free(pwd); free(pwd);
if (ret == 0) if (ret == 0) {
break; break;
}
} }
} }
} }
@ -699,8 +705,9 @@ void release_allocation_quota(uint8_t *user, int oauth, uint8_t *realm) {
} }
} }
} }
if (rp->status.total_current_allocs) if (rp->status.total_current_allocs) {
--(rp->status.total_current_allocs); --(rp->status.total_current_allocs);
}
ur_string_map_unlock(rp->status.alloc_counters); ur_string_map_unlock(rp->status.alloc_counters);
free(username); free(username);
} }
@ -800,8 +807,9 @@ static int del_secret(uint8_t *secret, uint8_t *realm) {
static int set_secret(uint8_t *secret, uint8_t *realm) { static int set_secret(uint8_t *secret, uint8_t *realm) {
if (!secret || (secret[0] == 0)) if (!secret || (secret[0] == 0)) {
return 0; return 0;
}
must_set_admin_realm(realm); must_set_admin_realm(realm);
@ -851,8 +859,9 @@ static int list_origins(uint8_t *realm) {
} }
static int set_realm_option_one(uint8_t *realm, unsigned long value, const char *opt) { static int set_realm_option_one(uint8_t *realm, unsigned long value, const char *opt) {
if (value == (unsigned long)-1) if (value == (unsigned long)-1) {
return 0; return 0;
}
const turn_dbdriver_t *dbd = get_dbdriver(); const turn_dbdriver_t *dbd = get_dbdriver();
if (dbd && dbd->set_realm_option_one) { if (dbd && dbd->set_realm_option_one) {
@ -956,16 +965,19 @@ int adminuser(uint8_t *user, uint8_t *realm, uint8_t *pwd, uint8_t *secret, uint
} else if (dbd) { } else if (dbd) {
if (!is_admin) if (!is_admin) {
must_set_admin_realm(realm); must_set_admin_realm(realm);
}
if (ct == TA_DELETE_USER) { if (ct == TA_DELETE_USER) {
if (is_admin) { if (is_admin) {
if (dbd->del_admin_user) if (dbd->del_admin_user) {
(*dbd->del_admin_user)(user); (*dbd->del_admin_user)(user);
}
} else { } else {
if (dbd->del_user) if (dbd->del_user) {
(*dbd->del_user)(user, realm); (*dbd->del_user)(user, realm);
}
} }
} else if (ct == TA_UPDATE_USER) { } else if (ct == TA_UPDATE_USER) {
if (is_admin) { if (is_admin) {
@ -976,8 +988,9 @@ int adminuser(uint8_t *user, uint8_t *realm, uint8_t *pwd, uint8_t *secret, uint
(*dbd->set_admin_user)(user, realm, password); (*dbd->set_admin_user)(user, realm, password);
} }
} else { } else {
if (dbd->set_user_key) if (dbd->set_user_key) {
(*dbd->set_user_key)(user, realm, skey); (*dbd->set_user_key)(user, realm, skey);
}
} }
} }
} }
@ -1152,8 +1165,9 @@ ip_range_list_t *get_ip_list(const char *kind) {
void ip_list_free(ip_range_list_t *l) { void ip_list_free(ip_range_list_t *l) {
if (l) { if (l) {
if (l->rs) if (l->rs) {
free(l->rs); free(l->rs);
}
free(l); free(l);
} }
} }
@ -1209,16 +1223,18 @@ int add_ip_list_range(const char *range0, const char *realm, ip_range_list_t *li
addr_cpy(&max, &min); addr_cpy(&max, &min);
} }
if (separator) if (separator) {
*separator = '-'; *separator = '-';
}
++(list->ranges_number); ++(list->ranges_number);
list->rs = (ip_range_t *)realloc(list->rs, sizeof(ip_range_t) * list->ranges_number); list->rs = (ip_range_t *)realloc(list->rs, sizeof(ip_range_t) * list->ranges_number);
STRCPY(list->rs[list->ranges_number - 1].str, range); STRCPY(list->rs[list->ranges_number - 1].str, range);
if (realm) if (realm) {
STRCPY(list->rs[list->ranges_number - 1].realm, realm); STRCPY(list->rs[list->ranges_number - 1].realm, realm);
else } else {
list->rs[list->ranges_number - 1].realm[0] = 0; list->rs[list->ranges_number - 1].realm[0] = 0;
}
free(range); free(range);
ioa_addr_range_set(&(list->rs[list->ranges_number - 1].enc), &min, &max); ioa_addr_range_set(&(list->rs[list->ranges_number - 1].enc), &min, &max);
@ -1253,8 +1269,9 @@ int check_ip_list_range(const char *range0) {
addr_cpy(&max, &min); addr_cpy(&max, &min);
} }
if (separator) if (separator) {
*separator = '-'; *separator = '-';
}
free(range); free(range);

View File

@ -95,8 +95,9 @@ static int check_oauth(void) {
printf("oauth token %s:", encs[i_encs]); printf("oauth token %s:", encs[i_encs]);
if (print_extra) if (print_extra) {
printf("\n"); printf("\n");
}
oauth_token ot; oauth_token ot;
memset(&ot, 0, sizeof(ot)); memset(&ot, 0, sizeof(ot));
@ -200,8 +201,9 @@ int main(int argc, const char **argv) {
UNUSED_ARG(argc); UNUSED_ARG(argc);
UNUSED_ARG(argv); UNUSED_ARG(argv);
if (argc > 1) if (argc > 1) {
print_extra = 1; print_extra = 1;
}
set_logfile("stdout"); set_logfile("stdout");
set_no_stdout_log(1); set_no_stdout_log(1);
@ -557,8 +559,9 @@ int main(int argc, const char **argv) {
} }
{ {
if (check_oauth() < 0) if (check_oauth() < 0) {
exit(-1); exit(-1);
}
} }
return 0; return 0;

View File

@ -64,30 +64,35 @@ static int run_stunclient(const char *rip, int rport, int *port, int *rfc5780, i
int new_udp_fd = -1; int new_udp_fd = -1;
memset((void *)&remote_addr, 0, sizeof(ioa_addr)); memset((void *)&remote_addr, 0, sizeof(ioa_addr));
if (make_ioa_addr((const uint8_t *)rip, rport, &remote_addr) < 0) if (make_ioa_addr((const uint8_t *)rip, rport, &remote_addr) < 0) {
err(-1, NULL); err(-1, NULL);
}
if (udp_fd < 0) { if (udp_fd < 0) {
udp_fd = socket(remote_addr.ss.sa_family, SOCK_DGRAM, 0); udp_fd = socket(remote_addr.ss.sa_family, SOCK_DGRAM, 0);
if (udp_fd < 0) if (udp_fd < 0) {
err(-1, NULL); err(-1, NULL);
}
if (!addr_any(&real_local_addr)) { if (!addr_any(&real_local_addr)) {
if (addr_bind(udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) if (addr_bind(udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
} }
if (response_port >= 0) { if (response_port >= 0) {
new_udp_fd = socket(remote_addr.ss.sa_family, SOCK_DGRAM, 0); new_udp_fd = socket(remote_addr.ss.sa_family, SOCK_DGRAM, 0);
if (new_udp_fd < 0) if (new_udp_fd < 0) {
err(-1, NULL); err(-1, NULL);
}
addr_set_port(&real_local_addr, response_port); addr_set_port(&real_local_addr, response_port);
if (addr_bind(new_udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) if (addr_bind(new_udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
turn::StunMsgRequest req(STUN_METHOD_BINDING); turn::StunMsgRequest req(STUN_METHOD_BINDING);
@ -152,8 +157,9 @@ static int run_stunclient(const char *rip, int rport, int *port, int *rfc5780, i
len = sendto(udp_fd, req.getRawBuffer(), req.getSize(), 0, (struct sockaddr *)&remote_addr, (socklen_t)slen); len = sendto(udp_fd, req.getRawBuffer(), req.getSize(), 0, (struct sockaddr *)&remote_addr, (socklen_t)slen);
} while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain())); } while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain()));
if (len < 0) if (len < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
if (addr_get_from_sock(udp_fd, &real_local_addr) < 0) { if (addr_get_from_sock(udp_fd, &real_local_addr) < 0) {
@ -186,8 +192,9 @@ static int run_stunclient(const char *rip, int rport, int *port, int *rfc5780, i
} }
} while (len < 0 && socket_eintr()); } while (len < 0 && socket_eintr());
if (recvd > 0) if (recvd > 0) {
len = recvd; len = recvd;
}
buf.len = len; buf.len = len;
try { try {
@ -259,30 +266,35 @@ static int run_stunclient(const char *rip, int rport, int *port, int *rfc5780, i
stun_buffer buf; stun_buffer buf;
memset(&remote_addr, 0, sizeof(remote_addr)); memset(&remote_addr, 0, sizeof(remote_addr));
if (make_ioa_addr((const uint8_t *)rip, rport, &remote_addr) < 0) if (make_ioa_addr((const uint8_t *)rip, rport, &remote_addr) < 0) {
err(-1, NULL); err(-1, NULL);
}
if (udp_fd < 0) { if (udp_fd < 0) {
udp_fd = socket(remote_addr.ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL); udp_fd = socket(remote_addr.ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL);
if (udp_fd < 0) if (udp_fd < 0) {
err(-1, NULL); err(-1, NULL);
}
if (!addr_any(&real_local_addr)) { if (!addr_any(&real_local_addr)) {
if (addr_bind(udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) if (addr_bind(udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
} }
if (response_port >= 0) { if (response_port >= 0) {
new_udp_fd = socket(remote_addr.ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL); new_udp_fd = socket(remote_addr.ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL);
if (new_udp_fd < 0) if (new_udp_fd < 0) {
err(-1, NULL); err(-1, NULL);
}
addr_set_port(&real_local_addr, response_port); addr_set_port(&real_local_addr, response_port);
if (addr_bind(new_udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) if (addr_bind(new_udp_fd, &real_local_addr, 0, 1, UDP_SOCKET) < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
stun_prepare_binding_request(&buf); stun_prepare_binding_request(&buf);
@ -307,8 +319,9 @@ static int run_stunclient(const char *rip, int rport, int *port, int *rfc5780, i
len = sendto(udp_fd, buf.buf, buf.len, 0, (struct sockaddr *)&remote_addr, (socklen_t)slen); len = sendto(udp_fd, buf.buf, buf.len, 0, (struct sockaddr *)&remote_addr, (socklen_t)slen);
} while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain())); } while (len < 0 && (socket_eintr() || socket_enobufs() || socket_eagain()));
if (len < 0) if (len < 0) {
err(-1, NULL); err(-1, NULL);
}
} }
if (addr_get_from_sock(udp_fd, &real_local_addr) < 0) { if (addr_get_from_sock(udp_fd, &real_local_addr) < 0) {
@ -340,8 +353,9 @@ static int run_stunclient(const char *rip, int rport, int *port, int *rfc5780, i
} }
} while (len < 0 && (socket_eintr() || socket_eagain())); } while (len < 0 && (socket_eintr() || socket_eagain()));
if (recvd > 0) if (recvd > 0) {
len = recvd; len = recvd;
}
buf.len = len; buf.len = len;
if (stun_is_command_message(&buf)) { if (stun_is_command_message(&buf)) {
@ -417,8 +431,9 @@ int main(int argc, char **argv) {
int c = 0; int c = 0;
int forceRfc5780 = 0; int forceRfc5780 = 0;
if (socket_init()) if (socket_init()) {
return -1; return -1;
}
set_logfile("stdout"); set_logfile("stdout");
set_no_stdout_log(1); set_no_stdout_log(1);

View File

@ -443,14 +443,16 @@ int main(int argc, char **argv) {
} }
if (port == 0) { if (port == 0) {
if (use_secure) if (use_secure) {
port = DEFAULT_STUN_TLS_PORT; port = DEFAULT_STUN_TLS_PORT;
else } else {
port = DEFAULT_STUN_PORT; port = DEFAULT_STUN_PORT;
}
} }
if (clmessage_length < (int)sizeof(message_info)) if (clmessage_length < (int)sizeof(message_info)) {
clmessage_length = (int)sizeof(message_info); clmessage_length = (int)sizeof(message_info);
}
const int max_header = 100; const int max_header = 100;
if (clmessage_length > (int)(STUN_BUFFER_SIZE - max_header)) { if (clmessage_length > (int)(STUN_BUFFER_SIZE - max_header)) {
@ -488,10 +490,11 @@ int main(int argc, char **argv) {
OpenSSL_add_ssl_algorithms(); OpenSSL_add_ssl_algorithms();
const char *csuite = "ALL"; //"AES256-SHA" "DH" const char *csuite = "ALL"; //"AES256-SHA" "DH"
if (use_null_cipher) if (use_null_cipher) {
csuite = "eNULL"; csuite = "eNULL";
else if (cipher_suite[0]) } else if (cipher_suite[0]) {
csuite = cipher_suite; csuite = cipher_suite;
}
if (use_tcp) { if (use_tcp) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L #if OPENSSL_VERSION_NUMBER < 0x10100000L

View File

@ -58,24 +58,27 @@ static const size_t kALPNProtosLen = sizeof(kALPNProtos) - 1;
///////////////////////////////////////// /////////////////////////////////////////
int rare_event(void) { int rare_event(void) {
if (dos) if (dos) {
return (((unsigned long)turn_random()) % 1000 == 777); return (((unsigned long)turn_random()) % 1000 == 777);
}
return 0; return 0;
} }
int not_rare_event(void) { int not_rare_event(void) {
if (dos) if (dos) {
return ((((unsigned long)turn_random()) % 1000) < 200); return ((((unsigned long)turn_random()) % 1000) < 200);
}
return 0; return 0;
} }
static int get_allocate_address_family(ioa_addr *relay_addr) { static int get_allocate_address_family(ioa_addr *relay_addr) {
if (relay_addr->ss.sa_family == AF_INET) if (relay_addr->ss.sa_family == AF_INET) {
return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT; return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT;
else if (relay_addr->ss.sa_family == AF_INET6) } else if (relay_addr->ss.sa_family == AF_INET6) {
return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6;
else } else {
return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_INVALID; return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_INVALID;
}
} }
///////////////////////////////////////// /////////////////////////////////////////
@ -122,8 +125,9 @@ static SSL *tls_connect(ioa_socket_raw fd, ioa_addr *remote_addr, int *try_again
SSL_set_max_cert_list(ssl, 655350); SSL_set_max_cert_list(ssl, 655350);
if (clnet_verbose) if (clnet_verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "call SSL_connect...\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "call SSL_connect...\n");
}
int rc = 0; int rc = 0;
@ -152,8 +156,9 @@ static SSL *tls_connect(ioa_socket_raw fd, ioa_addr *remote_addr, int *try_again
switch (SSL_get_error(ssl, rc)) { switch (SSL_get_error(ssl, rc)) {
case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_WRITE:
if (!dos) if (!dos) {
usleep(1000); usleep(1000);
}
continue; continue;
default: { default: {
char buf[1025]; char buf[1025];
@ -188,10 +193,12 @@ static SSL *tls_connect(ioa_socket_raw fd, ioa_addr *remote_addr, int *try_again
int socket_connect(evutil_socket_t clnet_fd, ioa_addr *remote_addr, int *connect_err) { int socket_connect(evutil_socket_t clnet_fd, ioa_addr *remote_addr, int *connect_err) {
if (addr_connect(clnet_fd, remote_addr, connect_err) < 0) { if (addr_connect(clnet_fd, remote_addr, connect_err) < 0) {
if (*connect_err == EINPROGRESS) if (*connect_err == EINPROGRESS) {
return 0; return 0;
if (*connect_err == EADDRINUSE) }
if (*connect_err == EADDRINUSE) {
return +1; return +1;
}
perror("connect"); perror("connect");
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: cannot connect to remote addr: %d\n", __FUNCTION__, *connect_err); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: cannot connect to remote addr: %d\n", __FUNCTION__, *connect_err);
exit(-1); exit(-1);
@ -216,8 +223,9 @@ start_socket:
connect_err = 0; connect_err = 0;
memset(&remote_addr, 0, sizeof(ioa_addr)); memset(&remote_addr, 0, sizeof(ioa_addr));
if (make_ioa_addr((const uint8_t *)remote_address, clnet_remote_port, &remote_addr) < 0) if (make_ioa_addr((const uint8_t *)remote_address, clnet_remote_port, &remote_addr) < 0) {
return -1; return -1;
}
memset(&local_addr, 0, sizeof(ioa_addr)); memset(&local_addr, 0, sizeof(ioa_addr));
@ -268,8 +276,9 @@ start_socket:
if (clnet_info->is_peer) { if (clnet_info->is_peer) {
; ;
} else if (socket_connect(clnet_fd, &remote_addr, &connect_err) > 0) } else if (socket_connect(clnet_fd, &remote_addr, &connect_err) > 0) {
goto start_socket; goto start_socket;
}
if (clnet_info) { if (clnet_info) {
addr_cpy(&(clnet_info->remote_addr), &remote_addr); addr_cpy(&(clnet_info->remote_addr), &remote_addr);
@ -298,8 +307,9 @@ start_socket:
addr_debug_print(verbose, &remote_addr, "Connected to"); addr_debug_print(verbose, &remote_addr, "Connected to");
} }
if (!dos) if (!dos) {
usleep(500); usleep(500);
}
return 0; return 0;
} }
@ -315,8 +325,9 @@ int read_mobility_ticket(app_ur_conn_info *clnet_info, stun_buffer *message) {
if (smid_val) { if (smid_val) {
memcpy(clnet_info->s_mobile_id, smid_val, (size_t)smid_len); memcpy(clnet_info->s_mobile_id, smid_val, (size_t)smid_len);
clnet_info->s_mobile_id[smid_len] = 0; clnet_info->s_mobile_id[smid_len] = 0;
if (clnet_verbose) if (clnet_verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: smid=%s\n", __FUNCTION__, clnet_info->s_mobile_id); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: smid=%s\n", __FUNCTION__, clnet_info->s_mobile_id);
}
} }
} else { } else {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: ERROR: smid_len=%d\n", __FUNCTION__, smid_len); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: ERROR: smid_len=%d\n", __FUNCTION__, smid_len);
@ -388,23 +399,27 @@ beg_allocate:
ep = ep - 1; ep = ep - 1;
} }
if (!dos) if (!dos) {
stun_set_allocate_request(&request_message, UCLIENT_SESSION_LIFETIME, af4, af6, relay_transport, mobility, rt, stun_set_allocate_request(&request_message, UCLIENT_SESSION_LIFETIME, af4, af6, relay_transport, mobility, rt,
ep); ep);
else } else {
stun_set_allocate_request(&request_message, UCLIENT_SESSION_LIFETIME / 3, af4, af6, relay_transport, mobility, rt, stun_set_allocate_request(&request_message, UCLIENT_SESSION_LIFETIME / 3, af4, af6, relay_transport, mobility, rt,
ep); ep);
}
if (bps) if (bps) {
stun_attr_add_bandwidth_str(request_message.buf, (size_t *)(&(request_message.len)), bps); stun_attr_add_bandwidth_str(request_message.buf, (size_t *)(&(request_message.len)), bps);
}
if (dont_fragment) if (dont_fragment) {
stun_attr_add(&request_message, STUN_ATTRIBUTE_DONT_FRAGMENT, NULL, 0); stun_attr_add(&request_message, STUN_ATTRIBUTE_DONT_FRAGMENT, NULL, 0);
}
add_origin(&request_message); add_origin(&request_message);
if (add_integrity(clnet_info, &request_message) < 0) if (add_integrity(clnet_info, &request_message) < 0) {
return -1; return -1;
}
stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len)); stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len));
@ -425,8 +440,9 @@ beg_allocate:
////////////<<==allocate send ////////////<<==allocate send
if (not_rare_event()) if (not_rare_event()) {
return 0; return 0;
}
////////allocate response==>> ////////allocate response==>>
{ {
@ -447,8 +463,9 @@ beg_allocate:
allocate_finished = 1; allocate_finished = 1;
if (clnet_info->nonce[0]) { if (clnet_info->nonce[0]) {
if (check_integrity(clnet_info, &response_message) < 0) if (check_integrity(clnet_info, &response_message) < 0) {
return -1; return -1;
}
} }
if (verbose) { if (verbose) {
@ -504,8 +521,9 @@ beg_allocate:
stun_attr_ref rt_sar = stun_attr_get_first_by_type(&response_message, STUN_ATTRIBUTE_RESERVATION_TOKEN); stun_attr_ref rt_sar = stun_attr_get_first_by_type(&response_message, STUN_ATTRIBUTE_RESERVATION_TOKEN);
uint64_t rtv = stun_attr_get_reservation_token_value(rt_sar); uint64_t rtv = stun_attr_get_reservation_token_value(rt_sar);
current_reservation_token = rtv; current_reservation_token = rtv;
if (verbose) if (verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: rtv=%llu\n", __FUNCTION__, (long long unsigned int)rtv); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: rtv=%llu\n", __FUNCTION__, (long long unsigned int)rtv);
}
read_mobility_ticket(clnet_info, &response_message); read_mobility_ticket(clnet_info, &response_message);
@ -520,8 +538,9 @@ beg_allocate:
if (err_code == 300) { if (err_code == 300) {
if (clnet_info->nonce[0]) { if (clnet_info->nonce[0]) {
if (check_integrity(clnet_info, &response_message) < 0) if (check_integrity(clnet_info, &response_message) < 0) {
return -1; return -1;
}
} }
ioa_addr alternate_server; ioa_addr alternate_server;
@ -558,8 +577,9 @@ beg_allocate:
} }
////////////<<== allocate response received ////////////<<== allocate response received
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (!allocate_finished) { if (!allocate_finished) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot complete Allocation\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "Cannot complete Allocation\n");
@ -647,8 +667,9 @@ beg_allocate:
add_origin(&request_message); add_origin(&request_message);
if (add_integrity(clnet_info, &request_message) < 0) if (add_integrity(clnet_info, &request_message) < 0) {
return -1; return -1;
}
stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len)); stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len));
@ -673,8 +694,9 @@ beg_allocate:
} }
} }
if (not_rare_event()) if (not_rare_event()) {
return 0; return 0;
}
////////refresh response==>> ////////refresh response==>>
{ {
@ -728,10 +750,7 @@ static int turn_channel_bind(int verbose, uint16_t *chn, app_ur_conn_info *clnet
stun_buffer request_message, response_message; stun_buffer request_message, response_message;
beg_bind : beg_bind:
{
int cb_sent = 0;
if (negative_test) { if (negative_test) {
*chn = stun_set_channel_bind_request(&request_message, peer_addr, (uint16_t)turn_random()); *chn = stun_set_channel_bind_request(&request_message, peer_addr, (uint16_t)turn_random());
@ -741,11 +760,14 @@ beg_bind :
add_origin(&request_message); add_origin(&request_message);
if (add_integrity(clnet_info, &request_message) < 0) if (add_integrity(clnet_info, &request_message) < 0) {
return -1; return -1;
}
stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len)); stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len));
int cb_sent = 0;
while (!cb_sent) { while (!cb_sent) {
int len = send_buffer(clnet_info, &request_message, 0, 0); int len = send_buffer(clnet_info, &request_message, 0, 0);
@ -759,12 +781,12 @@ beg_bind :
exit(1); exit(1);
} }
} }
}
////////////<<==channel bind send ////////////<<==channel bind send
if (not_rare_event()) if (not_rare_event()) {
return 0; return 0;
}
////////channel bind response==>> ////////channel bind response==>>
@ -784,8 +806,9 @@ beg_bind :
cb_received = 1; cb_received = 1;
if (clnet_info->nonce[0]) { if (clnet_info->nonce[0]) {
if (check_integrity(clnet_info, &response_message) < 0) if (check_integrity(clnet_info, &response_message) < 0) {
return -1; return -1;
}
} }
if (verbose) { if (verbose) {
@ -816,8 +839,9 @@ beg_bind :
static int turn_create_permission(int verbose, app_ur_conn_info *clnet_info, ioa_addr *peer_addr, int addrnum) { static int turn_create_permission(int verbose, app_ur_conn_info *clnet_info, ioa_addr *peer_addr, int addrnum) {
if (no_permissions || (addrnum < 1)) if (no_permissions || (addrnum < 1)) {
return 0; return 0;
}
char saddr[129] = "\0"; char saddr[129] = "\0";
if (verbose) { if (verbose) {
@ -826,10 +850,7 @@ static int turn_create_permission(int verbose, app_ur_conn_info *clnet_info, ioa
stun_buffer request_message, response_message; stun_buffer request_message, response_message;
beg_cp : beg_cp:
{
int cp_sent = 0;
stun_init_request(STUN_METHOD_CREATE_PERMISSION, &request_message); stun_init_request(STUN_METHOD_CREATE_PERMISSION, &request_message);
{ {
@ -841,11 +862,14 @@ beg_cp :
add_origin(&request_message); add_origin(&request_message);
if (add_integrity(clnet_info, &request_message) < 0) if (add_integrity(clnet_info, &request_message) < 0) {
return -1; return -1;
}
stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len)); stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len));
int cp_sent = 0;
while (!cp_sent) { while (!cp_sent) {
int len = send_buffer(clnet_info, &request_message, 0, 0); int len = send_buffer(clnet_info, &request_message, 0, 0);
@ -860,12 +884,12 @@ beg_cp :
exit(1); exit(1);
} }
} }
}
////////////<<==create permission send ////////////<<==create permission send
if (not_rare_event()) if (not_rare_event()) {
return 0; return 0;
}
////////create permission response==>> ////////create permission response==>>
@ -885,8 +909,9 @@ beg_cp :
cp_received = 1; cp_received = 1;
if (clnet_info->nonce[0]) { if (clnet_info->nonce[0]) {
if (check_integrity(clnet_info, &response_message) < 0) if (check_integrity(clnet_info, &response_message) < 0) {
return -1; return -1;
}
} }
if (verbose) { if (verbose) {
@ -941,8 +966,9 @@ int start_connection(uint16_t clnet_remote_port0, const char *remote_address0, c
/* Real: */ /* Real: */
*chn = 0; *chn = 0;
if (chn_rtcp) if (chn_rtcp) {
*chn_rtcp = 0; *chn_rtcp = 0;
}
if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info) < 0) { if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info) < 0) {
exit(-1); exit(-1);
@ -959,16 +985,18 @@ int start_connection(uint16_t clnet_remote_port0, const char *remote_address0, c
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (!no_rtcp) { if (!no_rtcp) {
af = default_address_family ? default_address_family : get_allocate_address_family(&peer_addr_rtcp); af = default_address_family ? default_address_family : get_allocate_address_family(&peer_addr_rtcp);
if (clnet_allocate(verbose, clnet_info_rtcp, &relay_addr_rtcp, af, NULL, NULL) < 0) { if (clnet_allocate(verbose, clnet_info_rtcp, &relay_addr_rtcp, af, NULL, NULL) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
} }
if (!dos) { if (!dos) {
@ -978,31 +1006,36 @@ int start_connection(uint16_t clnet_remote_port0, const char *remote_address0, c
if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr_rtcp) < 0) { if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr_rtcp) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr_rtcp) < 0) { if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr_rtcp) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
*chn = 0; *chn = 0;
if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr) < 0) { if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr) < 0) { if (turn_channel_bind(verbose, chn, clnet_info, &peer_addr) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (extra_requests) { if (extra_requests) {
const char *sarbaddr = "164.156.178.190"; const char *sarbaddr = "164.156.178.190";
if (turn_random() % 2 == 0) if (turn_random() % 2 == 0) {
sarbaddr = "2001::172"; sarbaddr = "2001::172";
}
ioa_addr arbaddr; ioa_addr arbaddr;
make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr); make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr);
int i; int i;
@ -1010,8 +1043,9 @@ int start_connection(uint16_t clnet_remote_port0, const char *remote_address0, c
for (i = 0; i < maxi; i++) { for (i = 0; i < maxi; i++) {
uint16_t chni = 0; uint16_t chni = 0;
int port = (unsigned short)turn_random(); int port = (unsigned short)turn_random();
if (port < 1024) if (port < 1024) {
port += 1024; port += 1024;
}
addr_set_port(&arbaddr, port); addr_set_port(&arbaddr, port);
uint8_t *u = (uint8_t *)&(arbaddr.s4.sin_addr); uint8_t *u = (uint8_t *)&(arbaddr.s4.sin_addr);
u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1; u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1;
@ -1027,20 +1061,23 @@ int start_connection(uint16_t clnet_remote_port0, const char *remote_address0, c
exit(-1); exit(-1);
} }
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (extra_requests) { if (extra_requests) {
const char *sarbaddr = "64.56.78.90"; const char *sarbaddr = "64.56.78.90";
if (turn_random() % 2 == 0) if (turn_random() % 2 == 0) {
sarbaddr = "2001::172"; sarbaddr = "2001::172";
}
ioa_addr arbaddr[EXTRA_CREATE_PERMS]; ioa_addr arbaddr[EXTRA_CREATE_PERMS];
make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr[0]); make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr[0]);
int i; int i;
int maxi = (unsigned short)turn_random() % EXTRA_CREATE_PERMS; int maxi = (unsigned short)turn_random() % EXTRA_CREATE_PERMS;
for (i = 0; i < maxi; i++) { for (i = 0; i < maxi; i++) {
if (i > 0) if (i > 0) {
addr_cpy(&arbaddr[i], &arbaddr[0]); addr_cpy(&arbaddr[i], &arbaddr[0]);
}
addr_set_port(&arbaddr[i], (unsigned short)turn_random()); addr_set_port(&arbaddr[i], (unsigned short)turn_random());
uint8_t *u = (uint8_t *)&(arbaddr[i].s4.sin_addr); uint8_t *u = (uint8_t *)&(arbaddr[i].s4.sin_addr);
u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1; u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1;
@ -1058,26 +1095,30 @@ int start_connection(uint16_t clnet_remote_port0, const char *remote_address0, c
if (turn_create_permission(verbose, clnet_info, &peer_addr, 1) < 0) { if (turn_create_permission(verbose, clnet_info, &peer_addr, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (turn_create_permission(verbose, clnet_info, &peer_addr_rtcp, 1) < 0) { if (turn_create_permission(verbose, clnet_info, &peer_addr_rtcp, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
} }
if (extra_requests) { if (extra_requests) {
const char *sarbaddr = "64.56.78.90"; const char *sarbaddr = "64.56.78.90";
if (turn_random() % 2 == 0) if (turn_random() % 2 == 0) {
sarbaddr = "2001::172"; sarbaddr = "2001::172";
}
ioa_addr arbaddr[EXTRA_CREATE_PERMS]; ioa_addr arbaddr[EXTRA_CREATE_PERMS];
make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr[0]); make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr[0]);
int i; int i;
int maxi = (unsigned short)turn_random() % EXTRA_CREATE_PERMS; int maxi = (unsigned short)turn_random() % EXTRA_CREATE_PERMS;
for (i = 0; i < maxi; i++) { for (i = 0; i < maxi; i++) {
if (i > 0) if (i > 0) {
addr_cpy(&arbaddr[i], &arbaddr[0]); addr_cpy(&arbaddr[i], &arbaddr[0]);
}
addr_set_port(&arbaddr[i], (unsigned short)turn_random()); addr_set_port(&arbaddr[i], (unsigned short)turn_random());
uint8_t *u = (uint8_t *)&(arbaddr[i].s4.sin_addr); uint8_t *u = (uint8_t *)&(arbaddr[i].s4.sin_addr);
u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1; u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1;
@ -1092,33 +1133,38 @@ int start_connection(uint16_t clnet_remote_port0, const char *remote_address0, c
if (turn_create_permission(verbose, clnet_info, &peer_addr, 1) < 0) { if (turn_create_permission(verbose, clnet_info, &peer_addr, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (turn_create_permission(verbose, clnet_info, &peer_addr_rtcp, 1) < 0) { if (turn_create_permission(verbose, clnet_info, &peer_addr_rtcp, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
} }
if (!no_rtcp) { if (!no_rtcp) {
if (turn_create_permission(verbose, clnet_info_rtcp, &peer_addr_rtcp, 1) < 0) { if (turn_create_permission(verbose, clnet_info_rtcp, &peer_addr_rtcp, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (turn_create_permission(verbose, clnet_info_rtcp, &peer_addr, 1) < 0) { if (turn_create_permission(verbose, clnet_info_rtcp, &peer_addr, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
} }
} }
} }
addr_cpy(&(clnet_info->peer_addr), &peer_addr); addr_cpy(&(clnet_info->peer_addr), &peer_addr);
if (!no_rtcp) if (!no_rtcp) {
addr_cpy(&(clnet_info_rtcp->peer_addr), &peer_addr_rtcp); addr_cpy(&(clnet_info_rtcp->peer_addr), &peer_addr_rtcp);
}
return 0; return 0;
} }
@ -1137,10 +1183,12 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
*chn1 = 0; *chn1 = 0;
*chn2 = 0; *chn2 = 0;
if (chn1_rtcp) if (chn1_rtcp) {
*chn1_rtcp = 0; *chn1_rtcp = 0;
if (chn2_rtcp) }
if (chn2_rtcp) {
*chn2_rtcp = 0; *chn2_rtcp = 0;
}
/* Probe: */ /* Probe: */
@ -1154,8 +1202,9 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
clnet_allocate(verbose, clnet_info_probe, &relay_addr1, default_address_family, remote_address, &clnet_remote_port); clnet_allocate(verbose, clnet_info_probe, &relay_addr1, default_address_family, remote_address, &clnet_remote_port);
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
/* Real: */ /* Real: */
@ -1163,22 +1212,25 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
exit(-1); exit(-1);
} }
if (!no_rtcp) if (!no_rtcp) {
if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info1_rtcp) < 0) { if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info1_rtcp) < 0) {
exit(-1); exit(-1);
} }
}
if (passive_tcp) if (passive_tcp) {
clnet_info2->is_peer = 1; clnet_info2->is_peer = 1;
}
if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info2) < 0) { if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info2) < 0) {
exit(-1); exit(-1);
} }
if (!no_rtcp) if (!no_rtcp) {
if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info2_rtcp) < 0) { if (clnet_connect(clnet_remote_port, remote_address, ifname, local_address, verbose, clnet_info2_rtcp) < 0) {
exit(-1); exit(-1);
} }
}
if (!no_rtcp) { if (!no_rtcp) {
@ -1186,42 +1238,48 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (clnet_allocate(verbose, clnet_info1_rtcp, &relay_addr1_rtcp, default_address_family, NULL, NULL) < 0) { if (clnet_allocate(verbose, clnet_info1_rtcp, &relay_addr1_rtcp, default_address_family, NULL, NULL) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (clnet_allocate(verbose, clnet_info2, &relay_addr2, default_address_family, NULL, NULL) < 0) { if (clnet_allocate(verbose, clnet_info2, &relay_addr2, default_address_family, NULL, NULL) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (clnet_allocate(verbose, clnet_info2_rtcp, &relay_addr2_rtcp, default_address_family, NULL, NULL) < 0) { if (clnet_allocate(verbose, clnet_info2_rtcp, &relay_addr2_rtcp, default_address_family, NULL, NULL) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
} else { } else {
if (clnet_allocate(verbose, clnet_info1, &relay_addr1, default_address_family, NULL, NULL) < 0) { if (clnet_allocate(verbose, clnet_info1, &relay_addr1, default_address_family, NULL, NULL) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (!(clnet_info2->is_peer)) { if (!(clnet_info2->is_peer)) {
if (clnet_allocate(verbose, clnet_info2, &relay_addr2, default_address_family, NULL, NULL) < 0) { if (clnet_allocate(verbose, clnet_info2, &relay_addr2, default_address_family, NULL, NULL) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
} else { } else {
addr_cpy(&(clnet_info2->remote_addr), &relay_addr1); addr_cpy(&(clnet_info2->remote_addr), &relay_addr1);
addr_cpy(&relay_addr2, &(clnet_info2->local_addr)); addr_cpy(&relay_addr2, &(clnet_info2->local_addr));
@ -1235,8 +1293,9 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
if (extra_requests) { if (extra_requests) {
const char *sarbaddr = "164.156.178.190"; const char *sarbaddr = "164.156.178.190";
if (turn_random() % 2 == 0) if (turn_random() % 2 == 0) {
sarbaddr = "2001::172"; sarbaddr = "2001::172";
}
ioa_addr arbaddr; ioa_addr arbaddr;
make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr); make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr);
int i; int i;
@ -1244,8 +1303,9 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
for (i = 0; i < maxi; i++) { for (i = 0; i < maxi; i++) {
uint16_t chni = 0; uint16_t chni = 0;
int port = (unsigned short)turn_random(); int port = (unsigned short)turn_random();
if (port < 1024) if (port < 1024) {
port += 1024; port += 1024;
}
addr_set_port(&arbaddr, port); addr_set_port(&arbaddr, port);
uint8_t *u = (uint8_t *)&(arbaddr.s4.sin_addr); uint8_t *u = (uint8_t *)&(arbaddr.s4.sin_addr);
u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1; u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1;
@ -1256,20 +1316,23 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
} }
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
if (extra_requests) { if (extra_requests) {
const char *sarbaddr = "64.56.78.90"; const char *sarbaddr = "64.56.78.90";
if (turn_random() % 2 == 0) if (turn_random() % 2 == 0) {
sarbaddr = "2001::172"; sarbaddr = "2001::172";
}
ioa_addr arbaddr[EXTRA_CREATE_PERMS]; ioa_addr arbaddr[EXTRA_CREATE_PERMS];
make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr[0]); make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr[0]);
int i; int i;
int maxi = (unsigned short)turn_random() % EXTRA_CREATE_PERMS; int maxi = (unsigned short)turn_random() % EXTRA_CREATE_PERMS;
for (i = 0; i < maxi; i++) { for (i = 0; i < maxi; i++) {
if (i > 0) if (i > 0) {
addr_cpy(&arbaddr[i], &arbaddr[0]); addr_cpy(&arbaddr[i], &arbaddr[0]);
}
addr_set_port(&arbaddr[i], (unsigned short)turn_random()); addr_set_port(&arbaddr[i], (unsigned short)turn_random());
uint8_t *u = (uint8_t *)&(arbaddr[i].s4.sin_addr); uint8_t *u = (uint8_t *)&(arbaddr[i].s4.sin_addr);
u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1; u[(unsigned short)turn_random() % 4] = u[(unsigned short)turn_random() % 4] + 1;
@ -1280,23 +1343,28 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
turn_create_permission(verbose, clnet_info1, arbaddr, maxi); turn_create_permission(verbose, clnet_info1, arbaddr, maxi);
} }
if (!no_rtcp) if (!no_rtcp) {
if (turn_channel_bind(verbose, chn1_rtcp, clnet_info1_rtcp, &relay_addr2_rtcp) < 0) { if (turn_channel_bind(verbose, chn1_rtcp, clnet_info1_rtcp, &relay_addr2_rtcp) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) }
if (rare_event()) {
return 0; return 0;
}
if (turn_channel_bind(verbose, chn2, clnet_info2, &relay_addr1) < 0) { if (turn_channel_bind(verbose, chn2, clnet_info2, &relay_addr1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
if (!no_rtcp) }
if (!no_rtcp) {
if (turn_channel_bind(verbose, chn2_rtcp, clnet_info2_rtcp, &relay_addr1_rtcp) < 0) { if (turn_channel_bind(verbose, chn2_rtcp, clnet_info2_rtcp, &relay_addr1_rtcp) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) }
if (rare_event()) {
return 0; return 0;
}
} else { } else {
if (turn_create_permission(verbose, clnet_info1, &relay_addr2, 1) < 0) { if (turn_create_permission(verbose, clnet_info1, &relay_addr2, 1) < 0) {
@ -1305,8 +1373,9 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
if (extra_requests) { if (extra_requests) {
const char *sarbaddr = "64.56.78.90"; const char *sarbaddr = "64.56.78.90";
if (turn_random() % 2 == 0) if (turn_random() % 2 == 0) {
sarbaddr = "2001::172"; sarbaddr = "2001::172";
}
ioa_addr arbaddr; ioa_addr arbaddr;
make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr); make_ioa_addr((const uint8_t *)sarbaddr, 333, &arbaddr);
int i; int i;
@ -1322,35 +1391,43 @@ int start_c2c_connection(uint16_t clnet_remote_port0, const char *remote_address
} }
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
if (!no_rtcp) }
if (!no_rtcp) {
if (turn_create_permission(verbose, clnet_info1_rtcp, &relay_addr2_rtcp, 1) < 0) { if (turn_create_permission(verbose, clnet_info1_rtcp, &relay_addr2_rtcp, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) }
if (rare_event()) {
return 0; return 0;
}
if (!(clnet_info2->is_peer)) { if (!(clnet_info2->is_peer)) {
if (turn_create_permission(verbose, clnet_info2, &relay_addr1, 1) < 0) { if (turn_create_permission(verbose, clnet_info2, &relay_addr1, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) if (rare_event()) {
return 0; return 0;
}
} }
if (!no_rtcp) if (!no_rtcp) {
if (turn_create_permission(verbose, clnet_info2_rtcp, &relay_addr1_rtcp, 1) < 0) { if (turn_create_permission(verbose, clnet_info2_rtcp, &relay_addr1_rtcp, 1) < 0) {
exit(-1); exit(-1);
} }
if (rare_event()) }
if (rare_event()) {
return 0; return 0;
}
} }
addr_cpy(&(clnet_info1->peer_addr), &relay_addr2); addr_cpy(&(clnet_info1->peer_addr), &relay_addr2);
if (!no_rtcp) if (!no_rtcp) {
addr_cpy(&(clnet_info1_rtcp->peer_addr), &relay_addr2_rtcp); addr_cpy(&(clnet_info1_rtcp->peer_addr), &relay_addr2_rtcp);
}
addr_cpy(&(clnet_info2->peer_addr), &relay_addr1); addr_cpy(&(clnet_info2->peer_addr), &relay_addr1);
if (!no_rtcp) if (!no_rtcp) {
addr_cpy(&(clnet_info2_rtcp->peer_addr), &relay_addr1_rtcp); addr_cpy(&(clnet_info2_rtcp->peer_addr), &relay_addr1_rtcp);
}
return 0; return 0;
} }
@ -1369,8 +1446,9 @@ int turn_tcp_connect(int verbose, app_ur_conn_info *clnet_info, ioa_addr *peer_a
add_origin(&message); add_origin(&message);
if (add_integrity(clnet_info, &message) < 0) if (add_integrity(clnet_info, &message) < 0) {
return -1; return -1;
}
stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len)); stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len));
@ -1399,24 +1477,24 @@ static int turn_tcp_connection_bind(int verbose, app_ur_conn_info *clnet_info, a
stun_buffer request_message, response_message; stun_buffer request_message, response_message;
beg_cb : beg_cb:
{
int cb_sent = 0;
uint32_t cid = atc->cid;
stun_init_request(STUN_METHOD_CONNECTION_BIND, &request_message); stun_init_request(STUN_METHOD_CONNECTION_BIND, &request_message);
uint32_t cid = atc->cid;
stun_attr_add(&request_message, STUN_ATTRIBUTE_CONNECTION_ID, (const char *)&cid, 4); stun_attr_add(&request_message, STUN_ATTRIBUTE_CONNECTION_ID, (const char *)&cid, 4);
add_origin(&request_message); add_origin(&request_message);
if (add_integrity(clnet_info, &request_message) < 0) if (add_integrity(clnet_info, &request_message) < 0) {
return -1; return -1;
}
stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len)); stun_attr_add_fingerprint_str(request_message.buf, (size_t *)&(request_message.len));
int cb_sent = 0;
while (!cb_sent) { while (!cb_sent) {
int len = send_buffer(clnet_info, &request_message, 1, atc); int len = send_buffer(clnet_info, &request_message, 1, atc);
@ -1427,18 +1505,19 @@ beg_cb :
} }
cb_sent = 1; cb_sent = 1;
} else { } else {
if (errorOK) if (errorOK) {
return 0; return 0;
}
perror("send"); perror("send");
exit(1); exit(1);
} }
} }
}
////////////<<==connection bind send ////////////<<==connection bind send
if (not_rare_event()) if (not_rare_event()) {
return 0; return 0;
}
////////connection bind response==>> ////////connection bind response==>>
@ -1456,12 +1535,14 @@ beg_cb :
if (stun_is_success_response(&response_message)) { if (stun_is_success_response(&response_message)) {
if (clnet_info->nonce[0]) { if (clnet_info->nonce[0]) {
if (check_integrity(clnet_info, &response_message) < 0) if (check_integrity(clnet_info, &response_message) < 0) {
return -1; return -1;
}
} }
if (stun_get_method(&response_message) != STUN_METHOD_CONNECTION_BIND) if (stun_get_method(&response_message) != STUN_METHOD_CONNECTION_BIND) {
continue; continue;
}
cb_received = 1; cb_received = 1;
if (verbose) { if (verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success\n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "success\n");
@ -1480,8 +1561,9 @@ beg_cb :
/* Try again ? */ /* Try again ? */
} }
} else { } else {
if (errorOK) if (errorOK) {
return 0; return 0;
}
perror("recv"); perror("recv");
exit(-1); exit(-1);
} }

View File

@ -96,10 +96,12 @@ static void __turn_getMSTime(void) {
#else #else
tp.tv_sec = time(NULL); tp.tv_sec = time(NULL);
#endif #endif
if (!start_sec) if (!start_sec) {
start_sec = tp.tv_sec; start_sec = tp.tv_sec;
if (current_time != (uint64_t)((uint64_t)(tp.tv_sec) - start_sec)) }
if (current_time != (uint64_t)((uint64_t)(tp.tv_sec) - start_sec)) {
show_statistics = 1; show_statistics = 1;
}
current_time = (uint64_t)((uint64_t)(tp.tv_sec) - start_sec); current_time = (uint64_t)((uint64_t)(tp.tv_sec) - start_sec);
current_mstime = (uint64_t)((current_time * 1000) + (tp.tv_nsec / 1000000)); current_mstime = (uint64_t)((current_time * 1000) + (tp.tv_nsec / 1000000));
} }
@ -251,8 +253,9 @@ int send_buffer(app_ur_conn_info *clnet_info, stun_buffer *message, int data_con
break; break;
case SSL_ERROR_SYSCALL: case SSL_ERROR_SYSCALL:
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Socket write error 111.666: \n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Socket write error 111.666: \n");
if (handle_socket_error()) if (handle_socket_error()) {
break; break;
}
/* Falls through. */ /* Falls through. */
case SSL_ERROR_SSL: { case SSL_ERROR_SSL: {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n");
@ -286,8 +289,9 @@ int send_buffer(app_ur_conn_info *clnet_info, stun_buffer *message, int data_con
} }
} }
if (left > 0) if (left > 0) {
return -1; return -1;
}
ret = (int)message->len; ret = (int)message->len;
} }
@ -304,8 +308,9 @@ static int wait_fd(int fd, unsigned int cycle) {
FD_ZERO(&fds); FD_ZERO(&fds);
FD_SET(fd, &fds); FD_SET(fd, &fds);
if (dos && cycle == 0) if (dos && cycle == 0) {
return 0; return 0;
}
struct timeval start_time; struct timeval start_time;
struct timeval ctime; struct timeval ctime;
@ -323,8 +328,9 @@ static int wait_fd(int fd, unsigned int cycle) {
} else { } else {
timeout.tv_sec = 1; timeout.tv_sec = 1;
while (--cycle) while (--cycle) {
timeout.tv_sec = timeout.tv_sec + timeout.tv_sec; timeout.tv_sec = timeout.tv_sec + timeout.tv_sec;
}
if (ctime.tv_sec > start_time.tv_sec) { if (ctime.tv_sec > start_time.tv_sec) {
if (ctime.tv_sec >= start_time.tv_sec + timeout.tv_sec) { if (ctime.tv_sec >= start_time.tv_sec + timeout.tv_sec) {
@ -360,12 +366,14 @@ int recv_buffer(app_ur_conn_info *clnet_info, stun_buffer *message, int sync, in
} }
ioa_socket_raw fd = clnet_info->fd; ioa_socket_raw fd = clnet_info->fd;
if (atc) if (atc) {
fd = atc->tcp_data_fd; fd = atc->tcp_data_fd;
}
SSL *ssl = clnet_info->ssl; SSL *ssl = clnet_info->ssl;
if (atc) if (atc) {
ssl = atc->tcp_data_ssl; ssl = atc->tcp_data_ssl;
}
recv_again: recv_again:
@ -374,13 +382,15 @@ recv_again:
unsigned int cycle = 0; unsigned int cycle = 0;
while (cycle < MAX_LISTENING_CYCLE_NUMBER) { while (cycle < MAX_LISTENING_CYCLE_NUMBER) {
int serc = wait_fd(fd, cycle); int serc = wait_fd(fd, cycle);
if (serc > 0) if (serc > 0) {
break; break;
}
if (serc < 0) { if (serc < 0) {
return -1; return -1;
} }
if (send_buffer(clnet_info, request_message, data_connection, atc) <= 0) if (send_buffer(clnet_info, request_message, data_connection, atc) <= 0) {
return -1; return -1;
}
++cycle; ++cycle;
} }
} }
@ -407,14 +417,16 @@ recv_again:
int cycle = 0; int cycle = 0;
while (!message_received && cycle++ < 100) { while (!message_received && cycle++ < 100) {
if (SSL_get_shutdown(ssl)) if (SSL_get_shutdown(ssl)) {
return -1; return -1;
}
rc = 0; rc = 0;
do { do {
rc = SSL_read(ssl, message->buf, sizeof(message->buf) - 1); rc = SSL_read(ssl, message->buf, sizeof(message->buf) - 1);
if (rc < 0 && socket_eagain() && sync) if (rc < 0 && socket_eagain() && sync) {
continue; continue;
}
} while (rc < 0 && socket_eintr()); } while (rc < 0 && socket_eintr());
if (rc > 0) { if (rc > 0) {
@ -444,8 +456,9 @@ recv_again:
break; break;
case SSL_ERROR_SYSCALL: case SSL_ERROR_SYSCALL:
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Socket read error 111.999: \n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Socket read error 111.999: \n");
if (handle_socket_error()) if (handle_socket_error()) {
break; break;
}
/* Falls through. */ /* Falls through. */
case SSL_ERROR_SSL: { case SSL_ERROR_SSL: {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n");
@ -460,8 +473,9 @@ recv_again:
return -1; return -1;
} }
if (!sync) if (!sync) {
break; break;
}
} }
} }
@ -473,13 +487,15 @@ recv_again:
int cycle = 0; int cycle = 0;
while (!message_received && cycle++ < 100) { while (!message_received && cycle++ < 100) {
if (SSL_get_shutdown(ssl)) if (SSL_get_shutdown(ssl)) {
return -1; return -1;
}
rc = 0; rc = 0;
do { do {
rc = SSL_read(ssl, message->buf, sizeof(message->buf) - 1); rc = SSL_read(ssl, message->buf, sizeof(message->buf) - 1);
if (rc < 0 && socket_eagain() && sync) if (rc < 0 && socket_eagain() && sync) {
continue; continue;
}
} while (rc < 0 && socket_eintr()); } while (rc < 0 && socket_eintr());
if (rc > 0) { if (rc > 0) {
@ -509,8 +525,9 @@ recv_again:
break; break;
case SSL_ERROR_SYSCALL: case SSL_ERROR_SYSCALL:
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Socket read error 111.999: \n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Socket read error 111.999: \n");
if (handle_socket_error()) if (handle_socket_error()) {
break; break;
}
/* Falls through. */ /* Falls through. */
case SSL_ERROR_SSL: { case SSL_ERROR_SSL: {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n"); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n");
@ -525,8 +542,9 @@ recv_again:
return -1; return -1;
} }
if (!sync) if (!sync) {
break; break;
}
} }
} }
@ -544,11 +562,13 @@ recv_again:
if (!atc) { if (!atc) {
mlen = stun_get_message_len_str(message->buf, rc, 1, &app_msg_len); mlen = stun_get_message_len_str(message->buf, rc, 1, &app_msg_len);
} else { } else {
if (!sync) if (!sync) {
mlen = clmessage_length; mlen = clmessage_length;
}
if (mlen > clmessage_length) if (mlen > clmessage_length) {
mlen = clmessage_length; mlen = clmessage_length;
}
app_msg_len = (size_t)mlen; app_msg_len = (size_t)mlen;
} }
@ -563,12 +583,14 @@ recv_again:
rcr = recv(fd, message->buf + rsf, (size_t)mlen - (size_t)rsf, 0); rcr = recv(fd, message->buf + rsf, (size_t)mlen - (size_t)rsf, 0);
} while (rcr < 0 && (socket_eintr() || (socket_eagain() && sync))); } while (rcr < 0 && (socket_eintr() || (socket_eagain() && sync)));
if (rcr > 0) if (rcr > 0) {
rsf += rcr; rsf += rcr;
}
} }
if (rsf < 1) if (rsf < 1) {
return -1; return -1;
}
if (rsf < (int)app_msg_len) { if (rsf < (int)app_msg_len) {
if ((size_t)(app_msg_len / (size_t)rsf) * ((size_t)(rsf)) != app_msg_len) { if ((size_t)(app_msg_len / (size_t)rsf) * ((size_t)(rsf)) != app_msg_len) {
@ -613,11 +635,13 @@ recv_again:
static int client_read(app_ur_session *elem, int is_tcp_data, app_tcp_conn_info *atc) { static int client_read(app_ur_session *elem, int is_tcp_data, app_tcp_conn_info *atc) {
if (!elem) if (!elem) {
return -1; return -1;
}
if (elem->state != UR_STATE_READY) if (elem->state != UR_STATE_READY) {
return -1; return -1;
}
elem->ctime = current_time; elem->ctime = current_time;
@ -706,8 +730,9 @@ static int client_read(app_ur_session *elem, int is_tcp_data, app_tcp_conn_info
} else if (stun_is_success_response(&(elem->in_buffer))) { } else if (stun_is_success_response(&(elem->in_buffer))) {
if (elem->pinfo.nonce[0]) { if (elem->pinfo.nonce[0]) {
if (check_integrity(&(elem->pinfo), &(elem->in_buffer)) < 0) if (check_integrity(&(elem->pinfo), &(elem->in_buffer)) < 0) {
return -1; return -1;
}
} }
if (is_TCP_relay() && (stun_get_method(&(elem->in_buffer)) == STUN_METHOD_CONNECT)) { if (is_TCP_relay() && (stun_get_method(&(elem->in_buffer)) == STUN_METHOD_CONNECT)) {
@ -764,22 +789,26 @@ static int client_read(app_ur_session *elem, int is_tcp_data, app_tcp_conn_info
printf("%s: 111.111: msgnum=%d, rmsgnum=%d, sent=%lu, recv=%lu\n",__FUNCTION__, printf("%s: 111.111: msgnum=%d, rmsgnum=%d, sent=%lu, recv=%lu\n",__FUNCTION__,
mi->msgnum,elem->recvmsgnum,(unsigned long)mi->mstime,(unsigned long)current_mstime); mi->msgnum,elem->recvmsgnum,(unsigned long)mi->mstime,(unsigned long)current_mstime);
*/ */
if (mi.msgnum != elem->recvmsgnum + 1) if (mi.msgnum != elem->recvmsgnum + 1) {
++(elem->loss); ++(elem->loss);
else { } else {
uint64_t clatency = (uint64_t)time_minus(current_mstime, mi.mstime); uint64_t clatency = (uint64_t)time_minus(current_mstime, mi.mstime);
if (clatency > max_latency) if (clatency > max_latency) {
max_latency = clatency; max_latency = clatency;
if (clatency < min_latency) }
if (clatency < min_latency) {
min_latency = clatency; min_latency = clatency;
}
elem->latency += clatency; elem->latency += clatency;
if (elem->rmsgnum > 0) { if (elem->rmsgnum > 0) {
uint64_t cjitter = abs((int)(current_mstime - elem->recvtimems) - RTP_PACKET_INTERVAL); uint64_t cjitter = abs((int)(current_mstime - elem->recvtimems) - RTP_PACKET_INTERVAL);
if (cjitter > max_jitter) if (cjitter > max_jitter) {
max_jitter = cjitter; max_jitter = cjitter;
if (cjitter < min_jitter) }
if (cjitter < min_jitter) {
min_jitter = cjitter; min_jitter = cjitter;
}
elem->jitter += cjitter; elem->jitter += cjitter;
} }
@ -790,10 +819,11 @@ static int client_read(app_ur_session *elem, int is_tcp_data, app_tcp_conn_info
elem->rmsgnum += buffers; elem->rmsgnum += buffers;
tot_recv_messages += buffers; tot_recv_messages += buffers;
if (applen > 0) if (applen > 0) {
tot_recv_bytes += applen; tot_recv_bytes += applen;
else } else {
tot_recv_bytes += elem->in_buffer.len; tot_recv_bytes += elem->in_buffer.len;
}
elem->recvtimems = current_mstime; elem->recvtimems = current_mstime;
elem->wait_cycles = 0; elem->wait_cycles = 0;
@ -808,8 +838,9 @@ static int client_read(app_ur_session *elem, int is_tcp_data, app_tcp_conn_info
static int client_shutdown(app_ur_session *elem) { static int client_shutdown(app_ur_session *elem) {
if (!elem) if (!elem) {
return -1; return -1;
}
elem->state = UR_STATE_DONE; elem->state = UR_STATE_DONE;
@ -817,19 +848,22 @@ static int client_shutdown(app_ur_session *elem) {
remove_all_from_ss(elem); remove_all_from_ss(elem);
if (clnet_verbose) if (clnet_verbose) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "done, connection 0x%lx closed.\n", (long)elem); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "done, connection 0x%lx closed.\n", (long)elem);
}
return 0; return 0;
} }
static int client_write(app_ur_session *elem) { static int client_write(app_ur_session *elem) {
if (!elem) if (!elem) {
return -1; return -1;
}
if (elem->state != UR_STATE_READY) if (elem->state != UR_STATE_READY) {
return -1; return -1;
}
elem->ctime = current_time; elem->ctime = current_time;
@ -870,11 +904,13 @@ static int client_write(app_ur_session *elem) {
stun_init_indication(STUN_METHOD_SEND, &(elem->out_buffer)); stun_init_indication(STUN_METHOD_SEND, &(elem->out_buffer));
stun_attr_add(&(elem->out_buffer), STUN_ATTRIBUTE_DATA, buffer_to_send, clmessage_length); stun_attr_add(&(elem->out_buffer), STUN_ATTRIBUTE_DATA, buffer_to_send, clmessage_length);
stun_attr_add_addr(&(elem->out_buffer), STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(elem->pinfo.peer_addr)); stun_attr_add_addr(&(elem->out_buffer), STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(elem->pinfo.peer_addr));
if (dont_fragment) if (dont_fragment) {
stun_attr_add(&(elem->out_buffer), STUN_ATTRIBUTE_DONT_FRAGMENT, NULL, 0); stun_attr_add(&(elem->out_buffer), STUN_ATTRIBUTE_DONT_FRAGMENT, NULL, 0);
}
if (use_fingerprints) if (use_fingerprints) {
stun_attr_add_fingerprint_str(elem->out_buffer.buf, (size_t *)&(elem->out_buffer.len)); stun_attr_add_fingerprint_str(elem->out_buffer.buf, (size_t *)&(elem->out_buffer.len));
}
} }
if (elem->out_buffer.len > 0) { if (elem->out_buffer.len > 0) {
@ -904,8 +940,9 @@ static int client_write(app_ur_session *elem) {
void client_input_handler(evutil_socket_t fd, short what, void *arg) { void client_input_handler(evutil_socket_t fd, short what, void *arg) {
if (!(what & EV_READ) || !arg) if (!(what & EV_READ) || !arg) {
return; return;
}
UNUSED_ARG(fd); UNUSED_ARG(fd);
@ -932,8 +969,9 @@ void client_input_handler(evutil_socket_t fd, short what, void *arg) {
} }
} }
int rc = client_read(elem, is_tcp_data, atc); int rc = client_read(elem, is_tcp_data, atc);
if (rc <= 0) if (rc <= 0) {
break; break;
}
} while (1); } while (1);
break; break;
@ -965,8 +1003,9 @@ static int start_client(const char *remote_address, int port, const unsigned cha
app_ur_session *ss = create_new_ss(); app_ur_session *ss = create_new_ss();
app_ur_session *ss_rtcp = NULL; app_ur_session *ss_rtcp = NULL;
if (!no_rtcp) if (!no_rtcp) {
ss_rtcp = create_new_ss(); ss_rtcp = create_new_ss();
}
app_ur_conn_info clnet_info_probe; /* for load balancing probe */ app_ur_conn_info clnet_info_probe; /* for load balancing probe */
memset(&clnet_info_probe, 0, sizeof(clnet_info_probe)); memset(&clnet_info_probe, 0, sizeof(clnet_info_probe));
@ -975,8 +1014,9 @@ static int start_client(const char *remote_address, int port, const unsigned cha
app_ur_conn_info *clnet_info = &(ss->pinfo); app_ur_conn_info *clnet_info = &(ss->pinfo);
app_ur_conn_info *clnet_info_rtcp = NULL; app_ur_conn_info *clnet_info_rtcp = NULL;
if (!no_rtcp) if (!no_rtcp) {
clnet_info_rtcp = &(ss_rtcp->pinfo); clnet_info_rtcp = &(ss_rtcp->pinfo);
}
uint16_t chnum = 0; uint16_t chnum = 0;
uint16_t chnum_rtcp = 0; uint16_t chnum_rtcp = 0;
@ -994,8 +1034,9 @@ static int start_client(const char *remote_address, int port, const unsigned cha
socket_set_nonblocking(clnet_info->fd); socket_set_nonblocking(clnet_info->fd);
if (!no_rtcp) if (!no_rtcp) {
socket_set_nonblocking(clnet_info_rtcp->fd); socket_set_nonblocking(clnet_info_rtcp->fd);
}
struct event *ev = event_new(client_event_base, clnet_info->fd, EV_READ | EV_PERSIST, client_input_handler, ss); struct event *ev = event_new(client_event_base, clnet_info->fd, EV_READ | EV_PERSIST, client_input_handler, ss);
@ -1022,8 +1063,9 @@ static int start_client(const char *remote_address, int port, const unsigned cha
ss_rtcp->input_ev = ev_rtcp; ss_rtcp->input_ev = ev_rtcp;
ss_rtcp->tot_msgnum = ss->tot_msgnum; ss_rtcp->tot_msgnum = ss->tot_msgnum;
if (ss_rtcp->tot_msgnum < 1) if (ss_rtcp->tot_msgnum < 1) {
ss_rtcp->tot_msgnum = 1; ss_rtcp->tot_msgnum = 1;
}
ss_rtcp->recvmsgnum = -1; ss_rtcp->recvmsgnum = -1;
ss_rtcp->chnum = chnum_rtcp; ss_rtcp->chnum = chnum_rtcp;
} }
@ -1032,8 +1074,9 @@ static int start_client(const char *remote_address, int port, const unsigned cha
refresh_channel(ss, 0, 600); refresh_channel(ss, 0, 600);
if (!no_rtcp) if (!no_rtcp) {
elems[i + 1] = ss_rtcp; elems[i + 1] = ss_rtcp;
}
return 0; return 0;
} }
@ -1044,14 +1087,16 @@ static int start_c2c(const char *remote_address, int port, const unsigned char *
app_ur_session *ss1 = create_new_ss(); app_ur_session *ss1 = create_new_ss();
app_ur_session *ss1_rtcp = NULL; app_ur_session *ss1_rtcp = NULL;
if (!no_rtcp) if (!no_rtcp) {
ss1_rtcp = create_new_ss(); ss1_rtcp = create_new_ss();
}
app_ur_session *ss2 = create_new_ss(); app_ur_session *ss2 = create_new_ss();
app_ur_session *ss2_rtcp = NULL; app_ur_session *ss2_rtcp = NULL;
if (!no_rtcp) if (!no_rtcp) {
ss2_rtcp = create_new_ss(); ss2_rtcp = create_new_ss();
}
app_ur_conn_info clnet_info_probe; /* for load balancing probe */ app_ur_conn_info clnet_info_probe; /* for load balancing probe */
memset(&clnet_info_probe, 0, sizeof(clnet_info_probe)); memset(&clnet_info_probe, 0, sizeof(clnet_info_probe));
@ -1060,14 +1105,16 @@ static int start_c2c(const char *remote_address, int port, const unsigned char *
app_ur_conn_info *clnet_info1 = &(ss1->pinfo); app_ur_conn_info *clnet_info1 = &(ss1->pinfo);
app_ur_conn_info *clnet_info1_rtcp = NULL; app_ur_conn_info *clnet_info1_rtcp = NULL;
if (!no_rtcp) if (!no_rtcp) {
clnet_info1_rtcp = &(ss1_rtcp->pinfo); clnet_info1_rtcp = &(ss1_rtcp->pinfo);
}
app_ur_conn_info *clnet_info2 = &(ss2->pinfo); app_ur_conn_info *clnet_info2 = &(ss2->pinfo);
app_ur_conn_info *clnet_info2_rtcp = NULL; app_ur_conn_info *clnet_info2_rtcp = NULL;
if (!no_rtcp) if (!no_rtcp) {
clnet_info2_rtcp = &(ss2_rtcp->pinfo); clnet_info2_rtcp = &(ss2_rtcp->pinfo);
}
uint16_t chnum1 = 0; uint16_t chnum1 = 0;
uint16_t chnum1_rtcp = 0; uint16_t chnum1_rtcp = 0;
@ -1087,13 +1134,15 @@ static int start_c2c(const char *remote_address, int port, const unsigned char *
socket_set_nonblocking(clnet_info1->fd); socket_set_nonblocking(clnet_info1->fd);
if (!no_rtcp) if (!no_rtcp) {
socket_set_nonblocking(clnet_info1_rtcp->fd); socket_set_nonblocking(clnet_info1_rtcp->fd);
}
socket_set_nonblocking(clnet_info2->fd); socket_set_nonblocking(clnet_info2->fd);
if (!no_rtcp) if (!no_rtcp) {
socket_set_nonblocking(clnet_info2_rtcp->fd); socket_set_nonblocking(clnet_info2_rtcp->fd);
}
struct event *ev1 = event_new(client_event_base, clnet_info1->fd, EV_READ | EV_PERSIST, client_input_handler, ss1); struct event *ev1 = event_new(client_event_base, clnet_info1->fd, EV_READ | EV_PERSIST, client_input_handler, ss1);
@ -1132,8 +1181,9 @@ static int start_c2c(const char *remote_address, int port, const unsigned char *
ss1_rtcp->input_ev = ev1_rtcp; ss1_rtcp->input_ev = ev1_rtcp;
ss1_rtcp->tot_msgnum = ss1->tot_msgnum; ss1_rtcp->tot_msgnum = ss1->tot_msgnum;
if (ss1_rtcp->tot_msgnum < 1) if (ss1_rtcp->tot_msgnum < 1) {
ss1_rtcp->tot_msgnum = 1; ss1_rtcp->tot_msgnum = 1;
}
ss1_rtcp->recvmsgnum = -1; ss1_rtcp->recvmsgnum = -1;
ss1_rtcp->chnum = chnum1_rtcp; ss1_rtcp->chnum = chnum1_rtcp;
} }
@ -1155,11 +1205,13 @@ static int start_c2c(const char *remote_address, int port, const unsigned char *
} }
elems[i++] = ss1; elems[i++] = ss1;
if (!no_rtcp) if (!no_rtcp) {
elems[i++] = ss1_rtcp; elems[i++] = ss1_rtcp;
}
elems[i++] = ss2; elems[i++] = ss2;
if (!no_rtcp) if (!no_rtcp) {
elems[i++] = ss2_rtcp; elems[i++] = ss2_rtcp;
}
return 0; return 0;
} }
@ -1169,8 +1221,9 @@ static int refresh_channel(app_ur_session *elem, uint16_t method, uint32_t lt) {
stun_buffer message; stun_buffer message;
app_ur_conn_info *clnet_info = &(elem->pinfo); app_ur_conn_info *clnet_info = &(elem->pinfo);
if (clnet_info->is_peer) if (clnet_info->is_peer) {
return 0; return 0;
}
if (!method || (method == STUN_METHOD_REFRESH)) { if (!method || (method == STUN_METHOD_REFRESH)) {
stun_init_request(STUN_METHOD_REFRESH, &message); stun_init_request(STUN_METHOD_REFRESH, &message);
@ -1191,10 +1244,12 @@ static int refresh_channel(app_ur_session *elem, uint16_t method, uint32_t lt) {
} }
add_origin(&message); add_origin(&message);
if (add_integrity(clnet_info, &message) < 0) if (add_integrity(clnet_info, &message) < 0) {
return -1; return -1;
if (use_fingerprints) }
if (use_fingerprints) {
stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len)); stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len));
}
send_buffer(clnet_info, &message, 0, 0); send_buffer(clnet_info, &message, 0, 0);
} }
@ -1205,10 +1260,12 @@ static int refresh_channel(app_ur_session *elem, uint16_t method, uint32_t lt) {
stun_init_request(STUN_METHOD_CREATE_PERMISSION, &message); stun_init_request(STUN_METHOD_CREATE_PERMISSION, &message);
stun_attr_add_addr(&message, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(elem->pinfo.peer_addr)); stun_attr_add_addr(&message, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(elem->pinfo.peer_addr));
add_origin(&message); add_origin(&message);
if (add_integrity(clnet_info, &message) < 0) if (add_integrity(clnet_info, &message) < 0) {
return -1; return -1;
if (use_fingerprints) }
if (use_fingerprints) {
stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len)); stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len));
}
send_buffer(&(elem->pinfo), &message, 0, 0); send_buffer(&(elem->pinfo), &message, 0, 0);
} }
} }
@ -1217,10 +1274,12 @@ static int refresh_channel(app_ur_session *elem, uint16_t method, uint32_t lt) {
if (STUN_VALID_CHANNEL(elem->chnum)) { if (STUN_VALID_CHANNEL(elem->chnum)) {
stun_set_channel_bind_request(&message, &(elem->pinfo.peer_addr), elem->chnum); stun_set_channel_bind_request(&message, &(elem->pinfo.peer_addr), elem->chnum);
add_origin(&message); add_origin(&message);
if (add_integrity(clnet_info, &message) < 0) if (add_integrity(clnet_info, &message) < 0) {
return -1; return -1;
if (use_fingerprints) }
if (use_fingerprints) {
stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len)); stun_attr_add_fingerprint_str(message.buf, (size_t *)&(message.len));
}
send_buffer(&(elem->pinfo), &message, 1, 0); send_buffer(&(elem->pinfo), &message, 1, 0);
} }
} }
@ -1237,15 +1296,17 @@ static inline int client_timer_handler(app_ur_session *elem, int *done) {
refresh_channel(elem, 0, 600); refresh_channel(elem, 0, 600);
} }
if (hang_on && elem->completed) if (hang_on && elem->completed) {
return 0; return 0;
}
int max_num = 50; int max_num = 50;
int cur_num = 0; int cur_num = 0;
while (!turn_time_before(current_mstime, elem->to_send_timems)) { while (!turn_time_before(current_mstime, elem->to_send_timems)) {
if (cur_num++ >= max_num) if (cur_num++ >= max_num) {
break; break;
}
if (elem->wmsgnum >= elem->tot_msgnum) { if (elem->wmsgnum >= elem->tot_msgnum) {
if (!turn_time_before(current_mstime, elem->finished_time) || (tot_recv_messages >= tot_messages)) { if (!turn_time_before(current_mstime, elem->finished_time) || (tot_recv_messages >= tot_messages)) {
/* /*
@ -1316,21 +1377,25 @@ static void timer_handler(evutil_socket_t fd, short event, void *arg) {
void start_mclient(const char *remote_address, int port, const unsigned char *ifname, const char *local_address, void start_mclient(const char *remote_address, int port, const unsigned char *ifname, const char *local_address,
int messagenumber, int mclient) { int messagenumber, int mclient) {
if (mclient < 1) if (mclient < 1) {
mclient = 1; mclient = 1;
}
total_clients = mclient; total_clients = mclient;
if (c2c) { if (c2c) {
// mclient must be a multiple of 4: // mclient must be a multiple of 4:
if (!no_rtcp) if (!no_rtcp) {
mclient += ((4 - (mclient & 0x00000003)) & 0x00000003); mclient += ((4 - (mclient & 0x00000003)) & 0x00000003);
else if (mclient & 0x1) } else if (mclient & 0x1) {
++mclient; ++mclient;
}
} else { } else {
if (!no_rtcp) if (!no_rtcp) {
if (mclient & 0x1) if (mclient & 0x1) {
++mclient; ++mclient;
}
}
} }
elems = (app_ur_session **)malloc(sizeof(app_ur_session) * ((mclient * 2) + 1) + sizeof(void *)); elems = (app_ur_session **)malloc(sizeof(app_ur_session) * ((mclient * 2) + 1) + sizeof(void *));
@ -1346,47 +1411,54 @@ void start_mclient(const char *remote_address, int port, const unsigned char *if
int tot_clients = 0; int tot_clients = 0;
if (c2c) { if (c2c) {
if (!no_rtcp) if (!no_rtcp) {
for (i = 0; i < (mclient >> 2); i++) { for (i = 0; i < (mclient >> 2); i++) {
if (!dos) if (!dos) {
usleep(SLEEP_INTERVAL); usleep(SLEEP_INTERVAL);
}
if (start_c2c(remote_address, port, ifname, local_address, messagenumber, i << 2) < 0) { if (start_c2c(remote_address, port, ifname, local_address, messagenumber, i << 2) < 0) {
exit(-1); exit(-1);
} }
tot_clients += 4; tot_clients += 4;
} }
else } else {
for (i = 0; i < (mclient >> 1); i++) { for (i = 0; i < (mclient >> 1); i++) {
if (!dos) if (!dos) {
usleep(SLEEP_INTERVAL); usleep(SLEEP_INTERVAL);
}
if (start_c2c(remote_address, port, ifname, local_address, messagenumber, i << 1) < 0) { if (start_c2c(remote_address, port, ifname, local_address, messagenumber, i << 1) < 0) {
exit(-1); exit(-1);
} }
tot_clients += 2; tot_clients += 2;
} }
}
} else { } else {
if (!no_rtcp) if (!no_rtcp) {
for (i = 0; i < (mclient >> 1); i++) { for (i = 0; i < (mclient >> 1); i++) {
if (!dos) if (!dos) {
usleep(SLEEP_INTERVAL); usleep(SLEEP_INTERVAL);
}
if (start_client(remote_address, port, ifname, local_address, messagenumber, i << 1) < 0) { if (start_client(remote_address, port, ifname, local_address, messagenumber, i << 1) < 0) {
exit(-1); exit(-1);
} }
tot_clients += 2; tot_clients += 2;
} }
else } else {
for (i = 0; i < mclient; i++) { for (i = 0; i < mclient; i++) {
if (!dos) if (!dos) {
usleep(SLEEP_INTERVAL); usleep(SLEEP_INTERVAL);
}
if (start_client(remote_address, port, ifname, local_address, messagenumber, i) < 0) { if (start_client(remote_address, port, ifname, local_address, messagenumber, i) < 0) {
exit(-1); exit(-1);
} }
tot_clients++; tot_clients++;
} }
}
} }
if (dos) if (dos) {
_exit(0); _exit(0);
}
total_clients = tot_clients; total_clients = tot_clients;
@ -1439,8 +1511,9 @@ void start_mclient(const char *remote_address, int port, const unsigned char *if
completed += elems[i]->pinfo.tcp_conn_number; completed += elems[i]->pinfo.tcp_conn_number;
} }
} }
if (completed >= total_clients) if (completed >= total_clients) {
break; break;
}
} else { } else {
for (i = 0; i < total_clients; ++i) { for (i = 0; i < total_clients; ++i) {
int j = 0; int j = 0;
@ -1498,11 +1571,13 @@ void start_mclient(const char *remote_address, int port, const unsigned char *if
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: tot_send_bytes ~ %lu, tot_recv_bytes ~ %lu\n", __FUNCTION__, TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: tot_send_bytes ~ %lu, tot_recv_bytes ~ %lu\n", __FUNCTION__,
(unsigned long)tot_send_bytes, (unsigned long)tot_recv_bytes); (unsigned long)tot_send_bytes, (unsigned long)tot_recv_bytes);
if (client_event_base) if (client_event_base) {
event_base_free(client_event_base); event_base_free(client_event_base);
}
if (tot_send_messages < tot_recv_messages) if (tot_send_messages < tot_recv_messages) {
tot_recv_messages = tot_send_messages; tot_recv_messages = tot_send_messages;
}
total_loss = tot_send_messages - tot_recv_messages; total_loss = tot_send_messages - tot_recv_messages;
@ -1547,8 +1622,9 @@ int add_integrity(app_ur_conn_info *clnet_info, stun_buffer *message) {
while (!random_lifetime) { while (!random_lifetime) {
random_lifetime = turn_random(); random_lifetime = turn_random();
} }
if (random_lifetime < 0) if (random_lifetime < 0) {
random_lifetime = -random_lifetime; random_lifetime = -random_lifetime;
}
random_lifetime = random_lifetime % halflifetime; random_lifetime = random_lifetime % halflifetime;
otoken.enc_block.lifetime = (uint32_t)(halflifetime + random_lifetime); otoken.enc_block.lifetime = (uint32_t)(halflifetime + random_lifetime);
otoken.enc_block.timestamp = ((uint64_t)turn_time()) << 16; otoken.enc_block.timestamp = ((uint64_t)turn_time()) << 16;

View File

@ -155,8 +155,9 @@ public:
*/ */
const uint8_t *getRawBuffer(size_t &sz) const { const uint8_t *getRawBuffer(size_t &sz) const {
int len = stun_attr_get_len(_sar); int len = stun_attr_get_len(_sar);
if (len < 0) if (len < 0) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
}
sz = (size_t)len; sz = (size_t)len;
const uint8_t *value = stun_attr_get_value(_sar); const uint8_t *value = stun_attr_get_value(_sar);
return value; return value;
@ -189,24 +190,28 @@ public:
} }
size_t sz = 0; size_t sz = 0;
const uint8_t *ptr = iter.getRawBuffer(sz); const uint8_t *ptr = iter.getRawBuffer(sz);
if (sz >= 0xFFFF) if (sz >= 0xFFFF) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
}
int at = iter.getType(); int at = iter.getType();
if (at < 0) if (at < 0) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
}
_attr_type = (uint16_t)at; _attr_type = (uint16_t)at;
_sz = sz; _sz = sz;
_value = (uint8_t *)malloc(_sz); _value = (uint8_t *)malloc(_sz);
if (ptr) if (ptr) {
memcpy(_value, ptr, _sz); memcpy(_value, ptr, _sz);
}
} }
/** /**
* Destructor * Destructor
*/ */
virtual ~StunAttr() { virtual ~StunAttr() {
if (_value) if (_value) {
free(_value); free(_value);
}
} }
/** /**
@ -221,14 +226,17 @@ public:
* Set raw data value * Set raw data value
*/ */
void setRawValue(uint8_t *value, size_t sz) { void setRawValue(uint8_t *value, size_t sz) {
if (sz > 0xFFFF) if (sz > 0xFFFF) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
if (_value) }
if (_value) {
free(_value); free(_value);
}
_sz = sz; _sz = sz;
_value = (uint8_t *)malloc(_sz); _value = (uint8_t *)malloc(_sz);
if (value) if (value) {
memcpy(_value, value, _sz); memcpy(_value, value, _sz);
}
} }
/** /**
@ -245,8 +253,9 @@ public:
* Add attribute to a message * Add attribute to a message
*/ */
template <class T> int addToMsg(T &msg) { template <class T> int addToMsg(T &msg) {
if (!_attr_type) if (!_attr_type) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
}
uint8_t *buffer = msg.getRawBuffer(); uint8_t *buffer = msg.getRawBuffer();
if (buffer) { if (buffer) {
size_t sz = msg.getSize(); size_t sz = msg.getSize();
@ -265,8 +274,9 @@ protected:
*/ */
virtual int addToBuffer(uint8_t *buffer, size_t &sz) { virtual int addToBuffer(uint8_t *buffer, size_t &sz) {
if (buffer) { if (buffer) {
if (!_value) if (!_value) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
}
if (stun_attr_add_str(buffer, &sz, _attr_type, _value, _sz) < 0) { if (stun_attr_add_str(buffer, &sz, _attr_type, _value, _sz) < 0) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
} }
@ -294,11 +304,13 @@ public:
StunAttrChannelNumber() : _cn(0) { setType(STUN_ATTRIBUTE_CHANNEL_NUMBER); } StunAttrChannelNumber() : _cn(0) { setType(STUN_ATTRIBUTE_CHANNEL_NUMBER); }
StunAttrChannelNumber(const StunAttrIterator &iter) : StunAttr(iter) { StunAttrChannelNumber(const StunAttrIterator &iter) : StunAttr(iter) {
if (iter.eof()) if (iter.eof()) {
throw EndOfStunMsgException(); throw EndOfStunMsgException();
}
_cn = stun_attr_get_channel_number(getSar(iter)); _cn = stun_attr_get_channel_number(getSar(iter));
if (!_cn) if (!_cn) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
}
} }
virtual ~StunAttrChannelNumber() {} virtual ~StunAttrChannelNumber() {}
uint16_t getChannelNumber() const { return _cn; } uint16_t getChannelNumber() const { return _cn; }
@ -319,8 +331,9 @@ public:
StunAttrEvenPort() : _ep(0) { setType(STUN_ATTRIBUTE_EVEN_PORT); } StunAttrEvenPort() : _ep(0) { setType(STUN_ATTRIBUTE_EVEN_PORT); }
StunAttrEvenPort(const StunAttrIterator &iter) : StunAttr(iter) { StunAttrEvenPort(const StunAttrIterator &iter) : StunAttr(iter) {
if (iter.eof()) if (iter.eof()) {
throw EndOfStunMsgException(); throw EndOfStunMsgException();
}
_ep = stun_attr_get_even_port(getSar(iter)); _ep = stun_attr_get_even_port(getSar(iter));
} }
virtual ~StunAttrEvenPort() {} virtual ~StunAttrEvenPort() {}
@ -344,8 +357,9 @@ public:
StunAttrReservationToken() : _rt(0) { setType(STUN_ATTRIBUTE_RESERVATION_TOKEN); } StunAttrReservationToken() : _rt(0) { setType(STUN_ATTRIBUTE_RESERVATION_TOKEN); }
StunAttrReservationToken(const StunAttrIterator &iter) : StunAttr(iter) { StunAttrReservationToken(const StunAttrIterator &iter) : StunAttr(iter) {
if (iter.eof()) if (iter.eof()) {
throw EndOfStunMsgException(); throw EndOfStunMsgException();
}
_rt = stun_attr_get_reservation_token_value(getSar(iter)); _rt = stun_attr_get_reservation_token_value(getSar(iter));
} }
virtual ~StunAttrReservationToken() {} virtual ~StunAttrReservationToken() {}
@ -373,8 +387,9 @@ public:
} }
StunAttrAddr(const StunAttrIterator &iter) : StunAttr(iter) { StunAttrAddr(const StunAttrIterator &iter) : StunAttr(iter) {
if (iter.eof()) if (iter.eof()) {
throw EndOfStunMsgException(); throw EndOfStunMsgException();
}
size_t sz = 0; size_t sz = 0;
const uint8_t *buf = iter.getRawBuffer(sz); const uint8_t *buf = iter.getRawBuffer(sz);
if (stun_attr_get_addr_str(buf, sz, getSar(iter), &_addr, NULL) < 0) { if (stun_attr_get_addr_str(buf, sz, getSar(iter), &_addr, NULL) < 0) {
@ -402,8 +417,9 @@ public:
StunAttrChangeRequest() : _changeIp(0), _changePort(0) { setType(STUN_ATTRIBUTE_CHANGE_REQUEST); } StunAttrChangeRequest() : _changeIp(0), _changePort(0) { setType(STUN_ATTRIBUTE_CHANGE_REQUEST); }
StunAttrChangeRequest(const StunAttrIterator &iter) : StunAttr(iter) { StunAttrChangeRequest(const StunAttrIterator &iter) : StunAttr(iter) {
if (iter.eof()) if (iter.eof()) {
throw EndOfStunMsgException(); throw EndOfStunMsgException();
}
if (stun_attr_get_change_request_str(getSar(iter), &_changeIp, &_changePort) < 0) { if (stun_attr_get_change_request_str(getSar(iter), &_changeIp, &_changePort) < 0) {
throw WrongStunAttrFormatException(); throw WrongStunAttrFormatException();
@ -412,17 +428,19 @@ public:
virtual ~StunAttrChangeRequest() {} virtual ~StunAttrChangeRequest() {}
bool getChangeIp() const { return _changeIp; } bool getChangeIp() const { return _changeIp; }
void setChangeIp(bool ci) { void setChangeIp(bool ci) {
if (ci) if (ci) {
_changeIp = 1; _changeIp = 1;
else } else {
_changeIp = 0; _changeIp = 0;
}
} }
bool getChangePort() const { return _changePort; } bool getChangePort() const { return _changePort; }
void setChangePort(bool cp) { void setChangePort(bool cp) {
if (cp) if (cp) {
_changePort = 1; _changePort = 1;
else } else {
_changePort = 0; _changePort = 0;
}
} }
protected: protected:
@ -443,8 +461,9 @@ public:
StunAttrResponsePort() : _rp(0) { setType(STUN_ATTRIBUTE_RESPONSE_PORT); } StunAttrResponsePort() : _rp(0) { setType(STUN_ATTRIBUTE_RESPONSE_PORT); }
StunAttrResponsePort(const StunAttrIterator &iter) : StunAttr(iter) { StunAttrResponsePort(const StunAttrIterator &iter) : StunAttr(iter) {
if (iter.eof()) if (iter.eof()) {
throw EndOfStunMsgException(); throw EndOfStunMsgException();
}
int rp = stun_attr_get_response_port_str(getSar(iter)); int rp = stun_attr_get_response_port_str(getSar(iter));
if (rp < 0) { if (rp < 0) {
@ -471,8 +490,9 @@ public:
StunAttrPadding() : _p(0) { setType(STUN_ATTRIBUTE_PADDING); } StunAttrPadding() : _p(0) { setType(STUN_ATTRIBUTE_PADDING); }
StunAttrPadding(const StunAttrIterator &iter) : StunAttr(iter) { StunAttrPadding(const StunAttrIterator &iter) : StunAttr(iter) {
if (iter.eof()) if (iter.eof()) {
throw EndOfStunMsgException(); throw EndOfStunMsgException();
}
int p = stun_attr_get_padding_len_str(getSar(iter)); int p = stun_attr_get_padding_len_str(getSar(iter));
if (p < 0) { if (p < 0) {
@ -550,8 +570,9 @@ public:
* Set message size * Set message size
*/ */
void setSize(size_t sz) { void setSize(size_t sz) {
if (sz > _allocated_sz) if (sz > _allocated_sz) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
_sz = sz; _sz = sz;
} }
@ -592,11 +613,13 @@ public:
* Check if the fingerprint is present. * Check if the fingerprint is present.
*/ */
static bool isFingerprintPresent(uint8_t *buffer, size_t sz) { static bool isFingerprintPresent(uint8_t *buffer, size_t sz) {
if (!stun_is_command_message_str(buffer, sz)) if (!stun_is_command_message_str(buffer, sz)) {
return false; return false;
}
stun_attr_ref sar = stun_attr_get_first_by_type_str(buffer, sz, STUN_ATTRIBUTE_FINGERPRINT); stun_attr_ref sar = stun_attr_get_first_by_type_str(buffer, sz, STUN_ATTRIBUTE_FINGERPRINT);
if (!sar) if (!sar) {
return false; return false;
}
return true; return true;
} }
@ -617,8 +640,9 @@ public:
* Get transaction ID * Get transaction ID
*/ */
virtual stun_tid getTid() const { virtual stun_tid getTid() const {
if (!_constructed || !isCommand()) if (!_constructed || !isCommand()) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
stun_tid tid; stun_tid tid;
stun_tid_from_message_str(_buffer, _sz, &tid); stun_tid_from_message_str(_buffer, _sz, &tid);
return tid; return tid;
@ -628,8 +652,9 @@ public:
* Set transaction ID * Set transaction ID
*/ */
virtual void setTid(stun_tid &tid) { virtual void setTid(stun_tid &tid) {
if (!_constructed || !isCommand()) if (!_constructed || !isCommand()) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
stun_tid_message_cpy(_buffer, &tid); stun_tid_message_cpy(_buffer, &tid);
} }
@ -637,8 +662,9 @@ public:
* Add fingerprint to the message * Add fingerprint to the message
*/ */
void addFingerprint() { void addFingerprint() {
if (!_constructed || !isCommand()) if (!_constructed || !isCommand()) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
stun_attr_add_fingerprint_str(_buffer, &_sz); stun_attr_add_fingerprint_str(_buffer, &_sz);
} }
@ -646,8 +672,9 @@ public:
* Check message integrity, in secure communications. * Check message integrity, in secure communications.
*/ */
bool checkMessageIntegrity(turn_credential_type ct, std::string &uname, std::string &realm, std::string &upwd) const { bool checkMessageIntegrity(turn_credential_type ct, std::string &uname, std::string &realm, std::string &upwd) const {
if (!_constructed || !isCommand()) if (!_constructed || !isCommand()) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
uint8_t *suname = (uint8_t *)strdup(uname.c_str()); uint8_t *suname = (uint8_t *)strdup(uname.c_str());
uint8_t *srealm = (uint8_t *)strdup(realm.c_str()); uint8_t *srealm = (uint8_t *)strdup(realm.c_str());
uint8_t *supwd = (uint8_t *)strdup(upwd.c_str()); uint8_t *supwd = (uint8_t *)strdup(upwd.c_str());
@ -664,8 +691,9 @@ public:
*/ */
void addLTMessageIntegrity(std::string &uname, std::string &realm, std::string &upwd, std::string &nonce) { void addLTMessageIntegrity(std::string &uname, std::string &realm, std::string &upwd, std::string &nonce) {
if (!_constructed || !isCommand()) if (!_constructed || !isCommand()) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
uint8_t *suname = (uint8_t *)strdup(uname.c_str()); uint8_t *suname = (uint8_t *)strdup(uname.c_str());
uint8_t *srealm = (uint8_t *)strdup(realm.c_str()); uint8_t *srealm = (uint8_t *)strdup(realm.c_str());
@ -685,8 +713,9 @@ public:
*/ */
void addSTMessageIntegrity(std::string &uname, std::string &upwd) { void addSTMessageIntegrity(std::string &uname, std::string &upwd) {
if (!_constructed || !isCommand()) if (!_constructed || !isCommand()) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
uint8_t *suname = (uint8_t *)strdup(uname.c_str()); uint8_t *suname = (uint8_t *)strdup(uname.c_str());
uint8_t *supwd = (uint8_t *)strdup(upwd.c_str()); uint8_t *supwd = (uint8_t *)strdup(upwd.c_str());
@ -766,8 +795,9 @@ protected:
} }
virtual bool check() { virtual bool check() {
if (!_constructed) if (!_constructed) {
return false; return false;
}
if (!stun_is_request_str(_buffer, _sz)) { if (!stun_is_request_str(_buffer, _sz)) {
return false; return false;
} }
@ -911,8 +941,9 @@ protected:
} }
virtual bool check() { virtual bool check() {
if (!_constructed) if (!_constructed) {
return false; return false;
}
if (!stun_is_success_response_str(_buffer, _sz)) { if (!stun_is_success_response_str(_buffer, _sz)) {
uint8_t errtxt[0xFFFF]; uint8_t errtxt[0xFFFF];
int cerr = 0; int cerr = 0;
@ -965,8 +996,9 @@ protected:
} }
virtual bool check() { virtual bool check() {
if (!_constructed) if (!_constructed) {
return false; return false;
}
if (!stun_is_indication_str(_buffer, _sz)) { if (!stun_is_indication_str(_buffer, _sz)) {
return false; return false;
} }
@ -993,13 +1025,15 @@ public:
if (!stun_is_channel_message_str(buffer, &_sz, &_cn, 0)) { if (!stun_is_channel_message_str(buffer, &_sz, &_cn, 0)) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
} }
if (_sz > 0xFFFF || _sz < 4) if (_sz > 0xFFFF || _sz < 4) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
_len = _sz - 4; _len = _sz - 4;
} else { } else {
if (total_sz > 0xFFFF || total_sz < 4) if (total_sz > 0xFFFF || total_sz < 4) {
throw WrongStunBufferFormatException(); throw WrongStunBufferFormatException();
}
_len = 0; _len = 0;
} }
@ -1027,8 +1061,9 @@ protected:
} }
virtual bool check() { virtual bool check() {
if (!_constructed) if (!_constructed) {
return false; return false;
}
uint16_t cn = 0; uint16_t cn = 0;
if (!stun_is_channel_message_str(_buffer, &_sz, &cn, 0)) { if (!stun_is_channel_message_str(_buffer, &_sz, &cn, 0)) {
return false; return false;

View File

@ -37,35 +37,40 @@
////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////
uint32_t get_ioa_addr_len(const ioa_addr *addr) { uint32_t get_ioa_addr_len(const ioa_addr *addr) {
if (addr->ss.sa_family == AF_INET) if (addr->ss.sa_family == AF_INET) {
return sizeof(struct sockaddr_in); return sizeof(struct sockaddr_in);
else if (addr->ss.sa_family == AF_INET6) } else if (addr->ss.sa_family == AF_INET6) {
return sizeof(struct sockaddr_in6); return sizeof(struct sockaddr_in6);
}
return 0; return 0;
} }
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
void addr_set_any(ioa_addr *addr) { void addr_set_any(ioa_addr *addr) {
if (addr) if (addr) {
memset(addr, 0, sizeof(ioa_addr)); memset(addr, 0, sizeof(ioa_addr));
}
} }
int addr_any(const ioa_addr *addr) { int addr_any(const ioa_addr *addr) {
if (!addr) if (!addr) {
return 1; return 1;
}
if (addr->ss.sa_family == AF_INET) { if (addr->ss.sa_family == AF_INET) {
return ((addr->s4.sin_addr.s_addr == 0) && (addr->s4.sin_port == 0)); return ((addr->s4.sin_addr.s_addr == 0) && (addr->s4.sin_port == 0));
} else if (addr->ss.sa_family == AF_INET6) { } else if (addr->ss.sa_family == AF_INET6) {
if (addr->s6.sin6_port != 0) if (addr->s6.sin6_port != 0) {
return 0; return 0;
else { } else {
size_t i; size_t i;
for (i = 0; i < sizeof(addr->s6.sin6_addr); i++) for (i = 0; i < sizeof(addr->s6.sin6_addr); i++) {
if (((const char *)&(addr->s6.sin6_addr))[i]) if (((const char *)&(addr->s6.sin6_addr))[i]) {
return 0; return 0;
}
}
} }
} }
@ -73,16 +78,19 @@ int addr_any(const ioa_addr *addr) {
} }
int addr_any_no_port(const ioa_addr *addr) { int addr_any_no_port(const ioa_addr *addr) {
if (!addr) if (!addr) {
return 1; return 1;
}
if (addr->ss.sa_family == AF_INET) { if (addr->ss.sa_family == AF_INET) {
return (addr->s4.sin_addr.s_addr == 0); return (addr->s4.sin_addr.s_addr == 0);
} else if (addr->ss.sa_family == AF_INET6) { } else if (addr->ss.sa_family == AF_INET6) {
size_t i; size_t i;
for (i = 0; i < sizeof(addr->s6.sin6_addr); i++) for (i = 0; i < sizeof(addr->s6.sin6_addr); i++) {
if (((const char *)(&(addr->s6.sin6_addr)))[i]) if (((const char *)(&(addr->s6.sin6_addr)))[i]) {
return 0; return 0;
}
}
} }
return 1; return 1;
@ -103,8 +111,9 @@ uint64_t hash_int64(uint64_t a) {
} }
uint32_t addr_hash(const ioa_addr *addr) { uint32_t addr_hash(const ioa_addr *addr) {
if (!addr) if (!addr) {
return 0; return 0;
}
uint32_t ret = 0; uint32_t ret = 0;
if (addr->ss.sa_family == AF_INET) { if (addr->ss.sa_family == AF_INET) {
@ -118,8 +127,9 @@ uint32_t addr_hash(const ioa_addr *addr) {
} }
uint32_t addr_hash_no_port(const ioa_addr *addr) { uint32_t addr_hash_no_port(const ioa_addr *addr) {
if (!addr) if (!addr) {
return 0; return 0;
}
uint32_t ret = 0; uint32_t ret = 0;
if (addr->ss.sa_family == AF_INET) { if (addr->ss.sa_family == AF_INET) {
@ -133,26 +143,30 @@ uint32_t addr_hash_no_port(const ioa_addr *addr) {
} }
void addr_cpy(ioa_addr *dst, const ioa_addr *src) { void addr_cpy(ioa_addr *dst, const ioa_addr *src) {
if (dst && src) if (dst && src) {
memcpy(dst, src, sizeof(ioa_addr)); memcpy(dst, src, sizeof(ioa_addr));
}
} }
void addr_cpy4(ioa_addr *dst, const struct sockaddr_in *src) { void addr_cpy4(ioa_addr *dst, const struct sockaddr_in *src) {
if (src && dst) if (src && dst) {
memcpy(dst, src, sizeof(struct sockaddr_in)); memcpy(dst, src, sizeof(struct sockaddr_in));
}
} }
void addr_cpy6(ioa_addr *dst, const struct sockaddr_in6 *src) { void addr_cpy6(ioa_addr *dst, const struct sockaddr_in6 *src) {
if (src && dst) if (src && dst) {
memcpy(dst, src, sizeof(struct sockaddr_in6)); memcpy(dst, src, sizeof(struct sockaddr_in6));
}
} }
int addr_eq(const ioa_addr *a1, const ioa_addr *a2) { int addr_eq(const ioa_addr *a1, const ioa_addr *a2) {
if (!a1) if (!a1) {
return (!a2); return (!a2);
else if (!a2) } else if (!a2) {
return (!a1); return (!a1);
}
if (a1->ss.sa_family == a2->ss.sa_family) { if (a1->ss.sa_family == a2->ss.sa_family) {
if (a1->ss.sa_family == AF_INET && a1->s4.sin_port == a2->s4.sin_port) { if (a1->ss.sa_family == AF_INET && a1->s4.sin_port == a2->s4.sin_port) {
@ -171,10 +185,11 @@ int addr_eq(const ioa_addr *a1, const ioa_addr *a2) {
int addr_eq_no_port(const ioa_addr *a1, const ioa_addr *a2) { int addr_eq_no_port(const ioa_addr *a1, const ioa_addr *a2) {
if (!a1) if (!a1) {
return (!a2); return (!a2);
else if (!a2) } else if (!a2) {
return (!a1); return (!a1);
}
if (a1->ss.sa_family == a2->ss.sa_family) { if (a1->ss.sa_family == a2->ss.sa_family) {
if (a1->ss.sa_family == AF_INET) { if (a1->ss.sa_family == AF_INET) {
@ -192,15 +207,17 @@ int addr_eq_no_port(const ioa_addr *a1, const ioa_addr *a2) {
int make_ioa_addr(const uint8_t *saddr0, int port, ioa_addr *addr) { int make_ioa_addr(const uint8_t *saddr0, int port, ioa_addr *addr) {
if (!saddr0 || !addr) if (!saddr0 || !addr) {
return -1; return -1;
}
char ssaddr[257]; char ssaddr[257];
STRCPY(ssaddr, saddr0); STRCPY(ssaddr, saddr0);
char *saddr = ssaddr; char *saddr = ssaddr;
while (*saddr == ' ') while (*saddr == ' ') {
++saddr; ++saddr;
}
size_t len = strlen(saddr); size_t len = strlen(saddr);
while (len > 0) { while (len > 0) {
@ -290,16 +307,18 @@ int make_ioa_addr(const uint8_t *saddr0, int port, ioa_addr *addr) {
static char *get_addr_string_and_port(char *s0, int *port) { static char *get_addr_string_and_port(char *s0, int *port) {
char *s = s0; char *s = s0;
while (*s && (*s == ' ')) while (*s && (*s == ' ')) {
++s; ++s;
}
if (*s == '[') { if (*s == '[') {
++s; ++s;
char *tail = strstr(s, "]"); char *tail = strstr(s, "]");
if (tail) { if (tail) {
*tail = 0; *tail = 0;
++tail; ++tail;
while (*tail && (*tail == ' ')) while (*tail && (*tail == ' ')) {
++tail; ++tail;
}
if (*tail == ':') { if (*tail == ':') {
++tail; ++tail;
*port = atoi(tail); *port = atoi(tail);
@ -325,16 +344,18 @@ static char *get_addr_string_and_port(char *s0, int *port) {
} }
int make_ioa_addr_from_full_string(const uint8_t *saddr, int default_port, ioa_addr *addr) { int make_ioa_addr_from_full_string(const uint8_t *saddr, int default_port, ioa_addr *addr) {
if (!addr) if (!addr) {
return -1; return -1;
}
int ret = -1; int ret = -1;
int port = 0; int port = 0;
char *s = strdup((const char *)saddr); char *s = strdup((const char *)saddr);
char *sa = get_addr_string_and_port(s, &port); char *sa = get_addr_string_and_port(s, &port);
if (sa) { if (sa) {
if (port < 1) if (port < 1) {
port = default_port; port = default_port;
}
ret = make_ioa_addr((uint8_t *)sa, port, addr); ret = make_ioa_addr((uint8_t *)sa, port, addr);
} }
free(s); free(s);
@ -349,16 +370,18 @@ int addr_to_string(const ioa_addr *addr, uint8_t *saddr) {
if (addr->ss.sa_family == AF_INET) { if (addr->ss.sa_family == AF_INET) {
inet_ntop(AF_INET, &addr->s4.sin_addr, addrtmp, INET_ADDRSTRLEN); inet_ntop(AF_INET, &addr->s4.sin_addr, addrtmp, INET_ADDRSTRLEN);
if (addr_get_port(addr) > 0) if (addr_get_port(addr) > 0) {
snprintf((char *)saddr, MAX_IOA_ADDR_STRING, "%s:%d", addrtmp, addr_get_port(addr)); snprintf((char *)saddr, MAX_IOA_ADDR_STRING, "%s:%d", addrtmp, addr_get_port(addr));
else } else {
strncpy((char *)saddr, addrtmp, MAX_IOA_ADDR_STRING); strncpy((char *)saddr, addrtmp, MAX_IOA_ADDR_STRING);
}
} else if (addr->ss.sa_family == AF_INET6) { } else if (addr->ss.sa_family == AF_INET6) {
inet_ntop(AF_INET6, &addr->s6.sin6_addr, addrtmp, INET6_ADDRSTRLEN); inet_ntop(AF_INET6, &addr->s6.sin6_addr, addrtmp, INET6_ADDRSTRLEN);
if (addr_get_port(addr) > 0) if (addr_get_port(addr) > 0) {
snprintf((char *)saddr, MAX_IOA_ADDR_STRING, "[%s]:%d", addrtmp, addr_get_port(addr)); snprintf((char *)saddr, MAX_IOA_ADDR_STRING, "[%s]:%d", addrtmp, addr_get_port(addr));
else } else {
strncpy((char *)saddr, addrtmp, MAX_IOA_ADDR_STRING); strncpy((char *)saddr, addrtmp, MAX_IOA_ADDR_STRING);
}
} else { } else {
return -1; return -1;
} }
@ -402,8 +425,9 @@ void addr_set_port(ioa_addr *addr, int port) {
} }
int addr_get_port(const ioa_addr *addr) { int addr_get_port(const ioa_addr *addr) {
if (!addr) if (!addr) {
return 0; return 0;
}
if (addr->s4.sin_family == AF_INET) { if (addr->s4.sin_family == AF_INET) {
return nswap16(addr->s4.sin_port); return nswap16(addr->s4.sin_port);
@ -417,37 +441,42 @@ int addr_get_port(const ioa_addr *addr) {
void ioa_addr_range_set(ioa_addr_range *range, const ioa_addr *addr_min, const ioa_addr *addr_max) { void ioa_addr_range_set(ioa_addr_range *range, const ioa_addr *addr_min, const ioa_addr *addr_max) {
if (range) { if (range) {
if (addr_min) if (addr_min) {
addr_cpy(&(range->min), addr_min); addr_cpy(&(range->min), addr_min);
else } else {
addr_set_any(&(range->min)); addr_set_any(&(range->min));
if (addr_max) }
if (addr_max) {
addr_cpy(&(range->max), addr_max); addr_cpy(&(range->max), addr_max);
else } else {
addr_set_any(&(range->max)); addr_set_any(&(range->max));
}
} }
} }
int addr_less_eq(const ioa_addr *addr1, const ioa_addr *addr2) { int addr_less_eq(const ioa_addr *addr1, const ioa_addr *addr2) {
if (!addr1) if (!addr1) {
return 1; return 1;
else if (!addr2) } else if (!addr2) {
return 0; return 0;
else { } else {
if (addr1->ss.sa_family != addr2->ss.sa_family) if (addr1->ss.sa_family != addr2->ss.sa_family) {
return (addr1->ss.sa_family < addr2->ss.sa_family); return (addr1->ss.sa_family < addr2->ss.sa_family);
else if (addr1->ss.sa_family == AF_INET) { } else if (addr1->ss.sa_family == AF_INET) {
return ((uint32_t)nswap32(addr1->s4.sin_addr.s_addr) <= (uint32_t)nswap32(addr2->s4.sin_addr.s_addr)); return ((uint32_t)nswap32(addr1->s4.sin_addr.s_addr) <= (uint32_t)nswap32(addr2->s4.sin_addr.s_addr));
} else if (addr1->ss.sa_family == AF_INET6) { } else if (addr1->ss.sa_family == AF_INET6) {
int i; int i;
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
if ((uint8_t)(((const char *)&(addr1->s6.sin6_addr))[i]) > (uint8_t)(((const char *)&(addr2->s6.sin6_addr))[i])) if ((uint8_t)(((const char *)&(addr1->s6.sin6_addr))[i]) >
(uint8_t)(((const char *)&(addr2->s6.sin6_addr))[i])) {
return 0; return 0;
}
} }
return 1; return 1;
} else } else {
return 1; return 1;
}
} }
} }
@ -498,8 +527,9 @@ int ioa_addr_is_loopback(ioa_addr *addr) {
if (u[15] == 1) { if (u[15] == 1) {
int i; int i;
for (i = 0; i < 15; ++i) { for (i = 0; i < 15; ++i) {
if (u[i]) if (u[i]) {
return 0; return 0;
}
} }
return 1; return 1;
} }
@ -523,8 +553,9 @@ int ioa_addr_is_zero(ioa_addr *addr) {
const uint8_t *u = ((const uint8_t *)&(addr->s6.sin6_addr)); const uint8_t *u = ((const uint8_t *)&(addr->s6.sin6_addr));
int i; int i;
for (i = 0; i <= 15; ++i) { for (i = 0; i <= 15; ++i) {
if (u[i]) if (u[i]) {
return 0; return 0;
}
} }
return 1; return 1;
} }

View File

@ -389,8 +389,9 @@ void print_hmac(const char *name, const void *s, size_t len);
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
int stun_get_command_message_len_str(const uint8_t *buf, size_t len) { int stun_get_command_message_len_str(const uint8_t *buf, size_t len) {
if (len < STUN_HEADER_LENGTH) if (len < STUN_HEADER_LENGTH) {
return -1; return -1;
}
/* Validate the size the buffer claims to be */ /* Validate the size the buffer claims to be */
size_t bufLen = (size_t)(nswap16(((const uint16_t *)(buf))[1]) + STUN_HEADER_LENGTH); size_t bufLen = (size_t)(nswap16(((const uint16_t *)(buf))[1]) + STUN_HEADER_LENGTH);
@ -402,8 +403,9 @@ int stun_get_command_message_len_str(const uint8_t *buf, size_t len) {
} }
static int stun_set_command_message_len_str(uint8_t *buf, int len) { static int stun_set_command_message_len_str(uint8_t *buf, int len) {
if (len < STUN_HEADER_LENGTH) if (len < STUN_HEADER_LENGTH) {
return -1; return -1;
}
((uint16_t *)buf)[1] = nswap16((uint16_t)(len - STUN_HEADER_LENGTH)); ((uint16_t *)buf)[1] = nswap16((uint16_t)(len - STUN_HEADER_LENGTH));
return 0; return 0;
} }
@ -416,8 +418,9 @@ uint16_t stun_make_type(uint16_t method) {
} }
uint16_t stun_get_method_str(const uint8_t *buf, size_t len) { uint16_t stun_get_method_str(const uint8_t *buf, size_t len) {
if (!buf || len < 2) if (!buf || len < 2) {
return (uint16_t)-1; return (uint16_t)-1;
}
uint16_t tt = nswap16(((const uint16_t *)buf)[0]); uint16_t tt = nswap16(((const uint16_t *)buf)[0]);
@ -425,8 +428,9 @@ uint16_t stun_get_method_str(const uint8_t *buf, size_t len) {
} }
uint16_t stun_get_msg_type_str(const uint8_t *buf, size_t len) { uint16_t stun_get_msg_type_str(const uint8_t *buf, size_t len) {
if (!buf || len < 2) if (!buf || len < 2) {
return (uint16_t)-1; return (uint16_t)-1;
}
return ((nswap16(((const uint16_t *)buf)[0])) & 0x3FFF); return ((nswap16(((const uint16_t *)buf)[0])) & 0x3FFF);
} }
@ -475,26 +479,31 @@ int old_stun_is_command_message_str(const uint8_t *buf, size_t blen, uint32_t *c
int stun_is_command_message_full_check_str(const uint8_t *buf, size_t blen, int must_check_fingerprint, int stun_is_command_message_full_check_str(const uint8_t *buf, size_t blen, int must_check_fingerprint,
int *fingerprint_present) { int *fingerprint_present) {
if (!stun_is_command_message_str(buf, blen)) if (!stun_is_command_message_str(buf, blen)) {
return 0; return 0;
}
stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, blen, STUN_ATTRIBUTE_FINGERPRINT); stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, blen, STUN_ATTRIBUTE_FINGERPRINT);
if (!sar) { if (!sar) {
if (fingerprint_present) if (fingerprint_present) {
*fingerprint_present = 0; *fingerprint_present = 0;
}
if (stun_get_method_str(buf, blen) == STUN_METHOD_BINDING) { if (stun_get_method_str(buf, blen) == STUN_METHOD_BINDING) {
return 1; return 1;
} }
return !must_check_fingerprint; return !must_check_fingerprint;
} }
if (stun_attr_get_len(sar) != 4) if (stun_attr_get_len(sar) != 4) {
return 0; return 0;
}
const uint32_t *fingerprint = (const uint32_t *)stun_attr_get_value(sar); const uint32_t *fingerprint = (const uint32_t *)stun_attr_get_value(sar);
if (!fingerprint) if (!fingerprint) {
return !must_check_fingerprint; return !must_check_fingerprint;
}
uint32_t crc32len = (uint32_t)((((const uint8_t *)fingerprint) - buf) - 4); uint32_t crc32len = (uint32_t)((((const uint8_t *)fingerprint) - buf) - 4);
int ret = (*fingerprint == nswap32(ns_crc32(buf, crc32len) ^ ((uint32_t)0x5354554e))); int ret = (*fingerprint == nswap32(ns_crc32(buf, crc32len) ^ ((uint32_t)0x5354554e)));
if (ret && fingerprint_present) if (ret && fingerprint_present) {
*fingerprint_present = ret; *fingerprint_present = ret;
}
return ret; return ret;
} }
@ -503,20 +512,23 @@ int stun_is_command_message_offset_str(const uint8_t *buf, size_t blen, int offs
} }
int stun_is_request_str(const uint8_t *buf, size_t len) { int stun_is_request_str(const uint8_t *buf, size_t len) {
if (is_channel_msg_str(buf, len)) if (is_channel_msg_str(buf, len)) {
return 0; return 0;
}
return IS_STUN_REQUEST(stun_get_msg_type_str(buf, len)); return IS_STUN_REQUEST(stun_get_msg_type_str(buf, len));
} }
int stun_is_success_response_str(const uint8_t *buf, size_t len) { int stun_is_success_response_str(const uint8_t *buf, size_t len) {
if (is_channel_msg_str(buf, len)) if (is_channel_msg_str(buf, len)) {
return 0; return 0;
}
return IS_STUN_SUCCESS_RESP(stun_get_msg_type_str(buf, len)); return IS_STUN_SUCCESS_RESP(stun_get_msg_type_str(buf, len));
} }
int stun_is_error_response_str(const uint8_t *buf, size_t len, int *err_code, uint8_t *err_msg, size_t err_msg_size) { int stun_is_error_response_str(const uint8_t *buf, size_t len, int *err_code, uint8_t *err_msg, size_t err_msg_size) {
if (is_channel_msg_str(buf, len)) if (is_channel_msg_str(buf, len)) {
return 0; return 0;
}
if (IS_STUN_ERR_RESP(stun_get_msg_type_str(buf, len))) { if (IS_STUN_ERR_RESP(stun_get_msg_type_str(buf, len))) {
if (err_code) { if (err_code) {
stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_ERROR_CODE); stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_ERROR_CODE);
@ -528,8 +540,9 @@ int stun_is_error_response_str(const uint8_t *buf, size_t len, int *err_code, ui
err_msg[0] = 0; err_msg[0] = 0;
if (stun_attr_get_len(sar) > 4) { if (stun_attr_get_len(sar) > 4) {
size_t msg_len = stun_attr_get_len(sar) - 4; size_t msg_len = stun_attr_get_len(sar) - 4;
if (msg_len > (err_msg_size - 1)) if (msg_len > (err_msg_size - 1)) {
msg_len = err_msg_size - 1; msg_len = err_msg_size - 1;
}
memcpy(err_msg, val + 4, msg_len); memcpy(err_msg, val + 4, msg_len);
err_msg[msg_len] = 0; err_msg[msg_len] = 0;
} }
@ -596,18 +609,22 @@ int stun_is_challenge_response_str(const uint8_t *buf, size_t len, int *err_code
} }
int stun_is_response_str(const uint8_t *buf, size_t len) { int stun_is_response_str(const uint8_t *buf, size_t len) {
if (is_channel_msg_str(buf, len)) if (is_channel_msg_str(buf, len)) {
return 0; return 0;
if (IS_STUN_SUCCESS_RESP(stun_get_msg_type_str(buf, len))) }
if (IS_STUN_SUCCESS_RESP(stun_get_msg_type_str(buf, len))) {
return 1; return 1;
if (IS_STUN_ERR_RESP(stun_get_msg_type_str(buf, len))) }
if (IS_STUN_ERR_RESP(stun_get_msg_type_str(buf, len))) {
return 1; return 1;
}
return 0; return 0;
} }
int stun_is_indication_str(const uint8_t *buf, size_t len) { int stun_is_indication_str(const uint8_t *buf, size_t len) {
if (is_channel_msg_str(buf, len)) if (is_channel_msg_str(buf, len)) {
return 0; return 0;
}
return IS_STUN_INDICATION(stun_get_msg_type_str(buf, len)); return IS_STUN_INDICATION(stun_get_msg_type_str(buf, len));
} }
@ -781,13 +798,15 @@ void stun_init_error_response_str(uint16_t method, uint8_t *buf, size_t *len, ui
int stun_init_channel_message_str(uint16_t chnumber, uint8_t *buf, size_t *len, int length, int do_padding) { int stun_init_channel_message_str(uint16_t chnumber, uint8_t *buf, size_t *len, int length, int do_padding) {
uint16_t rlen = (uint16_t)length; uint16_t rlen = (uint16_t)length;
if (length < 0 || (MAX_STUN_MESSAGE_SIZE < (4 + length))) if (length < 0 || (MAX_STUN_MESSAGE_SIZE < (4 + length))) {
return -1; return -1;
}
((uint16_t *)(buf))[0] = nswap16(chnumber); ((uint16_t *)(buf))[0] = nswap16(chnumber);
((uint16_t *)(buf))[1] = nswap16((uint16_t)length); ((uint16_t *)(buf))[1] = nswap16((uint16_t)length);
if (do_padding && (rlen & 0x0003)) if (do_padding && (rlen & 0x0003)) {
rlen = ((rlen >> 2) + 1) << 2; rlen = ((rlen >> 2) + 1) << 2;
}
*len = 4 + rlen; *len = 4 + rlen;
@ -798,22 +817,26 @@ int stun_is_channel_message_str(const uint8_t *buf, size_t *blen, uint16_t *chnu
uint16_t datalen_header; uint16_t datalen_header;
uint16_t datalen_actual; uint16_t datalen_actual;
if (!blen || (*blen < 4)) if (!blen || (*blen < 4)) {
return 0; return 0;
}
uint16_t chn = nswap16(((const uint16_t *)(buf))[0]); uint16_t chn = nswap16(((const uint16_t *)(buf))[0]);
if (!STUN_VALID_CHANNEL(chn)) if (!STUN_VALID_CHANNEL(chn)) {
return 0; return 0;
}
if (*blen > (uint16_t)-1) if (*blen > (uint16_t)-1) {
*blen = (uint16_t)-1; *blen = (uint16_t)-1;
}
datalen_actual = (uint16_t)(*blen) - 4; datalen_actual = (uint16_t)(*blen) - 4;
datalen_header = ((const uint16_t *)buf)[1]; datalen_header = ((const uint16_t *)buf)[1];
datalen_header = nswap16(datalen_header); datalen_header = nswap16(datalen_header);
if (datalen_header > datalen_actual) if (datalen_header > datalen_actual) {
return 0; return 0;
}
if (datalen_header != datalen_actual) { if (datalen_header != datalen_actual) {
@ -827,16 +850,18 @@ int stun_is_channel_message_str(const uint8_t *buf, size_t *blen, uint16_t *chnu
return 0; return 0;
} else { } else {
uint16_t diff = datalen_actual - datalen_header; uint16_t diff = datalen_actual - datalen_header;
if (diff > 3) if (diff > 3) {
return 0; return 0;
}
} }
} }
} }
*blen = datalen_header + 4; *blen = datalen_header + 4;
if (chnumber) if (chnumber) {
*chnumber = chn; *chnumber = chn;
}
return 1; return 1;
} }
@ -976,29 +1001,34 @@ int stun_set_allocate_request_str(uint8_t *buf, size_t *len, uint32_t lifetime,
field[1] = 0; field[1] = 0;
field[2] = 0; field[2] = 0;
field[3] = 0; field[3] = 0;
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_TRANSPORT, field, sizeof(field)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_TRANSPORT, field, sizeof(field)) < 0) {
return -1; return -1;
}
} }
// LIFETIME // LIFETIME
{ {
if (lifetime < 1) if (lifetime < 1) {
lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME; lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME;
}
uint32_t field = nswap32(lifetime); uint32_t field = nswap32(lifetime);
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_LIFETIME, (uint8_t *)(&field), sizeof(field)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_LIFETIME, (uint8_t *)(&field), sizeof(field)) < 0) {
return -1; return -1;
}
} }
// MICE // MICE
if (mobile) { if (mobile) {
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MOBILITY_TICKET, (const uint8_t *)"", 0) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MOBILITY_TICKET, (const uint8_t *)"", 0) < 0) {
return -1; return -1;
}
} }
if (ep > -1) { if (ep > -1) {
uint8_t value = ep ? 0x80 : 0x00; uint8_t value = ep ? 0x80 : 0x00;
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_EVEN_PORT, (const uint8_t *)&value, 1) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_EVEN_PORT, (const uint8_t *)&value, 1) < 0) {
return -1; return -1;
}
} }
// RESERVATION-TOKEN, EVEN-PORT and DUAL-ALLOCATION are mutually exclusive: // RESERVATION-TOKEN, EVEN-PORT and DUAL-ALLOCATION are mutually exclusive:
@ -1015,8 +1045,9 @@ int stun_set_allocate_request_str(uint8_t *buf, size_t *len, uint32_t lifetime,
field[1] = 0; field[1] = 0;
field[2] = 0; field[2] = 0;
field[3] = 0; field[3] = 0;
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, field, sizeof(field)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, field, sizeof(field)) < 0) {
return -1; return -1;
}
} }
if (af6 && !af4) { if (af6 && !af4) {
@ -1025,8 +1056,9 @@ int stun_set_allocate_request_str(uint8_t *buf, size_t *len, uint32_t lifetime,
field[1] = 0; field[1] = 0;
field[2] = 0; field[2] = 0;
field[3] = 0; field[3] = 0;
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, field, sizeof(field)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, field, sizeof(field)) < 0) {
return -1; return -1;
}
} }
if (af4 && af6) { if (af4 && af6) {
@ -1035,8 +1067,9 @@ int stun_set_allocate_request_str(uint8_t *buf, size_t *len, uint32_t lifetime,
field[1] = 0; field[1] = 0;
field[2] = 0; field[2] = 0;
field[3] = 0; field[3] = 0;
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY, field, sizeof(field)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_ADDITIONAL_ADDRESS_FAMILY, field, sizeof(field)) < 0) {
return -1; return -1;
}
} }
} }
@ -1053,18 +1086,21 @@ int stun_set_allocate_response_str(uint8_t *buf, size_t *len, stun_tid *tid, con
stun_init_success_response_str(STUN_METHOD_ALLOCATE, buf, len, tid); stun_init_success_response_str(STUN_METHOD_ALLOCATE, buf, len, tid);
if (relayed_addr1) { if (relayed_addr1) {
if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS, relayed_addr1) < 0) if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS, relayed_addr1) < 0) {
return -1; return -1;
}
} }
if (relayed_addr2) { if (relayed_addr2) {
if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS, relayed_addr2) < 0) if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_RELAYED_ADDRESS, relayed_addr2) < 0) {
return -1; return -1;
}
} }
if (reflexive_addr) { if (reflexive_addr) {
if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, reflexive_addr) < 0) if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, reflexive_addr) < 0) {
return -1; return -1;
}
} }
if (reservation_token) { if (reservation_token) {
@ -1073,19 +1109,23 @@ int stun_set_allocate_response_str(uint8_t *buf, size_t *len, stun_tid *tid, con
} }
{ {
if (lifetime < 1) if (lifetime < 1) {
lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME; lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME;
else if (lifetime > max_lifetime) } else if (lifetime > max_lifetime) {
lifetime = max_lifetime; lifetime = max_lifetime;
}
uint32_t field = nswap32(lifetime); uint32_t field = nswap32(lifetime);
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_LIFETIME, (uint8_t *)(&field), sizeof(field)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_LIFETIME, (uint8_t *)(&field), sizeof(field)) < 0) {
return -1; return -1;
}
} }
if (mobile_id && *mobile_id) { if (mobile_id && *mobile_id) {
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MOBILITY_TICKET, (uint8_t *)mobile_id, (int)strlen(mobile_id)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MOBILITY_TICKET, (uint8_t *)mobile_id, (int)strlen(mobile_id)) <
0) {
return -1; return -1;
}
} }
} else { } else {
@ -1106,18 +1146,21 @@ uint16_t stun_set_channel_bind_request_str(uint8_t *buf, size_t *len, const ioa_
stun_init_request_str(STUN_METHOD_CHANNEL_BIND, buf, len); stun_init_request_str(STUN_METHOD_CHANNEL_BIND, buf, len);
if (stun_attr_add_channel_number_str(buf, len, channel_number) < 0) if (stun_attr_add_channel_number_str(buf, len, channel_number) < 0) {
return 0; return 0;
}
if (!peer_addr) { if (!peer_addr) {
ioa_addr ca; ioa_addr ca;
memset(&ca, 0, sizeof(ioa_addr)); memset(&ca, 0, sizeof(ioa_addr));
if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &ca) < 0) if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &ca) < 0) {
return 0; return 0;
}
} else { } else {
if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, peer_addr) < 0) if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, peer_addr) < 0) {
return 0; return 0;
}
} }
return channel_number; return channel_number;
@ -1148,13 +1191,15 @@ int stun_set_binding_response_str(uint8_t *buf, size_t *len, stun_tid *tid, cons
old_stun_init_success_response_str(STUN_METHOD_BINDING, buf, len, tid, cookie); old_stun_init_success_response_str(STUN_METHOD_BINDING, buf, len, tid, cookie);
} }
if (!old_stun && reflexive_addr) { if (!old_stun && reflexive_addr) {
if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, reflexive_addr) < 0) if (stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS, reflexive_addr) < 0) {
return -1; return -1;
}
} }
if (reflexive_addr) { if (reflexive_addr) {
if (!no_stun_backward_compatibility && if (!no_stun_backward_compatibility &&
stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_MAPPED_ADDRESS, reflexive_addr) < 0) stun_attr_add_addr_str(buf, len, STUN_ATTRIBUTE_MAPPED_ADDRESS, reflexive_addr) < 0) {
return -1; return -1;
}
} }
} else if (!old_stun) { } else if (!old_stun) {
stun_init_error_response_str(STUN_METHOD_BINDING, buf, len, error_code, reason, tid); stun_init_error_response_str(STUN_METHOD_BINDING, buf, len, error_code, reason, tid);
@ -1190,27 +1235,33 @@ int stun_is_binding_response_str(const uint8_t *buf, size_t len) {
/////////////////////////////// TID /////////////////////////////// /////////////////////////////// TID ///////////////////////////////
int stun_tid_equals(const stun_tid *id1, const stun_tid *id2) { int stun_tid_equals(const stun_tid *id1, const stun_tid *id2) {
if (id1 == id2) if (id1 == id2) {
return 1; return 1;
if (!id1) }
if (!id1) {
return 0; return 0;
if (!id2) }
if (!id2) {
return 0; return 0;
}
{ {
unsigned int i = 0; unsigned int i = 0;
for (i = 0; i < STUN_TID_SIZE; ++i) { for (i = 0; i < STUN_TID_SIZE; ++i) {
if (id1->tsx_id[i] != id2->tsx_id[i]) if (id1->tsx_id[i] != id2->tsx_id[i]) {
return 0; return 0;
}
} }
} }
return 1; return 1;
} }
void stun_tid_cpy(stun_tid *id1, const stun_tid *id2) { void stun_tid_cpy(stun_tid *id1, const stun_tid *id2) {
if (!id1) if (!id1) {
return; return;
if (!id2) }
if (!id2) {
return; return;
}
memcpy((void *)(id1->tsx_id), (const void *)(id2->tsx_id), STUN_TID_SIZE); memcpy((void *)(id1->tsx_id), (const void *)(id2->tsx_id), STUN_TID_SIZE);
} }
@ -1245,8 +1296,9 @@ void stun_tid_generate(stun_tid *id) {
void stun_tid_generate_in_message_str(uint8_t *buf, stun_tid *id) { void stun_tid_generate_in_message_str(uint8_t *buf, stun_tid *id) {
stun_tid tmp; stun_tid tmp;
if (!id) if (!id) {
id = &tmp; id = &tmp;
}
stun_tid_generate(id); stun_tid_generate(id);
stun_tid_message_cpy(buf, id); stun_tid_message_cpy(buf, id);
} }
@ -1256,12 +1308,13 @@ void stun_tid_generate_in_message_str(uint8_t *buf, stun_tid *id) {
turn_time_t stun_adjust_allocate_lifetime(turn_time_t lifetime, turn_time_t max_allowed_lifetime, turn_time_t stun_adjust_allocate_lifetime(turn_time_t lifetime, turn_time_t max_allowed_lifetime,
turn_time_t max_lifetime) { turn_time_t max_lifetime) {
if (!lifetime) if (!lifetime) {
lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME; lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME;
else if (lifetime < STUN_MIN_ALLOCATE_LIFETIME) } else if (lifetime < STUN_MIN_ALLOCATE_LIFETIME) {
lifetime = STUN_MIN_ALLOCATE_LIFETIME; lifetime = STUN_MIN_ALLOCATE_LIFETIME;
else if (lifetime > max_allowed_lifetime) } else if (lifetime > max_allowed_lifetime) {
lifetime = max_allowed_lifetime; lifetime = max_allowed_lifetime;
}
if (max_lifetime && (max_lifetime < lifetime)) { if (max_lifetime && (max_lifetime < lifetime)) {
lifetime = max_lifetime; lifetime = max_lifetime;
@ -1273,22 +1326,25 @@ turn_time_t stun_adjust_allocate_lifetime(turn_time_t lifetime, turn_time_t max_
////////////// ATTR ///////////////////////////////////////////////////////////// ////////////// ATTR /////////////////////////////////////////////////////////////
int stun_attr_get_type(stun_attr_ref attr) { int stun_attr_get_type(stun_attr_ref attr) {
if (attr) if (attr) {
return (int)(nswap16(((const uint16_t *)attr)[0])); return (int)(nswap16(((const uint16_t *)attr)[0]));
}
return -1; return -1;
} }
int stun_attr_get_len(stun_attr_ref attr) { int stun_attr_get_len(stun_attr_ref attr) {
if (attr) if (attr) {
return (int)(nswap16(((const uint16_t *)attr)[1])); return (int)(nswap16(((const uint16_t *)attr)[1]));
}
return -1; return -1;
} }
const uint8_t *stun_attr_get_value(stun_attr_ref attr) { const uint8_t *stun_attr_get_value(stun_attr_ref attr) {
if (attr) { if (attr) {
int len = (int)(nswap16(((const uint16_t *)attr)[1])); int len = (int)(nswap16(((const uint16_t *)attr)[1]));
if (len < 1) if (len < 1) {
return NULL; return NULL;
}
return ((const uint8_t *)attr) + 4; return ((const uint8_t *)attr) + 4;
} }
return NULL; return NULL;
@ -1297,8 +1353,9 @@ const uint8_t *stun_attr_get_value(stun_attr_ref attr) {
int stun_get_requested_address_family(stun_attr_ref attr) { int stun_get_requested_address_family(stun_attr_ref attr) {
if (attr) { if (attr) {
int len = (int)(nswap16(((const uint16_t *)attr)[1])); int len = (int)(nswap16(((const uint16_t *)attr)[1]));
if (len != 4) if (len != 4) {
return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_INVALID; return STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_INVALID;
}
int val = ((const uint8_t *)attr)[4]; int val = ((const uint8_t *)attr)[4];
switch (val) { switch (val) {
case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4: case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4:
@ -1317,8 +1374,9 @@ uint16_t stun_attr_get_channel_number(stun_attr_ref attr) {
const uint8_t *value = stun_attr_get_value(attr); const uint8_t *value = stun_attr_get_value(attr);
if (value && (stun_attr_get_len(attr) >= 2)) { if (value && (stun_attr_get_len(attr) >= 2)) {
uint16_t cn = nswap16(((const uint16_t *)value)[0]); uint16_t cn = nswap16(((const uint16_t *)value)[0]);
if (STUN_VALID_CHANNEL(cn)) if (STUN_VALID_CHANNEL(cn)) {
return cn; return cn;
}
} }
} }
return 0; return 0;
@ -1374,8 +1432,9 @@ uint8_t stun_attr_get_even_port(stun_attr_ref attr) {
if (attr) { if (attr) {
const uint8_t *value = stun_attr_get_value(attr); const uint8_t *value = stun_attr_get_value(attr);
if (value) { if (value) {
if ((uint8_t)(value[0]) > 0x7F) if ((uint8_t)(value[0]) > 0x7F) {
return 1; return 1;
}
} }
} }
return 0; return 0;
@ -1429,9 +1488,9 @@ stun_attr_ref stun_attr_get_first_str(const uint8_t *buf, size_t len) {
stun_attr_ref stun_attr_get_next_str(const uint8_t *buf, size_t len, stun_attr_ref prev) { stun_attr_ref stun_attr_get_next_str(const uint8_t *buf, size_t len, stun_attr_ref prev) {
if (!prev) if (!prev) {
return stun_attr_get_first_str(buf, len); return stun_attr_get_first_str(buf, len);
else { } else {
const uint8_t *end = buf + stun_get_command_message_len_str(buf, len); const uint8_t *end = buf + stun_get_command_message_len_str(buf, len);
int attrlen = stun_attr_get_len(prev); int attrlen = stun_attr_get_len(prev);
uint16_t rem4 = ((uint16_t)attrlen) & 0x0003; uint16_t rem4 = ((uint16_t)attrlen) & 0x0003;
@ -1448,8 +1507,9 @@ stun_attr_ref stun_attr_get_next_str(const uint8_t *buf, size_t len, stun_attr_r
} }
int stun_attr_add_str(uint8_t *buf, size_t *len, uint16_t attr, const uint8_t *avalue, int alen) { int stun_attr_add_str(uint8_t *buf, size_t *len, uint16_t attr, const uint8_t *avalue, int alen) {
if (alen < 0) if (alen < 0) {
alen = 0; alen = 0;
}
uint8_t tmp[1]; uint8_t tmp[1];
if (!avalue) { if (!avalue) {
alen = 0; alen = 0;
@ -1463,9 +1523,9 @@ int stun_attr_add_str(uint8_t *buf, size_t *len, uint16_t attr, const uint8_t *a
paddinglen = 4 - newlenrem4; paddinglen = 4 - newlenrem4;
newlen = newlen + paddinglen; newlen = newlen + paddinglen;
} }
if (newlen >= MAX_STUN_MESSAGE_SIZE) if (newlen >= MAX_STUN_MESSAGE_SIZE) {
return -1; return -1;
else { } else {
uint8_t *attr_start = buf + clen; uint8_t *attr_start = buf + clen;
uint16_t *attr_start_16t = (uint16_t *)attr_start; uint16_t *attr_start_16t = (uint16_t *)attr_start;
@ -1475,8 +1535,9 @@ int stun_attr_add_str(uint8_t *buf, size_t *len, uint16_t attr, const uint8_t *a
attr_start_16t[0] = nswap16(attr); attr_start_16t[0] = nswap16(attr);
attr_start_16t[1] = nswap16(alen); attr_start_16t[1] = nswap16(alen);
if (alen > 0) if (alen > 0) {
memcpy(attr_start + 4, avalue, alen); memcpy(attr_start + 4, avalue, alen);
}
// Write 0 padding to not leak data // Write 0 padding to not leak data
memset(attr_start + 4 + alen, 0, paddinglen); memset(attr_start + 4 + alen, 0, paddinglen);
@ -1509,8 +1570,9 @@ int stun_attr_add_addr_str(uint8_t *buf, size_t *len, uint16_t attr_type, const
return -1; return -1;
} }
if (stun_attr_add_str(buf, len, attr_type, (uint8_t *)(&cfield), clen) < 0) if (stun_attr_add_str(buf, len, attr_type, (uint8_t *)(&cfield), clen) < 0) {
return -1; return -1;
}
return 0; return 0;
} }
@ -1526,8 +1588,9 @@ int stun_attr_get_addr_str(const uint8_t *buf, size_t len, stun_attr_ref attr, i
addr_set_any(&public_addr); addr_set_any(&public_addr);
int attr_type = stun_attr_get_type(attr); int attr_type = stun_attr_get_type(attr);
if (attr_type < 0) if (attr_type < 0) {
return -1; return -1;
}
int xor_ed = 0; int xor_ed = 0;
switch (attr_type) { switch (attr_type) {
@ -1540,8 +1603,9 @@ int stun_attr_get_addr_str(const uint8_t *buf, size_t len, stun_attr_ref attr, i
}; };
const uint8_t *cfield = stun_attr_get_value(attr); const uint8_t *cfield = stun_attr_get_value(attr);
if (!cfield) if (!cfield) {
return -1; return -1;
}
if (stun_addr_decode(&public_addr, cfield, stun_attr_get_len(attr), xor_ed, STUN_MAGIC_COOKIE, tid.tsx_id) < 0) { if (stun_addr_decode(&public_addr, cfield, stun_attr_get_len(attr), xor_ed, STUN_MAGIC_COOKIE, tid.tsx_id) < 0) {
return -1; return -1;
@ -1738,8 +1802,9 @@ static void make_crctable(void)
static uint32_t ns_crc32(const uint8_t *buffer, uint32_t len) { static uint32_t ns_crc32(const uint8_t *buffer, uint32_t len) {
uint32_t crc = CRC_MASK; uint32_t crc = CRC_MASK;
while (len--) while (len--) {
UPDATE_CRC(crc, *buffer++); UPDATE_CRC(crc, *buffer++);
}
return (~crc); return (~crc);
} }
@ -1771,10 +1836,12 @@ int SASLprep(uint8_t *s) {
case 0x7F: case 0x7F:
return -1; return -1;
default: default:
if (c < 0x1F) if (c < 0x1F) {
return -1; return -1;
if (c >= 0x80 && c <= 0x9F) }
if (c >= 0x80 && c <= 0x9F) {
return -1; return -1;
}
*strout = c; *strout = c;
++strout; ++strout;
++strin; ++strin;
@ -1788,12 +1855,15 @@ int SASLprep(uint8_t *s) {
//////////////// Message Integrity //////////////////////////// //////////////// Message Integrity ////////////////////////////
size_t get_hmackey_size(SHATYPE shatype) { size_t get_hmackey_size(SHATYPE shatype) {
if (shatype == SHATYPE_SHA256) if (shatype == SHATYPE_SHA256) {
return 32; return 32;
if (shatype == SHATYPE_SHA384) }
if (shatype == SHATYPE_SHA384) {
return 48; return 48;
if (shatype == SHATYPE_SHA512) }
if (shatype == SHATYPE_SHA512) {
return 64; return 64;
}
return 16; return 16;
} }
@ -1826,17 +1896,20 @@ int stun_attr_add_integrity_str(turn_credential_type ct, uint8_t *buf, size_t *l
shasize = SHA1SIZEBYTES; shasize = SHA1SIZEBYTES;
}; };
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MESSAGE_INTEGRITY, hmac, shasize) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_MESSAGE_INTEGRITY, hmac, shasize) < 0) {
return -1; return -1;
}
if (ct == TURN_CREDENTIALS_SHORT_TERM) { if (ct == TURN_CREDENTIALS_SHORT_TERM) {
if (stun_calculate_hmac(buf, *len - 4 - shasize, pwd, strlen((char *)pwd), buf + *len - shasize, &shasize, if (stun_calculate_hmac(buf, *len - 4 - shasize, pwd, strlen((char *)pwd), buf + *len - shasize, &shasize,
shatype) < 0) shatype) < 0) {
return -1; return -1;
}
} else { } else {
if (stun_calculate_hmac(buf, *len - 4 - shasize, key, get_hmackey_size(shatype), buf + *len - shasize, &shasize, if (stun_calculate_hmac(buf, *len - 4 - shasize, key, get_hmackey_size(shatype), buf + *len - shasize, &shasize,
shatype) < 0) shatype) < 0) {
return -1; return -1;
}
} }
return 0; return 0;
@ -1844,14 +1917,17 @@ int stun_attr_add_integrity_str(turn_credential_type ct, uint8_t *buf, size_t *l
int stun_attr_add_integrity_by_key_str(uint8_t *buf, size_t *len, const uint8_t *uname, const uint8_t *realm, int stun_attr_add_integrity_by_key_str(uint8_t *buf, size_t *len, const uint8_t *uname, const uint8_t *realm,
hmackey_t key, const uint8_t *nonce, SHATYPE shatype) { hmackey_t key, const uint8_t *nonce, SHATYPE shatype) {
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_USERNAME, uname, (int)strlen((const char *)uname)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_USERNAME, uname, (int)strlen((const char *)uname)) < 0) {
return -1; return -1;
}
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_NONCE, nonce, (int)strlen((const char *)nonce)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_NONCE, nonce, (int)strlen((const char *)nonce)) < 0) {
return -1; return -1;
}
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REALM, realm, (int)strlen((const char *)realm)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_REALM, realm, (int)strlen((const char *)realm)) < 0) {
return -1; return -1;
}
password_t p; password_t p;
return stun_attr_add_integrity_str(TURN_CREDENTIALS_LONG_TERM, buf, len, key, p, shatype); return stun_attr_add_integrity_str(TURN_CREDENTIALS_LONG_TERM, buf, len, key, p, shatype);
@ -1861,16 +1937,18 @@ int stun_attr_add_integrity_by_user_str(uint8_t *buf, size_t *len, const uint8_t
const uint8_t *upwd, const uint8_t *nonce, SHATYPE shatype) { const uint8_t *upwd, const uint8_t *nonce, SHATYPE shatype) {
hmackey_t key; hmackey_t key;
if (stun_produce_integrity_key_str(uname, realm, upwd, key, shatype) < 0) if (stun_produce_integrity_key_str(uname, realm, upwd, key, shatype) < 0) {
return -1; return -1;
}
return stun_attr_add_integrity_by_key_str(buf, len, uname, realm, key, nonce, shatype); return stun_attr_add_integrity_by_key_str(buf, len, uname, realm, key, nonce, shatype);
} }
int stun_attr_add_integrity_by_user_short_term_str(uint8_t *buf, size_t *len, const uint8_t *uname, password_t pwd, int stun_attr_add_integrity_by_user_short_term_str(uint8_t *buf, size_t *len, const uint8_t *uname, password_t pwd,
SHATYPE shatype) { SHATYPE shatype) {
if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_USERNAME, uname, (int)strlen((const char *)uname)) < 0) if (stun_attr_add_str(buf, len, STUN_ATTRIBUTE_USERNAME, uname, (int)strlen((const char *)uname)) < 0) {
return -1; return -1;
}
hmackey_t key; hmackey_t key;
return stun_attr_add_integrity_str(TURN_CREDENTIALS_SHORT_TERM, buf, len, key, pwd, shatype); return stun_attr_add_integrity_str(TURN_CREDENTIALS_SHORT_TERM, buf, len, key, pwd, shatype);
@ -1896,46 +1974,54 @@ int stun_check_message_integrity_by_key_str(turn_credential_type ct, uint8_t *bu
const uint8_t *old_hmac = NULL; const uint8_t *old_hmac = NULL;
stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_MESSAGE_INTEGRITY); stun_attr_ref sar = stun_attr_get_first_by_type_str(buf, len, STUN_ATTRIBUTE_MESSAGE_INTEGRITY);
if (!sar) if (!sar) {
return -1; return -1;
}
int sarlen = stun_attr_get_len(sar); int sarlen = stun_attr_get_len(sar);
switch (sarlen) { switch (sarlen) {
case SHA256SIZEBYTES: case SHA256SIZEBYTES:
shasize = SHA256SIZEBYTES; shasize = SHA256SIZEBYTES;
if (shatype != SHATYPE_SHA256) if (shatype != SHATYPE_SHA256) {
return -1; return -1;
}
break; break;
case SHA384SIZEBYTES: case SHA384SIZEBYTES:
shasize = SHA384SIZEBYTES; shasize = SHA384SIZEBYTES;
if (shatype != SHATYPE_SHA384) if (shatype != SHATYPE_SHA384) {
return -1; return -1;
}
break; break;
case SHA512SIZEBYTES: case SHA512SIZEBYTES:
shasize = SHA512SIZEBYTES; shasize = SHA512SIZEBYTES;
if (shatype != SHATYPE_SHA512) if (shatype != SHATYPE_SHA512) {
return -1; return -1;
}
break; break;
case SHA1SIZEBYTES: case SHA1SIZEBYTES:
shasize = SHA1SIZEBYTES; shasize = SHA1SIZEBYTES;
if (shatype != SHATYPE_SHA1) if (shatype != SHATYPE_SHA1) {
return -1; return -1;
}
break; break;
default: default:
return -1; return -1;
}; };
int orig_len = stun_get_command_message_len_str(buf, len); int orig_len = stun_get_command_message_len_str(buf, len);
if (orig_len < 0) if (orig_len < 0) {
return -1; return -1;
}
int new_len = (int)((const uint8_t *)sar - buf) + 4 + shasize; int new_len = (int)((const uint8_t *)sar - buf) + 4 + shasize;
if (new_len > orig_len) if (new_len > orig_len) {
return -1; return -1;
}
if (stun_set_command_message_len_str(buf, new_len) < 0) if (stun_set_command_message_len_str(buf, new_len) < 0) {
return -1; return -1;
}
if (ct == TURN_CREDENTIALS_SHORT_TERM) { if (ct == TURN_CREDENTIALS_SHORT_TERM) {
res = res =
@ -1946,15 +2032,18 @@ int stun_check_message_integrity_by_key_str(turn_credential_type ct, uint8_t *bu
} }
stun_set_command_message_len_str(buf, orig_len); stun_set_command_message_len_str(buf, orig_len);
if (res < 0) if (res < 0) {
return -1; return -1;
}
old_hmac = stun_attr_get_value(sar); old_hmac = stun_attr_get_value(sar);
if (!old_hmac) if (!old_hmac) {
return -1; return -1;
}
if (memcmp(old_hmac, new_hmac, shasize)) if (memcmp(old_hmac, new_hmac, shasize)) {
return 0; return 0;
}
return +1; return +1;
} }
@ -2028,8 +2117,9 @@ int stun_attr_add_response_port_str(uint8_t *buf, size_t *len, uint16_t port) {
int stun_attr_get_padding_len_str(stun_attr_ref attr) { int stun_attr_get_padding_len_str(stun_attr_ref attr) {
int len = stun_attr_get_len(attr); int len = stun_attr_get_len(attr);
if (len < 0) if (len < 0) {
return -1; return -1;
}
return (uint16_t)len; return (uint16_t)len;
} }
@ -2047,8 +2137,9 @@ int stun_attr_add_padding_str(uint8_t *buf, size_t *len, uint16_t padding_len) {
static void remove_spaces(char *s) { static void remove_spaces(char *s) {
char *sfns = s; char *sfns = s;
while (*sfns) { while (*sfns) {
if (*sfns != ' ') if (*sfns != ' ') {
break; break;
}
++sfns; ++sfns;
} }
if (*sfns) { if (*sfns) {
@ -2074,9 +2165,9 @@ static void remove_spaces(char *s) {
static void normalize_algorithm(char *s) { static void normalize_algorithm(char *s) {
char c = *s; char c = *s;
while (c) { while (c) {
if (c == '_') if (c == '_') {
*s = '-'; *s = '-';
else if ((c >= 'a') && (c <= 'z')) { } else if ((c >= 'a') && (c <= 'z')) {
*s = c - 'a' + 'A'; *s = c - 'a' + 'A';
} }
++s; ++s;
@ -2159,10 +2250,12 @@ int convert_oauth_key_data(const oauth_key_data *oakd0, oauth_key *key, char *er
key->timestamp = oakd->timestamp; key->timestamp = oakd->timestamp;
key->lifetime = oakd->lifetime; key->lifetime = oakd->lifetime;
if (!(key->timestamp)) if (!(key->timestamp)) {
key->timestamp = OAUTH_DEFAULT_TIMESTAMP; key->timestamp = OAUTH_DEFAULT_TIMESTAMP;
if (!(key->lifetime)) }
if (!(key->lifetime)) {
key->lifetime = OAUTH_DEFAULT_LIFETIME; key->lifetime = OAUTH_DEFAULT_LIFETIME;
}
key->as_rs_alg = ENC_ALG_ERROR; key->as_rs_alg = ENC_ALG_ERROR;
#if !defined(TURN_NO_GCM) #if !defined(TURN_NO_GCM)
@ -2227,12 +2320,14 @@ int my_EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, con
while ((out_len < inl) && (++cycle < 128)) { while ((out_len < inl) && (++cycle < 128)) {
int tmp_outl = 0; int tmp_outl = 0;
unsigned char *ptr = NULL; unsigned char *ptr = NULL;
if (out) if (out) {
ptr = out + out_len; ptr = out + out_len;
}
int ret = EVP_EncryptUpdate(ctx, ptr, &tmp_outl, in + out_len, inl - out_len); int ret = EVP_EncryptUpdate(ctx, ptr, &tmp_outl, in + out_len, inl - out_len);
out_len += tmp_outl; out_len += tmp_outl;
if (ret < 1) if (ret < 1) {
return ret; return ret;
}
} }
*outl = out_len; *outl = out_len;
return 1; return 1;
@ -2245,12 +2340,14 @@ int my_EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, con
while ((out_len < inl) && (++cycle < 128)) { while ((out_len < inl) && (++cycle < 128)) {
int tmp_outl = 0; int tmp_outl = 0;
unsigned char *ptr = NULL; unsigned char *ptr = NULL;
if (out) if (out) {
ptr = out + out_len; ptr = out + out_len;
}
int ret = EVP_DecryptUpdate(ctx, ptr, &tmp_outl, in + out_len, inl - out_len); int ret = EVP_DecryptUpdate(ctx, ptr, &tmp_outl, in + out_len, inl - out_len);
out_len += tmp_outl; out_len += tmp_outl;
if (ret < 1) if (ret < 1) {
return ret; return ret;
}
} }
*outl = out_len; *outl = out_len;
return 1; return 1;
@ -2475,8 +2572,9 @@ static int encode_oauth_token_gcm(const uint8_t *server_name, encoded_oauth_toke
len += 4; len += 4;
const EVP_CIPHER *cipher = get_cipher_type(key->as_rs_alg); const EVP_CIPHER *cipher = get_cipher_type(key->as_rs_alg);
if (!cipher) if (!cipher) {
return -1; return -1;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L #if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX ctx; EVP_CIPHER_CTX ctx;
@ -2487,18 +2585,21 @@ static int encode_oauth_token_gcm(const uint8_t *server_name, encoded_oauth_toke
EVP_CIPHER_CTX_init(ctxp); EVP_CIPHER_CTX_init(ctxp);
/* Initialize the encryption operation. */ /* Initialize the encryption operation. */
if (1 != EVP_EncryptInit_ex(ctxp, cipher, NULL, NULL, NULL)) if (1 != EVP_EncryptInit_ex(ctxp, cipher, NULL, NULL, NULL)) {
return -1; return -1;
}
EVP_CIPHER_CTX_set_padding(ctxp, 1); EVP_CIPHER_CTX_set_padding(ctxp, 1);
/* Set IV length if default 12 bytes (96 bits) is not appropriate */ /* Set IV length if default 12 bytes (96 bits) is not appropriate */
if (1 != EVP_CIPHER_CTX_ctrl(ctxp, EVP_CTRL_GCM_SET_IVLEN, OAUTH_GCM_NONCE_SIZE, NULL)) if (1 != EVP_CIPHER_CTX_ctrl(ctxp, EVP_CTRL_GCM_SET_IVLEN, OAUTH_GCM_NONCE_SIZE, NULL)) {
return -1; return -1;
}
/* Initialize key and IV */ /* Initialize key and IV */
if (1 != EVP_EncryptInit_ex(ctxp, NULL, NULL, (const unsigned char *)key->as_rs_key, nonce)) if (1 != EVP_EncryptInit_ex(ctxp, NULL, NULL, (const unsigned char *)key->as_rs_key, nonce)) {
return -1; return -1;
}
int outl = 0; int outl = 0;
size_t sn_len = strlen((const char *)server_name); size_t sn_len = strlen((const char *)server_name);
@ -2506,8 +2607,9 @@ static int encode_oauth_token_gcm(const uint8_t *server_name, encoded_oauth_toke
/* Provide any AAD data. This can be called zero or more times as /* Provide any AAD data. This can be called zero or more times as
* required * required
*/ */
if (1 != my_EVP_EncryptUpdate(ctxp, NULL, &outl, server_name, (int)sn_len)) if (1 != my_EVP_EncryptUpdate(ctxp, NULL, &outl, server_name, (int)sn_len)) {
return -1; return -1;
}
outl = 0; outl = 0;
unsigned char *encoded_field = (unsigned char *)etoken->token; unsigned char *encoded_field = (unsigned char *)etoken->token;
@ -2516,8 +2618,9 @@ static int encode_oauth_token_gcm(const uint8_t *server_name, encoded_oauth_toke
unsigned char *start_field = orig_field + OAUTH_GCM_NONCE_SIZE + 2; unsigned char *start_field = orig_field + OAUTH_GCM_NONCE_SIZE + 2;
len -= OAUTH_GCM_NONCE_SIZE + 2; len -= OAUTH_GCM_NONCE_SIZE + 2;
if (1 != my_EVP_EncryptUpdate(ctxp, encoded_field, &outl, start_field, (int)len)) if (1 != my_EVP_EncryptUpdate(ctxp, encoded_field, &outl, start_field, (int)len)) {
return -1; return -1;
}
int tmp_outl = 0; int tmp_outl = 0;
EVP_EncryptFinal_ex(ctxp, encoded_field + outl, &tmp_outl); EVP_EncryptFinal_ex(ctxp, encoded_field + outl, &tmp_outl);

View File

@ -34,8 +34,9 @@
int stun_addr_encode(const ioa_addr *ca, uint8_t *cfield, int *clen, int xor_ed, uint32_t mc, const uint8_t *tsx_id) { int stun_addr_encode(const ioa_addr *ca, uint8_t *cfield, int *clen, int xor_ed, uint32_t mc, const uint8_t *tsx_id) {
if (!cfield || !clen || !ca || !tsx_id) if (!cfield || !clen || !ca || !tsx_id) {
return -1; return -1;
}
if (ca->ss.sa_family == AF_INET || ca->ss.sa_family == 0) { if (ca->ss.sa_family == AF_INET || ca->ss.sa_family == 0) {
@ -109,8 +110,9 @@ int stun_addr_encode(const ioa_addr *ca, uint8_t *cfield, int *clen, int xor_ed,
int stun_addr_decode(ioa_addr *ca, const uint8_t *cfield, int len, int xor_ed, uint32_t mc, const uint8_t *tsx_id) { int stun_addr_decode(ioa_addr *ca, const uint8_t *cfield, int len, int xor_ed, uint32_t mc, const uint8_t *tsx_id) {
if (!cfield || !len || !ca || !tsx_id || (len < 8)) if (!cfield || !len || !ca || !tsx_id || (len < 8)) {
return -1; return -1;
}
if (cfield[0] != 0) { if (cfield[0] != 0) {
return -1; return -1;
@ -118,19 +120,21 @@ int stun_addr_decode(ioa_addr *ca, const uint8_t *cfield, int len, int xor_ed, u
int sa_family; int sa_family;
if (cfield[1] == 1) if (cfield[1] == 1) {
sa_family = AF_INET; sa_family = AF_INET;
else if (cfield[1] == 2) } else if (cfield[1] == 2) {
sa_family = AF_INET6; sa_family = AF_INET6;
else } else {
return -1; return -1;
}
ca->ss.sa_family = sa_family; ca->ss.sa_family = sa_family;
if (sa_family == AF_INET) { if (sa_family == AF_INET) {
if (len != 8) if (len != 8) {
return -1; return -1;
}
/* IPv4 address */ /* IPv4 address */
@ -149,8 +153,9 @@ int stun_addr_decode(ioa_addr *ca, const uint8_t *cfield, int len, int xor_ed, u
/* IPv6 address */ /* IPv6 address */
if (len != 20) if (len != 20) {
return -1; return -1;
}
/* Port */ /* Port */
ca->s6.sin6_port = ((const uint16_t *)cfield)[1]; ca->s6.sin6_port = ((const uint16_t *)cfield)[1];

View File

@ -51,8 +51,9 @@ void init_allocation(void *owner, allocation *a, ur_map *tcp_connections) {
void clear_allocation(allocation *a, SOCKET_TYPE socket_type) { void clear_allocation(allocation *a, SOCKET_TYPE socket_type) {
if (a) { if (a) {
if (a->is_valid) if (a->is_valid) {
turn_report_allocation_delete(a, socket_type); turn_report_allocation_delete(a, socket_type);
}
if (a->tcs.elems) { if (a->tcs.elems) {
size_t i; size_t i;
@ -87,25 +88,29 @@ void clear_allocation(allocation *a, SOCKET_TYPE socket_type) {
} }
relay_endpoint_session *get_relay_session(allocation *a, int family) { relay_endpoint_session *get_relay_session(allocation *a, int family) {
if (a) if (a) {
return &(a->relay_sessions[ALLOC_INDEX(family)]); return &(a->relay_sessions[ALLOC_INDEX(family)]);
}
return NULL; return NULL;
} }
int get_relay_session_failure(allocation *a, int family) { int get_relay_session_failure(allocation *a, int family) {
if (a) if (a) {
return a->relay_sessions_failure[ALLOC_INDEX(family)]; return a->relay_sessions_failure[ALLOC_INDEX(family)];
}
return 0; return 0;
} }
void set_relay_session_failure(allocation *a, int family) { void set_relay_session_failure(allocation *a, int family) {
if (a) if (a) {
a->relay_sessions_failure[ALLOC_INDEX(family)] = 1; a->relay_sessions_failure[ALLOC_INDEX(family)] = 1;
}
} }
ioa_socket_handle get_relay_socket(allocation *a, int family) { ioa_socket_handle get_relay_socket(allocation *a, int family) {
if (a) if (a) {
return a->relay_sessions[ALLOC_INDEX(family)].s; return a->relay_sessions[ALLOC_INDEX(family)].s;
}
return NULL; return NULL;
} }
@ -143,15 +148,17 @@ void set_allocation_lifetime_ev(allocation *a, turn_time_t exp_time, ioa_timer_h
} }
int is_allocation_valid(const allocation *a) { int is_allocation_valid(const allocation *a) {
if (a) if (a) {
return a->is_valid; return a->is_valid;
else } else {
return 0; return 0;
}
} }
void set_allocation_valid(allocation *a, int value) { void set_allocation_valid(allocation *a, int value) {
if (a) if (a) {
a->is_valid = value; a->is_valid = value;
}
} }
turn_permission_info *allocation_get_permission(allocation *a, const ioa_addr *addr) { turn_permission_info *allocation_get_permission(allocation *a, const ioa_addr *addr) {
@ -186,8 +193,9 @@ void turn_permission_clean(turn_permission_info *tinfo) {
} }
static void init_turn_permission_hashtable(turn_permission_hashtable *map) { static void init_turn_permission_hashtable(turn_permission_hashtable *map) {
if (map) if (map) {
memset(map, 0, sizeof(turn_permission_hashtable)); memset(map, 0, sizeof(turn_permission_hashtable));
}
} }
static void free_turn_permission_hashtable(turn_permission_hashtable *map) { static void free_turn_permission_hashtable(turn_permission_hashtable *map) {
@ -228,8 +236,9 @@ static void free_turn_permission_hashtable(turn_permission_hashtable *map) {
} }
static turn_permission_info *get_from_turn_permission_hashtable(turn_permission_hashtable *map, const ioa_addr *addr) { static turn_permission_info *get_from_turn_permission_hashtable(turn_permission_hashtable *map, const ioa_addr *addr) {
if (!addr || !map) if (!addr || !map) {
return NULL; return NULL;
}
uint32_t index = addr_hash_no_port(addr) & (TURN_PERMISSION_HASHTABLE_SIZE - 1); uint32_t index = addr_hash_no_port(addr) & (TURN_PERMISSION_HASHTABLE_SIZE - 1);
turn_permission_array *parray = &(map->table[index]); turn_permission_array *parray = &(map->table[index]);
@ -312,8 +321,9 @@ ch_info *allocation_get_new_ch_info(allocation *a, uint16_t chnum, ioa_addr *pee
turn_permission_info *tinfo = get_from_turn_permission_hashtable(&(a->addr_to_perm), peer_addr); turn_permission_info *tinfo = get_from_turn_permission_hashtable(&(a->addr_to_perm), peer_addr);
if (!tinfo) if (!tinfo) {
tinfo = allocation_add_permission(a, peer_addr); tinfo = allocation_add_permission(a, peer_addr);
}
ch_info *chn = ch_map_get(&(a->chns), chnum, 1); ch_info *chn = ch_map_get(&(a->chns), chnum, 1);
@ -557,8 +567,9 @@ tcp_connection *create_tcp_connection(uint8_t server_id, allocation *a, stun_tid
} }
tcp_connection *tc = (tcp_connection *)calloc(sizeof(tcp_connection), 1); tcp_connection *tc = (tcp_connection *)calloc(sizeof(tcp_connection), 1);
addr_cpy(&(tc->peer_addr), peer_addr); addr_cpy(&(tc->peer_addr), peer_addr);
if (tid) if (tid) {
memcpy(&(tc->tid), tid, sizeof(stun_tid)); memcpy(&(tc->tid), tid, sizeof(stun_tid));
}
tc->owner = a; tc->owner = a;
int found = 0; int found = 0;
@ -663,8 +674,9 @@ tcp_connection *get_tcp_connection_by_peer(allocation *a, ioa_addr *peer_addr) {
} }
int can_accept_tcp_connection_from_peer(allocation *a, ioa_addr *peer_addr, int server_relay) { int can_accept_tcp_connection_from_peer(allocation *a, ioa_addr *peer_addr, int server_relay) {
if (server_relay) if (server_relay) {
return 1; return 1;
}
if (a && peer_addr) { if (a && peer_addr) {
return (get_from_turn_permission_hashtable(&(a->addr_to_perm), peer_addr) != NULL); return (get_from_turn_permission_hashtable(&(a->addr_to_perm), peer_addr) != NULL);

View File

@ -54,8 +54,9 @@ typedef struct {
} relay_endpoint_session; } relay_endpoint_session;
static inline void clear_relay_endpoint_session_data(relay_endpoint_session *cdi) { static inline void clear_relay_endpoint_session_data(relay_endpoint_session *cdi) {
if (cdi) if (cdi) {
IOA_CLOSE_SOCKET(cdi->s); IOA_CLOSE_SOCKET(cdi->s);
}
} }
////////// RFC 6062 TCP connection //////// ////////// RFC 6062 TCP connection ////////

View File

@ -426,9 +426,11 @@ static const double __ac_HASH_UPPER = 0.77;
*/ */
static kh_inline khint_t __ac_X31_hash_string(const char *s) { static kh_inline khint_t __ac_X31_hash_string(const char *s) {
khint_t h = (khint_t)*s; khint_t h = (khint_t)*s;
if (h) if (h) {
for (++s; *s; ++s) for (++s; *s; ++s) {
h = (h << 5) - h + (khint_t)*s; h = (h << 5) - h + (khint_t)*s;
}
}
return h; return h;
} }
/*! @function /*! @function

View File

@ -73,9 +73,9 @@ ur_map *ur_map_create(void) {
* -1 - error * -1 - error
*/ */
int ur_map_put(ur_map *map, ur_map_key_type key, ur_map_value_type value) { int ur_map_put(ur_map *map, ur_map_key_type key, ur_map_value_type value) {
if (!ur_map_valid(map)) if (!ur_map_valid(map)) {
return -1; return -1;
else { } else {
int ret = 0; int ret = 0;
khiter_t k; khiter_t k;
@ -104,16 +104,17 @@ int ur_map_put(ur_map *map, ur_map_key_type key, ur_map_value_type value) {
* 0 - not found * 0 - not found
*/ */
int ur_map_get(const ur_map *map, ur_map_key_type key, ur_map_value_type *value) { int ur_map_get(const ur_map *map, ur_map_key_type key, ur_map_value_type *value) {
if (!ur_map_valid(map)) if (!ur_map_valid(map)) {
return 0; return 0;
else { } else {
khiter_t k; khiter_t k;
k = kh_get(3, map->h, key); k = kh_get(3, map->h, key);
if ((k != kh_end(map->h)) && kh_exist(map->h, k)) { if ((k != kh_end(map->h)) && kh_exist(map->h, k)) {
if (value) if (value) {
*value = kh_value(map->h, k); *value = kh_value(map->h, k);
}
return 1; return 1;
} }
@ -127,9 +128,9 @@ int ur_map_get(const ur_map *map, ur_map_key_type key, ur_map_value_type *value)
* 0 - not found * 0 - not found
*/ */
int ur_map_del(ur_map *map, ur_map_key_type key, ur_map_del_func delfunc) { int ur_map_del(ur_map *map, ur_map_key_type key, ur_map_del_func delfunc) {
if (!ur_map_valid(map)) if (!ur_map_valid(map)) {
return 0; return 0;
else { } else {
khiter_t k; khiter_t k;
@ -152,9 +153,9 @@ int ur_map_del(ur_map *map, ur_map_key_type key, ur_map_del_func delfunc) {
* 0 - not found * 0 - not found
*/ */
int ur_map_exist(const ur_map *map, ur_map_key_type key) { int ur_map_exist(const ur_map *map, ur_map_key_type key) {
if (!ur_map_valid(map)) if (!ur_map_valid(map)) {
return 0; return 0;
else { } else {
khiter_t k; khiter_t k;
@ -171,8 +172,9 @@ void ur_map_free(ur_map **map) {
if (map && ur_map_valid(*map)) { if (map && ur_map_valid(*map)) {
{ {
static int khctest = 0; static int khctest = 0;
if (khctest) if (khctest) {
kh_clear(3, (*map)->h); kh_clear(3, (*map)->h);
}
} }
kh_destroy(3, (*map)->h); kh_destroy(3, (*map)->h);
(*map)->h = NULL; (*map)->h = NULL;
@ -355,8 +357,9 @@ int lm_map_get(const lm_map *map, ur_map_key_type key, ur_map_value_type *value)
ur_map_value_type *valuep = a->extra_values[i]; ur_map_value_type *valuep = a->extra_values[i];
if (keyp && valuep) { if (keyp && valuep) {
if (*keyp == key) { if (*keyp == key) {
if (value) if (value) {
*value = *valuep; *value = *valuep;
}
return 1; return 1;
} }
} }
@ -402,8 +405,9 @@ int lm_map_del(lm_map *map, ur_map_key_type key, ur_map_del_func delfunc) {
ur_map_value_type *valuep = a->extra_values[i]; ur_map_value_type *valuep = a->extra_values[i];
if (keyp && valuep) { if (keyp && valuep) {
if (*keyp == key) { if (*keyp == key) {
if (delfunc) if (delfunc) {
delfunc(*valuep); delfunc(*valuep);
}
*keyp = 0; *keyp = 0;
*valuep = 0; *valuep = 0;
return 1; return 1;
@ -580,8 +584,9 @@ static void addr_list_free(addr_list_header *slh) {
static void addr_list_add(addr_list_header *slh, const ioa_addr *key, ur_addr_map_value_type value) { static void addr_list_add(addr_list_header *slh, const ioa_addr *key, ur_addr_map_value_type value) {
if (!key || !value) if (!key || !value) {
return; return;
}
addr_elem *elem = NULL; addr_elem *elem = NULL;
size_t i; size_t i;
@ -615,11 +620,13 @@ static void addr_list_add(addr_list_header *slh, const ioa_addr *key, ur_addr_ma
} }
static void addr_list_remove(addr_list_header *slh, const ioa_addr *key, ur_addr_map_func delfunc, int *counter) { static void addr_list_remove(addr_list_header *slh, const ioa_addr *key, ur_addr_map_func delfunc, int *counter) {
if (!slh || !key) if (!slh || !key) {
return; return;
}
if (counter) if (counter) {
*counter = 0; *counter = 0;
}
size_t i; size_t i;
@ -627,8 +634,9 @@ static void addr_list_remove(addr_list_header *slh, const ioa_addr *key, ur_addr
addr_elem *elem = &(slh->main_list[i]); addr_elem *elem = &(slh->main_list[i]);
if (elem->value) { if (elem->value) {
if (addr_eq(&(elem->key), key)) { if (addr_eq(&(elem->key), key)) {
if (delfunc && elem->value) if (delfunc && elem->value) {
delfunc(elem->value); delfunc(elem->value);
}
elem->value = 0; elem->value = 0;
if (counter) { if (counter) {
*counter += 1; *counter += 1;
@ -642,8 +650,9 @@ static void addr_list_remove(addr_list_header *slh, const ioa_addr *key, ur_addr
addr_elem *elem = &(slh->extra_list[i]); addr_elem *elem = &(slh->extra_list[i]);
if (elem->value) { if (elem->value) {
if (addr_eq(&(elem->key), key)) { if (addr_eq(&(elem->key), key)) {
if (delfunc && elem->value) if (delfunc && elem->value) {
delfunc(elem->value); delfunc(elem->value);
}
elem->value = 0; elem->value = 0;
if (counter) { if (counter) {
*counter += 1; *counter += 1;
@ -721,8 +730,9 @@ static size_t addr_list_size(const addr_list_header *slh) {
static addr_elem *addr_list_get(addr_list_header *slh, const ioa_addr *key) { static addr_elem *addr_list_get(addr_list_header *slh, const ioa_addr *key) {
if (!slh || !key) if (!slh || !key) {
return NULL; return NULL;
}
size_t i; size_t i;
@ -751,8 +761,9 @@ static addr_elem *addr_list_get(addr_list_header *slh, const ioa_addr *key) {
static const addr_elem *addr_list_get_const(const addr_list_header *slh, const ioa_addr *key) { static const addr_elem *addr_list_get_const(const addr_list_header *slh, const ioa_addr *key) {
if (!slh || !key) if (!slh || !key) {
return NULL; return NULL;
}
size_t i; size_t i;
@ -812,8 +823,9 @@ void ur_addr_map_clean(ur_addr_map *map) {
*/ */
int ur_addr_map_put(ur_addr_map *map, ioa_addr *key, ur_addr_map_value_type value) { int ur_addr_map_put(ur_addr_map *map, ioa_addr *key, ur_addr_map_value_type value) {
if (!ur_addr_map_valid(map)) if (!ur_addr_map_valid(map)) {
return -1; return -1;
}
else { else {
@ -837,8 +849,9 @@ int ur_addr_map_put(ur_addr_map *map, ioa_addr *key, ur_addr_map_value_type valu
*/ */
int ur_addr_map_get(const ur_addr_map *map, ioa_addr *key, ur_addr_map_value_type *value) { int ur_addr_map_get(const ur_addr_map *map, ioa_addr *key, ur_addr_map_value_type *value) {
if (!ur_addr_map_valid(map)) if (!ur_addr_map_valid(map)) {
return 0; return 0;
}
else { else {
@ -846,8 +859,9 @@ int ur_addr_map_get(const ur_addr_map *map, ioa_addr *key, ur_addr_map_value_typ
const addr_elem *elem = addr_list_get_const(slh, key); const addr_elem *elem = addr_list_get_const(slh, key);
if (elem) { if (elem) {
if (value) if (value) {
*value = elem->value; *value = elem->value;
}
return 1; return 1;
} }
@ -862,8 +876,9 @@ int ur_addr_map_get(const ur_addr_map *map, ioa_addr *key, ur_addr_map_value_typ
*/ */
int ur_addr_map_del(ur_addr_map *map, ioa_addr *key, ur_addr_map_func delfunc) { int ur_addr_map_del(ur_addr_map *map, ioa_addr *key, ur_addr_map_func delfunc) {
if (!ur_addr_map_valid(map)) if (!ur_addr_map_valid(map)) {
return 0; return 0;
}
else { else {
@ -948,8 +963,9 @@ typedef struct _string_list_header {
} string_list_header; } string_list_header;
static size_t string_list_size(const string_list *sl) { static size_t string_list_size(const string_list *sl) {
if (!sl) if (!sl) {
return 0; return 0;
}
return 1 + string_list_size(sl->next); return 1 + string_list_size(sl->next);
} }
@ -959,10 +975,12 @@ static void string_list_free(string_list_header *slh, ur_string_map_func del_val
while (list) { while (list) {
string_elem *elem = (string_elem *)list; string_elem *elem = (string_elem *)list;
string_list *tail = elem->list.next; string_list *tail = elem->list.next;
if (elem->key) if (elem->key) {
free(elem->key); free(elem->key);
if (del_value_func && elem->value) }
if (del_value_func && elem->value) {
del_value_func(elem->value); del_value_func(elem->value);
}
free(elem); free(elem);
list = tail; list = tail;
} }
@ -971,8 +989,9 @@ static void string_list_free(string_list_header *slh, ur_string_map_func del_val
} }
static string_list *string_list_add(string_list *sl, const ur_string_map_key_type key, ur_string_map_value_type value) { static string_list *string_list_add(string_list *sl, const ur_string_map_key_type key, ur_string_map_value_type value) {
if (!key) if (!key) {
return sl; return sl;
}
string_elem *elem = (string_elem *)malloc(sizeof(string_elem)); string_elem *elem = (string_elem *)malloc(sizeof(string_elem));
elem->list.next = sl; elem->list.next = sl;
elem->key_size = strlen(key) + 1; elem->key_size = strlen(key) + 1;
@ -984,17 +1003,20 @@ static string_list *string_list_add(string_list *sl, const ur_string_map_key_typ
static string_list *string_list_remove(string_list *sl, const ur_string_map_key_type key, static string_list *string_list_remove(string_list *sl, const ur_string_map_key_type key,
ur_string_map_func del_value_func, int *counter) { ur_string_map_func del_value_func, int *counter) {
if (!sl || !key) if (!sl || !key) {
return sl; return sl;
}
string_elem *elem = (string_elem *)sl; string_elem *elem = (string_elem *)sl;
string_list *tail = elem->list.next; string_list *tail = elem->list.next;
if (strcmp(elem->key, key) == 0) { if (strcmp(elem->key, key) == 0) {
free(elem->key); free(elem->key);
if (del_value_func) if (del_value_func) {
del_value_func(elem->value); del_value_func(elem->value);
}
free(elem); free(elem);
if (counter) if (counter) {
*counter += 1; *counter += 1;
}
sl = string_list_remove(tail, key, del_value_func, counter); sl = string_list_remove(tail, key, del_value_func, counter);
} else { } else {
elem->list.next = string_list_remove(tail, key, del_value_func, counter); elem->list.next = string_list_remove(tail, key, del_value_func, counter);
@ -1004,8 +1026,9 @@ static string_list *string_list_remove(string_list *sl, const ur_string_map_key_
static string_elem *string_list_get(string_list *sl, const ur_string_map_key_type key) { static string_elem *string_list_get(string_list *sl, const ur_string_map_key_type key) {
if (!sl || !key) if (!sl || !key) {
return NULL; return NULL;
}
string_elem *elem = (string_elem *)sl; string_elem *elem = (string_elem *)sl;
if (strcmp(elem->key, key) == 0) { if (strcmp(elem->key, key) == 0) {
@ -1033,8 +1056,9 @@ static uint32_t string_hash(const ur_string_map_key_type key) {
uint32_t hash = 0; uint32_t hash = 0;
int c = 0; int c = 0;
while ((c = *str++)) while ((c = *str++)) {
hash = c + (hash << 6) + (hash << 16) - hash; hash = c + (hash << 6) + (hash << 16) - hash;
}
return hash; return hash;
} }
@ -1077,8 +1101,9 @@ ur_string_map *ur_string_map_create(ur_string_map_func del_value_func) {
*/ */
int ur_string_map_put(ur_string_map *map, const ur_string_map_key_type key, ur_string_map_value_type value) { int ur_string_map_put(ur_string_map *map, const ur_string_map_key_type key, ur_string_map_value_type value) {
if (!ur_string_map_valid(map)) if (!ur_string_map_valid(map)) {
return -1; return -1;
}
else { else {
@ -1087,8 +1112,9 @@ int ur_string_map_put(ur_string_map *map, const ur_string_map_key_type key, ur_s
string_elem *elem = string_list_get(slh->list, key); string_elem *elem = string_list_get(slh->list, key);
if (elem) { if (elem) {
if (elem->value != value) { if (elem->value != value) {
if (map->del_value_func) if (map->del_value_func) {
map->del_value_func(elem->value); map->del_value_func(elem->value);
}
elem->value = value; elem->value = value;
} }
return 0; return 0;
@ -1107,16 +1133,18 @@ int ur_string_map_put(ur_string_map *map, const ur_string_map_key_type key, ur_s
*/ */
int ur_string_map_get(ur_string_map *map, const ur_string_map_key_type key, ur_string_map_value_type *value) { int ur_string_map_get(ur_string_map *map, const ur_string_map_key_type key, ur_string_map_value_type *value) {
if (!ur_string_map_valid(map)) if (!ur_string_map_valid(map)) {
return 0; return 0;
}
else { else {
string_list_header *slh = get_string_list_header(map, key); string_list_header *slh = get_string_list_header(map, key);
string_elem *elem = string_list_get(slh->list, key); string_elem *elem = string_list_get(slh->list, key);
if (elem) { if (elem) {
if (value) if (value) {
*value = elem->value; *value = elem->value;
}
return 1; return 1;
} else { } else {
return 0; return 0;
@ -1131,8 +1159,9 @@ int ur_string_map_get(ur_string_map *map, const ur_string_map_key_type key, ur_s
*/ */
int ur_string_map_del(ur_string_map *map, const ur_string_map_key_type key) { int ur_string_map_del(ur_string_map *map, const ur_string_map_key_type key) {
if (!ur_string_map_valid(map)) if (!ur_string_map_valid(map)) {
return 0; return 0;
}
else { else {

View File

@ -108,9 +108,9 @@ static int foreachcb_free(ur_map_key_type key, ur_map_value_type value) {
* 0 - not found * 0 - not found
*/ */
static int rtcp_map_del(rtcp_map *map, rtcp_token_type token) { static int rtcp_map_del(rtcp_map *map, rtcp_token_type token) {
if (!rtcp_map_valid(map)) if (!rtcp_map_valid(map)) {
return 0; return 0;
else { } else {
TURN_MUTEX_LOCK(&map->mutex); TURN_MUTEX_LOCK(&map->mutex);
int ret = ur_map_del(map->map, token, rtcp_alloc_free); int ret = ur_map_del(map->map, token, rtcp_alloc_free);
TURN_MUTEX_UNLOCK(&map->mutex); TURN_MUTEX_UNLOCK(&map->mutex);
@ -119,9 +119,9 @@ static int rtcp_map_del(rtcp_map *map, rtcp_token_type token) {
} }
static int rtcp_map_del_savefd(rtcp_map *map, rtcp_token_type token) { static int rtcp_map_del_savefd(rtcp_map *map, rtcp_token_type token) {
if (!rtcp_map_valid(map)) if (!rtcp_map_valid(map)) {
return 0; return 0;
else { } else {
int ret = ur_map_del(map->map, token, rtcp_alloc_free_savefd); int ret = ur_map_del(map->map, token, rtcp_alloc_free_savefd);
return ret; return ret;
} }
@ -131,8 +131,9 @@ static void rtcp_map_timeout_handler(ioa_engine_handle e, void *arg) {
UNUSED_ARG(e); UNUSED_ARG(e);
if (!arg) if (!arg) {
return; return;
}
rtcp_map *map = (rtcp_map *)arg; rtcp_map *map = (rtcp_map *)arg;
@ -160,11 +161,13 @@ static int rtcp_map_init(rtcp_map *map, ioa_engine_handle e) {
if (map->magic != MAGIC_RTCP_MAP) { if (map->magic != MAGIC_RTCP_MAP) {
map->magic = MAGIC_RTCP_MAP; map->magic = MAGIC_RTCP_MAP;
map->map = ur_map_create(); map->map = ur_map_create();
if (e) if (e) {
map->timer_ev = set_ioa_timer(e, 3, 0, rtcp_map_timeout_handler, map, 1, "rtcp_map_timeout_handler"); map->timer_ev = set_ioa_timer(e, 3, 0, rtcp_map_timeout_handler, map, 1, "rtcp_map_timeout_handler");
}
TURN_MUTEX_INIT(&map->mutex); TURN_MUTEX_INIT(&map->mutex);
if (rtcp_map_valid(map)) if (rtcp_map_valid(map)) {
return 0; return 0;
}
} }
} }
return -1; return -1;
@ -185,12 +188,13 @@ rtcp_map *rtcp_map_create(ioa_engine_handle e) {
* -1 - error * -1 - error
*/ */
int rtcp_map_put(rtcp_map *map, rtcp_token_type token, ioa_socket_handle s) { int rtcp_map_put(rtcp_map *map, rtcp_token_type token, ioa_socket_handle s) {
if (!rtcp_map_valid(map)) if (!rtcp_map_valid(map)) {
return -1; return -1;
else { } else {
rtcp_alloc_type *value = (rtcp_alloc_type *)calloc(sizeof(rtcp_alloc_type), 1); rtcp_alloc_type *value = (rtcp_alloc_type *)calloc(sizeof(rtcp_alloc_type), 1);
if (!value) if (!value) {
return -1; return -1;
}
value->s = s; value->s = s;
value->t = turn_time() + RTCP_TIMEOUT; value->t = turn_time() + RTCP_TIMEOUT;
@ -199,8 +203,9 @@ int rtcp_map_put(rtcp_map *map, rtcp_token_type token, ioa_socket_handle s) {
int ret = ur_map_put(map->map, token, (ur_map_value_type)value); int ret = ur_map_put(map->map, token, (ur_map_value_type)value);
// TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s: 111.111: ret=%d, token=%llu\n",__FUNCTION__,ret,token); // TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s: 111.111: ret=%d, token=%llu\n",__FUNCTION__,ret,token);
TURN_MUTEX_UNLOCK(&map->mutex); TURN_MUTEX_UNLOCK(&map->mutex);
if (ret < 0) if (ret < 0) {
free(value); free(value);
}
return ret; return ret;
} }
} }

View File

@ -55,10 +55,11 @@ static inline int get_family(int stun_family, ioa_engine_handle e, ioa_socket_ha
return AF_INET6; return AF_INET6;
break; break;
case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT: case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT:
if (e->default_relays && get_ioa_socket_address_family(client_socket) == AF_INET6) if (e->default_relays && get_ioa_socket_address_family(client_socket) == AF_INET6) {
return AF_INET6; return AF_INET6;
else } else {
return AF_INET; return AF_INET;
}
default: default:
return AF_INET; return AF_INET;
}; };
@ -81,8 +82,9 @@ int TURN_MAX_ALLOCATE_TIMEOUT_STUN_ONLY = 3;
static inline void log_method(ts_ur_super_session *ss, const char *method, int err_code, const uint8_t *reason) { static inline void log_method(ts_ur_super_session *ss, const char *method, int err_code, const uint8_t *reason) {
if (ss) { if (ss) {
if (!method) if (!method) {
method = "unknown"; method = "unknown";
}
if (!err_code) { if (!err_code) {
if (ss->origin[0]) { if (ss->origin[0]) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
@ -95,8 +97,9 @@ static inline void log_method(ts_ur_super_session *ss, const char *method, int e
(unsigned long long)(ss->id), (const char *)(ss->realm_options.name), (const char *)(ss->username), method); (unsigned long long)(ss->id), (const char *)(ss->realm_options.name), (const char *)(ss->username), method);
} }
} else { } else {
if (!reason) if (!reason) {
reason = get_default_reason(err_code); reason = get_default_reason(err_code);
}
if (ss->origin[0]) { if (ss->origin[0]) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
"session %018llu: origin <%s> realm <%s> user <%s>: incoming packet %s processed, error %d: %s\n", "session %018llu: origin <%s> realm <%s> user <%s>: incoming packet %s processed, error %d: %s\n",
@ -231,8 +234,9 @@ void set_rfc5780(turn_turnserver *server, get_alt_addr_cb cb, send_message_cb sm
} }
static int is_rfc5780(turn_turnserver *server) { static int is_rfc5780(turn_turnserver *server) {
if (!server) if (!server) {
return 0; return 0;
}
return ((server->rfc5780) && (server->alt_addr_cb)); return ((server->rfc5780) && (server->alt_addr_cb));
} }
@ -264,12 +268,15 @@ static int good_peer_addr(turn_turnserver *server, const char *realm, ioa_addr *
turnserver_id server_id = (turnserver_id)(session_id / TURN_SESSION_ID_FACTOR); turnserver_id server_id = (turnserver_id)(session_id / TURN_SESSION_ID_FACTOR);
if (server && peer_addr) { if (server && peer_addr) {
if (*(server->no_multicast_peers) && ioa_addr_is_multicast(peer_addr)) if (*(server->no_multicast_peers) && ioa_addr_is_multicast(peer_addr)) {
return 0; return 0;
if (!*(server->allow_loopback_peers) && ioa_addr_is_loopback(peer_addr)) }
if (!*(server->allow_loopback_peers) && ioa_addr_is_loopback(peer_addr)) {
return 0; return 0;
if (ioa_addr_is_zero(peer_addr)) }
if (ioa_addr_is_zero(peer_addr)) {
return 0; return 0;
}
{ {
int i; int i;
@ -278,8 +285,9 @@ static int good_peer_addr(turn_turnserver *server, const char *realm, ioa_addr *
// White listing of addr ranges // White listing of addr ranges
for (i = server->ip_whitelist->ranges_number - 1; i >= 0; --i) { for (i = server->ip_whitelist->ranges_number - 1; i >= 0; --i) {
CHECK_REALM(server->ip_whitelist->rs[i].realm); CHECK_REALM(server->ip_whitelist->rs[i].realm);
if (ioa_addr_in_range(&(server->ip_whitelist->rs[i].enc), peer_addr)) if (ioa_addr_in_range(&(server->ip_whitelist->rs[i].enc), peer_addr)) {
return 1; return 1;
}
} }
} }
@ -480,45 +488,53 @@ int turn_session_info_copy_from(struct turn_session_info *tsi, ts_ur_super_sessi
STRCPY(tsi->realm, ss->realm_options.name); STRCPY(tsi->realm, ss->realm_options.name);
STRCPY(tsi->origin, ss->origin); STRCPY(tsi->origin, ss->origin);
if (ss->t_received_packets > ss->received_packets) if (ss->t_received_packets > ss->received_packets) {
tsi->received_packets = ss->t_received_packets; tsi->received_packets = ss->t_received_packets;
else } else {
tsi->received_packets = ss->received_packets; tsi->received_packets = ss->received_packets;
}
if (ss->t_sent_packets > ss->sent_packets) if (ss->t_sent_packets > ss->sent_packets) {
tsi->sent_packets = ss->t_sent_packets; tsi->sent_packets = ss->t_sent_packets;
else } else {
tsi->sent_packets = ss->sent_packets; tsi->sent_packets = ss->sent_packets;
}
if (ss->t_received_bytes > ss->received_bytes) if (ss->t_received_bytes > ss->received_bytes) {
tsi->received_bytes = ss->t_received_bytes; tsi->received_bytes = ss->t_received_bytes;
else } else {
tsi->received_bytes = ss->received_bytes; tsi->received_bytes = ss->received_bytes;
}
if (ss->t_sent_bytes > ss->sent_bytes) if (ss->t_sent_bytes > ss->sent_bytes) {
tsi->sent_bytes = ss->t_sent_bytes; tsi->sent_bytes = ss->t_sent_bytes;
else } else {
tsi->sent_bytes = ss->sent_bytes; tsi->sent_bytes = ss->sent_bytes;
}
if (ss->t_peer_received_packets > ss->peer_received_packets) if (ss->t_peer_received_packets > ss->peer_received_packets) {
tsi->peer_received_packets = ss->t_peer_received_packets; tsi->peer_received_packets = ss->t_peer_received_packets;
else } else {
tsi->peer_received_packets = ss->peer_received_packets; tsi->peer_received_packets = ss->peer_received_packets;
}
if (ss->t_peer_sent_packets > ss->peer_sent_packets) if (ss->t_peer_sent_packets > ss->peer_sent_packets) {
tsi->peer_sent_packets = ss->t_peer_sent_packets; tsi->peer_sent_packets = ss->t_peer_sent_packets;
else } else {
tsi->peer_sent_packets = ss->peer_sent_packets; tsi->peer_sent_packets = ss->peer_sent_packets;
}
if (ss->t_peer_received_bytes > ss->peer_received_bytes) if (ss->t_peer_received_bytes > ss->peer_received_bytes) {
tsi->peer_received_bytes = ss->t_peer_received_bytes; tsi->peer_received_bytes = ss->t_peer_received_bytes;
else } else {
tsi->peer_received_bytes = ss->peer_received_bytes; tsi->peer_received_bytes = ss->peer_received_bytes;
}
if (ss->t_peer_sent_bytes > ss->peer_sent_bytes) if (ss->t_peer_sent_bytes > ss->peer_sent_bytes) {
tsi->peer_sent_bytes = ss->t_peer_sent_bytes; tsi->peer_sent_bytes = ss->t_peer_sent_bytes;
else } else {
tsi->peer_sent_bytes = ss->peer_sent_bytes; tsi->peer_sent_bytes = ss->peer_sent_bytes;
}
{ {
tsi->received_rate = ss->received_rate; tsi->received_rate = ss->received_rate;
@ -597,8 +613,9 @@ int report_turn_session_info(turn_turnserver *server, ts_ur_super_session *ss, i
if (turn_session_info_copy_from(&tsi, ss) < 0) { if (turn_session_info_copy_from(&tsi, ss) < 0) {
turn_session_info_clean(&tsi); turn_session_info_clean(&tsi);
} else { } else {
if (force_invalid) if (force_invalid) {
tsi.valid = 0; tsi.valid = 0;
}
if (server->send_turn_session_info(&tsi) < 0) { if (server->send_turn_session_info(&tsi) < 0) {
turn_session_info_clean(&tsi); turn_session_info_clean(&tsi);
} else { } else {
@ -615,13 +632,15 @@ int report_turn_session_info(turn_turnserver *server, ts_ur_super_session *ss, i
static int mobile_id_to_string(mobile_id_t mid, char *dst, size_t dst_sz) { static int mobile_id_to_string(mobile_id_t mid, char *dst, size_t dst_sz) {
size_t output_length = 0; size_t output_length = 0;
if (!dst) if (!dst) {
return -1; return -1;
}
char *s = base64_encode((const unsigned char *)&mid, sizeof(mid), &output_length); char *s = base64_encode((const unsigned char *)&mid, sizeof(mid), &output_length);
if (!s) if (!s) {
return -1; return -1;
}
if (!output_length || (output_length + 1 > dst_sz)) { if (!output_length || (output_length + 1 > dst_sz)) {
free(s); free(s);
@ -668,9 +687,9 @@ static mobile_id_t get_new_mobile_id(turn_turnserver *server) {
sid = sid << 56; sid = sid << 56;
do { do {
while (!newid) { while (!newid) {
if (TURN_RANDOM_SIZE == sizeof(mobile_id_t)) if (TURN_RANDOM_SIZE == sizeof(mobile_id_t)) {
newid = (mobile_id_t)turn_random(); newid = (mobile_id_t)turn_random();
else { } else {
newid = (mobile_id_t)turn_random(); newid = (mobile_id_t)turn_random();
newid = (newid << 32) + (mobile_id_t)turn_random(); newid = (newid << 32) + (mobile_id_t)turn_random();
} }
@ -791,9 +810,9 @@ static void delete_ur_map_ss(void *p, SOCKET_TYPE socket_type) {
/////////// clean all ///////////////////// /////////// clean all /////////////////////
static int turn_server_remove_all_from_ur_map_ss(ts_ur_super_session *ss, SOCKET_TYPE socket_type) { static int turn_server_remove_all_from_ur_map_ss(ts_ur_super_session *ss, SOCKET_TYPE socket_type) {
if (!ss) if (!ss) {
return 0; return 0;
else { } else {
int ret = 0; int ret = 0;
if (ss->client_socket) { if (ss->client_socket) {
clear_ioa_socket_session_if(ss->client_socket, ss); clear_ioa_socket_session_if(ss->client_socket, ss);
@ -815,8 +834,9 @@ static void client_ss_channel_timeout_handler(ioa_engine_handle e, void *arg) {
UNUSED_ARG(e); UNUSED_ARG(e);
if (!arg) if (!arg) {
return; return;
}
ch_info *chn = (ch_info *)arg; ch_info *chn = (ch_info *)arg;
@ -861,8 +881,9 @@ static int update_turn_permission_lifetime(ts_ur_super_session *ss, turn_permiss
if (server) { if (server) {
if (!time_delta) if (!time_delta) {
time_delta = *(server->permission_lifetime); time_delta = *(server->permission_lifetime);
}
tinfo->expiration_time = server->ctime + time_delta; tinfo->expiration_time = server->ctime + time_delta;
IOA_EVENT_DEL(tinfo->lifetime_ev); IOA_EVENT_DEL(tinfo->lifetime_ev);
@ -896,8 +917,9 @@ static int update_channel_lifetime(ts_ur_super_session *ss, ch_info *chn) {
if (server) { if (server) {
if (update_turn_permission_lifetime(ss, tinfo, *(server->channel_lifetime)) < 0) if (update_turn_permission_lifetime(ss, tinfo, *(server->channel_lifetime)) < 0) {
return -1; return -1;
}
chn->expiration_time = server->ctime + *(server->channel_lifetime); chn->expiration_time = server->ctime + *(server->channel_lifetime);
@ -1090,8 +1112,9 @@ static int handle_turn_allocate(turn_turnserver *server, ts_ur_super_session *ss
} break; } break;
case STUN_ATTRIBUTE_DONT_FRAGMENT: case STUN_ATTRIBUTE_DONT_FRAGMENT:
dont_fragment = 1; dont_fragment = 1;
if (!(server->dont_fragment)) if (!(server->dont_fragment)) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
break; break;
case STUN_ATTRIBUTE_LIFETIME: { case STUN_ATTRIBUTE_LIFETIME: {
if (stun_attr_get_len(sar) != 4) { if (stun_attr_get_len(sar) != 4) {
@ -1178,8 +1201,9 @@ static int handle_turn_allocate(turn_turnserver *server, ts_ur_super_session *ss
} }
} break; } break;
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh),
sar); sar);
@ -1188,8 +1212,9 @@ static int handle_turn_allocate(turn_turnserver *server, ts_ur_super_session *ss
if (!transport) { if (!transport) {
*err_code = 400; *err_code = 400;
if (!(*reason)) if (!(*reason)) {
*reason = (const uint8_t *)"Transport field missed or wrong"; *reason = (const uint8_t *)"Transport field missed or wrong";
}
} else if (*ua_num > 0) { } else if (*ua_num > 0) {
@ -1203,8 +1228,9 @@ static int handle_turn_allocate(turn_turnserver *server, ts_ur_super_session *ss
(dont_fragment || in_reservation_token || (even_port != -1))) { (dont_fragment || in_reservation_token || (even_port != -1))) {
*err_code = 400; *err_code = 400;
if (!(*reason)) if (!(*reason)) {
*reason = (const uint8_t *)"Request parameters are incompatible with TCP transport"; *reason = (const uint8_t *)"Request parameters are incompatible with TCP transport";
}
} else { } else {
@ -1237,10 +1263,12 @@ static int handle_turn_allocate(turn_turnserver *server, ts_ur_super_session *ss
} }
} }
if (af4) if (af4) {
af4 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4; af4 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4;
if (af6) }
if (af6) {
af6 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6; af6 = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6;
}
if (af4 && af6) { if (af4 && af6) {
if (server->external_ip_set) { if (server->external_ip_set) {
@ -1527,8 +1555,9 @@ static int handle_turn_refresh(turn_turnserver *server, ts_ur_super_session *ss,
*reason = (const uint8_t *)"Wrong lifetime field data"; *reason = (const uint8_t *)"Wrong lifetime field data";
} else { } else {
lifetime = nswap32(*((const uint32_t *)value)); lifetime = nswap32(*((const uint32_t *)value));
if (!lifetime) if (!lifetime) {
to_delete = 1; to_delete = 1;
}
} }
} }
} break; } break;
@ -1564,8 +1593,9 @@ static int handle_turn_refresh(turn_turnserver *server, ts_ur_super_session *ss,
} }
} break; } break;
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh),
sar); sar);
@ -1653,9 +1683,9 @@ static int handle_turn_refresh(turn_turnserver *server, ts_ur_super_session *ss,
// Session transfer: // Session transfer:
if (to_delete) if (to_delete) {
lifetime = 0; lifetime = 0;
else { } else {
lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime),
ss->max_session_time_auth); ss->max_session_time_auth);
} }
@ -1767,9 +1797,9 @@ static int handle_turn_refresh(turn_turnserver *server, ts_ur_super_session *ss,
} else { } else {
if (to_delete) if (to_delete) {
lifetime = 0; lifetime = 0;
else { } else {
lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth); lifetime = stun_adjust_allocate_lifetime(lifetime, *(server->max_allocate_lifetime), ss->max_session_time_auth);
} }
@ -1840,8 +1870,9 @@ static void tcp_deliver_delayed_buffer(unsent_buffer *ub, ioa_socket_handle s, t
size_t i = 0; size_t i = 0;
do { do {
ioa_network_buffer_handle nbh = top_unsent_buffer(ub); ioa_network_buffer_handle nbh = top_unsent_buffer(ub);
if (!nbh) if (!nbh) {
break; break;
}
uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh); uint32_t bytes = (uint32_t)ioa_network_buffer_get_size(nbh);
@ -1860,8 +1891,9 @@ static void tcp_deliver_delayed_buffer(unsent_buffer *ub, ioa_socket_handle s, t
static void tcp_peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, static void tcp_peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg,
int can_resume) { int can_resume) {
if (!(event_type & IOA_EV_READ) || !arg) if (!(event_type & IOA_EV_READ) || !arg) {
return; return;
}
UNUSED_ARG(s); UNUSED_ARG(s);
UNUSED_ARG(can_resume); UNUSED_ARG(can_resume);
@ -1904,8 +1936,9 @@ static void tcp_peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_
static void tcp_client_input_handler_rfc6062data(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, static void tcp_client_input_handler_rfc6062data(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer,
void *arg, int can_resume) { void *arg, int can_resume) {
if (!(event_type & IOA_EV_READ) || !arg) if (!(event_type & IOA_EV_READ) || !arg) {
return; return;
}
UNUSED_ARG(s); UNUSED_ARG(s);
UNUSED_ARG(can_resume); UNUSED_ARG(can_resume);
@ -1917,11 +1950,13 @@ static void tcp_client_input_handler_rfc6062data(ioa_socket_handle s, int event_
ss = (ts_ur_super_session *)a->owner; ss = (ts_ur_super_session *)a->owner;
} }
if (tc->state != TC_STATE_READY) if (tc->state != TC_STATE_READY) {
return; return;
}
if (!(tc->peer_s)) if (!(tc->peer_s)) {
return; return;
}
ioa_network_buffer_handle nbh = in_buffer->nbh; ioa_network_buffer_handle nbh = in_buffer->nbh;
in_buffer->nbh = NULL; in_buffer->nbh = NULL;
@ -1943,8 +1978,9 @@ static void tcp_client_input_handler_rfc6062data(ioa_socket_handle s, int event_
ss->peer_sent_bytes += bytes; ss->peer_sent_bytes += bytes;
} }
if (ss) if (ss) {
turn_report_session_usage(ss, 0); turn_report_session_usage(ss, 0);
}
} }
static void tcp_conn_bind_timeout_handler(ioa_engine_handle e, void *arg) { static void tcp_conn_bind_timeout_handler(ioa_engine_handle e, void *arg) {
@ -1995,8 +2031,9 @@ static void tcp_peer_connection_completed_callback(int success, void *arg) {
char ls[257] = "\0"; char ls[257] = "\0";
char rs[257] = "\0"; char rs[257] = "\0";
ioa_addr *laddr = get_local_addr_from_ioa_socket(ss->client_socket); ioa_addr *laddr = get_local_addr_from_ioa_socket(ss->client_socket);
if (laddr) if (laddr) {
addr_to_string(laddr, (uint8_t *)ls); addr_to_string(laddr, (uint8_t *)ls);
}
addr_to_string(&(tc->peer_addr), (uint8_t *)rs); addr_to_string(&(tc->peer_addr), (uint8_t *)rs);
TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: failure to connect from %s to %s\n", __FUNCTION__, ls, rs); TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: failure to connect from %s to %s\n", __FUNCTION__, ls, rs);
} }
@ -2134,8 +2171,9 @@ static void tcp_peer_accept_connection(ioa_socket_handle s, void *arg) {
tcp_connection *tc = get_tcp_connection_by_peer(a, peer_addr); tcp_connection *tc = get_tcp_connection_by_peer(a, peer_addr);
if (tc) { if (tc) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: peer data socket with this address already exist\n", __FUNCTION__); TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: peer data socket with this address already exist\n", __FUNCTION__);
if (tc->peer_s != s) if (tc->peer_s != s) {
close_ioa_socket(s); close_ioa_socket(s);
}
FUNCEND; FUNCEND;
return; return;
} }
@ -2254,8 +2292,9 @@ static int handle_turn_connect(turn_turnserver *server, ts_ur_super_session *ss,
break; break;
} }
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh),
sar); sar);
@ -2335,8 +2374,9 @@ static int handle_turn_connection_bind(turn_turnserver *server, ts_ur_super_sess
} }
} break; } break;
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh),
sar); sar);
@ -2394,8 +2434,9 @@ static int handle_turn_connection_bind(turn_turnserver *server, ts_ur_super_sess
int turnserver_accept_tcp_client_data_connection(turn_turnserver *server, tcp_connection_id tcid, stun_tid *tid, int turnserver_accept_tcp_client_data_connection(turn_turnserver *server, tcp_connection_id tcid, stun_tid *tid,
ioa_socket_handle s, int message_integrity, ioa_net_data *in_buffer, ioa_socket_handle s, int message_integrity, ioa_net_data *in_buffer,
int can_resume) { int can_resume) {
if (!server) if (!server) {
return -1; return -1;
}
FUNCSTART; FUNCSTART;
@ -2453,8 +2494,9 @@ int turnserver_accept_tcp_client_data_connection(turn_turnserver *server, tcp_co
} }
} }
if (tc) if (tc) {
get_and_clean_tcp_connection_by_id(server->tcp_relay_connections, tcid); get_and_clean_tcp_connection_by_id(server->tcp_relay_connections, tcid);
}
if (!resp_constructed) { if (!resp_constructed) {
if (!err_code) { if (!err_code) {
@ -2575,8 +2617,9 @@ static int handle_turn_channel_bind(turn_turnserver *server, ts_ur_super_session
break; break;
} }
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh),
sar); sar);
@ -2701,8 +2744,9 @@ static int handle_turn_binding(turn_turnserver *server, ts_ur_super_session *ss,
SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket); SOCKET_TYPE st = get_ioa_socket_type(ss->client_socket);
int use_reflected_from = 0; int use_reflected_from = 0;
if (!(ss->client_socket)) if (!(ss->client_socket)) {
return -1; return -1;
}
*origin_changed = 0; *origin_changed = 0;
*dest_changed = 0; *dest_changed = 0;
@ -2781,8 +2825,9 @@ static int handle_turn_binding(turn_turnserver *server, ts_ur_super_session *ss,
} }
break; break;
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh),
sar); sar);
@ -2863,8 +2908,9 @@ static int handle_turn_binding(turn_turnserver *server, ts_ur_super_session *ss,
if (padding) { if (padding) {
int mtu = get_local_mtu_ioa_socket(ss->client_socket); int mtu = get_local_mtu_ioa_socket(ss->client_socket);
if (mtu < 68) if (mtu < 68) {
mtu = 1500; mtu = 1500;
}
mtu = (mtu >> 2) << 2; mtu = (mtu >> 2) << 2;
stun_attr_add_padding_str(ioa_network_buffer_data(nbh), &len, (uint16_t)mtu); stun_attr_add_padding_str(ioa_network_buffer_data(nbh), &len, (uint16_t)mtu);
@ -2905,10 +2951,11 @@ static int handle_turn_send(turn_turnserver *server, ts_ur_super_session *ss, in
switch (attr_type) { switch (attr_type) {
SKIP_ATTRIBUTES; SKIP_ATTRIBUTES;
case STUN_ATTRIBUTE_DONT_FRAGMENT: case STUN_ATTRIBUTE_DONT_FRAGMENT:
if (!(server->dont_fragment)) if (!(server->dont_fragment)) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
else } else {
set_df = 1; set_df = 1;
}
break; break;
case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: { case STUN_ATTRIBUTE_XOR_PEER_ADDRESS: {
if (addr_found) { if (addr_found) {
@ -2929,8 +2976,9 @@ static int handle_turn_send(turn_turnserver *server, ts_ur_super_session *ss, in
} }
} break; } break;
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), ioa_network_buffer_get_size(in_buffer->nbh),
sar); sar);
@ -2946,8 +2994,9 @@ static int handle_turn_send(turn_turnserver *server, ts_ur_super_session *ss, in
turn_permission_info *tinfo = NULL; turn_permission_info *tinfo = NULL;
if (!(server->server_relay)) if (!(server->server_relay)) {
tinfo = allocation_get_permission(a, &peer_addr); tinfo = allocation_get_permission(a, &peer_addr);
}
if (tinfo || (server->server_relay)) { if (tinfo || (server->server_relay)) {
@ -2985,8 +3034,9 @@ static int handle_turn_send(turn_turnserver *server, ts_ur_super_session *ss, in
static int update_permission(ts_ur_super_session *ss, ioa_addr *peer_addr) { static int update_permission(ts_ur_super_session *ss, ioa_addr *peer_addr) {
if (!ss || !peer_addr) if (!ss || !peer_addr) {
return -1; return -1;
}
allocation *a = get_allocation_ss(ss); allocation *a = get_allocation_ss(ss);
@ -2996,16 +3046,19 @@ static int update_permission(ts_ur_super_session *ss, ioa_addr *peer_addr) {
tinfo = allocation_add_permission(a, peer_addr); tinfo = allocation_add_permission(a, peer_addr);
} }
if (!tinfo) if (!tinfo) {
return -1; return -1;
}
if (update_turn_permission_lifetime(ss, tinfo, 0) < 0) if (update_turn_permission_lifetime(ss, tinfo, 0) < 0) {
return -1; return -1;
}
ch_info *chn = get_turn_channel(tinfo, peer_addr); ch_info *chn = get_turn_channel(tinfo, peer_addr);
if (chn) { if (chn) {
if (update_channel_lifetime(ss, chn) < 0) if (update_channel_lifetime(ss, chn) < 0) {
return -1; return -1;
}
} }
return 0; return 0;
@ -3057,8 +3110,9 @@ static int handle_turn_create_permission(turn_turnserver *server, ts_ur_super_se
} }
} break; } break;
default: default:
if (attr_type >= 0x0000 && attr_type <= 0x7FFF) if (attr_type >= 0x0000 && attr_type <= 0x7FFF) {
unknown_attrs[(*ua_num)++] = nswap16(attr_type); unknown_attrs[(*ua_num)++] = nswap16(attr_type);
}
}; };
sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh), sar = stun_attr_get_next_str(ioa_network_buffer_data(in_buffer->nbh),
ioa_network_buffer_get_size(in_buffer->nbh), sar); ioa_network_buffer_get_size(in_buffer->nbh), sar);
@ -3210,8 +3264,9 @@ static int check_stun_auth(turn_turnserver *server, ts_ur_super_session *ss, stu
uint8_t realm[STUN_MAX_REALM_SIZE + 1]; uint8_t realm[STUN_MAX_REALM_SIZE + 1];
size_t alen = 0; size_t alen = 0;
if (!need_stun_authentication(server, ss)) if (!need_stun_authentication(server, ss)) {
return 0; return 0;
}
int new_nonce = 0; int new_nonce = 0;
@ -3441,13 +3496,15 @@ static void set_alternate_server(turn_server_addrs_list_t *asl, const ioa_addr *
for (i = 0; i < asl->size; ++i) { for (i = 0; i < asl->size; ++i) {
ioa_addr *addr = &(asl->addrs[i]); ioa_addr *addr = &(asl->addrs[i]);
if (addr_eq(addr, local_addr)) if (addr_eq(addr, local_addr)) {
return; return;
}
} }
for (i = 0; i < asl->size; ++i) { for (i = 0; i < asl->size; ++i) {
if (*counter >= asl->size) if (*counter >= asl->size) {
*counter = 0; *counter = 0;
}
ioa_addr *addr = &(asl->addrs[*counter]); ioa_addr *addr = &(asl->addrs[*counter]);
*counter += 1; *counter += 1;
if (addr->ss.sa_family == local_addr->ss.sa_family) { if (addr->ss.sa_family == local_addr->ss.sa_family) {
@ -3475,8 +3532,9 @@ static int handle_turn_command(turn_turnserver *server, ts_ur_super_session *ss,
int no_response = 0; int no_response = 0;
int message_integrity = 0; int message_integrity = 0;
if (!(ss->client_socket)) if (!(ss->client_socket)) {
return -1; return -1;
}
uint16_t unknown_attrs[MAX_NUMBER_OF_UNKNOWN_ATTRS]; uint16_t unknown_attrs[MAX_NUMBER_OF_UNKNOWN_ATTRS];
uint16_t ua_num = 0; uint16_t ua_num = 0;
@ -3636,8 +3694,9 @@ static int handle_turn_command(turn_turnserver *server, ts_ur_super_session *ss,
int postpone_reply = 0; int postpone_reply = 0;
check_stun_auth(server, ss, &tid, resp_constructed, &err_code, &reason, in_buffer, nbh, method, check_stun_auth(server, ss, &tid, resp_constructed, &err_code, &reason, in_buffer, nbh, method,
&message_integrity, &postpone_reply, can_resume); &message_integrity, &postpone_reply, can_resume);
if (postpone_reply) if (postpone_reply) {
no_response = 1; no_response = 1;
}
} }
} }
} }
@ -3667,8 +3726,9 @@ static int handle_turn_command(turn_turnserver *server, ts_ur_super_session *ss,
log_method(ss, "CONNECT", err_code, reason); log_method(ss, "CONNECT", err_code, reason);
} }
if (!err_code) if (!err_code) {
no_response = 1; no_response = 1;
}
break; break;
@ -3808,8 +3868,9 @@ static int handle_turn_command(turn_turnserver *server, ts_ur_super_session *ss,
} }
} }
if (ss->to_be_closed || !(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) if (ss->to_be_closed || !(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) {
return 0; return 0;
}
if (ua_num > 0) { if (ua_num > 0) {
@ -3830,8 +3891,9 @@ static int handle_turn_command(turn_turnserver *server, ts_ur_super_session *ss,
if (!(*resp_constructed)) { if (!(*resp_constructed)) {
if (!err_code) if (!err_code) {
err_code = 400; err_code = 400;
}
size_t len = ioa_network_buffer_get_size(nbh); size_t len = ioa_network_buffer_get_size(nbh);
stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid); stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid);
@ -3918,8 +3980,9 @@ static int handle_old_stun_command(turn_turnserver *server, ts_ur_super_session
size_t newsz = (((oldsz) >> 2) + 1) << 2; size_t newsz = (((oldsz) >> 2) + 1) << 2;
uint8_t software[120]; uint8_t software[120];
memset(software, 0, sizeof(software)); memset(software, 0, sizeof(software));
if (newsz > sizeof(software)) if (newsz > sizeof(software)) {
newsz = sizeof(software); newsz = sizeof(software);
}
memcpy(software, get_version(server), oldsz); memcpy(software, get_version(server), oldsz);
size_t len = ioa_network_buffer_get_size(nbh); size_t len = ioa_network_buffer_get_size(nbh);
stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz);
@ -3959,8 +4022,9 @@ static int handle_old_stun_command(turn_turnserver *server, ts_ur_super_session
if (!(*resp_constructed)) { if (!(*resp_constructed)) {
if (!err_code) if (!err_code) {
err_code = 400; err_code = 400;
}
size_t len = ioa_network_buffer_get_size(nbh); size_t len = ioa_network_buffer_get_size(nbh);
old_stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid, cookie); old_stun_init_error_response_str(method, ioa_network_buffer_data(nbh), &len, err_code, reason, &tid, cookie);
@ -3973,8 +4037,9 @@ static int handle_old_stun_command(turn_turnserver *server, ts_ur_super_session
size_t newsz = (((oldsz) >> 2) + 1) << 2; size_t newsz = (((oldsz) >> 2) + 1) << 2;
uint8_t software[120]; uint8_t software[120];
memset(software, 0, sizeof(software)); memset(software, 0, sizeof(software));
if (newsz > sizeof(software)) if (newsz > sizeof(software)) {
newsz = sizeof(software); newsz = sizeof(software);
}
memcpy(software, get_version(server), oldsz); memcpy(software, get_version(server), oldsz);
size_t len = ioa_network_buffer_get_size(nbh); size_t len = ioa_network_buffer_get_size(nbh);
stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz); stun_attr_add_str(ioa_network_buffer_data(nbh), &len, OLD_STUN_ATTRIBUTE_SERVER, software, newsz);
@ -4008,8 +4073,9 @@ static int write_to_peerchannel(ts_ur_super_session *ss, uint16_t chnum, ioa_net
ch_info *chn = allocation_get_ch_info(a, chnum); ch_info *chn = allocation_get_ch_info(a, chnum);
if (!chn) if (!chn) {
return -1; return -1;
}
/* Channel packets are always sent with DF=0: */ /* Channel packets are always sent with DF=0: */
set_df_on_ioa_socket(get_relay_socket_ss(ss, chn->peer_addr.ss.sa_family), 0); set_df_on_ioa_socket(get_relay_socket_ss(ss, chn->peer_addr.ss.sa_family), 0);
@ -4047,8 +4113,9 @@ int shutdown_client_connection(turn_turnserver *server, ts_ur_super_session *ss,
FUNCSTART; FUNCSTART;
if (!ss) if (!ss) {
return -1; return -1;
}
SOCKET_TYPE socket_type = get_ioa_socket_type(ss->client_socket); SOCKET_TYPE socket_type = get_ioa_socket_type(ss->client_socket);
@ -4089,8 +4156,9 @@ int shutdown_client_connection(turn_turnserver *server, ts_ur_super_session *ss,
(long)ss->client_socket, (long)get_ioa_socket_session(ss->client_socket)); (long)ss->client_socket, (long)get_ioa_socket_session(ss->client_socket));
} }
if (server->disconnect) if (server->disconnect) {
server->disconnect(ss); server->disconnect(ss);
}
if (server->verbose) { if (server->verbose) {
@ -4123,8 +4191,9 @@ int shutdown_client_connection(turn_turnserver *server, ts_ur_super_session *ss,
static void client_to_be_allocated_timeout_handler(ioa_engine_handle e, void *arg) { static void client_to_be_allocated_timeout_handler(ioa_engine_handle e, void *arg) {
if (!arg) if (!arg) {
return; return;
}
UNUSED_ARG(e); UNUSED_ARG(e);
@ -4132,8 +4201,9 @@ static void client_to_be_allocated_timeout_handler(ioa_engine_handle e, void *ar
turn_turnserver *server = (turn_turnserver *)(ss->server); turn_turnserver *server = (turn_turnserver *)(ss->server);
if (!server) if (!server) {
return; return;
}
FUNCSTART; FUNCSTART;
@ -4201,18 +4271,21 @@ static void client_ss_allocation_timeout_handler(ioa_engine_handle e, void *arg)
UNUSED_ARG(e); UNUSED_ARG(e);
if (!arg) if (!arg) {
return; return;
}
relay_endpoint_session *rsession = (relay_endpoint_session *)arg; relay_endpoint_session *rsession = (relay_endpoint_session *)arg;
if (!(rsession->s)) if (!(rsession->s)) {
return; return;
}
ts_ur_super_session *ss = get_ioa_socket_session(rsession->s); ts_ur_super_session *ss = get_ioa_socket_session(rsession->s);
if (!ss) if (!ss) {
return; return;
}
allocation *a = get_allocation_ss(ss); allocation *a = get_allocation_ss(ss);
@ -4287,10 +4360,12 @@ static int create_relay_connection(turn_turnserver *server, ts_ur_super_session
int res = create_relay_ioa_sockets(server->e, ss->client_socket, address_family, transport, even_port, int res = create_relay_ioa_sockets(server->e, ss->client_socket, address_family, transport, even_port,
&(newelem->s), &rtcp_s, out_reservation_token, err_code, reason, acb, ss); &(newelem->s), &rtcp_s, out_reservation_token, err_code, reason, acb, ss);
if (res < 0) { if (res < 0) {
if (!(*err_code)) if (!(*err_code)) {
*err_code = 508; *err_code = 508;
if (!(*reason)) }
if (!(*reason)) {
*reason = (const uint8_t *)"Cannot create socket"; *reason = (const uint8_t *)"Cannot create socket";
}
IOA_CLOSE_SOCKET(newelem->s); IOA_CLOSE_SOCKET(newelem->s);
IOA_CLOSE_SOCKET(rtcp_s); IOA_CLOSE_SOCKET(rtcp_s);
return -1; return -1;
@ -4318,8 +4393,9 @@ static int create_relay_connection(turn_turnserver *server, ts_ur_super_session
/* RFC6156: do not use DF when IPv6 is involved: */ /* RFC6156: do not use DF when IPv6 is involved: */
if ((get_ioa_socket_address_family(newelem->s) == AF_INET6) || if ((get_ioa_socket_address_family(newelem->s) == AF_INET6) ||
(get_ioa_socket_address_family(ss->client_socket) == AF_INET6)) (get_ioa_socket_address_family(ss->client_socket) == AF_INET6)) {
set_do_not_use_df(newelem->s); set_do_not_use_df(newelem->s);
}
if (get_ioa_socket_type(newelem->s) != TCP_SOCKET) { if (get_ioa_socket_type(newelem->s) != TCP_SOCKET) {
if (register_callback_on_ioa_socket(server->e, newelem->s, IOA_EV_READ, peer_input_handler, ss, 0) < 0) { if (register_callback_on_ioa_socket(server->e, newelem->s, IOA_EV_READ, peer_input_handler, ss, 0) < 0) {
@ -4327,10 +4403,11 @@ static int create_relay_connection(turn_turnserver *server, ts_ur_super_session
} }
} }
if (lifetime < 1) if (lifetime < 1) {
lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME; lifetime = STUN_DEFAULT_ALLOCATE_LIFETIME;
else if (lifetime > (uint32_t) * (server->max_allocate_lifetime)) } else if (lifetime > (uint32_t) * (server->max_allocate_lifetime)) {
lifetime = (uint32_t) * (server->max_allocate_lifetime); lifetime = (uint32_t) * (server->max_allocate_lifetime);
}
ioa_timer_handle ev = set_ioa_timer(server->e, lifetime, 0, client_ss_allocation_timeout_handler, newelem, 0, ioa_timer_handle ev = set_ioa_timer(server->e, lifetime, 0, client_ss_allocation_timeout_handler, newelem, 0,
"client_ss_allocation_timeout_handler"); "client_ss_allocation_timeout_handler");
@ -4457,8 +4534,9 @@ static int read_client_connection(turn_turnserver *server, ts_ur_super_session *
handle_turn_command(server, ss, in_buffer, nbh, &resp_constructed, can_resume); handle_turn_command(server, ss, in_buffer, nbh, &resp_constructed, can_resume);
if ((method != STUN_METHOD_BINDING) && (method != STUN_METHOD_SEND)) if ((method != STUN_METHOD_BINDING) && (method != STUN_METHOD_SEND)) {
report_turn_session_info(server, ss, 0); report_turn_session_info(server, ss, 0);
}
if (ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) { if (ss->to_be_closed || ioa_socket_tobeclosed(ss->client_socket)) {
FUNCEND; FUNCEND;
@ -4619,11 +4697,13 @@ static int attach_socket_to_session(turn_turnserver *server, ioa_socket_handle s
int open_client_connection_session(turn_turnserver *server, struct socket_message *sm) { int open_client_connection_session(turn_turnserver *server, struct socket_message *sm) {
int ret = 0; int ret = 0;
FUNCSTART; FUNCSTART;
if (!server) if (!server) {
return -1; return -1;
}
if (!(sm->s)) if (!(sm->s)) {
return -1; return -1;
}
ts_ur_super_session *ss = create_new_ss(server); ts_ur_super_session *ss = create_new_ss(server);
@ -4636,8 +4716,9 @@ int open_client_connection_session(turn_turnserver *server, struct socket_messag
set_ioa_socket_session(ss->client_socket, ss); set_ioa_socket_session(ss->client_socket, ss);
int at = TURN_MAX_ALLOCATE_TIMEOUT; int at = TURN_MAX_ALLOCATE_TIMEOUT;
if (*(server->stun_only)) if (*(server->stun_only)) {
at = TURN_MAX_ALLOCATE_TIMEOUT_STUN_ONLY; at = TURN_MAX_ALLOCATE_TIMEOUT_STUN_ONLY;
}
IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev); IOA_EVENT_DEL(ss->to_be_allocated_timeout_ev);
ss->to_be_allocated_timeout_ev = set_ioa_timer(server->e, at, 0, client_to_be_allocated_timeout_handler, ss, 1, ss->to_be_allocated_timeout_ev = set_ioa_timer(server->e, at, 0, client_to_be_allocated_timeout_handler, ss, 1,
@ -4659,32 +4740,39 @@ int open_client_connection_session(turn_turnserver *server, struct socket_messag
static void peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg, static void peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *in_buffer, void *arg,
int can_resume) { int can_resume) {
if (!(event_type & IOA_EV_READ) || !arg) if (!(event_type & IOA_EV_READ) || !arg) {
return; return;
}
if (in_buffer->recv_ttl == 0) if (in_buffer->recv_ttl == 0) {
return; return;
}
UNUSED_ARG(can_resume); UNUSED_ARG(can_resume);
if (!s || ioa_socket_tobeclosed(s)) if (!s || ioa_socket_tobeclosed(s)) {
return; return;
}
ts_ur_super_session *ss = (ts_ur_super_session *)arg; ts_ur_super_session *ss = (ts_ur_super_session *)arg;
if (!ss) if (!ss) {
return; return;
}
if (ss->to_be_closed) if (ss->to_be_closed) {
return; return;
}
if (!(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) if (!(ss->client_socket) || ioa_socket_tobeclosed(ss->client_socket)) {
return; return;
}
turn_turnserver *server = (turn_turnserver *)(ss->server); turn_turnserver *server = (turn_turnserver *)(ss->server);
if (!server) if (!server) {
return; return;
}
relay_endpoint_session *elem = get_relay_session_ss(ss, get_ioa_socket_address_family(s)); relay_endpoint_session *elem = get_relay_session_ss(ss, get_ioa_socket_address_family(s));
if (elem->s == NULL) { if (elem->s == NULL) {
@ -4773,8 +4861,9 @@ static void peer_input_handler(ioa_socket_handle s, int event_type, ioa_net_data
static void client_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume) { static void client_input_handler(ioa_socket_handle s, int event_type, ioa_net_data *data, void *arg, int can_resume) {
if (!arg) if (!arg) {
return; return;
}
UNUSED_ARG(s); UNUSED_ARG(s);
UNUSED_ARG(event_type); UNUSED_ARG(event_type);
@ -4821,8 +4910,9 @@ void init_turn_server(turn_turnserver *server, turnserver_id id, int verbose, io
vintp log_binding, vintp no_stun_backward_compatibility, vintp response_origin_only_with_rfc5780, vintp log_binding, vintp no_stun_backward_compatibility, vintp response_origin_only_with_rfc5780,
vintp respond_http_unsupported) { vintp respond_http_unsupported) {
if (!server) if (!server) {
return; return;
}
memset(server, 0, sizeof(turn_turnserver)); memset(server, 0, sizeof(turn_turnserver));
@ -4844,10 +4934,12 @@ void init_turn_server(turn_turnserver *server, turnserver_id id, int verbose, io
server->send_turn_session_info = send_turn_session_info; server->send_turn_session_info = send_turn_session_info;
server->send_https_socket = send_https_socket; server->send_https_socket = send_https_socket;
server->oauth = oauth; server->oauth = oauth;
if (oauth) if (oauth) {
server->oauth_server_name = oauth_server_name; server->oauth_server_name = oauth_server_name;
if (mobility) }
if (mobility) {
server->mobile_connections_map = ur_map_create(); server->mobile_connections_map = ur_map_create();
}
server->acme_redirect = acme_redirect; server->acme_redirect = acme_redirect;
TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "turn server id=%d created\n", (int)id); TURN_LOG_FUNC(TURN_LOG_LEVEL_DEBUG, "turn server id=%d created\n", (int)id);
@ -4876,8 +4968,9 @@ void init_turn_server(turn_turnserver *server, turnserver_id id, int verbose, io
addr_cpy(&(server->external_ip), external_ip); addr_cpy(&(server->external_ip), external_ip);
server->external_ip_set = 1; server->external_ip_set = 1;
} }
if (stun_port < 1) if (stun_port < 1) {
stun_port = DEFAULT_STUN_PORT; stun_port = DEFAULT_STUN_PORT;
}
server->verbose = verbose; server->verbose = verbose;
@ -4902,8 +4995,9 @@ void init_turn_server(turn_turnserver *server, turnserver_id id, int verbose, io
} }
ioa_engine_handle turn_server_get_engine(turn_turnserver *s) { ioa_engine_handle turn_server_get_engine(turn_turnserver *s) {
if (s) if (s) {
return s->e; return s->e;
}
return NULL; return NULL;
} }