From b198d1da2e53984e528d6477d8cce1873a97911f Mon Sep 17 00:00:00 2001 From: Max Lv Date: Wed, 12 Nov 2014 13:12:59 +0800 Subject: [PATCH] bump version --- .uncrustify.cfg | 80 +++ README.md | 2 +- configure | 20 +- configure.ac | 2 +- debian/changelog | 6 + openwrt/Makefile | 2 +- src/acl.c | 73 ++- src/acl.h | 4 +- src/cache.c | 70 +-- src/cache.h | 18 +- src/encrypt.c | 464 ++++++--------- src/encrypt.h | 23 +- src/jconf.c | 111 ++-- src/jconf.h | 14 +- src/json.c | 748 ++++++++++++------------ src/json.h | 291 +++++----- src/local.c | 668 +++++++++------------- src/local.h | 15 +- src/redir.c | 439 ++++++-------- src/redir.h | 15 +- src/server.c | 613 ++++++++------------ src/server.h | 15 +- src/shadowsocks.h | 33 +- src/socks5.h | 12 +- src/tunnel.c | 419 ++++++-------- src/tunnel.h | 15 +- src/udprelay.c | 379 ++++++------ src/udprelay.h | 21 +- src/uthash.h | 1395 +++++++++++++++++++++++---------------------- src/utils.c | 173 +++--- src/utils.h | 144 ++--- src/win32.c | 29 +- src/win32.h | 2 +- 33 files changed, 2953 insertions(+), 3362 deletions(-) create mode 100644 .uncrustify.cfg diff --git a/.uncrustify.cfg b/.uncrustify.cfg new file mode 100644 index 00000000..589e53b5 --- /dev/null +++ b/.uncrustify.cfg @@ -0,0 +1,80 @@ +# +# based on uncrustify config file for the linux kernel +# + +code_width = 80 +indent_case_brace = 4 +indent_columns = 4 +indent_label = 2 # pos: absolute col, neg: relative column +indent_with_tabs = 0 + +# +# inter-symbol newlines +# +nl_brace_else = remove # "} else" vs "} \n else" - cuddle else +nl_brace_while = remove # "} while" vs "} \n while" - cuddle while +nl_do_brace = remove # "do {" vs "do \n {" +nl_else_brace = remove # "else {" vs "else \n {" +nl_enum_brace = remove # "enum {" vs "enum \n {" +nl_fcall_brace = remove # "list_for_each() {" vs "list_for_each()\n{" +nl_fdef_brace = force # "int foo() {" vs "int foo()\n{" +nl_for_brace = remove # "for () {" vs "for () \n {" +nl_func_var_def_blk = 0 # don't add newlines after a block of var declarations +nl_if_brace = remove # "if () {" vs "if () \n {" +nl_multi_line_define = true +nl_struct_brace = remove # "struct {" vs "struct \n {" +nl_switch_brace = remove # "switch () {" vs "switch () \n {" +nl_union_brace = remove # "union {" vs "union \n {" +nl_while_brace = remove # "while () {" vs "while () \n {" + + +# +# Source code modifications +# +mod_full_brace_do = force # "do a--; while ();" vs "do { a--; } while ();" +mod_full_brace_for = force # "for () a--;" vs "for () { a--; }" +mod_full_brace_if = force # "if (a) a--;" vs "if (a) { a--; }" +mod_full_brace_nl = 3 # don't remove if more than 3 newlines +mod_full_brace_while = force # "while (a) a--;" vs "while (a) { a--; }" +mod_paren_on_return = remove # "return 1;" vs "return (1);" + + +# +# inter-character spacing options +# +sp_after_cast = remove # "(int) a" vs "(int)a" +sp_after_comma = force +sp_after_sparen = force # "if () {" vs "if (){" +sp_arith = force +sp_assign = force +sp_assign = force +sp_before_comma = remove +sp_before_ptr_star = force # "char *foo" vs "char* foo +sp_before_sparen = force # "if (" vs "if(" +sp_between_ptr_star = remove # "char * *foo" vs "char **foo" +sp_bool = force +sp_compare = force +sp_func_call_paren = remove # "foo (" vs "foo(" +sp_func_def_paren = remove # "int foo (){" vs "int foo(){" +sp_func_proto_paren = remove # "int foo ();" vs "int foo();" +sp_inside_braces = force # "{ 1 }" vs "{1}" +sp_inside_braces_enum = force # "{ 1 }" vs "{1}" +sp_inside_braces_struct = force # "{ 1 }" vs "{1}" +sp_inside_sparen = remove +sp_paren_brace = force +sp_sizeof_paren = remove # "sizeof (int)" vs "sizeof(int)" +sp_else_brace = force +sp_brace_else = force + +# +# Aligning stuff +# +align_enum_equ_span = 4 # '=' in enum definition +align_nl_cont = true +align_on_tabstop = FALSE # align on tabstops +align_right_cmt_span = 3 +align_struct_init_span = 1 +align_struct_init_span = 3 # align stuff in a structure init '= { }' +align_var_def_star_style = 2 # void *foo; +align_var_struct_span = 0 +align_with_tabs = FALSE # use tabs to align diff --git a/README.md b/README.md index b959d73b..2b4e688b 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ It is a port of [shadowsocks](https://github.com/clowwindy/shadowsocks) created by [@clowwindy](https://github.com/clowwindy) maintained by [@madeye](https://github.com/madeye) and [@linusyang](https://github.com/linusyang). -Current version: 1.5.1 | [![Build Status](https://travis-ci.org/madeye/shadowsocks-libev.png?branch=master)](https://travis-ci.org/madeye/shadowsocks-libev) | [Changelog](Changes) +Current version: 1.5.2 | [![Build Status](https://travis-ci.org/madeye/shadowsocks-libev.png?branch=master)](https://travis-ci.org/madeye/shadowsocks-libev) | [Changelog](Changes) Features -------- diff --git a/configure b/configure index dbc0e6b0..68eabb9d 100755 --- a/configure +++ b/configure @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.68 for shadowsocks 1.5.1. +# Generated by GNU Autoconf 2.68 for shadowsocks 1.5.2. # # Report bugs to . # @@ -570,8 +570,8 @@ MAKEFLAGS= # Identity of this package. PACKAGE_NAME='shadowsocks' PACKAGE_TARNAME='shadowsocks' -PACKAGE_VERSION='1.5.1' -PACKAGE_STRING='shadowsocks 1.5.1' +PACKAGE_VERSION='1.5.2' +PACKAGE_STRING='shadowsocks 1.5.2' PACKAGE_BUGREPORT='max.c.lv@gmail.com' PACKAGE_URL='' @@ -1307,7 +1307,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures shadowsocks 1.5.1 to adapt to many kinds of systems. +\`configure' configures shadowsocks 1.5.2 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1377,7 +1377,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of shadowsocks 1.5.1:";; + short | recursive ) echo "Configuration of shadowsocks 1.5.2:";; esac cat <<\_ACEOF @@ -1494,7 +1494,7 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -shadowsocks configure 1.5.1 +shadowsocks configure 1.5.2 generated by GNU Autoconf 2.68 Copyright (C) 2010 Free Software Foundation, Inc. @@ -2016,7 +2016,7 @@ cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by shadowsocks $as_me 1.5.1, which was +It was created by shadowsocks $as_me 1.5.2, which was generated by GNU Autoconf 2.68. Invocation command line was $ $0 $@ @@ -2837,7 +2837,7 @@ fi # Define the identity of the package. PACKAGE='shadowsocks' - VERSION='1.5.1' + VERSION='1.5.2' cat >>confdefs.h <<_ACEOF @@ -15533,7 +15533,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by shadowsocks $as_me 1.5.1, which was +This file was extended by shadowsocks $as_me 1.5.2, which was generated by GNU Autoconf 2.68. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -15599,7 +15599,7 @@ _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ -shadowsocks config.status 1.5.1 +shadowsocks config.status 1.5.2 configured by $0, generated by GNU Autoconf 2.68, with options \\"\$ac_cs_config\\" diff --git a/configure.ac b/configure.ac index f97e111f..b34eebda 100755 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl -*- Autoconf -*- dnl Process this file with autoconf to produce a configure script. AC_PREREQ([2.67]) -AC_INIT([shadowsocks], [1.5.1], [max.c.lv@gmail.com]) +AC_INIT([shadowsocks], [1.5.2], [max.c.lv@gmail.com]) AC_CONFIG_SRCDIR([src/encrypt.c]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_AUX_DIR(auto) diff --git a/debian/changelog b/debian/changelog index 76a30af7..5161056a 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +shadowsocks (1.5.2-1) unstable; urgency=low + + * Handle SIGTERM and SIGKILL nicely. + + -- Max Lv Tue, 12 Nov 2014 13:11:29 +0800 + shadowsocks (1.5.1-1) unstable; urgency=low * Fix a bug of tcp fast open. diff --git a/openwrt/Makefile b/openwrt/Makefile index 263b7187..786a9b55 100644 --- a/openwrt/Makefile +++ b/openwrt/Makefile @@ -1,7 +1,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=shadowsocks-libev -PKG_VERSION:=1.5.1 +PKG_VERSION:=1.5.2 PKG_RELEASE=$(PKG_SOURCE_VERSION) PKG_SOURCE_URL:=https://github.com/madeye/shadowsocks-libev/archive diff --git a/src/acl.c b/src/acl.c index f9b5bf11..5cf67fef 100644 --- a/src/acl.c +++ b/src/acl.c @@ -34,26 +34,20 @@ static void parse_addr_cidr(const char *str, char **host, int *cidr) char *pch; pch = strchr(str, '/'); - while (pch != NULL) - { + while (pch != NULL) { n++; ret = pch - str; pch = strchr(pch + 1, '/'); } - if (n > 1) - { - if (strcmp(str+ret, "]") != 0) - { + if (n > 1) { + if (strcmp(str + ret, "]") != 0) { ret = -1; } } - if (ret == -1) - { + if (ret == -1) { *host = strdup(str); *cidr = -1; - } - else - { + } else { *host = ss_strndup(str, ret); *cidr = atoi(strdup(str + ret + 1)); } @@ -69,21 +63,17 @@ int init_acl(const char *path) cork_string_array_init(&acl_domain_array); FILE *f = fopen(path, "r"); - if (f == NULL) - { + if (f == NULL) { LOGE("Invalid acl path."); return -1; } char line[256]; - while(!feof(f)) - { - if (fgets(line, 256, f)) - { + while (!feof(f)) { + if (fgets(line, 256, f)) { // Trim the newline int len = strlen(line); - if (len > 0 && line[len - 1] == '\n') - { + if (len > 0 && line[len - 1] == '\n') { line[len - 1] = '\0'; } @@ -91,24 +81,23 @@ int init_acl(const char *path) int cidr; parse_addr_cidr(line, &host, &cidr); - if (cidr == -1) - { + if (cidr == -1) { cork_string_array_append(&acl_domain_array, host); - } - else - { + } else { struct cork_ipv4 addr; int err = cork_ipv4_init(&addr, host); - if (!err) - { - if (cidr >= 0) + if (!err) { + if (cidr >= 0) { ipset_ipv4_add_network(&acl_ip_set, &addr, cidr); - else + } else { ipset_ipv4_add(&acl_ip_set, &addr); + } } } - if (host != NULL) free(host); + if (host != NULL) { + free(host); + } } } @@ -122,39 +111,43 @@ void free_acl(void) ipset_done(&acl_ip_set); } -int acl_contains_domain(const char* domain) +int acl_contains_domain(const char * domain) { const char **list = acl_domain_array.items; const int size = acl_domain_array.size; const int domain_len = strlen(domain); int i, offset; - for (i = 0; i < size; i++) - { + for (i = 0; i < size; i++) { const char *acl_domain = list[i]; const int acl_domain_len = strlen(acl_domain); - if (acl_domain_len > domain_len) continue; + if (acl_domain_len > domain_len) { + continue; + } int match = true; - for (offset = 1; offset <= acl_domain_len; offset++) - { - if (domain[domain_len - offset] != acl_domain[acl_domain_len - offset]) - { + for (offset = 1; offset <= acl_domain_len; offset++) { + if (domain[domain_len - offset] != + acl_domain[acl_domain_len - offset]) { match = false; break; } } - if (match) return 1; + if (match) { + return 1; + } } return 0; } -int acl_contains_ip(const char* host) +int acl_contains_ip(const char * host) { struct cork_ipv4 addr; int err = cork_ipv4_init(&addr, host); - if (err) return 0; + if (err) { + return 0; + } struct cork_ip ip; cork_ip_from_ipv4(&ip, &addr); diff --git a/src/acl.h b/src/acl.h index 04e0982b..7a32d332 100644 --- a/src/acl.h +++ b/src/acl.h @@ -26,7 +26,7 @@ int init_acl(const char *path); void free_acl(void); -int acl_contains_ip(const char* ip); -int acl_contains_domain(const char* domain); +int acl_contains_ip(const char * ip); +int acl_contains_domain(const char * domain); #endif // _ACL_H diff --git a/src/cache.c b/src/cache.c index 077986f7..b8673c7b 100644 --- a/src/cache.c +++ b/src/cache.c @@ -42,17 +42,19 @@ The maximum number of elements this cache object can hold @return EINVAL if dst is NULL, ENOMEM if malloc fails, 0 otherwise -*/ + */ int cache_create(struct cache **dst, const size_t capacity, void (*free_cb) (void *element)) { struct cache *new = NULL; - if (!dst) + if (!dst) { return EINVAL; + } - if ((new = malloc(sizeof(*new))) == NULL) + if ((new = malloc(sizeof(*new))) == NULL) { return ENOMEM; + } new->max_entries = capacity; new->entries = NULL; @@ -71,25 +73,23 @@ int cache_create(struct cache **dst, const size_t capacity, Whether to free contained data or just delete references to it @return EINVAL if cache is NULL, 0 otherwise -*/ + */ int cache_delete(struct cache *cache, int keep_data) { struct cache_entry *entry, *tmp; - if (!cache) + if (!cache) { return EINVAL; - - if (keep_data) - { - HASH_CLEAR(hh, cache->entries); } - else - { - HASH_ITER(hh, cache->entries, entry, tmp) - { + + if (keep_data) { + HASH_CLEAR(hh, cache->entries); + } else { + HASH_ITER(hh, cache->entries, entry, tmp){ HASH_DEL(cache->entries, entry); - if (cache->free_cb) + if (cache->free_cb) { cache->free_cb(entry->data); + } free(entry); } } @@ -108,21 +108,22 @@ int cache_delete(struct cache *cache, int keep_data) The key of the entry to remove @return EINVAL if cache is NULL, 0 otherwise -*/ + */ int cache_remove(struct cache *cache, char *key) { struct cache_entry *tmp; - if (!cache || !key) + if (!cache || !key) { return EINVAL; + } HASH_FIND_STR(cache->entries, key, tmp); - if (tmp) - { + if (tmp) { HASH_DEL(cache->entries, tmp); - if (cache->free_cb) + if (cache->free_cb) { cache->free_cb(tmp->data); + } free(tmp); } @@ -145,25 +146,23 @@ int cache_remove(struct cache *cache, char *key) otherwise this will blow up in your face. @return EINVAL if cache is NULL, 0 otherwise -*/ + */ int cache_lookup(struct cache *cache, char *key, void *result) { struct cache_entry *tmp = NULL; char **dirty_hack = result; - if (!cache || !key || !result) + if (!cache || !key || !result) { return EINVAL; + } HASH_FIND_STR(cache->entries, key, tmp); - if (tmp) - { + if (tmp) { size_t key_len = strnlen(tmp->key, KEY_MAX_LENGTH); HASH_DELETE(hh, cache->entries, tmp); HASH_ADD_KEYPTR(hh, cache->entries, tmp->key, key_len, tmp); *dirty_hack = tmp->data; - } - else - { + } else { *dirty_hack = result = NULL; } @@ -182,33 +181,34 @@ int cache_lookup(struct cache *cache, char *key, void *result) Data associated with @return EINVAL if cache is NULL, ENOMEM if malloc fails, 0 otherwise -*/ + */ int cache_insert(struct cache *cache, char *key, void *data) { struct cache_entry *entry = NULL; struct cache_entry *tmp_entry = NULL; size_t key_len = 0; - if (!cache || !data) + if (!cache || !data) { return EINVAL; + } - if ((entry = malloc(sizeof(*entry))) == NULL) + if ((entry = malloc(sizeof(*entry))) == NULL) { return ENOMEM; + } entry->key = key; entry->data = data; key_len = strnlen(entry->key, KEY_MAX_LENGTH); HASH_ADD_KEYPTR(hh, cache->entries, entry->key, key_len, entry); - if (HASH_COUNT(cache->entries) >= cache->max_entries) - { - HASH_ITER(hh, cache->entries, entry, tmp_entry) - { + if (HASH_COUNT(cache->entries) >= cache->max_entries) { + HASH_ITER(hh, cache->entries, entry, tmp_entry){ HASH_DELETE(hh, cache->entries, entry); - if (cache->free_cb) + if (cache->free_cb) { cache->free_cb(entry->data); - else + } else { free(entry->data); + } /* free(key->key) if data has been copied */ free(entry); break; diff --git a/src/cache.h b/src/cache.h index b53469d3..e1a76da0 100644 --- a/src/cache.h +++ b/src/cache.h @@ -30,26 +30,24 @@ #include "uthash.h" -#define KEY_MAX_LENGTH 32 +#define KEY_MAX_LENGTH 32 /** * A cache entry */ -struct cache_entry -{ - char *key; /** 0 && rlength > 0) - { - if (random_compare(ll, rr, salt, key) <= 0) - { + while (llength > 0 && rlength > 0) { + if (random_compare(ll, rr, salt, key) <= 0) { *result = *ll; ++ll; --llength; - } - else - { + } else { *result = *rr; ++rr; --rlength; @@ -185,22 +181,21 @@ static void merge(uint8_t *left, int llength, uint8_t *right, ++result; } - if (llength > 0) - while (llength > 0) - { + if (llength > 0) { + while (llength > 0) { *result = *ll; ++result; ++ll; --llength; } - else - while (rlength > 0) - { + } else { + while (rlength > 0) { *result = *rr; ++result; ++rr; --rlength; } + } free(ltmp); free(rtmp); @@ -213,8 +208,9 @@ static void merge_sort(uint8_t array[], int length, uint8_t *left, *right; int llength; - if (length <= 1) + if (length <= 1) { return; + } middle = length / 2; @@ -239,8 +235,7 @@ unsigned char *enc_md5(const unsigned char *d, size_t n, unsigned char *md) return MD5(d, n, md); #elif defined(USE_CRYPTO_POLARSSL) static unsigned char m[16]; - if (md == NULL) - { + if (md == NULL) { md = m; } md5(d, n, md); @@ -260,22 +255,18 @@ void enc_table_init(const char *pass) digest = enc_md5((const uint8_t *)pass, strlen(pass), NULL); - for (i = 0; i < 8; i++) - { + for (i = 0; i < 8; i++) { key += OFFSET_ROL(digest, i); } - for(i = 0; i < 256; ++i) - { + for (i = 0; i < 256; ++i) { enc_table[i] = i; } - for(i = 1; i < 1024; ++i) - { + for (i = 1; i < 1024; ++i) { salt = i; merge_sort(enc_table, 256, salt, key); } - for(i = 0; i < 256; ++i) - { + for (i = 0; i < 256; ++i) { // gen decrypt table from encrypt table dec_table[enc_table[i]] = i; } @@ -284,38 +275,37 @@ void enc_table_init(const char *pass) int cipher_iv_size(const cipher_kt_t *cipher) { #if defined(USE_CRYPTO_OPENSSL) - return EVP_CIPHER_iv_length (cipher); + return EVP_CIPHER_iv_length(cipher); #elif defined(USE_CRYPTO_POLARSSL) - if (cipher == NULL) - { + if (cipher == NULL) { return 0; } return cipher->iv_size; #endif } -int cipher_key_size (const cipher_kt_t *cipher) +int cipher_key_size(const cipher_kt_t *cipher) { #if defined(USE_CRYPTO_OPENSSL) return EVP_CIPHER_key_length(cipher); #elif defined(USE_CRYPTO_POLARSSL) - if (cipher == NULL) - { + if (cipher == NULL) { return 0; } /* Override PolarSSL 32 bit default key size with sane 128 bit default */ - if (cipher->base != NULL && POLARSSL_CIPHER_ID_BLOWFISH == cipher->base->cipher) - { + if (cipher->base != NULL && POLARSSL_CIPHER_ID_BLOWFISH == + cipher->base->cipher) { return 128 / 8; } return cipher->key_length / 8; #endif } -int bytes_to_key(const cipher_kt_t *cipher, const digest_type_t *md, const uint8_t *pass, uint8_t *key, uint8_t *iv) +int bytes_to_key(const cipher_kt_t *cipher, const digest_type_t *md, + const uint8_t *pass, uint8_t *key, uint8_t *iv) { size_t datal; - datal = strlen((const char *) pass); + datal = strlen((const char *)pass); #if defined(USE_CRYPTO_OPENSSL) return EVP_BytesToKey(cipher, md, NULL, pass, datal, 1, key, iv); #elif defined(USE_CRYPTO_POLARSSL) @@ -331,79 +321,78 @@ int bytes_to_key(const cipher_kt_t *cipher, const digest_type_t *md, const uint8 nkey = cipher_key_size(cipher); niv = cipher_iv_size(cipher); rv = nkey; - if (pass == NULL) - { + if (pass == NULL) { return nkey; } memset(&c, 0, sizeof(md_context_t)); - if (md_init_ctx(&c, md)) - { + if (md_init_ctx(&c, md)) { return 0; } addmd = 0; mds = md_get_size(md); - for (;;) - { + for (;; ) { int error; - do - { + do { error = 1; - if (md_starts(&c)) - { + if (md_starts(&c)) { break; } - if (addmd) - { - if (md_update(&c, &(md_buf[0]), mds)) - { + if (addmd) { + if (md_update(&c, &(md_buf[0]), mds)) { break; } - } - else - { + } else { addmd = 1; } - if (md_update(&c, pass, datal)) + if (md_update(&c, pass, datal)) { break; - if (md_finish(&c, &(md_buf[0]))) + } + if (md_finish(&c, &(md_buf[0]))) { break; + } error = 0; - } - while (0); - if (error) - { + } while (0); + if (error) { md_free_ctx(&c); memset(md_buf, 0, MAX_MD_SIZE); return 0; } - i=0; - if (nkey) - { - for (;;) - { - if (nkey == 0) break; - if (i == mds) break; - if (key != NULL) - *(key++)=md_buf[i]; + i = 0; + if (nkey) { + for (;; ) { + if (nkey == 0) { + break; + } + if (i == mds) { + break; + } + if (key != NULL) { + *(key++) = md_buf[i]; + } nkey--; i++; } } - if (niv && (i != mds)) - { - for (;;) - { - if (niv == 0) break; - if (i == mds) break; - if (iv != NULL) - *(iv++)=md_buf[i]; + if (niv && (i != mds)) { + for (;; ) { + if (niv == 0) { + break; + } + if (i == mds) { + break; + } + if (iv != NULL) { + *(iv++) = md_buf[i]; + } niv--; i++; } } - if ((nkey == 0) && (niv == 0)) break; + if ((nkey == 0) && (niv == 0)) { + break; + } } md_free_ctx(&c); memset(md_buf, 0, MAX_MD_SIZE); @@ -421,49 +410,40 @@ int rand_bytes(uint8_t *output, int len) static unsigned char rand_initialised = 0; const size_t blen = min(len, CTR_DRBG_MAX_REQUEST); - if (!rand_initialised) - { + if (!rand_initialised) { #ifdef _WIN32 HCRYPTPROV hProvider; - union - { + union { unsigned __int64 seed; BYTE buffer[8]; } rand_buffer; hProvider = 0; if (CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, \ - CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) - { + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { CryptGenRandom(hProvider, 8, rand_buffer.buffer); CryptReleaseContext(hProvider, 0); - } - else - { - rand_buffer.seed = (unsigned __int64) clock(); + } else { + rand_buffer.seed = (unsigned __int64)clock(); } #else FILE *urand; - union - { + union { uint64_t seed; uint8_t buffer[8]; } rand_buffer; urand = fopen("/dev/urandom", "r"); - if (urand) - { + if (urand) { fread(&rand_buffer.seed, sizeof(rand_buffer.seed), 1, urand); fclose(urand); - } - else - { - rand_buffer.seed = (uint64_t) clock(); + } else { + rand_buffer.seed = (uint64_t)clock(); } #endif entropy_init(&ec); - if (ctr_drbg_init(&cd_ctx, entropy_func, &ec, (const unsigned char *) rand_buffer.buffer, 8) != 0) - { + if (ctr_drbg_init(&cd_ctx, entropy_func, &ec, + (const unsigned char *)rand_buffer.buffer, 8) != 0) { #if POLARSSL_VERSION_NUMBER >= 0x01030000 entropy_free(&ec); #endif @@ -471,10 +451,8 @@ int rand_bytes(uint8_t *output, int len) } rand_initialised = 1; } - while (len > 0) - { - if (ctr_drbg_random(&cd_ctx, output, blen) != 0) - { + while (len > 0) { + if (ctr_drbg_random(&cd_ctx, output, blen) != 0) { return 0; } output += blen; @@ -486,13 +464,11 @@ int rand_bytes(uint8_t *output, int len) const cipher_kt_t *get_cipher_type(int method) { - if (method <= TABLE || method >= CIPHER_NUM) - { + if (method <= TABLE || method >= CIPHER_NUM) { LOGE("get_cipher_type(): Illegal method"); return NULL; } - if (method == RC4_MD5) - { + if (method == RC4_MD5) { method = RC4; } @@ -501,9 +477,9 @@ const cipher_kt_t *get_cipher_type(int method) return EVP_get_cipherbyname(ciphername); #elif defined(USE_CRYPTO_POLARSSL) const char *polarname = supported_ciphers_polarssl[method]; - if (strcmp(polarname, CIPHER_UNSUPPORTED) == 0) - { - LOGE("Cipher %s currently is not supported by PolarSSL library", ciphername); + if (strcmp(polarname, CIPHER_UNSUPPORTED) == 0) { + LOGE("Cipher %s currently is not supported by PolarSSL library", + ciphername); return NULL; } return cipher_info_from_string(polarname); @@ -512,8 +488,7 @@ const cipher_kt_t *get_cipher_type(int method) const digest_type_t *get_digest_type(const char *digest) { - if (digest == NULL) - { + if (digest == NULL) { LOGE("get_digest_type(): Digest name is null"); return NULL; } @@ -527,8 +502,7 @@ const digest_type_t *get_digest_type(const char *digest) void cipher_context_init(cipher_ctx_t *ctx, int method, int enc) { - if (method <= TABLE || method >= CIPHER_NUM) - { + if (method <= TABLE || method >= CIPHER_NUM) { LOGE("cipher_context_init(): Illegal method"); return; } @@ -538,20 +512,14 @@ void cipher_context_init(cipher_ctx_t *ctx, int method, int enc) cipher_cc_t *cc = &ctx->cc; cc->cryptor = NULL; cc->cipher = supported_ciphers_applecc[method]; - if (cc->cipher == kCCAlgorithmInvalid) - { + if (cc->cipher == kCCAlgorithmInvalid) { cc->valid = kCCContextInvalid; - } - else - { + } else { cc->valid = kCCContextValid; - if (cc->cipher == kCCAlgorithmRC4) - { + if (cc->cipher == kCCAlgorithmRC4) { cc->mode = kCCModeRC4; cc->padding = ccNoPadding; - } - else - { + } else { cc->mode = kCCModeCFB; cc->padding = ccPKCS7Padding; } @@ -562,93 +530,79 @@ void cipher_context_init(cipher_ctx_t *ctx, int method, int enc) cipher_evp_t *evp = &ctx->evp; const cipher_kt_t *cipher = get_cipher_type(method); #if defined(USE_CRYPTO_OPENSSL) - if (cipher == NULL) - { + if (cipher == NULL) { LOGE("Cipher %s not found in OpenSSL library", ciphername); FATAL("Cannot initialize cipher"); } EVP_CIPHER_CTX_init(evp); - if (!EVP_CipherInit_ex(evp, cipher, NULL, NULL, NULL, enc)) - { + if (!EVP_CipherInit_ex(evp, cipher, NULL, NULL, NULL, enc)) { LOGE("Cannot initialize cipher %s", ciphername); exit(EXIT_FAILURE); } - if (!EVP_CIPHER_CTX_set_key_length(evp, enc_key_len)) - { + if (!EVP_CIPHER_CTX_set_key_length(evp, enc_key_len)) { EVP_CIPHER_CTX_cleanup(evp); LOGE("Invalid key length: %d", enc_key_len); exit(EXIT_FAILURE); } - if (method > RC4_MD5) - { + if (method > RC4_MD5) { EVP_CIPHER_CTX_set_padding(evp, 1); } #elif defined(USE_CRYPTO_POLARSSL) - if (cipher == NULL) - { + if (cipher == NULL) { LOGE("Cipher %s not found in PolarSSL library", ciphername); FATAL("Cannot initialize PolarSSL cipher"); } - if (cipher_init_ctx(evp, cipher) != 0) - { + if (cipher_init_ctx(evp, cipher) != 0) { FATAL("Cannot initialize PolarSSL cipher context"); } #endif } -void cipher_context_set_iv(cipher_ctx_t *ctx, uint8_t *iv, size_t iv_len, int enc) +void cipher_context_set_iv(cipher_ctx_t *ctx, uint8_t *iv, size_t iv_len, + int enc) { const unsigned char *true_key; - if (iv == NULL) - { + if (iv == NULL) { LOGE("cipher_context_set_iv(): IV is null"); return; } - if (enc) - { + if (enc) { rand_bytes(iv, iv_len); } - if (enc_method == RC4_MD5) - { + if (enc_method == RC4_MD5) { unsigned char key_iv[32]; memcpy(key_iv, enc_key, 16); memcpy(key_iv + 16, iv, 16); true_key = enc_md5(key_iv, 32, NULL); iv_len = 0; - } - else - { + } else { true_key = enc_key; } #ifdef USE_CRYPTO_APPLECC cipher_cc_t *cc = &ctx->cc; - if (cc->valid == kCCContextValid) - { + if (cc->valid == kCCContextValid) { memcpy(cc->iv, iv, iv_len); memcpy(cc->key, true_key, enc_key_len); cc->iv_len = iv_len; cc->key_len = enc_key_len; cc->encrypt = enc ? kCCEncrypt : kCCDecrypt; - if (cc->cryptor != NULL) - { + if (cc->cryptor != NULL) { CCCryptorRelease(cc->cryptor); cc->cryptor = NULL; } CCCryptorStatus ret; ret = CCCryptorCreateWithMode( - cc->encrypt, - cc->mode, - cc->cipher, - cc->padding, - cc->iv, cc->key, cc->key_len, - NULL, 0, 0, 0, - &cc->cryptor); - if (ret != kCCSuccess) - { - if (cc->cryptor != NULL) - { + cc->encrypt, + cc->mode, + cc->cipher, + cc->padding, + cc->iv, cc->key, cc->key_len, + NULL, 0, 0, 0, + &cc->cryptor); + if (ret != kCCSuccess) { + if (cc->cryptor != NULL) { CCCryptorRelease(cc->cryptor); cc->cryptor = NULL; } @@ -659,37 +613,31 @@ void cipher_context_set_iv(cipher_ctx_t *ctx, uint8_t *iv, size_t iv_len, int en #endif cipher_evp_t *evp = &ctx->evp; - if (evp == NULL) - { + if (evp == NULL) { LOGE("cipher_context_set_iv(): Cipher context is null"); return; } #if defined(USE_CRYPTO_OPENSSL) - if (!EVP_CipherInit_ex(evp, NULL, NULL, true_key, iv, enc)) - { + if (!EVP_CipherInit_ex(evp, NULL, NULL, true_key, iv, enc)) { EVP_CIPHER_CTX_cleanup(evp); FATAL("Cannot set key and IV"); } #elif defined(USE_CRYPTO_POLARSSL) - if (cipher_setkey(evp, true_key, enc_key_len * 8, enc) != 0) - { + if (cipher_setkey(evp, true_key, enc_key_len * 8, enc) != 0) { cipher_free_ctx(evp); FATAL("Cannot set PolarSSL cipher key"); } #if POLARSSL_VERSION_NUMBER >= 0x01030000 - if (cipher_set_iv(evp, iv, iv_len) != 0) - { + if (cipher_set_iv(evp, iv, iv_len) != 0) { cipher_free_ctx(evp); FATAL("Cannot set PolarSSL cipher IV"); } - if(cipher_reset(evp) != 0) - { + if (cipher_reset(evp) != 0) { cipher_free_ctx(evp); FATAL("Cannot finalize PolarSSL cipher context"); } #else - if(cipher_reset(evp, iv) != 0) - { + if (cipher_reset(evp, iv) != 0) { cipher_free_ctx(evp); FATAL("Cannot set PolarSSL cipher IV"); } @@ -697,7 +645,7 @@ void cipher_context_set_iv(cipher_ctx_t *ctx, uint8_t *iv, size_t iv_len, int en #endif #ifdef DEBUG - dump("IV", (char *) iv, iv_len); + dump("IV", (char *)iv, iv_len); #endif } @@ -705,13 +653,11 @@ void cipher_context_release(cipher_ctx_t *ctx) { #ifdef USE_CRYPTO_APPLECC cipher_cc_t *cc = &ctx->cc; - if (cc->cryptor != NULL) - { + if (cc->cryptor != NULL) { CCCryptorRelease(cc->cryptor); cc->cryptor = NULL; } - if (cc->valid == kCCContextValid) - { + if (cc->valid == kCCContextValid) { return; } #endif @@ -729,27 +675,26 @@ static int cipher_context_update(cipher_ctx_t *ctx, uint8_t *output, int *olen, { #ifdef USE_CRYPTO_APPLECC cipher_cc_t *cc = &ctx->cc; - if (cc->valid == kCCContextValid) - { + if (cc->valid == kCCContextValid) { CCCryptorStatus ret; - ret = CCCryptorUpdate(cc->cryptor, input, ilen, output, ilen + BLOCK_SIZE, (size_t *) olen); + ret = CCCryptorUpdate(cc->cryptor, input, ilen, output, + ilen + BLOCK_SIZE, (size_t *)olen); return (ret == kCCSuccess) ? 1 : 0; } #endif cipher_evp_t *evp = &ctx->evp; #if defined(USE_CRYPTO_OPENSSL) - return EVP_CipherUpdate(evp, (uint8_t *) output, olen, - (const uint8_t *) input, (size_t) ilen); + return EVP_CipherUpdate(evp, (uint8_t *)output, olen, + (const uint8_t *)input, (size_t)ilen); #elif defined(USE_CRYPTO_POLARSSL) - return !cipher_update(evp, (const uint8_t *) input, (size_t) ilen, - (uint8_t *) output, (size_t *) olen); + return !cipher_update(evp, (const uint8_t *)input, (size_t)ilen, + (uint8_t *)output, (size_t *)olen); #endif } -char* ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method) +char * ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method) { - if (method > TABLE) - { + if (method > TABLE) { cipher_ctx_t evp; cipher_context_init(&evp, method, 1); @@ -762,11 +707,10 @@ char* ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method) cipher_context_set_iv(&evp, iv, iv_len, 1); memcpy(ciphertext, iv, iv_len); - err = cipher_context_update(&evp, (uint8_t*)(ciphertext+iv_len), + err = cipher_context_update(&evp, (uint8_t *)(ciphertext + iv_len), &c_len, (const uint8_t *)plaintext, *len); - if (!err) - { + if (!err) { free(ciphertext); free(plaintext); cipher_context_release(&evp); @@ -784,12 +728,9 @@ char* ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method) return ciphertext; - } - else - { + } else { char *begin = plaintext; - while (plaintext < begin + *len) - { + while (plaintext < begin + *len) { *plaintext = (char)enc_table[(uint8_t)*plaintext]; plaintext++; } @@ -797,17 +738,16 @@ char* ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method) } } -char* ss_encrypt(int buf_size, char *plaintext, ssize_t *len, struct enc_ctx *ctx) +char * ss_encrypt(int buf_size, char *plaintext, ssize_t *len, + struct enc_ctx *ctx) { - if (ctx != NULL) - { + if (ctx != NULL) { int c_len = *len + BLOCK_SIZE; int iv_len = 0; int err = 0; char *ciphertext = malloc(max(iv_len + c_len, buf_size)); - if (!ctx->init) - { + if (!ctx->init) { uint8_t iv[MAX_IV_LENGTH]; iv_len = enc_iv_len; cipher_context_set_iv(&ctx->evp, iv, iv_len, 1); @@ -815,10 +755,9 @@ char* ss_encrypt(int buf_size, char *plaintext, ssize_t *len, struct enc_ctx *ct ctx->init = 1; } - err = cipher_context_update(&ctx->evp, (uint8_t*)(ciphertext+iv_len), + err = cipher_context_update(&ctx->evp, (uint8_t *)(ciphertext + iv_len), &c_len, (const uint8_t *)plaintext, *len); - if (!err) - { + if (!err) { free(ciphertext); free(plaintext); return NULL; @@ -832,12 +771,9 @@ char* ss_encrypt(int buf_size, char *plaintext, ssize_t *len, struct enc_ctx *ct *len = iv_len + c_len; free(plaintext); return ciphertext; - } - else - { + } else { char *begin = plaintext; - while (plaintext < begin + *len) - { + while (plaintext < begin + *len) { *plaintext = (char)enc_table[(uint8_t)*plaintext]; plaintext++; } @@ -845,10 +781,9 @@ char* ss_encrypt(int buf_size, char *plaintext, ssize_t *len, struct enc_ctx *ct } } -char* ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method) +char * ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method) { - if (method > TABLE) - { + if (method > TABLE) { cipher_ctx_t evp; cipher_context_init(&evp, method, 0); @@ -861,10 +796,10 @@ char* ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method) memcpy(iv, ciphertext, iv_len); cipher_context_set_iv(&evp, iv, iv_len, 0); - err = cipher_context_update(&evp, (uint8_t*)plaintext, &p_len, - (const uint8_t*)(ciphertext + iv_len), *len - iv_len); - if (!err) - { + err = cipher_context_update(&evp, (uint8_t *)plaintext, &p_len, + (const uint8_t *)(ciphertext + iv_len), + *len - iv_len); + if (!err) { free(ciphertext); free(plaintext); cipher_context_release(&evp); @@ -880,12 +815,9 @@ char* ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method) free(ciphertext); cipher_context_release(&evp); return plaintext; - } - else - { + } else { char *begin = ciphertext; - while (ciphertext < begin + *len) - { + while (ciphertext < begin + *len) { *ciphertext = (char)dec_table[(uint8_t)*ciphertext]; ciphertext++; } @@ -893,17 +825,16 @@ char* ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method) } } -char* ss_decrypt(int buf_size, char *ciphertext, ssize_t *len, struct enc_ctx *ctx) +char * ss_decrypt(int buf_size, char *ciphertext, ssize_t *len, + struct enc_ctx *ctx) { - if (ctx != NULL) - { + if (ctx != NULL) { int p_len = *len + BLOCK_SIZE; int iv_len = 0; int err = 0; char *plaintext = malloc(max(p_len, buf_size)); - if (!ctx->init) - { + if (!ctx->init) { uint8_t iv[MAX_IV_LENGTH]; iv_len = enc_iv_len; memcpy(iv, ciphertext, iv_len); @@ -911,11 +842,11 @@ char* ss_decrypt(int buf_size, char *ciphertext, ssize_t *len, struct enc_ctx *c ctx->init = 1; } - err = cipher_context_update(&ctx->evp, (uint8_t*)plaintext, &p_len, - (const uint8_t*)(ciphertext + iv_len), *len - iv_len); + err = cipher_context_update(&ctx->evp, (uint8_t *)plaintext, &p_len, + (const uint8_t *)(ciphertext + iv_len), + *len - iv_len); - if (!err) - { + if (!err) { free(ciphertext); free(plaintext); return NULL; @@ -929,12 +860,9 @@ char* ss_decrypt(int buf_size, char *ciphertext, ssize_t *len, struct enc_ctx *c *len = p_len; free(ciphertext); return plaintext; - } - else - { + } else { char *begin = ciphertext; - while (ciphertext < begin + *len) - { + while (ciphertext < begin + *len) { *ciphertext = (char)dec_table[(uint8_t)*ciphertext]; ciphertext++; } @@ -950,8 +878,7 @@ void enc_ctx_init(int method, struct enc_ctx *ctx, int enc) void enc_key_init(int method, const char *pass) { - if (method <= TABLE || method >= CIPHER_NUM) - { + if (method <= TABLE || method >= CIPHER_NUM) { LOGE("enc_key_init(): Illegal method"); return; } @@ -966,42 +893,34 @@ void enc_key_init(int method, const char *pass) uint8_t iv[MAX_IV_LENGTH]; const cipher_kt_t *cipher = get_cipher_type(method); - if (cipher == NULL) - { - do - { + if (cipher == NULL) { + do { #if defined(USE_CRYPTO_POLARSSL) && defined(USE_CRYPTO_APPLECC) - if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) - { + if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) { cipher_info.base = NULL; cipher_info.key_length = supported_ciphers_key_size[method] * 8; cipher_info.iv_size = supported_ciphers_iv_size[method]; - cipher = (const cipher_kt_t *) &cipher_info; + cipher = (const cipher_kt_t *)&cipher_info; break; } #endif - LOGE("Cipher %s not found in crypto library", supported_ciphers[method]); + LOGE("Cipher %s not found in crypto library", + supported_ciphers[method]); FATAL("Cannot initialize cipher"); - } - while (0); + } while (0); } const digest_type_t *md = get_digest_type("MD5"); - if (md == NULL) - { + if (md == NULL) { FATAL("MD5 Digest not found in crypto library"); } - enc_key_len = bytes_to_key(cipher, md, (const uint8_t *) pass, enc_key, iv); - if (enc_key_len == 0) - { + enc_key_len = bytes_to_key(cipher, md, (const uint8_t *)pass, enc_key, iv); + if (enc_key_len == 0) { FATAL("Cannot generate key and IV"); } - if (method == RC4_MD5) - { + if (method == RC4_MD5) { enc_iv_len = 16; - } - else - { + } else { enc_iv_len = cipher_iv_size(cipher); } enc_method = method; @@ -1010,27 +929,20 @@ void enc_key_init(int method, const char *pass) int enc_init(const char *pass, const char *method) { int m = TABLE; - if (method != NULL) - { - for (m = TABLE; m < CIPHER_NUM; m++) - { - if (strcmp(method, supported_ciphers[m]) == 0) - { + if (method != NULL) { + for (m = TABLE; m < CIPHER_NUM; m++) { + if (strcmp(method, supported_ciphers[m]) == 0) { break; } } - if (m >= CIPHER_NUM) - { + if (m >= CIPHER_NUM) { LOGE("Invalid cipher name: %s, use table instead", method); m = TABLE; } } - if (m == TABLE) - { + if (m == TABLE) { enc_table_init(pass); - } - else - { + } else { enc_key_init(m, pass); } return m; diff --git a/src/encrypt.h b/src/encrypt.h index 691b3093..233bb8e6 100644 --- a/src/encrypt.h +++ b/src/encrypt.h @@ -74,8 +74,7 @@ typedef md_info_t digest_type_t; #define kCCContextValid 0 #define kCCContextInvalid -1 -typedef struct -{ +typedef struct { CCCryptorRef cryptor; int valid; CCOperation encrypt; @@ -90,8 +89,7 @@ typedef struct #endif -typedef struct -{ +typedef struct { cipher_evp_t evp; #ifdef USE_CRYPTO_APPLECC cipher_cc_t cc; @@ -124,19 +122,20 @@ typedef struct #define RC2_CFB 13 #define SEED_CFB 14 -#define min(a,b) (((a)<(b))?(a):(b)) -#define max(a,b) (((a)>(b))?(a):(b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) +#define max(a, b) (((a) > (b)) ? (a) : (b)) -struct enc_ctx -{ +struct enc_ctx { uint8_t init; cipher_ctx_t evp; }; -char* ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method); -char* ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method); -char* ss_encrypt(int buf_size, char *plaintext, ssize_t *len, struct enc_ctx *ctx); -char* ss_decrypt(int buf_size, char *ciphertext, ssize_t *len, struct enc_ctx *ctx); +char * ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method); +char * ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method); +char * ss_encrypt(int buf_size, char *plaintext, ssize_t *len, + struct enc_ctx *ctx); +char * ss_decrypt(int buf_size, char *ciphertext, ssize_t *len, + struct enc_ctx *ctx); void enc_ctx_init(int method, struct enc_ctx *ctx, int enc); int enc_init(const char *pass, const char *method); int enc_get_iv_len(void); diff --git a/src/jconf.c b/src/jconf.c index bbfed55c..00eb4d2a 100644 --- a/src/jconf.c +++ b/src/jconf.c @@ -32,24 +32,17 @@ static char *to_string(const json_value *value) { - if (value->type == json_string) - { + if (value->type == json_string) { return ss_strndup(value->u.string.ptr, value->u.string.length); - } - else if (value->type == json_integer) - { + } else if (value->type == json_integer) { #ifdef __MINGW32__ return strdup(ss_itoa(value->u.integer)); #else return strdup(itoa(value->u.integer)); #endif - } - else if (value->type == json_null) - { + } else if (value->type == json_null) { return "null"; - } - else - { + } else { LOGE("%d", value->type); FATAL("Invalid config format."); } @@ -69,32 +62,26 @@ void parse_addr(const char *str, ss_addr_t *addr) int ret = -1, n = 0; char *pch; pch = strchr(str, ':'); - while (pch != NULL) - { + while (pch != NULL) { n++; ret = pch - str; pch = strchr(pch + 1, ':'); } - if (n > 1) - { - if (strcmp(str+ret, "]") != 0) - { + if (n > 1) { + if (strcmp(str + ret, "]") != 0) { ret = -1; } } - if (ret == -1) - { + if (ret == -1) { addr->host = strdup(str); addr->port = NULL; - } - else - { + } else { addr->host = ss_strndup(str, ret); addr->port = strdup(str + ret + 1); } } -jconf_t *read_jconf(const char* file) +jconf_t *read_jconf(const char * file) { static jconf_t conf; @@ -103,19 +90,27 @@ jconf_t *read_jconf(const char* file) json_value *obj; FILE *f = fopen(file, "rb"); - if (f == NULL) FATAL("Invalid config path."); + if (f == NULL) { + FATAL("Invalid config path."); + } fseek(f, 0, SEEK_END); long pos = ftell(f); fseek(f, 0, SEEK_SET); - if (pos >= MAX_CONF_SIZE) FATAL("Too large config file."); + if (pos >= MAX_CONF_SIZE) { + FATAL("Too large config file."); + } buf = malloc(pos + 1); - if (buf == NULL) FATAL("No enough memory."); + if (buf == NULL) { + FATAL("No enough memory."); + } int nread = fread(buf, pos, 1, f); - if (!nread) FATAL("Failed to read the config file."); + if (!nread) { + FATAL("Failed to read the config file."); + } fclose(f); buf[pos] = '\0'; // end of string @@ -124,73 +119,49 @@ jconf_t *read_jconf(const char* file) char error_buf[512]; obj = json_parse_ex(&settings, buf, pos, error_buf); - if (obj == NULL) - { + if (obj == NULL) { FATAL(error_buf); } - if (obj->type == json_object) - { + if (obj->type == json_object) { int i, j; - for (i = 0; i < obj->u.object.length; i++) - { + for (i = 0; i < obj->u.object.length; i++) { char *name = obj->u.object.values[i].name; json_value *value = obj->u.object.values[i].value; - if (strcmp(name, "server") == 0) - { - if (value->type == json_array) - { - for (j = 0; j < value->u.array.length; j++) - { - if (j >= MAX_REMOTE_NUM) break; + if (strcmp(name, "server") == 0) { + if (value->type == json_array) { + for (j = 0; j < value->u.array.length; j++) { + if (j >= MAX_REMOTE_NUM) { + break; + } json_value *v = value->u.array.values[j]; parse_addr(to_string(v), conf.remote_addr + j); conf.remote_num = j + 1; } - } - else if (value->type == json_string) - { + } else if (value->type == json_string) { conf.remote_addr[0].host = to_string(value); conf.remote_addr[0].port = NULL; conf.remote_num = 1; } - } - else if (strcmp(name, "server_port") == 0) - { + } else if (strcmp(name, "server_port") == 0) { conf.remote_port = to_string(value); - } - else if (strcmp(name, "local") == 0) - { + } else if (strcmp(name, "local") == 0) { conf.local_addr = to_string(value); - } - else if (strcmp(name, "local_port") == 0) - { + } else if (strcmp(name, "local_port") == 0) { conf.local_port = to_string(value); - } - else if (strcmp(name, "password") == 0) - { + } else if (strcmp(name, "password") == 0) { conf.password = to_string(value); - } - else if (strcmp(name, "method") == 0) - { + } else if (strcmp(name, "method") == 0) { conf.method = to_string(value); - } - else if (strcmp(name, "timeout") == 0) - { + } else if (strcmp(name, "timeout") == 0) { conf.timeout = to_string(value); - } - else if (strcmp(name, "fast_open") == 0) - { + } else if (strcmp(name, "fast_open") == 0) { conf.fast_open = value->u.boolean; - } - else if (strcmp(name, "nofile") == 0) - { + } else if (strcmp(name, "nofile") == 0) { conf.nofile = value->u.integer; } } - } - else - { + } else { FATAL("Invalid config file"); } diff --git a/src/jconf.h b/src/jconf.h index 52a5d58b..6b8a38b9 100644 --- a/src/jconf.h +++ b/src/jconf.h @@ -26,15 +26,13 @@ #define MAX_CONF_SIZE 16 * 1024 #define DNS_THREAD_NUM 4 -typedef struct -{ +typedef struct { char *host; char *port; } ss_addr_t; -typedef struct -{ - int remote_num; +typedef struct { + int remote_num; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port; char *local_addr; @@ -42,11 +40,11 @@ typedef struct char *password; char *method; char *timeout; - int fast_open; - int nofile; + int fast_open; + int nofile; } jconf_t; -jconf_t *read_jconf(const char* file); +jconf_t *read_jconf(const char * file); void parse_addr(const char *str, ss_addr_t *addr); void free_addr(ss_addr_t *addr); diff --git a/src/json.c b/src/json.c index 74c5d698..0690de42 100644 --- a/src/json.c +++ b/src/json.c @@ -48,13 +48,13 @@ const struct _json_value json_value_none = { 0 }; typedef unsigned short json_uchar; -static unsigned char hex_value (json_char c) +static unsigned char hex_value(json_char c) { - if (isdigit((uint8_t)c)) + if (isdigit((uint8_t)c)) { return c - '0'; + } - switch (c) - { + switch (c) { case 'a': case 'A': return 0x0A; @@ -78,8 +78,7 @@ static unsigned char hex_value (json_char c) } } -typedef struct -{ +typedef struct { unsigned long used_memory; unsigned int uint_max; @@ -90,51 +89,51 @@ typedef struct } json_state; -static void * default_alloc (size_t size, int zero, void * user_data) +static void * default_alloc(size_t size, int zero, void * user_data) { - return zero ? calloc (1, size) : malloc (size); + return zero ? calloc(1, size) : malloc(size); } -static void default_free (void * ptr, void * user_data) +static void default_free(void * ptr, void * user_data) { - free (ptr); + free(ptr); } -static void * json_alloc (json_state * state, unsigned long size, int zero) +static void * json_alloc(json_state * state, unsigned long size, int zero) { - if ((state->ulong_max - state->used_memory) < size) - return 0; - - if (state->settings.max_memory - && (state->used_memory += size) > state->settings.max_memory) - { + if ((state->ulong_max - state->used_memory) < size) { return 0; } - return state->settings.mem_alloc (size, zero, state->settings.user_data); + if (state->settings.max_memory + && (state->used_memory += size) > state->settings.max_memory) { + return 0; + } + + return state->settings.mem_alloc(size, zero, state->settings.user_data); } static int new_value -(json_state * state, json_value ** top, json_value ** root, json_value ** alloc, json_type type) + (json_state * state, json_value ** top, json_value ** root, + json_value ** alloc, json_type type) { json_value * value; int values_size; - if (!state->first_pass) - { + if (!state->first_pass) { value = *top = *alloc; *alloc = (*alloc)->_reserved.next_alloc; - if (!*root) + if (!*root) { *root = value; + } - switch (value->type) - { + switch (value->type) { case json_array: - if (! (value->u.array.values = (json_value **) json_alloc - (state, value->u.array.length * sizeof (json_value *), 0)) ) - { + if (!(value->u.array.values = (json_value **)json_alloc + (state, value->u.array.length * + sizeof(json_value *), 0)) ) { return 0; } @@ -143,24 +142,30 @@ static int new_value case json_object: - values_size = sizeof (*value->u.object.values) * value->u.object.length; + values_size = sizeof(*value->u.object.values) * + value->u.object.length; - if (! ((*(void **) &value->u.object.values) = json_alloc - (state, values_size + ((size_t) value->u.object.values), 0)) ) - { + if (!((*(void **)&value->u.object.values) = json_alloc + (state, + values_size + + ((size_t)value->u. + object.values), + 0)) ) { return 0; } - value->_reserved.object_mem = (*(char **) &value->u.object.values) + values_size; + value->_reserved.object_mem = (*(char **)&value->u.object.values) + + values_size; value->u.object.length = 0; break; case json_string: - if (! (value->u.string.ptr = (json_char *) json_alloc - (state, (value->u.string.length + 1) * sizeof (json_char), 0)) ) - { + if (!(value->u.string.ptr = (json_char *)json_alloc + (state, + (value->u.string.length + + 1) * sizeof(json_char), 0)) ) { return 0; } @@ -169,24 +174,28 @@ static int new_value default: break; - }; + } + ; return 1; } - value = (json_value *) json_alloc (state, sizeof (json_value), 1); + value = (json_value *)json_alloc(state, sizeof(json_value), 1); - if (!value) + if (!value) { return 0; + } - if (!*root) + if (!*root) { *root = value; + } value->type = type; value->parent = *top; - if (*alloc) + if (*alloc) { (*alloc)->_reserved.next_alloc = value; + } *alloc = *top = value; @@ -194,36 +203,37 @@ static int new_value } #define e_off \ - ((int) (i - cur_line_begin)) + ((int)(i - cur_line_begin)) -#define whitespace \ - case '\n': ++ cur_line; cur_line_begin = i; \ - case ' ': case '\t': case '\r' +#define whitespace \ +case '\n': ++cur_line; cur_line_begin = i; \ +case ' ': case '\t': case '\r' -#define string_add(b) \ - do { if (!state.first_pass) string [string_length] = b; ++ string_length; } while (0); +#define string_add(b) \ + do { if (!state.first_pass) { string [string_length] = b; \ + } ++string_length; } while (0); static const long -flag_next = 1 << 0, -flag_reproc = 1 << 1, -flag_need_comma = 1 << 2, -flag_seek_value = 1 << 3, -flag_escaped = 1 << 4, -flag_string = 1 << 5, -flag_need_colon = 1 << 6, -flag_done = 1 << 7, -flag_num_negative = 1 << 8, -flag_num_zero = 1 << 9, -flag_num_e = 1 << 10, -flag_num_e_got_sign = 1 << 11, -flag_num_e_negative = 1 << 12, -flag_line_comment = 1 << 13, -flag_block_comment = 1 << 14; + flag_next = 1 << 0, + flag_reproc = 1 << 1, + flag_need_comma = 1 << 2, + flag_seek_value = 1 << 3, + flag_escaped = 1 << 4, + flag_string = 1 << 5, + flag_need_colon = 1 << 6, + flag_done = 1 << 7, + flag_num_negative = 1 << 8, + flag_num_zero = 1 << 9, + flag_num_e = 1 << 10, + flag_num_e_got_sign = 1 << 11, + flag_num_e_negative = 1 << 12, + flag_line_comment = 1 << 13, + flag_block_comment = 1 << 14; -json_value * json_parse_ex (json_settings * settings, - const json_char * json, - size_t length, - char * error_buf) +json_value * json_parse_ex(json_settings * settings, + const json_char * json, + size_t length, + char * error_buf) { json_char error [json_error_max]; unsigned int cur_line; @@ -236,10 +246,9 @@ json_value * json_parse_ex (json_settings * settings, /* Skip UTF-8 BOM */ - if (length >= 3 && ((unsigned char) json [0]) == 0xEF - && ((unsigned char) json [1]) == 0xBB - && ((unsigned char) json [2]) == 0xBF) - { + if (length >= 3 && ((unsigned char)json [0]) == 0xEF + && ((unsigned char)json [1]) == 0xBB + && ((unsigned char)json [2]) == 0xBF) { json += 3; length -= 3; } @@ -247,22 +256,23 @@ json_value * json_parse_ex (json_settings * settings, error[0] = '\0'; end = (json + length); - memcpy (&state.settings, settings, sizeof (json_settings)); + memcpy(&state.settings, settings, sizeof(json_settings)); - if (!state.settings.mem_alloc) + if (!state.settings.mem_alloc) { state.settings.mem_alloc = default_alloc; + } - if (!state.settings.mem_free) + if (!state.settings.mem_free) { state.settings.mem_free = default_free; + } - memset (&state.uint_max, 0xFF, sizeof (state.uint_max)); - memset (&state.ulong_max, 0xFF, sizeof (state.ulong_max)); + memset(&state.uint_max, 0xFF, sizeof(state.uint_max)); + memset(&state.ulong_max, 0xFF, sizeof(state.ulong_max)); state.uint_max -= 8; /* limit of how much can be added before next check */ state.ulong_max -= 8; - for (state.first_pass = 1; state.first_pass >= 0; -- state.first_pass) - { + for (state.first_pass = 1; state.first_pass >= 0; --state.first_pass) { json_uchar uchar; unsigned char uc_b1, uc_b2, uc_b3, uc_b4; json_char * string = 0; @@ -274,110 +284,116 @@ json_value * json_parse_ex (json_settings * settings, cur_line = 1; cur_line_begin = json; - for (i = json ;; ++ i) - { + for (i = json;; ++i) { json_char b = (i == end ? 0 : *i); - if (flags & flag_string) - { - if (!b) - { - sprintf (error, "Unexpected EOF in string (at %d:%d)", cur_line, e_off); + if (flags & flag_string) { + if (!b) { + sprintf(error, "Unexpected EOF in string (at %d:%d)", + cur_line, e_off); goto e_failed; } - if (string_length > state.uint_max) + if (string_length > state.uint_max) { goto e_overflow; + } - if (flags & flag_escaped) - { - flags &= ~ flag_escaped; + if (flags & flag_escaped) { + flags &= ~flag_escaped; - switch (b) - { + switch (b) { case 'b': - string_add ('\b'); + string_add('\b'); break; case 'f': - string_add ('\f'); + string_add('\f'); break; case 'n': - string_add ('\n'); + string_add('\n'); break; case 'r': - string_add ('\r'); + string_add('\r'); break; case 't': - string_add ('\t'); + string_add('\t'); break; case 'u': if (end - i < 4 || - (uc_b1 = hex_value (*++ i)) == 0xFF || (uc_b2 = hex_value (*++ i)) == 0xFF - || (uc_b3 = hex_value (*++ i)) == 0xFF || (uc_b4 = hex_value (*++ i)) == 0xFF) - { - sprintf (error, "Invalid character value `%c` (at %d:%d)", b, cur_line, e_off); + (uc_b1 = hex_value(*++i)) == 0xFF || + (uc_b2 = hex_value(*++i)) == 0xFF + || (uc_b3 = hex_value(*++i)) == 0xFF || + (uc_b4 = hex_value(*++i)) == 0xFF) { + sprintf(error, + "Invalid character value `%c` (at %d:%d)", + b, cur_line, e_off); goto e_failed; } uc_b1 = uc_b1 * 16 + uc_b2; uc_b2 = uc_b3 * 16 + uc_b4; - uchar = ((json_char) uc_b1) * 256 + uc_b2; + uchar = ((json_char)uc_b1) * 256 + uc_b2; - if (sizeof (json_char) >= sizeof (json_uchar) || (uc_b1 == 0 && uc_b2 <= 0x7F)) - { - string_add ((json_char) uchar); + if (sizeof(json_char) >= sizeof(json_uchar) || + (uc_b1 == 0 && uc_b2 <= 0x7F)) { + string_add((json_char)uchar); break; } - if (uchar <= 0x7FF) - { - if (state.first_pass) + if (uchar <= 0x7FF) { + if (state.first_pass) { string_length += 2; - else - { - string [string_length ++] = 0xC0 | ((uc_b2 & 0xC0) >> 6) | ((uc_b1 & 0x7) << 2); - string [string_length ++] = 0x80 | (uc_b2 & 0x3F); + } else { + string [string_length++] = 0xC0 | + ((uc_b2 & + 0xC0) >> + 6) | + ((uc_b1 & 0x7) << 2); + string [string_length++] = 0x80 | + (uc_b2 & 0x3F); } break; } - if (state.first_pass) + if (state.first_pass) { string_length += 3; - else - { - string [string_length ++] = 0xE0 | ((uc_b1 & 0xF0) >> 4); - string [string_length ++] = 0x80 | ((uc_b1 & 0xF) << 2) | ((uc_b2 & 0xC0) >> 6); - string [string_length ++] = 0x80 | (uc_b2 & 0x3F); + } else { + string [string_length++] = 0xE0 | + ((uc_b1 & 0xF0) >> 4); + string [string_length++] = 0x80 | + ((uc_b1 & + 0xF) << + 2) | + ((uc_b2 & 0xC0) >> 6); + string [string_length++] = 0x80 | (uc_b2 & 0x3F); } break; default: - string_add (b); - }; + string_add(b); + } + ; continue; } - if (b == '\\') - { + if (b == '\\') { flags |= flag_escaped; continue; } - if (b == '"') - { - if (!state.first_pass) + if (b == '"') { + if (!state.first_pass) { string [string_length] = 0; + } - flags &= ~ flag_string; + flags &= ~flag_string; string = 0; - switch (top->type) - { + switch (top->type) { case json_string: top->u.string.length = string_length; @@ -387,17 +403,19 @@ json_value * json_parse_ex (json_settings * settings, case json_object: - if (state.first_pass) - (*(json_char **) &top->u.object.values) += string_length + 1; - else - { + if (state.first_pass) { + (*(json_char **)&top->u.object.values) += + string_length + 1; + } else { top->u.object.values [top->u.object.length].name - = (json_char *) top->_reserved.object_mem; + = (json_char *)top->_reserved.object_mem; - top->u.object.values [top->u.object.length].name_length - = string_length; + top->u.object.values [top->u.object.length]. + name_length + = string_length; - (*(json_char **) &top->_reserved.object_mem) += string_length + 1; + (*(json_char **)&top->_reserved.object_mem) += + string_length + 1; } flags |= flag_seek_value | flag_need_colon; @@ -405,63 +423,55 @@ json_value * json_parse_ex (json_settings * settings, default: break; - }; - } - else - { - string_add (b); + } + ; + } else { + string_add(b); continue; } } - if (state.settings.settings & json_enable_comments) - { - if (flags & (flag_line_comment | flag_block_comment)) - { - if (flags & flag_line_comment) - { - if (b == '\r' || b == '\n' || !b) - { - flags &= ~ flag_line_comment; - -- i; /* so null can be reproc'd */ + if (state.settings.settings & json_enable_comments) { + if (flags & (flag_line_comment | flag_block_comment)) { + if (flags & flag_line_comment) { + if (b == '\r' || b == '\n' || !b) { + flags &= ~flag_line_comment; + --i; /* so null can be reproc'd */ } continue; } - if (flags & flag_block_comment) - { - if (!b) - { - sprintf (error, "%d:%d: Unexpected EOF in block comment", cur_line, e_off); + if (flags & flag_block_comment) { + if (!b) { + sprintf(error, + "%d:%d: Unexpected EOF in block comment", + cur_line, e_off); goto e_failed; } - if (b == '*' && i < (end - 1) && i [1] == '/') - { - flags &= ~ flag_block_comment; - ++ i; /* skip closing sequence */ + if (b == '*' && i < (end - 1) && i [1] == '/') { + flags &= ~flag_block_comment; + ++i; /* skip closing sequence */ } continue; } - } - else if (b == '/') - { - if (! (flags & (flag_seek_value | flag_done)) && top->type != json_object) - { - sprintf (error, "%d:%d: Comment not allowed here", cur_line, e_off); + } else if (b == '/') { + if (!(flags & (flag_seek_value | flag_done)) && top->type != + json_object) { + sprintf(error, "%d:%d: Comment not allowed here", + cur_line, e_off); goto e_failed; } - if (++ i == end) - { - sprintf (error, "%d:%d: EOF unexpected", cur_line, e_off); + if (++i == end) { + sprintf(error, "%d:%d: EOF unexpected", cur_line, + e_off); goto e_failed; } - switch (b = *i) - { + switch (b = *i) { case '/': flags |= flag_line_comment; continue; @@ -471,42 +481,45 @@ json_value * json_parse_ex (json_settings * settings, continue; default: - sprintf (error, "%d:%d: Unexpected `%c` in comment opening sequence", cur_line, e_off, b); + sprintf(error, + "%d:%d: Unexpected `%c` in comment opening sequence", cur_line, e_off, + b); goto e_failed; - }; + } + ; } } - if (flags & flag_done) - { - if (!b) + if (flags & flag_done) { + if (!b) { break; + } - switch (b) - { -whitespace: + switch (b) { + whitespace: continue; default: - sprintf (error, "%d:%d: Trailing garbage: `%c`", cur_line, e_off, b); + sprintf(error, "%d:%d: Trailing garbage: `%c`", cur_line, + e_off, b); goto e_failed; - }; + } + ; } - if (flags & flag_seek_value) - { - switch (b) - { -whitespace: + if (flags & flag_seek_value) { + switch (b) { + whitespace: continue; case ']': - if (top->type == json_array) - flags = (flags & ~ (flag_need_comma | flag_seek_value)) | flag_next; - else - { - sprintf (error, "%d:%d: Unexpected ]", cur_line, e_off); + if (top->type == json_array) { + flags = + (flags & + ~(flag_need_comma | flag_seek_value)) | flag_next; + } else { + sprintf(error, "%d:%d: Unexpected ]", cur_line, e_off); goto e_failed; } @@ -514,57 +527,56 @@ whitespace: default: - if (flags & flag_need_comma) - { - if (b == ',') - { - flags &= ~ flag_need_comma; + if (flags & flag_need_comma) { + if (b == ',') { + flags &= ~flag_need_comma; continue; - } - else - { - sprintf (error, "%d:%d: Expected , before %c", cur_line, e_off, b); + } else { + sprintf(error, "%d:%d: Expected , before %c", + cur_line, e_off, b); goto e_failed; } } - if (flags & flag_need_colon) - { - if (b == ':') - { - flags &= ~ flag_need_colon; + if (flags & flag_need_colon) { + if (b == ':') { + flags &= ~flag_need_colon; continue; - } - else - { - sprintf (error, "%d:%d: Expected : before %c", cur_line, e_off, b); + } else { + sprintf(error, "%d:%d: Expected : before %c", + cur_line, e_off, b); goto e_failed; } } - flags &= ~ flag_seek_value; + flags &= ~flag_seek_value; - switch (b) - { + switch (b) { case '{': - if (!new_value (&state, &top, &root, &alloc, json_object)) + if (!new_value(&state, &top, &root, &alloc, + json_object)) { goto e_alloc_failure; + } continue; case '[': - if (!new_value (&state, &top, &root, &alloc, json_array)) + if (!new_value(&state, &top, &root, &alloc, + json_array)) { goto e_alloc_failure; + } flags |= flag_seek_value; continue; case '"': - if (!new_value (&state, &top, &root, &alloc, json_string)) + if (!new_value(&state, &top, &root, &alloc, + json_string)) { goto e_alloc_failure; + } flags |= flag_string; @@ -575,11 +587,15 @@ whitespace: case 't': - if ((end - i) < 3 || *(++ i) != 'r' || *(++ i) != 'u' || *(++ i) != 'e') + if ((end - i) < 3 || *(++i) != 'r' || *(++i) != 'u' || + *(++i) != 'e') { goto e_unknown_value; + } - if (!new_value (&state, &top, &root, &alloc, json_boolean)) + if (!new_value(&state, &top, &root, &alloc, + json_boolean)) { goto e_alloc_failure; + } top->u.boolean = 1; @@ -588,40 +604,47 @@ whitespace: case 'f': - if ((end - i) < 4 || *(++ i) != 'a' || *(++ i) != 'l' || *(++ i) != 's' || *(++ i) != 'e') + if ((end - i) < 4 || *(++i) != 'a' || *(++i) != 'l' || + *(++i) != 's' || *(++i) != 'e') { goto e_unknown_value; + } - if (!new_value (&state, &top, &root, &alloc, json_boolean)) + if (!new_value(&state, &top, &root, &alloc, + json_boolean)) { goto e_alloc_failure; + } flags |= flag_next; break; case 'n': - if ((end - i) < 3 || *(++ i) != 'u' || *(++ i) != 'l' || *(++ i) != 'l') + if ((end - i) < 3 || *(++i) != 'u' || *(++i) != 'l' || + *(++i) != 'l') { goto e_unknown_value; + } - if (!new_value (&state, &top, &root, &alloc, json_null)) + if (!new_value(&state, &top, &root, &alloc, + json_null)) { goto e_alloc_failure; + } flags |= flag_next; break; default: - if (isdigit ((uint8_t)b) || b == '-') - { - if (!new_value (&state, &top, &root, &alloc, json_integer)) + if (isdigit((uint8_t)b) || b == '-') { + if (!new_value(&state, &top, &root, &alloc, + json_integer)) { goto e_alloc_failure; + } - if (!state.first_pass) - { - while (isdigit ((uint8_t)b) || b == '+' || b == '-' - || b == 'e' || b == 'E' || b == '.') - { - if ( (++ i) == end) - { + if (!state.first_pass) { + while (isdigit((uint8_t)b) || b == '+' || b == + '-' + || b == 'e' || b == 'E' || b == '.') { + if ( (++i) == end) { b = 0; break; } @@ -633,100 +656,96 @@ whitespace: break; } - flags &= ~ (flag_num_negative | flag_num_e | - flag_num_e_got_sign | flag_num_e_negative | - flag_num_zero); + flags &= ~(flag_num_negative | flag_num_e | + flag_num_e_got_sign | + flag_num_e_negative | + flag_num_zero); num_digits = 0; num_fraction = 0; num_e = 0; - if (b != '-') - { + if (b != '-') { flags |= flag_reproc; break; } flags |= flag_num_negative; continue; - } - else - { - sprintf (error, "%d:%d: Unexpected %c when seeking value", cur_line, e_off, b); + } else { + sprintf(error, + "%d:%d: Unexpected %c when seeking value", + cur_line, e_off, b); goto e_failed; } - }; - }; - } - else - { - switch (top->type) - { + } + ; + } + ; + } else { + switch (top->type) { case json_object: - switch (b) - { -whitespace: + switch (b) { + whitespace: continue; case '"': - if (flags & flag_need_comma) - { - sprintf (error, "%d:%d: Expected , before \"", cur_line, e_off); + if (flags & flag_need_comma) { + sprintf(error, "%d:%d: Expected , before \"", + cur_line, e_off); goto e_failed; } flags |= flag_string; - string = (json_char *) top->_reserved.object_mem; + string = (json_char *)top->_reserved.object_mem; string_length = 0; break; case '}': - flags = (flags & ~ flag_need_comma) | flag_next; + flags = (flags & ~flag_need_comma) | flag_next; break; case ',': - if (flags & flag_need_comma) - { - flags &= ~ flag_need_comma; + if (flags & flag_need_comma) { + flags &= ~flag_need_comma; break; } default: - sprintf (error, "%d:%d: Unexpected `%c` in object", cur_line, e_off, b); + sprintf(error, "%d:%d: Unexpected `%c` in object", + cur_line, e_off, b); goto e_failed; - }; + } + ; break; case json_integer: case json_double: - if (isdigit ((uint8_t)b)) - { - ++ num_digits; + if (isdigit((uint8_t)b)) { + ++num_digits; - if (top->type == json_integer || flags & flag_num_e) - { - if (! (flags & flag_num_e)) - { - if (flags & flag_num_zero) - { - sprintf (error, "%d:%d: Unexpected `0` before `%c`", cur_line, e_off, b); + if (top->type == json_integer || flags & flag_num_e) { + if (!(flags & flag_num_e)) { + if (flags & flag_num_zero) { + sprintf(error, + "%d:%d: Unexpected `0` before `%c`", + cur_line, e_off, b); goto e_failed; } - if (num_digits == 1 && b == '0') + if (num_digits == 1 && b == '0') { flags |= flag_num_zero; - } - else - { + } + } else { flags |= flag_num_e_got_sign; num_e = (num_e * 10) + (b - '0'); continue; @@ -740,79 +759,76 @@ whitespace: continue; } - if (b == '+' || b == '-') - { - if ( (flags & flag_num_e) && !(flags & flag_num_e_got_sign)) - { + if (b == '+' || b == '-') { + if ( (flags & flag_num_e) && + !(flags & flag_num_e_got_sign)) { flags |= flag_num_e_got_sign; - if (b == '-') + if (b == '-') { flags |= flag_num_e_negative; + } continue; } - } - else if (b == '.' && top->type == json_integer) - { - if (!num_digits) - { - sprintf (error, "%d:%d: Expected digit before `.`", cur_line, e_off); + } else if (b == '.' && top->type == json_integer) { + if (!num_digits) { + sprintf(error, "%d:%d: Expected digit before `.`", + cur_line, e_off); goto e_failed; } top->type = json_double; - top->u.dbl = (double) top->u.integer; + top->u.dbl = (double)top->u.integer; num_digits = 0; continue; } - if (! (flags & flag_num_e)) - { - if (top->type == json_double) - { - if (!num_digits) - { - sprintf (error, "%d:%d: Expected digit after `.`", cur_line, e_off); + if (!(flags & flag_num_e)) { + if (top->type == json_double) { + if (!num_digits) { + sprintf(error, + "%d:%d: Expected digit after `.`", + cur_line, e_off); goto e_failed; } - top->u.dbl += ((double) num_fraction) / (pow (10, (double) num_digits)); + top->u.dbl += ((double)num_fraction) / + (pow(10, (double)num_digits)); } - if (b == 'e' || b == 'E') - { + if (b == 'e' || b == 'E') { flags |= flag_num_e; - if (top->type == json_integer) - { + if (top->type == json_integer) { top->type = json_double; - top->u.dbl = (double) top->u.integer; + top->u.dbl = (double)top->u.integer; } num_digits = 0; - flags &= ~ flag_num_zero; + flags &= ~flag_num_zero; continue; } - } - else - { - if (!num_digits) - { - sprintf (error, "%d:%d: Expected digit after `e`", cur_line, e_off); + } else { + if (!num_digits) { + sprintf(error, "%d:%d: Expected digit after `e`", + cur_line, e_off); goto e_failed; } - top->u.dbl *= pow (10, (double) (flags & flag_num_e_negative ? - num_e : num_e)); + top->u.dbl *= + pow(10, + (double)(flags & + flag_num_e_negative ? -num_e : num_e)); } - if (flags & flag_num_negative) - { - if (top->type == json_integer) - top->u.integer = - top->u.integer; - else - top->u.dbl = - top->u.dbl; + if (flags & flag_num_negative) { + if (top->type == json_integer) { + top->u.integer = -top->u.integer; + } else { + top->u.dbl = -top->u.dbl; + } } flags |= flag_next | flag_reproc; @@ -820,36 +836,33 @@ whitespace: default: break; - }; + } + ; } - if (flags & flag_reproc) - { - flags &= ~ flag_reproc; - -- i; + if (flags & flag_reproc) { + flags &= ~flag_reproc; + --i; } - if (flags & flag_next) - { - flags = (flags & ~ flag_next) | flag_need_comma; + if (flags & flag_next) { + flags = (flags & ~flag_next) | flag_need_comma; - if (!top->parent) - { + if (!top->parent) { /* root value done */ flags |= flag_done; continue; } - if (top->parent->type == json_array) + if (top->parent->type == json_array) { flags |= flag_seek_value; + } - if (!state.first_pass) - { + if (!state.first_pass) { json_value * parent = top->parent; - switch (parent->type) - { + switch (parent->type) { case json_object: parent->u.object.values @@ -866,11 +879,13 @@ whitespace: default: break; - }; + } + ; } - if ( (++ top->parent->u.array.length) > state.uint_max) + if ( (++top->parent->u.array.length) > state.uint_max) { goto e_overflow; + } top = top->parent; @@ -883,107 +898,106 @@ whitespace: return root; -e_unknown_value: + e_unknown_value: - sprintf (error, "%d:%d: Unknown value", cur_line, e_off); + sprintf(error, "%d:%d: Unknown value", cur_line, e_off); goto e_failed; -e_alloc_failure: + e_alloc_failure: - strcpy (error, "Memory allocation failure"); + strcpy(error, "Memory allocation failure"); goto e_failed; -e_overflow: + e_overflow: - sprintf (error, "%d:%d: Too long (caught overflow)", cur_line, e_off); + sprintf(error, "%d:%d: Too long (caught overflow)", cur_line, e_off); goto e_failed; -e_failed: + e_failed: - if (error_buf) - { - if (*error) - strcpy (error_buf, error); - else - strcpy (error_buf, "Unknown error"); + if (error_buf) { + if (*error) { + strcpy(error_buf, error); + } else { + strcpy(error_buf, "Unknown error"); + } } - if (state.first_pass) + if (state.first_pass) { alloc = root; + } - while (alloc) - { + while (alloc) { top = alloc->_reserved.next_alloc; - state.settings.mem_free (alloc, state.settings.user_data); + state.settings.mem_free(alloc, state.settings.user_data); alloc = top; } - if (!state.first_pass) - json_value_free_ex (&state.settings, root); + if (!state.first_pass) { + json_value_free_ex(&state.settings, root); + } return 0; } -json_value * json_parse (const json_char * json, size_t length) +json_value * json_parse(const json_char * json, size_t length) { json_settings settings = { 0 }; - return json_parse_ex (&settings, json, length, 0); + return json_parse_ex(&settings, json, length, 0); } -void json_value_free_ex (json_settings * settings, json_value * value) +void json_value_free_ex(json_settings * settings, json_value * value) { json_value * cur_value; - if (!value) + if (!value) { return; + } value->parent = 0; - while (value) - { - switch (value->type) - { + while (value) { + switch (value->type) { case json_array: - if (!value->u.array.length) - { - settings->mem_free (value->u.array.values, settings->user_data); + if (!value->u.array.length) { + settings->mem_free(value->u.array.values, settings->user_data); break; } - value = value->u.array.values [-- value->u.array.length]; + value = value->u.array.values [--value->u.array.length]; continue; case json_object: - if (!value->u.object.length) - { - settings->mem_free (value->u.object.values, settings->user_data); + if (!value->u.object.length) { + settings->mem_free(value->u.object.values, settings->user_data); break; } - value = value->u.object.values [-- value->u.object.length].value; + value = value->u.object.values [--value->u.object.length].value; continue; case json_string: - settings->mem_free (value->u.string.ptr, settings->user_data); + settings->mem_free(value->u.string.ptr, settings->user_data); break; default: break; - }; + } + ; cur_value = value; value = value->parent; - settings->mem_free (cur_value, settings->user_data); + settings->mem_free(cur_value, settings->user_data); } } -void json_value_free (json_value * value) +void json_value_free(json_value * value) { json_settings settings = { 0 }; settings.mem_free = default_free; - json_value_free_ex (&settings, value); + json_value_free_ex(&settings, value); } diff --git a/src/json.h b/src/json.h index 8ac9ed9d..bd3d2561 100644 --- a/src/json.h +++ b/src/json.h @@ -54,216 +54,207 @@ extern "C" #endif - typedef struct - { - unsigned long max_memory; - int settings; +typedef struct { + unsigned long max_memory; + int settings; - /* Custom allocator support (leave null to use malloc/free) - */ + /* Custom allocator support (leave null to use malloc/free) + */ - void * (* mem_alloc) (size_t, int zero, void * user_data); - void (* mem_free) (void *, void * user_data); + void * (*mem_alloc)(size_t, int zero, void * user_data); + void (* mem_free)(void *, void * user_data); - void * user_data; /* will be passed to mem_alloc and mem_free */ + void * user_data; /* will be passed to mem_alloc and mem_free */ - } json_settings; +} json_settings; #define json_enable_comments 0x01 - typedef enum - { - json_none, - json_object, - json_array, - json_integer, - json_double, - json_string, - json_boolean, - json_null +typedef enum { + json_none, + json_object, + json_array, + json_integer, + json_double, + json_string, + json_boolean, + json_null - } json_type; +} json_type; - extern const struct _json_value json_value_none; +extern const struct _json_value json_value_none; - typedef struct _json_value - { - struct _json_value * parent; +typedef struct _json_value { + struct _json_value * parent; - json_type type; + json_type type; - union - { - int boolean; - json_int_t integer; - double dbl; + union { + int boolean; + json_int_t integer; + double dbl; - struct - { - unsigned int length; - json_char * ptr; /* null terminated */ + struct { + unsigned int length; + json_char * ptr; /* null terminated */ - } string; + } string; - struct - { - unsigned int length; + struct { + unsigned int length; - struct - { - json_char * name; - unsigned int name_length; + struct { + json_char * name; + unsigned int name_length; - struct _json_value * value; + struct _json_value * value; - } * values; + } * values; #if defined(__cplusplus) && __cplusplus >= 201103L - decltype(values) begin () const - { - return values; - } - decltype(values) end () const - { - return values + length; - } + decltype(values) begin() const + { + return values; + } + decltype(values) end() const + { + return values + length; + } #endif - } object; + } object; - struct - { - unsigned int length; - struct _json_value ** values; + struct { + unsigned int length; + struct _json_value ** values; #if defined(__cplusplus) && __cplusplus >= 201103L - decltype(values) begin () const - { - return values; - } - decltype(values) end () const - { - return values + length; - } + decltype(values) begin() const + { + return values; + } + decltype(values) end() const + { + return values + length; + } #endif - } array; + } array; - } u; + } u; - union - { - struct _json_value * next_alloc; - void * object_mem; + union { + struct _json_value * next_alloc; + void * object_mem; - } _reserved; + } _reserved; - /* Some C++ operator sugar */ + /* Some C++ operator sugar */ #ifdef __cplusplus - public: +public: - inline _json_value () - { - memset (this, 0, sizeof (_json_value)); - } - - inline const struct _json_value &operator [] (int index) const - { - if (type != json_array || index < 0 - || ((unsigned int) index) >= u.array.length) - { - return json_value_none; - } - - return *u.array.values [index]; - } - - inline const struct _json_value &operator [] (const char * index) const - { - if (type != json_object) - return json_value_none; - - for (unsigned int i = 0; i < u.object.length; ++ i) - if (!strcmp (u.object.values [i].name, index)) - return *u.object.values [i].value; + inline _json_value(){ + memset(this, 0, sizeof(_json_value)); + } + inline const struct _json_value &operator [] (int index) const { + if (type != json_array || index < 0 + || ((unsigned int)index) >= u.array.length) { return json_value_none; } - inline operator const char * () const - { - switch (type) - { - case json_string: - return u.string.ptr; + return *u.array.values [index]; + } - default: - return ""; - }; + inline const struct _json_value &operator [] (const char * index) const { + if (type != json_object) { + return json_value_none; } - inline operator json_int_t () const - { - switch (type) - { - case json_integer: - return u.integer; - - case json_double: - return (json_int_t) u.dbl; - - default: - return 0; - }; + for (unsigned int i = 0; i < u.object.length; ++i) { + if (!strcmp(u.object.values [i].name, index)) { + return *u.object.values [i].value; + } } - inline operator bool () const - { - if (type != json_boolean) - return false; + return json_value_none; + } - return u.boolean != 0; + inline operator const char * () const + { + switch (type) { + case json_string: + return u.string.ptr; + + default: + return ""; + } + ; + } + + inline operator json_int_t() const + { + switch (type) { + case json_integer: + return u.integer; + + case json_double: + return (json_int_t)u.dbl; + + default: + return 0; + } + ; + } + + inline operator bool() const + { + if (type != json_boolean) { + return false; } - inline operator double () const - { - switch (type) - { - case json_integer: - return (double) u.integer; + return u.boolean != 0; + } - case json_double: - return u.dbl; + inline operator double () const + { + switch (type) { + case json_integer: + return (double)u.integer; - default: - return 0; - }; + case json_double: + return u.dbl; + + default: + return 0; } + ; + } #endif - } json_value; +} json_value; - json_value * json_parse (const json_char * json, - size_t length); +json_value * json_parse(const json_char * json, + size_t length); #define json_error_max 128 - json_value * json_parse_ex (json_settings * settings, - const json_char * json, - size_t length, - char * error); +json_value * json_parse_ex(json_settings * settings, + const json_char * json, + size_t length, + char * error); - void json_value_free (json_value *); +void json_value_free(json_value *); - /* Not usually necessary, unless you used a custom mem_alloc and now want to - * use a custom mem_free. - */ - void json_value_free_ex (json_settings * settings, - json_value *); +/* Not usually necessary, unless you used a custom mem_alloc and now want to + * use a custom mem_free. + */ +void json_value_free_ex(json_settings * settings, + json_value *); #ifdef __cplusplus diff --git a/src/local.c b/src/local.c index 13da08e5..a1eef926 100644 --- a/src/local.c +++ b/src/local.c @@ -85,22 +85,23 @@ static int nofile = 0; #endif #endif -static void server_recv_cb (EV_P_ ev_io *w, int revents); -static void server_send_cb (EV_P_ ev_io *w, int revents); -static void remote_recv_cb (EV_P_ ev_io *w, int revents); -static void remote_send_cb (EV_P_ ev_io *w, int revents); -static void accept_cb (EV_P_ ev_io *w, int revents); -static void signal_cb (EV_P_ ev_signal *w, int revents); +static void server_recv_cb(EV_P_ ev_io *w, int revents); +static void server_send_cb(EV_P_ ev_io *w, int revents); +static void remote_recv_cb(EV_P_ ev_io *w, int revents); +static void remote_send_cb(EV_P_ ev_io *w, int revents); +static void accept_cb(EV_P_ ev_io *w, int revents); +static void signal_cb(EV_P_ ev_signal *w, int revents); -static int create_and_bind (const char *addr, const char *port); -static struct remote* connect_to_remote (struct listen_ctx *listener, const char *host, const char *port); -static void free_remote (struct remote *remote); -static void close_and_free_remote (EV_P_ struct remote *remote); -static void free_server (struct server *server); -static void close_and_free_server (EV_P_ struct server *server); +static int create_and_bind(const char *addr, const char *port); +static struct remote * connect_to_remote(struct listen_ctx *listener, + const char *host, const char *port); +static void free_remote(struct remote *remote); +static void close_and_free_remote(EV_P_ struct remote *remote); +static void free_server(struct server *server); +static void close_and_free_server(EV_P_ struct server *server); -static struct remote* new_remote (int fd, int timeout); -static struct server* new_server (int fd, int method); +static struct remote * new_remote(int fd, int timeout); +static struct server * new_server(int fd, int method); static TAILQ_HEAD(connection_head, server) connections; @@ -108,19 +109,21 @@ static TAILQ_HEAD(connection_head, server) connections; int setnonblocking(int fd) { int flags; - if (-1 ==(flags = fcntl(fd, F_GETFL, 0))) + if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { flags = 0; + } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } #endif #ifdef SET_INTERFACE -int setinterface(int socket_fd, const char* interface_name) +int setinterface(int socket_fd, const char * interface_name) { struct ifreq interface; memset(&interface, 0, sizeof(interface)); strncpy(interface.ifr_name, interface_name, IFNAMSIZ); - int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, sizeof(struct ifreq)); + int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, + sizeof(struct ifreq)); return res; } #endif @@ -132,21 +135,20 @@ int create_and_bind(const char *addr, const char *port) int s, listen_sock; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ + hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */ s = getaddrinfo(addr, port, &hints, &result); - if (s != 0) - { + if (s != 0) { LOGD("getaddrinfo: %s", gai_strerror(s)); return -1; } - for (rp = result; rp != NULL; rp = rp->ai_next) - { + for (rp = result; rp != NULL; rp = rp->ai_next) { listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - if (listen_sock == -1) + if (listen_sock == -1) { continue; + } int opt = 1; setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); @@ -156,21 +158,17 @@ int create_and_bind(const char *addr, const char *port) #endif s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen); - if (s == 0) - { + if (s == 0) { /* We managed to bind successfully! */ break; - } - else - { + } else { ERROR("bind"); } close(listen_sock); } - if (rp == NULL) - { + if (rp == NULL) { LOGE("Could not bind"); return -1; } @@ -183,49 +181,39 @@ int create_and_bind(const char *addr, const char *port) static void free_connections(struct ev_loop *loop) { struct server *iter; - while ((iter = TAILQ_FIRST(&connections)) != NULL) - { + while ((iter = TAILQ_FIRST(&connections)) != NULL) { struct remote *remote = iter->remote; close_and_free_server(loop, iter); close_and_free_remote(loop, remote); } } -static void server_recv_cb (EV_P_ ev_io *w, int revents) +static void server_recv_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_recv_ctx = (struct server_ctx *)w; struct server *server = server_recv_ctx->server; struct remote *remote = server->remote; char *buf; - if (remote == NULL) - { + if (remote == NULL) { buf = server->buf; - } - else - { + } else { buf = remote->buf; } ssize_t r = recv(server->fd, buf, BUF_SIZE, 0); - if (r == 0) - { + if (r == 0) { // connection closed close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else if (r < 0) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("server_recv_cb_recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -233,25 +221,21 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) } } - while (1) - { + while (1) { // local socks5 server - if (server->stage == 5) - { - if (remote == NULL) - { + if (server->stage == 5) { + if (remote == NULL) { LOGE("invalid remote."); close_and_free_server(EV_A_ server); return; } // insert shadowsocks header - if (!remote->direct) - { - remote->buf = ss_encrypt(BUF_SIZE, remote->buf, &r, server->e_ctx); + if (!remote->direct) { + remote->buf = ss_encrypt(BUF_SIZE, remote->buf, &r, + server->e_ctx); - if (remote->buf == NULL) - { + if (remote->buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -259,43 +243,37 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) } } - if (!remote->send_ctx->connected) - { + if (!remote->send_ctx->connected) { remote->buf_idx = 0; remote->buf_len = r; - if (!fast_open || remote->direct) - { + if (!fast_open || remote->direct) { // connecting, wait until connected - connect(remote->fd, remote->addr_info->ai_addr, remote->addr_info->ai_addrlen); + connect(remote->fd, remote->addr_info->ai_addr, + remote->addr_info->ai_addrlen); // wait on remote connected event - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); - ev_timer_start(EV_A_ &remote->send_ctx->watcher); - } - else - { + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); + ev_timer_start(EV_A_ & remote->send_ctx->watcher); + } else { #ifdef TCP_FASTOPEN int s = sendto(remote->fd, remote->buf, r, MSG_FASTOPEN, - remote->addr_info->ai_addr, remote->addr_info->ai_addrlen); - if (s == -1) - { - if (errno == EINPROGRESS) - { + remote->addr_info->ai_addr, + remote->addr_info->ai_addrlen); + if (s == -1) { + if (errno == EINPROGRESS) { // in progress, wait until connected remote->buf_idx = 0; remote->buf_len = r; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); return; - } - else - { + } else { ERROR("sendto"); - if (errno == ENOTCONN) - { - LOGE("fast open is not supported on this platform"); + if (errno == ENOTCONN) { + LOGE( + "fast open is not supported on this platform"); // just turn it off fast_open = 0; } @@ -303,61 +281,49 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) close_and_free_server(EV_A_ server); return; } - } - else if (s < r) - { + } else if (s < r) { remote->buf_len = r - s; remote->buf_idx = s; } // Just connected remote->send_ctx->connected = 1; - ev_timer_stop(EV_A_ &remote->send_ctx->watcher); - ev_io_start(EV_A_ &remote->recv_ctx->io); + ev_timer_stop(EV_A_ & remote->send_ctx->watcher); + ev_io_start(EV_A_ & remote->recv_ctx->io); #else // if TCP_FASTOPEN is not defined, fast_open will always be 0 LOGE("can't come here"); exit(1); #endif } - } - else - { + } else { int s = send(remote->fd, remote->buf, r, 0); - if (s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send remote->buf_idx = 0; remote->buf_len = r; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); return; - } - else - { + } else { ERROR("server_recv_cb_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else if (s < r) - { + } else if (s < r) { remote->buf_len = r - s; remote->buf_idx = s; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); return; } } // all processed return; - } - else if (server->stage == 0) - { + } else if (server->stage == 0) { struct method_select_response response; response.ver = SVERSION; response.method = 0; @@ -365,9 +331,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) send(server->fd, send_buf, sizeof(response), 0); server->stage = 1; return; - } - else if (server->stage == 1) - { + } else if (server->stage == 1) { struct socks5_request *request = (struct socks5_request *)buf; struct sockaddr_in sock_addr; @@ -375,19 +339,15 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) int udp_assc = 0; - if (udprelay && request->cmd == 3) - { + if (udprelay && request->cmd == 3) { udp_assc = 1; socklen_t addr_len = sizeof(sock_addr); getsockname(server->fd, (struct sockaddr *)&sock_addr, &addr_len); - if (verbose) - { + if (verbose) { LOGD("udp assc request accepted."); } - } - else if (request->cmd != 1) - { + } else if (request->cmd != 1) { LOGE("unsupported cmd: %d", request->cmd); struct socks5_response response; response.ver = SVERSION; @@ -399,63 +359,57 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { char *ss_addr_to_send = malloc(BUF_SIZE); ssize_t addr_len = 0; ss_addr_to_send[addr_len++] = request->atyp; char host[256], port[16]; // get remote addr and port - if (request->atyp == 1) - { + if (request->atyp == 1) { // IP V4 size_t in_addr_len = sizeof(struct in_addr); - memcpy(ss_addr_to_send + addr_len, buf + 4, in_addr_len + 2); + memcpy(ss_addr_to_send + addr_len, buf + 4, in_addr_len + + 2); addr_len += in_addr_len + 2; - if (acl || verbose) - { - uint16_t p = ntohs(*(uint16_t *)(buf + 4 + in_addr_len)); + if (acl || verbose) { + uint16_t p = + ntohs(*(uint16_t *)(buf + 4 + in_addr_len)); inet_ntop(AF_INET, (const void *)(buf + 4), host, INET_ADDRSTRLEN); sprintf(port, "%d", p); } - } - else if (request->atyp == 3) - { + } else if (request->atyp == 3) { // Domain name uint8_t name_len = *(uint8_t *)(buf + 4); ss_addr_to_send[addr_len++] = name_len; - memcpy(ss_addr_to_send + addr_len, buf + 4 + 1, name_len + 2); + memcpy(ss_addr_to_send + addr_len, buf + 4 + 1, name_len + + 2); addr_len += name_len + 2; - if (acl || verbose) - { - uint16_t p = ntohs(*(uint16_t *)(buf + 4 + 1 + name_len)); + if (acl || verbose) { + uint16_t p = + ntohs(*(uint16_t *)(buf + 4 + 1 + name_len)); memcpy(host, buf + 4 + 1, name_len); host[name_len] = '\0'; sprintf(port, "%d", p); } - } - else if (request->atyp == 4) - { + } else if (request->atyp == 4) { // IP V6 size_t in6_addr_len = sizeof(struct in6_addr); - memcpy(ss_addr_to_send + addr_len, buf + 4, in6_addr_len + 2); + memcpy(ss_addr_to_send + addr_len, buf + 4, in6_addr_len + + 2); addr_len += in6_addr_len + 2; - if (acl || verbose) - { - uint16_t p = ntohs(*(uint16_t *)(buf + 4 + in6_addr_len)); + if (acl || verbose) { + uint16_t p = + ntohs(*(uint16_t *)(buf + 4 + in6_addr_len)); inet_ntop(AF_INET6, (const void *)(buf + 4), host, INET6_ADDRSTRLEN); sprintf(port, "%d", p); } - } - else - { + } else { LOGE("unsupported addrtype: %d", request->atyp); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -467,46 +421,36 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) r -= (3 + addr_len); buf += (3 + addr_len); - if (verbose) - { + if (verbose) { LOGD("connect to %s:%s", host, port); } if ((acl && request->atyp == 1 && acl_contains_ip(host)) - || (acl && request->atyp == 3 && acl_contains_domain(host))) - { + || (acl && request->atyp == 3 && + acl_contains_domain(host))) { remote = connect_to_remote(server->listener, host, port); remote->direct = 1; - if (verbose) - { + if (verbose) { LOGD("bypass %s:%s", host, port); } - } - else - { + } else { remote = connect_to_remote(server->listener, NULL, NULL); } - if (remote == NULL) - { + if (remote == NULL) { LOGE("invalid remote addr."); close_and_free_server(EV_A_ server); return; } - if (!remote->direct) - { + if (!remote->direct) { memcpy(remote->buf, ss_addr_to_send, addr_len); - if (r > 0) - { + if (r > 0) { memcpy(remote->buf + addr_len, buf, r); } r += addr_len; - } - else - { - if (r > 0) - { + } else { + if (r > 0) { memcpy(remote->buf, buf, r); } } @@ -523,22 +467,24 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) response.atyp = 1; memcpy(server->buf, &response, sizeof(struct socks5_response)); - memcpy(server->buf + sizeof(struct socks5_response), &sock_addr.sin_addr, sizeof(sock_addr.sin_addr)); - memcpy(server->buf + sizeof(struct socks5_response) + sizeof(sock_addr.sin_addr), + memcpy(server->buf + sizeof(struct socks5_response), + &sock_addr.sin_addr, sizeof(sock_addr.sin_addr)); + memcpy(server->buf + sizeof(struct socks5_response) + + sizeof(sock_addr.sin_addr), &sock_addr.sin_port, sizeof(sock_addr.sin_port)); - int reply_size = sizeof(struct socks5_response) + sizeof(sock_addr.sin_addr) + sizeof(sock_addr.sin_port); + int reply_size = sizeof(struct socks5_response) + + sizeof(sock_addr.sin_addr) + + sizeof(sock_addr.sin_port); int s = send(server->fd, server->buf, reply_size, 0); - if (s < reply_size) - { + if (s < reply_size) { LOGE("failed to send fake reply."); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - if (udp_assc) - { + if (udp_assc) { close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; @@ -547,47 +493,38 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) } } -static void server_send_cb (EV_P_ ev_io *w, int revents) +static void server_send_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_send_ctx = (struct server_ctx *)w; struct server *server = server_send_ctx->server; struct remote *remote = server->remote; - if (server->buf_len == 0) - { + if (server->buf_len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(server->fd, server->buf + server->buf_idx, server->buf_len, 0); - if (s < 0) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("server_send_cb_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < server->buf_len) - { + } else if (s < server->buf_len) { // partly sent, move memory, wait for the next time to send server->buf_len -= s; server->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading server->buf_len = 0; server->buf_idx = 0; - ev_io_stop(EV_A_ &server_send_ctx->io); - ev_io_start(EV_A_ &remote->recv_ctx->io); + ev_io_stop(EV_A_ & server_send_ctx->io); + ev_io_start(EV_A_ & remote->recv_ctx->io); } } @@ -595,8 +532,8 @@ static void server_send_cb (EV_P_ ev_io *w, int revents) static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) { - struct remote_ctx *remote_ctx = (struct remote_ctx *) (((void*)watcher) - - sizeof(ev_io)); + struct remote_ctx *remote_ctx = (struct remote_ctx *)(((void *)watcher) + - sizeof(ev_io)); struct remote *remote = remote_ctx->remote; struct server *server = remote->server; @@ -606,33 +543,27 @@ static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) close_and_free_server(EV_A_ server); } -static void remote_recv_cb (EV_P_ ev_io *w, int revents) +static void remote_recv_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_recv_ctx = (struct remote_ctx *)w; struct remote *remote = remote_recv_ctx->remote; struct server *server = remote->server; - ev_timer_again(EV_A_ &remote->recv_ctx->watcher); + ev_timer_again(EV_A_ & remote->recv_ctx->watcher); ssize_t r = recv(remote->fd, server->buf, BUF_SIZE, 0); - if (r == 0) - { + if (r == 0) { // connection closed close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else if (r < 0) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("remote_recv_cb_recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -640,11 +571,9 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) } } - if (!remote->direct) - { + if (!remote->direct) { server->buf = ss_decrypt(BUF_SIZE, server->buf, &r, server->d_ctx); - if (server->buf == NULL) - { + if (server->buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -654,63 +583,52 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) int s = send(server->fd, server->buf, r, 0); - if (s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send server->buf_len = r; server->buf_idx = 0; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); return; - } - else - { + } else { ERROR("remote_recv_cb_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else if (s < r) - { + } else if (s < r) { server->buf_len = r - s; server->buf_idx = s; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); return; } } -static void remote_send_cb (EV_P_ ev_io *w, int revents) +static void remote_send_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_send_ctx = (struct remote_ctx *)w; struct remote *remote = remote_send_ctx->remote; struct server *server = remote->server; - if (!remote_send_ctx->connected) - { + if (!remote_send_ctx->connected) { struct sockaddr_storage addr; socklen_t len = sizeof addr; - int r = getpeername(remote->fd, (struct sockaddr*)&addr, &len); - if (r == 0) - { + int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len); + if (r == 0) { remote_send_ctx->connected = 1; - ev_timer_stop(EV_A_ &remote_send_ctx->watcher); - ev_timer_start(EV_A_ &remote->recv_ctx->watcher); - ev_io_start(EV_A_ &remote->recv_ctx->io); + ev_timer_stop(EV_A_ & remote_send_ctx->watcher); + ev_timer_start(EV_A_ & remote->recv_ctx->watcher); + ev_io_start(EV_A_ & remote->recv_ctx->io); // no need to send any data - if (remote->buf_len == 0) - { - ev_io_stop(EV_A_ &remote_send_ctx->io); - ev_io_start(EV_A_ &server->recv_ctx->io); + if (remote->buf_len == 0) { + ev_io_stop(EV_A_ & remote_send_ctx->io); + ev_io_start(EV_A_ & server->recv_ctx->io); return; } - } - else - { + } else { // not connected ERROR("getpeername"); close_and_free_remote(EV_A_ remote); @@ -719,48 +637,39 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) } } - if (remote->buf_len == 0) - { + if (remote->buf_len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(remote->fd, remote->buf + remote->buf_idx, remote->buf_len, 0); - if (s < 0) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("remote_send_cb_send"); // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < remote->buf_len) - { + } else if (s < remote->buf_len) { // partly sent, move memory, wait for the next time to send remote->buf_len -= s; remote->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading remote->buf_len = 0; remote->buf_idx = 0; - ev_io_stop(EV_A_ &remote_send_ctx->io); - ev_io_start(EV_A_ &server->recv_ctx->io); + ev_io_stop(EV_A_ & remote_send_ctx->io); + ev_io_start(EV_A_ & server->recv_ctx->io); } } } -static struct remote* new_remote(int fd, int timeout) +static struct remote * new_remote(int fd, int timeout) { struct remote *remote; remote = malloc(sizeof(struct remote)); @@ -776,7 +685,8 @@ static struct remote* new_remote(int fd, int timeout) ev_io_init(&remote->recv_ctx->io, remote_recv_cb, fd, EV_READ); ev_io_init(&remote->send_ctx->io, remote_send_cb, fd, EV_WRITE); ev_timer_init(&remote->send_ctx->watcher, remote_timeout_cb, timeout, 0); - ev_timer_init(&remote->recv_ctx->watcher, remote_timeout_cb, timeout, timeout * 60); + ev_timer_init(&remote->recv_ctx->watcher, remote_timeout_cb, timeout, + timeout * 60); remote->recv_ctx->remote = remote; remote->send_ctx->remote = remote; return remote; @@ -784,18 +694,14 @@ static struct remote* new_remote(int fd, int timeout) static void free_remote(struct remote *remote) { - if (remote != NULL) - { - if (remote->server != NULL) - { + if (remote != NULL) { + if (remote->server != NULL) { remote->server->remote = NULL; } - if (remote->buf != NULL) - { + if (remote->buf != NULL) { free(remote->buf); } - if (remote->addr_info != NULL) - { + if (remote->addr_info != NULL) { freeaddrinfo(remote->addr_info); } free(remote->recv_ctx); @@ -806,18 +712,17 @@ static void free_remote(struct remote *remote) static void close_and_free_remote(EV_P_ struct remote *remote) { - if (remote != NULL) - { - ev_timer_stop(EV_A_ &remote->send_ctx->watcher); - ev_timer_stop(EV_A_ &remote->recv_ctx->watcher); - ev_io_stop(EV_A_ &remote->send_ctx->io); - ev_io_stop(EV_A_ &remote->recv_ctx->io); + if (remote != NULL) { + ev_timer_stop(EV_A_ & remote->send_ctx->watcher); + ev_timer_stop(EV_A_ & remote->recv_ctx->watcher); + ev_io_stop(EV_A_ & remote->send_ctx->io); + ev_io_stop(EV_A_ & remote->recv_ctx->io); close(remote->fd); free_remote(remote); } } -static struct server* new_server(int fd, int method) +static struct server * new_server(int fd, int method) { struct server *server; server = malloc(sizeof(struct server)); @@ -834,15 +739,12 @@ static struct server* new_server(int fd, int method) ev_io_init(&server->send_ctx->io, server_send_cb, fd, EV_WRITE); server->recv_ctx->server = server; server->send_ctx->server = server; - if (method) - { + if (method) { server->e_ctx = malloc(sizeof(struct enc_ctx)); server->d_ctx = malloc(sizeof(struct enc_ctx)); enc_ctx_init(method, server->e_ctx, 1); enc_ctx_init(method, server->d_ctx, 0); - } - else - { + } else { server->e_ctx = NULL; server->d_ctx = NULL; } @@ -856,22 +758,18 @@ static void free_server(struct server *server) { TAILQ_REMOVE(&connections, server, entries); - if (server->remote != NULL) - { + if (server->remote != NULL) { server->remote->server = NULL; } - if (server->e_ctx != NULL) - { + if (server->e_ctx != NULL) { cipher_context_release(&server->e_ctx->evp); free(server->e_ctx); } - if (server->d_ctx != NULL) - { + if (server->d_ctx != NULL) { cipher_context_release(&server->d_ctx->evp); free(server->d_ctx); } - if (server->buf != NULL) - { + if (server->buf != NULL) { free(server->buf); } free(server->recv_ctx); @@ -881,17 +779,16 @@ static void free_server(struct server *server) static void close_and_free_server(EV_P_ struct server *server) { - if (server != NULL) - { - ev_io_stop(EV_A_ &server->send_ctx->io); - ev_io_stop(EV_A_ &server->recv_ctx->io); + if (server != NULL) { + ev_io_stop(EV_A_ & server->send_ctx->io); + ev_io_stop(EV_A_ & server->recv_ctx->io); close(server->fd); free_server(server); } } -static struct remote* connect_to_remote(struct listen_ctx *listener, - const char *host, const char *port) +static struct remote * connect_to_remote(struct listen_ctx *listener, + const char *host, const char *port) { int opt = 1; int sockfd; @@ -903,21 +800,19 @@ static struct remote* connect_to_remote(struct listen_ctx *listener, hints.ai_socktype = SOCK_STREAM; int index = rand() % listener->remote_num; int err; - if (host == NULL || port == NULL) - { - if (verbose) - { + if (host == NULL || port == NULL) { + if (verbose) { LOGD("connect to server: %s:%s", listener->remote_addr[index].host, listener->remote_addr[index].port); } err = getaddrinfo(listener->remote_addr[index].host, - listener->remote_addr[index].port, &hints, &remote_res); - } - else + listener->remote_addr[index].port, &hints, + &remote_res); + } else { err = getaddrinfo(host, port, &hints, &remote_res); + } - if (err) - { + if (err) { ERROR("getaddrinfo"); return NULL; } @@ -925,8 +820,7 @@ static struct remote* connect_to_remote(struct listen_ctx *listener, sockfd = socket(remote_res->ai_family, remote_res->ai_socktype, remote_res->ai_protocol); - if (sockfd < 0) - { + if (sockfd < 0) { ERROR("socket"); freeaddrinfo(remote_res); return NULL; @@ -940,7 +834,9 @@ static struct remote* connect_to_remote(struct listen_ctx *listener, // Setup setnonblocking(sockfd); #ifdef SET_INTERFACE - if (listener->iface) setinterface(sockfd, listener->iface); + if (listener->iface) { + setinterface(sockfd, listener->iface); + } #endif struct remote *remote = new_remote(sockfd, listener->timeout); @@ -949,12 +845,10 @@ static struct remote* connect_to_remote(struct listen_ctx *listener, return remote; } -static void signal_cb (EV_P_ ev_signal *w, int revents) +static void signal_cb(EV_P_ ev_signal *w, int revents) { - if (revents & EV_SIGNAL) - { - switch (w->signum) - { + if (revents & EV_SIGNAL) { + switch (w->signum) { case SIGINT: case SIGTERM: ev_unloop(EV_A_ EVUNLOOP_ALL); @@ -962,12 +856,11 @@ static void signal_cb (EV_P_ ev_signal *w, int revents) } } -void accept_cb (EV_P_ ev_io *w, int revents) +void accept_cb(EV_P_ ev_io *w, int revents) { struct listen_ctx *listener = (struct listen_ctx *)w; int serverfd = accept(listener->fd, NULL, NULL); - if (serverfd == -1) - { + if (serverfd == -1) { ERROR("accept"); return; } @@ -981,11 +874,11 @@ void accept_cb (EV_P_ ev_io *w, int revents) struct server *server = new_server(serverfd, listener->method); server->listener = listener; - ev_io_start(EV_A_ &server->recv_ctx->io); + ev_io_start(EV_A_ & server->recv_ctx->io); } #ifndef LIB_ONLY -int main (int argc, char **argv) +int main(int argc, char **argv) { int i, c; @@ -1009,30 +902,28 @@ int main (int argc, char **argv) int option_index = 0; static struct option long_options[] = { - {"fast-open", no_argument, 0, 0 }, - {"acl", required_argument, 0, 0 }, - {0, 0, 0, 0 } + { "fast-open", no_argument, 0, + 0 }, + { "acl", required_argument, 0, + 0 }, + { 0, 0, 0, + 0 } }; opterr = 0; while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:uv", - long_options, &option_index)) != -1) - { - switch (c) - { + long_options, &option_index)) != -1) { + switch (c) { case 0: - if (option_index == 0) - { + if (option_index == 0) { #ifdef TCP_FASTOPEN fast_open = 1; LOGD("using tcp fast open"); #else LOGE("tcp fast open is not supported by this environment"); #endif - } - else if (option_index == 1) - { + } else if (option_index == 1) { LOGD("initialize acl..."); acl = !init_acl(optarg); } @@ -1081,40 +972,50 @@ int main (int argc, char **argv) } } - if (opterr) - { + if (opterr) { usage(); exit(EXIT_FAILURE); } - if (conf_path != NULL) - { + if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); - if (remote_num == 0) - { + if (remote_num == 0) { remote_num = conf->remote_num; - for (i = 0; i < remote_num; i++) - { + for (i = 0; i < remote_num; i++) { remote_addr[i] = conf->remote_addr[i]; } } - if (remote_port == NULL) remote_port = conf->remote_port; - if (local_addr == NULL) local_addr = conf->local_addr; - if (local_port == NULL) local_port = conf->local_port; - if (password == NULL) password = conf->password; - if (method == NULL) method = conf->method; - if (timeout == NULL) timeout = conf->timeout; - if (fast_open == 0) fast_open = conf->fast_open; + if (remote_port == NULL) { + remote_port = conf->remote_port; + } + if (local_addr == NULL) { + local_addr = conf->local_addr; + } + if (local_port == NULL) { + local_port = conf->local_port; + } + if (password == NULL) { + password = conf->password; + } + if (method == NULL) { + method = conf->method; + } + if (timeout == NULL) { + timeout = conf->timeout; + } + if (fast_open == 0) { + fast_open = conf->fast_open; + } #ifdef HAVE_SETRLIMIT - if (nofile == 0) nofile = conf->nofile; + if (nofile == 0) { + nofile = conf->nofile; + } /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ - if (nofile) - { - if (verbose) - { + if (nofile) { + if (verbose) { LOGD("setting NOFILE to %d", nofile); } set_nofile(nofile); @@ -1123,18 +1024,20 @@ int main (int argc, char **argv) } if (remote_num == 0 || remote_port == NULL || - local_port == NULL || password == NULL) - { + local_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } - if (timeout == NULL) timeout = "10"; + if (timeout == NULL) { + timeout = "10"; + } - if (local_addr == NULL) local_addr = "0.0.0.0"; + if (local_addr == NULL) { + local_addr = "0.0.0.0"; + } - if (pid_flags) - { + if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } @@ -1161,12 +1064,10 @@ int main (int argc, char **argv) // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); - if (listenfd < 0) - { + if (listenfd < 0) { FATAL("bind() error.."); } - if (listen(listenfd, SOMAXCONN) == -1) - { + if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error."); } setnonblocking(listenfd); @@ -1176,10 +1077,11 @@ int main (int argc, char **argv) struct listen_ctx listen_ctx; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = malloc(sizeof(ss_addr_t) * remote_num); - while (remote_num > 0) - { + while (remote_num > 0) { int index = --remote_num; - if (remote_addr[index].port == NULL) remote_addr[index].port = remote_port; + if (remote_addr[index].port == NULL) { + remote_addr[index].port = remote_port; + } listen_ctx.remote_addr[index] = remote_addr[index]; } listen_ctx.timeout = atoi(timeout); @@ -1188,32 +1090,31 @@ int main (int argc, char **argv) listen_ctx.method = m; struct ev_loop *loop = EV_DEFAULT; - if (!loop) - { + if (!loop) { FATAL("ev_loop error."); } - ev_io_init (&listen_ctx.io, accept_cb, listenfd, EV_READ); - ev_io_start (loop, &listen_ctx.io); + ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); + ev_io_start(loop, &listen_ctx.io); // Setup UDP - if (udprelay) - { + if (udprelay) { LOGD("udprelay enabled."); - init_udprelay(local_addr, local_port, remote_addr[0].host, remote_addr[0].port, m, listen_ctx.timeout, iface); + init_udprelay(local_addr, local_port, remote_addr[0].host, + remote_addr[0].port, m, listen_ctx.timeout, iface); } // setuid - if (user != NULL) + if (user != NULL) { run_as(user); + } // Init connections TAILQ_INIT(&connections); // Enter the loop - ev_run (loop, 0); + ev_run(loop, 0); - if (verbose) - { + if (verbose) { LOGD("closed nicely."); } @@ -1256,12 +1157,13 @@ int start_ss_local_server(profile_t profile) USE_LOGFILE(log); - if (profile.acl != NULL) - { + if (profile.acl != NULL) { acl = !init_acl(profile.acl); } - if (local_addr == NULL) local_addr = "0.0.0.0"; + if (local_addr == NULL) { + local_addr = "0.0.0.0"; + } #ifdef __MINGW32__ winsock_init(); @@ -1285,12 +1187,10 @@ int start_ss_local_server(profile_t profile) // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port_str); - if (listenfd < 0) - { + if (listenfd < 0) { FATAL("bind()"); } - if (listen(listenfd, SOMAXCONN) == -1) - { + if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen()"); } setnonblocking(listenfd); @@ -1309,28 +1209,26 @@ int start_ss_local_server(profile_t profile) listen_ctx.iface = NULL; struct ev_loop *loop = EV_DEFAULT; - if (!loop) - { + if (!loop) { FATAL("ev_loop error."); } - ev_io_init (&listen_ctx.io, accept_cb, listenfd, EV_READ); - ev_io_start (loop, &listen_ctx.io); + ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); + ev_io_start(loop, &listen_ctx.io); // Setup UDP - if (udprelay) - { + if (udprelay) { LOGD("udprelay enabled."); - init_udprelay(local_addr, local_port_str, remote_host, remote_port_str, m, listen_ctx.timeout, NULL); + init_udprelay(local_addr, local_port_str, remote_host, remote_port_str, + m, listen_ctx.timeout, NULL); } // Init connections TAILQ_INIT(&connections); // Enter the loop - ev_run (loop, 0); + ev_run(loop, 0); - if (verbose) - { + if (verbose) { LOGD("closed nicely."); } diff --git a/src/local.h b/src/local.h index de792199..0e62c1d4 100644 --- a/src/local.h +++ b/src/local.h @@ -30,8 +30,7 @@ #include "common.h" -struct listen_ctx -{ +struct listen_ctx { ev_io io; ss_addr_t *remote_addr; char *iface; @@ -42,15 +41,13 @@ struct listen_ctx struct sockaddr sock; }; -struct server_ctx -{ +struct server_ctx { ev_io io; int connected; struct server *server; }; -struct server -{ +struct server { int fd; ssize_t buf_len; ssize_t buf_idx; @@ -66,16 +63,14 @@ struct server TAILQ_ENTRY(server) entries; }; -struct remote_ctx -{ +struct remote_ctx { ev_io io; ev_timer watcher; int connected; struct remote *remote; }; -struct remote -{ +struct remote { int fd; ssize_t buf_len; ssize_t buf_idx; diff --git a/src/redir.c b/src/redir.c index dd810c70..8d030d7e 100644 --- a/src/redir.c +++ b/src/redir.c @@ -64,14 +64,14 @@ #define IP6T_SO_ORIGINAL_DST 80 #endif -static void accept_cb (EV_P_ ev_io *w, int revents); -static void server_recv_cb (EV_P_ ev_io *w, int revents); -static void server_send_cb (EV_P_ ev_io *w, int revents); -static void remote_recv_cb (EV_P_ ev_io *w, int revents); -static void remote_send_cb (EV_P_ ev_io *w, int revents); +static void accept_cb(EV_P_ ev_io *w, int revents); +static void server_recv_cb(EV_P_ ev_io *w, int revents); +static void server_send_cb(EV_P_ ev_io *w, int revents); +static void remote_recv_cb(EV_P_ ev_io *w, int revents); +static void remote_send_cb(EV_P_ ev_io *w, int revents); -static struct remote* new_remote(int fd, int timeout); -static struct server* new_server(int fd, int method); +static struct remote * new_remote(int fd, int timeout); +static struct server * new_server(int fd, int method); static void free_remote(struct remote *remote); static void close_and_free_remote(EV_P_ struct remote *remote); @@ -82,14 +82,12 @@ static void close_and_free_server(EV_P_ struct server *server); int getdestaddr(int fd, struct sockaddr_storage *destaddr) { socklen_t socklen = sizeof(*destaddr); - int error=0; + int error = 0; - error = getsockopt(fd, SOL_IPV6, IP6T_SO_ORIGINAL_DST,destaddr, &socklen); - if (error) // Didn't find a proper way to detect IP version. - { - error = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST,destaddr, &socklen); - if(error) - { + error = getsockopt(fd, SOL_IPV6, IP6T_SO_ORIGINAL_DST, destaddr, &socklen); + if (error) { // Didn't find a proper way to detect IP version. + error = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, destaddr, &socklen); + if (error) { return -1; } } @@ -99,8 +97,9 @@ int getdestaddr(int fd, struct sockaddr_storage *destaddr) int setnonblocking(int fd) { int flags; - if (-1 ==(flags = fcntl(fd, F_GETFL, 0))) + if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { flags = 0; + } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } @@ -111,21 +110,20 @@ int create_and_bind(const char *addr, const char *port) int s, listen_sock; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ + hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */ s = getaddrinfo(addr, port, &hints, &result); - if (s != 0) - { + if (s != 0) { LOGD("getaddrinfo: %s", gai_strerror(s)); return -1; } - for (rp = result; rp != NULL; rp = rp->ai_next) - { + for (rp = result; rp != NULL; rp = rp->ai_next) { listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - if (listen_sock == -1) + if (listen_sock == -1) { continue; + } int opt = 1; setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); @@ -135,21 +133,17 @@ int create_and_bind(const char *addr, const char *port) #endif s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen); - if (s == 0) - { + if (s == 0) { /* We managed to bind successfully! */ break; - } - else - { + } else { ERROR("bind"); } close(listen_sock); } - if (rp == NULL) - { + if (rp == NULL) { LOGE("Could not bind"); return -1; } @@ -159,42 +153,34 @@ int create_and_bind(const char *addr, const char *port) return listen_sock; } -static void server_recv_cb (EV_P_ ev_io *w, int revents) +static void server_recv_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_recv_ctx = (struct server_ctx *)w; struct server *server = server_recv_ctx->server; struct remote *remote = server->remote; - if (remote == NULL) - { + if (remote == NULL) { close_and_free_server(EV_A_ server); return; } ssize_t r = recv(server->fd, remote->buf, BUF_SIZE, 0); - if (r == 0) - { + if (r == 0) { // connection closed remote->buf_len = 0; remote->buf_idx = 0; close_and_free_server(EV_A_ server); - if (remote != NULL) - { - ev_io_start(EV_A_ &remote->send_ctx->io); + if (remote != NULL) { + ev_io_start(EV_A_ & remote->send_ctx->io); } return; - } - else if(r < 0) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("server recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -203,8 +189,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) } remote->buf = ss_encrypt(BUF_SIZE, remote->buf, &r, server->e_ctx); - if (remote->buf == NULL) - { + if (remote->buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -212,82 +197,64 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) } int s = send(remote->fd, remote->buf, r, 0); - if(s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send remote->buf_len = r; remote->buf_idx = 0; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); return; - } - else - { + } else { ERROR("send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else if(s < r) - { + } else if (s < r) { remote->buf_len = r - s; remote->buf_idx = s; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); return; } } -static void server_send_cb (EV_P_ ev_io *w, int revents) +static void server_send_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_send_ctx = (struct server_ctx *)w; struct server *server = server_send_ctx->server; struct remote *remote = server->remote; - if (server->buf_len == 0) - { + if (server->buf_len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(server->fd, server->buf + server->buf_idx, server->buf_len, 0); - if (s < 0) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < server->buf_len) - { + } else if (s < server->buf_len) { // partly sent, move memory, wait for the next time to send server->buf_len -= s; server->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading server->buf_len = 0; server->buf_idx = 0; - ev_io_stop(EV_A_ &server_send_ctx->io); - if (remote != NULL) - { - ev_io_start(EV_A_ &remote->recv_ctx->io); - } - else - { + ev_io_stop(EV_A_ & server_send_ctx->io); + if (remote != NULL) { + ev_io_start(EV_A_ & remote->recv_ctx->io); + } else { close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; @@ -299,8 +266,8 @@ static void server_send_cb (EV_P_ ev_io *w, int revents) static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) { - struct remote_ctx *remote_ctx = (struct remote_ctx *) (((void*)watcher) - - sizeof(ev_io)); + struct remote_ctx *remote_ctx = (struct remote_ctx *)(((void *)watcher) + - sizeof(ev_io)); struct remote *remote = remote_ctx->remote; struct server *server = remote->server; @@ -308,8 +275,7 @@ static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) ev_timer_stop(EV_A_ watcher); - if (server == NULL) - { + if (server == NULL) { close_and_free_remote(EV_A_ remote); return; } @@ -317,41 +283,33 @@ static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) close_and_free_server(EV_A_ server); } -static void remote_recv_cb (EV_P_ ev_io *w, int revents) +static void remote_recv_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_recv_ctx = (struct remote_ctx *)w; struct remote *remote = remote_recv_ctx->remote; struct server *server = remote->server; - if (server == NULL) - { + if (server == NULL) { close_and_free_remote(EV_A_ remote); return; } ssize_t r = recv(remote->fd, server->buf, BUF_SIZE, 0); - if (r == 0) - { + if (r == 0) { // connection closed server->buf_len = 0; server->buf_idx = 0; close_and_free_remote(EV_A_ remote); - if (server != NULL) - { - ev_io_start(EV_A_ &server->send_ctx->io); + if (server != NULL) { + ev_io_start(EV_A_ & server->send_ctx->io); } return; - } - else if(r < 0) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("remote recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -360,8 +318,7 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) } server->buf = ss_decrypt(BUF_SIZE, server->buf, &r, server->d_ctx); - if (server->buf == NULL) - { + if (server->buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -369,78 +326,75 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) } int s = send(server->fd, server->buf, r, 0); - if (s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send server->buf_len = r; server->buf_idx = 0; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); return; - } - else - { + } else { ERROR("send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else if (s < r) - { + } else if (s < r) { server->buf_len = r - s; server->buf_idx = s; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); return; } } -static void remote_send_cb (EV_P_ ev_io *w, int revents) +static void remote_send_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_send_ctx = (struct remote_ctx *)w; struct remote *remote = remote_send_ctx->remote; struct server *server = remote->server; - if (!remote_send_ctx->connected) - { + if (!remote_send_ctx->connected) { struct sockaddr_storage addr; socklen_t len = sizeof addr; - int r = getpeername(remote->fd, (struct sockaddr*)&addr, &len); - if (r == 0) - { + int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len); + if (r == 0) { remote_send_ctx->connected = 1; - ev_io_stop(EV_A_ &remote_send_ctx->io); - ev_timer_stop(EV_A_ &remote_send_ctx->watcher); + ev_io_stop(EV_A_ & remote_send_ctx->io); + ev_timer_stop(EV_A_ & remote_send_ctx->watcher); // send destaddr char *ss_addr_to_send = malloc(BUF_SIZE); ssize_t addr_len = 0; - if(AF_INET6==server->destaddr.ss_family) // IPv6 - { - ss_addr_to_send[addr_len++] = 4; //Type 4 is IPv6 address + if (AF_INET6 == server->destaddr.ss_family) { // IPv6 + ss_addr_to_send[addr_len++] = 4; //Type 4 is IPv6 address size_t in_addr_len = sizeof(struct in6_addr); - memcpy(ss_addr_to_send + addr_len, &(((struct sockaddr_in6*)&(server->destaddr))->sin6_addr), in_addr_len); + memcpy(ss_addr_to_send + addr_len, + &(((struct sockaddr_in6 *)&(server->destaddr))->sin6_addr), + in_addr_len); addr_len += in_addr_len; - memcpy(ss_addr_to_send + addr_len, &(((struct sockaddr_in6*)&(server->destaddr))->sin6_port), 2); - } - else //IPv4 - { - ss_addr_to_send[addr_len++] = 1; //Type 1 is IPv4 address + memcpy(ss_addr_to_send + addr_len, + &(((struct sockaddr_in6 *)&(server->destaddr))->sin6_port), + 2); + } else { //IPv4 + ss_addr_to_send[addr_len++] = 1; //Type 1 is IPv4 address size_t in_addr_len = sizeof(struct in_addr); - memcpy(ss_addr_to_send + addr_len, &((struct sockaddr_in*)&(server->destaddr))->sin_addr, in_addr_len); + memcpy(ss_addr_to_send + addr_len, + &((struct sockaddr_in *)&(server->destaddr))->sin_addr, + in_addr_len); addr_len += in_addr_len; - memcpy(ss_addr_to_send + addr_len, &((struct sockaddr_in*)&(server->destaddr))->sin_port, 2); + memcpy(ss_addr_to_send + addr_len, + &((struct sockaddr_in *)&(server->destaddr))->sin_port, + 2); } addr_len += 2; - ss_addr_to_send = ss_encrypt(BUF_SIZE, ss_addr_to_send, &addr_len, server->e_ctx); - if (ss_addr_to_send == NULL) - { + ss_addr_to_send = ss_encrypt(BUF_SIZE, ss_addr_to_send, &addr_len, + server->e_ctx); + if (ss_addr_to_send == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -450,71 +404,54 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) int s = send(remote->fd, ss_addr_to_send, addr_len, 0); free(ss_addr_to_send); - if (s < addr_len) - { + if (s < addr_len) { LOGE("failed to send remote addr."); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } - ev_io_start(EV_A_ &server->recv_ctx->io); - ev_io_start(EV_A_ &remote->recv_ctx->io); + ev_io_start(EV_A_ & server->recv_ctx->io); + ev_io_start(EV_A_ & remote->recv_ctx->io); return; - } - else - { + } else { ERROR("getpeername"); // not connected close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else - { - if (remote->buf_len == 0) - { + } else { + if (remote->buf_len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(remote->fd, remote->buf + remote->buf_idx, remote->buf_len, 0); - if (s < 0) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("send"); // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < remote->buf_len) - { + } else if (s < remote->buf_len) { // partly sent, move memory, wait for the next time to send remote->buf_len -= s; remote->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading remote->buf_len = 0; remote->buf_idx = 0; - ev_io_stop(EV_A_ &remote_send_ctx->io); - if (server != NULL) - { - ev_io_start(EV_A_ &server->recv_ctx->io); - } - else - { + ev_io_stop(EV_A_ & remote_send_ctx->io); + if (server != NULL) { + ev_io_start(EV_A_ & server->recv_ctx->io); + } else { close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; @@ -525,7 +462,7 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) } } -static struct remote* new_remote(int fd, int timeout) +static struct remote * new_remote(int fd, int timeout) { struct remote *remote; remote = malloc(sizeof(struct remote)); @@ -547,14 +484,11 @@ static struct remote* new_remote(int fd, int timeout) static void free_remote(struct remote *remote) { - if (remote != NULL) - { - if (remote->server != NULL) - { + if (remote != NULL) { + if (remote->server != NULL) { remote->server->remote = NULL; } - if (remote->buf != NULL) - { + if (remote->buf != NULL) { free(remote->buf); } free(remote->recv_ctx); @@ -565,17 +499,16 @@ static void free_remote(struct remote *remote) static void close_and_free_remote(EV_P_ struct remote *remote) { - if (remote != NULL) - { - ev_timer_stop(EV_A_ &remote->send_ctx->watcher); - ev_io_stop(EV_A_ &remote->send_ctx->io); - ev_io_stop(EV_A_ &remote->recv_ctx->io); + if (remote != NULL) { + ev_timer_stop(EV_A_ & remote->send_ctx->watcher); + ev_io_stop(EV_A_ & remote->send_ctx->io); + ev_io_stop(EV_A_ & remote->recv_ctx->io); close(remote->fd); free_remote(remote); } } -static struct server* new_server(int fd, int method) +static struct server * new_server(int fd, int method) { struct server *server; server = malloc(sizeof(struct server)); @@ -589,15 +522,12 @@ static struct server* new_server(int fd, int method) server->recv_ctx->connected = 0; server->send_ctx->server = server; server->send_ctx->connected = 0; - if (method) - { + if (method) { server->e_ctx = malloc(sizeof(struct enc_ctx)); server->d_ctx = malloc(sizeof(struct enc_ctx)); enc_ctx_init(method, server->e_ctx, 1); enc_ctx_init(method, server->d_ctx, 0); - } - else - { + } else { server->e_ctx = NULL; server->d_ctx = NULL; } @@ -608,24 +538,19 @@ static struct server* new_server(int fd, int method) static void free_server(struct server *server) { - if (server != NULL) - { - if (server->remote != NULL) - { + if (server != NULL) { + if (server->remote != NULL) { server->remote->server = NULL; } - if (server->e_ctx != NULL) - { + if (server->e_ctx != NULL) { cipher_context_release(&server->e_ctx->evp); free(server->e_ctx); } - if (server->d_ctx != NULL) - { + if (server->d_ctx != NULL) { cipher_context_release(&server->d_ctx->evp); free(server->d_ctx); } - if (server->buf != NULL) - { + if (server->buf != NULL) { free(server->buf); } free(server->recv_ctx); @@ -636,31 +561,28 @@ static void free_server(struct server *server) static void close_and_free_server(EV_P_ struct server *server) { - if (server != NULL) - { - ev_io_stop(EV_A_ &server->send_ctx->io); - ev_io_stop(EV_A_ &server->recv_ctx->io); + if (server != NULL) { + ev_io_stop(EV_A_ & server->send_ctx->io); + ev_io_stop(EV_A_ & server->recv_ctx->io); close(server->fd); free_server(server); } } -static void accept_cb (EV_P_ ev_io *w, int revents) +static void accept_cb(EV_P_ ev_io *w, int revents) { struct listen_ctx *listener = (struct listen_ctx *)w; struct sockaddr_storage destaddr; int err; int clientfd = accept(listener->fd, NULL, NULL); - if (clientfd == -1) - { + if (clientfd == -1) { ERROR("accept"); return; } err = getdestaddr(clientfd, &destaddr); - if (err) - { + if (err) { ERROR("getdestaddr"); return; } @@ -678,16 +600,16 @@ static void accept_cb (EV_P_ ev_io *w, int revents) hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; int index = rand() % listener->remote_num; - err = getaddrinfo(listener->remote_addr[index].host, listener->remote_addr[index].port, &hints, &res); - if (err) - { + err = + getaddrinfo(listener->remote_addr[index].host, + listener->remote_addr[index].port, &hints, &res); + if (err) { ERROR("getaddrinfo"); return; } sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if (sockfd < 0) - { + if (sockfd < 0) { ERROR("socket"); freeaddrinfo(res); return; @@ -710,11 +632,11 @@ static void accept_cb (EV_P_ ev_io *w, int revents) connect(sockfd, res->ai_addr, res->ai_addrlen); freeaddrinfo(res); // listen to remote connected event - ev_io_start(EV_A_ &remote->send_ctx->io); - ev_timer_start(EV_A_ &remote->send_ctx->watcher); + ev_io_start(EV_A_ & remote->send_ctx->io); + ev_timer_start(EV_A_ & remote->send_ctx->watcher); } -int main (int argc, char **argv) +int main(int argc, char **argv) { int i, c; @@ -734,10 +656,8 @@ int main (int argc, char **argv) opterr = 0; - while ((c = getopt (argc, argv, "f:s:p:l:k:t:m:c:b:a:")) != -1) - { - switch (c) - { + while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:c:b:a:")) != -1) { + switch (c) { case 's': remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; @@ -773,44 +693,54 @@ int main (int argc, char **argv) } } - if (opterr) - { + if (opterr) { usage(); exit(EXIT_FAILURE); } - if (conf_path != NULL) - { + if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); - if (remote_num == 0) - { + if (remote_num == 0) { remote_num = conf->remote_num; - for (i = 0; i < remote_num; i++) - { + for (i = 0; i < remote_num; i++) { remote_addr[i] = conf->remote_addr[i]; } } - if (remote_port == NULL) remote_port = conf->remote_port; - if (local_addr == NULL) local_addr = conf->local_addr; - if (local_port == NULL) local_port = conf->local_port; - if (password == NULL) password = conf->password; - if (method == NULL) method = conf->method; - if (timeout == NULL) timeout = conf->timeout; + if (remote_port == NULL) { + remote_port = conf->remote_port; + } + if (local_addr == NULL) { + local_addr = conf->local_addr; + } + if (local_port == NULL) { + local_port = conf->local_port; + } + if (password == NULL) { + password = conf->password; + } + if (method == NULL) { + method = conf->method; + } + if (timeout == NULL) { + timeout = conf->timeout; + } } if (remote_num == 0 || remote_port == NULL || - local_port == NULL || password == NULL) - { + local_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } - if (timeout == NULL) timeout = "10"; + if (timeout == NULL) { + timeout = "10"; + } - if (local_addr == NULL) local_addr = "0.0.0.0"; + if (local_addr == NULL) { + local_addr = "0.0.0.0"; + } - if (pid_flags) - { + if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } @@ -826,12 +756,10 @@ int main (int argc, char **argv) // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); - if (listenfd < 0) - { + if (listenfd < 0) { FATAL("bind() error.."); } - if (listen(listenfd, SOMAXCONN) == -1) - { + if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error."); } setnonblocking(listenfd); @@ -841,10 +769,11 @@ int main (int argc, char **argv) struct listen_ctx listen_ctx; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = malloc(sizeof(ss_addr_t) * remote_num); - while (remote_num > 0) - { + while (remote_num > 0) { int index = --remote_num; - if (remote_addr[index].port == NULL) remote_addr[index].port = remote_port; + if (remote_addr[index].port == NULL) { + remote_addr[index].port = remote_port; + } listen_ctx.remote_addr[index] = remote_addr[index]; } listen_ctx.timeout = atoi(timeout); @@ -852,18 +781,18 @@ int main (int argc, char **argv) listen_ctx.method = m; struct ev_loop *loop = ev_default_loop(0); - if (!loop) - { + if (!loop) { FATAL("ev_loop error."); } - ev_io_init (&listen_ctx.io, accept_cb, listenfd, EV_READ); - ev_io_start (loop, &listen_ctx.io); + ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); + ev_io_start(loop, &listen_ctx.io); // setuid - if (user != NULL) + if (user != NULL) { run_as(user); + } - ev_run (loop, 0); + ev_run(loop, 0); return 0; } diff --git a/src/redir.h b/src/redir.h index e2c9673a..95a94127 100644 --- a/src/redir.h +++ b/src/redir.h @@ -27,8 +27,7 @@ #include "encrypt.h" #include "jconf.h" -struct listen_ctx -{ +struct listen_ctx { ev_io io; ss_addr_t *remote_addr; int remote_num; @@ -38,15 +37,13 @@ struct listen_ctx struct sockaddr sock; }; -struct server_ctx -{ +struct server_ctx { ev_io io; int connected; struct server *server; }; -struct server -{ +struct server { int fd; ssize_t buf_len; ssize_t buf_idx; @@ -59,16 +56,14 @@ struct server struct remote *remote; }; -struct remote_ctx -{ +struct remote_ctx { ev_io io; ev_timer watcher; int connected; struct remote *remote; }; -struct remote -{ +struct remote { int fd; ssize_t buf_len; ssize_t buf_idx; diff --git a/src/server.c b/src/server.c index f626f646..4d042875 100644 --- a/src/server.c +++ b/src/server.c @@ -62,17 +62,18 @@ #define BUF_SIZE 2048 #endif -static void accept_cb (EV_P_ ev_io *w, int revents); -static void server_recv_cb (EV_P_ ev_io *w, int revents); -static void server_send_cb (EV_P_ ev_io *w, int revents); -static void remote_recv_cb (EV_P_ ev_io *w, int revents); -static void remote_send_cb (EV_P_ ev_io *w, int revents); +static void accept_cb(EV_P_ ev_io *w, int revents); +static void server_recv_cb(EV_P_ ev_io *w, int revents); +static void server_send_cb(EV_P_ ev_io *w, int revents); +static void remote_recv_cb(EV_P_ ev_io *w, int revents); +static void remote_send_cb(EV_P_ ev_io *w, int revents); static void server_resolve_cb(EV_P_ ev_io *w, int revents); static void server_timeout_cb(EV_P_ ev_timer *watcher, int revents); -static struct remote* new_remote(int fd); -static struct server* new_server(int fd, struct listen_ctx *listener); -static struct remote *connect_to_remote(struct addrinfo *res, struct server *server); +static struct remote * new_remote(int fd); +static struct server * new_server(int fd, struct listen_ctx *listener); +static struct remote *connect_to_remote(struct addrinfo *res, + struct server *server); static void free_remote(struct remote *remote); static void close_and_free_remote(EV_P_ struct remote *remote); @@ -94,18 +95,20 @@ static int server_conn = 0; int setnonblocking(int fd) { int flags; - if (-1 ==(flags = fcntl(fd, F_GETFL, 0))) + if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { flags = 0; + } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } #ifdef SET_INTERFACE -int setinterface(int socket_fd, const char* interface_name) +int setinterface(int socket_fd, const char * interface_name) { struct ifreq interface; memset(&interface, 0, sizeof(interface)); strncpy(interface.ifr_name, interface_name, IFNAMSIZ); - int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, sizeof(struct ifreq)); + int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, + sizeof(struct ifreq)); return res; } #endif @@ -117,21 +120,20 @@ int create_and_bind(const char *host, const char *port) int s, listen_sock; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ + hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */ s = getaddrinfo(host, port, &hints, &result); - if (s != 0) - { + if (s != 0) { LOGE("getaddrinfo: %s", gai_strerror(s)); return -1; } - for (rp = result; rp != NULL; rp = rp->ai_next) - { + for (rp = result; rp != NULL; rp = rp->ai_next) { listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - if (listen_sock == -1) + if (listen_sock == -1) { continue; + } int opt = 1; setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); @@ -140,18 +142,14 @@ int create_and_bind(const char *host, const char *port) setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif #ifdef TCP_FASTOPEN - if (fast_open) - { + if (fast_open) { opt = 5; - int r = setsockopt(listen_sock, IPPROTO_TCP, TCP_FASTOPEN, &opt, sizeof(opt)); - if (r == -1) - { - if (errno == EPROTONOSUPPORT || errno == ENOPROTOOPT) - { + int r = setsockopt(listen_sock, IPPROTO_TCP, TCP_FASTOPEN, &opt, + sizeof(opt)); + if (r == -1) { + if (errno == EPROTONOSUPPORT || errno == ENOPROTOOPT) { LOGE("fast open is not supported on this platform"); - } - else - { + } else { ERROR("setsockopt"); } } @@ -159,21 +157,17 @@ int create_and_bind(const char *host, const char *port) #endif s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen); - if (s == 0) - { + if (s == 0) { /* We managed to bind successfully! */ break; - } - else - { + } else { ERROR("bind"); } close(listen_sock); } - if (rp == NULL) - { + if (rp == NULL) { LOGE("Could not bind"); return -1; } @@ -183,7 +177,8 @@ int create_and_bind(const char *host, const char *port) return listen_sock; } -static struct remote *connect_to_remote(struct addrinfo *res, struct server *server) +static struct remote *connect_to_remote(struct addrinfo *res, + struct server *server) { int sockfd; int opt = 1; @@ -193,8 +188,7 @@ static struct remote *connect_to_remote(struct addrinfo *res, struct server *ser // initilize remote socks sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if (sockfd < 0) - { + if (sockfd < 0) { ERROR("socket"); close(sockfd); return NULL; @@ -210,49 +204,42 @@ static struct remote *connect_to_remote(struct addrinfo *res, struct server *ser // setup remote socks setnonblocking(sockfd); #ifdef SET_INTERFACE - if (iface) setinterface(sockfd, iface); + if (iface) { + setinterface(sockfd, iface); + } #endif #ifdef TCP_FASTOPEN - if (fast_open) - { - ssize_t s = sendto(sockfd, server->buf + server->buf_idx, server->buf_len, MSG_FASTOPEN, res->ai_addr, res->ai_addrlen); - if (s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (fast_open) { + ssize_t s = sendto(sockfd, server->buf + server->buf_idx, + server->buf_len, MSG_FASTOPEN, res->ai_addr, + res->ai_addrlen); + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // The remote server doesn't support tfo or it's the first connection to the server. // It will automatically fall back to conventional TCP. - } - else if (errno == EOPNOTSUPP || errno == EPROTONOSUPPORT || errno == ENOPROTOOPT) - { + } else if (errno == EOPNOTSUPP || errno == EPROTONOSUPPORT || + errno == ENOPROTOOPT) { LOGE("fast open is not supported on this platform"); connect(sockfd, res->ai_addr, res->ai_addrlen); - } - else - { + } else { ERROR("sendto"); } - } - else if (s < server->buf_len) - { + } else if (s < server->buf_len) { server->buf_idx += s; server->buf_len -= s; - } - else - { + } else { server->buf_idx = 0; server->buf_len = 0; } - } - else + } else #endif - connect(sockfd, res->ai_addr, res->ai_addrlen); + connect(sockfd, res->ai_addr, res->ai_addrlen); return remote; } -static void server_recv_cb (EV_P_ ev_io *w, int revents) +static void server_recv_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_recv_ctx = (struct server_ctx *)w; struct server *server = server_recv_ctx->server; @@ -261,10 +248,9 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) int len = server->buf_len; char **buf = &server->buf; - ev_timer_again(EV_A_ &server->recv_ctx->watcher); + ev_timer_again(EV_A_ & server->recv_ctx->watcher); - if (server->stage != 0) - { + if (server->stage != 0) { remote = server->remote; buf = &remote->buf; len = 0; @@ -272,27 +258,20 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) ssize_t r = recv(server->fd, *buf + len, BUF_SIZE - len, 0); - if (r == 0) - { + if (r == 0) { // connection closed - if (verbose) - { + if (verbose) { LOGD("server_recv close the connection"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else if (r == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("server recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -301,29 +280,23 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) } // handle incomplete header - if (server->stage == 0) - { + if (server->stage == 0) { r += server->buf_len; - if (r <= enc_get_iv_len()) - { + if (r <= enc_get_iv_len()) { // wait for more - if (verbose) - { + if (verbose) { LOGD("imcomplete header: %zu", r); } server->buf_len = r; return; - } - else - { + } else { server->buf_len = 0; } } *buf = ss_decrypt(BUF_SIZE, *buf, &r, server->d_ctx); - if (*buf == NULL) - { + if (*buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -331,38 +304,29 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) } // handshake and transmit data - if (server->stage == 5) - { + if (server->stage == 5) { int s = send(remote->fd, remote->buf, r, 0); - if (s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send remote->buf_len = r; remote->buf_idx = 0; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); - } - else - { + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); + } else { ERROR("server_recv_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } - } - else if (s < r) - { + } else if (s < r) { remote->buf_len = r - s; remote->buf_idx = s; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); } return; - } - else if (server->stage == 0) - { + } else if (server->stage == 0) { /* * Shadowsocks Protocol: @@ -376,45 +340,36 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) int offset = 0; char atyp = server->buf[offset++]; - char host[256] = {0}; - char port[64] = {0}; + char host[256] = { 0 }; + char port[64] = { 0 }; // get remote addr and port - if (atyp == 1) - { + if (atyp == 1) { // IP V4 size_t in_addr_len = sizeof(struct in_addr); - if (r > in_addr_len) - { + if (r > in_addr_len) { inet_ntop(AF_INET, (const void *)(server->buf + offset), host, INET_ADDRSTRLEN); offset += in_addr_len; } - } - else if (atyp == 3) - { + } else if (atyp == 3) { // Domain name uint8_t name_len = *(uint8_t *)(server->buf + offset); - if (name_len < r && name_len < 255 && name_len > 0) - { + if (name_len < r && name_len < 255 && name_len > 0) { memcpy(host, server->buf + offset + 1, name_len); offset += name_len + 1; } - } - else if (atyp == 4) - { + } else if (atyp == 4) { // IP V6 size_t in6_addr_len = sizeof(struct in6_addr); - if (r > in6_addr_len) - { - inet_ntop(AF_INET6, (const void*)(server->buf + offset), + if (r > in6_addr_len) { + inet_ntop(AF_INET6, (const void *)(server->buf + offset), host, INET6_ADDRSTRLEN); offset += in6_addr_len; } } - if (offset == 1) - { + if (offset == 1) { LOGE("invalid header with addr type %d", atyp); close_and_free_server(EV_A_ server); return; @@ -425,8 +380,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) offset += 2; - if (verbose) - { + if (verbose) { LOGD("connect to: %s:%s", host, port); } @@ -439,8 +393,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) query = asyncns_getaddrinfo(server->listen_ctx->asyncns, host, port, &hints); - if (query == NULL) - { + if (query == NULL) { ERROR("asyncns_getaddrinfo"); close_and_free_server(EV_A_ server); return; @@ -449,8 +402,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) asyncns_setuserdata(server->listen_ctx->asyncns, query, server); // XXX: should handle buffer carefully - if (r > offset) - { + if (r > offset) { server->buf_len = r - offset; server->buf_idx = offset; } @@ -458,7 +410,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) server->stage = 4; server->query = query; - ev_io_stop(EV_A_ &server_recv_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); return; } @@ -466,65 +418,51 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) FATAL("server context error."); } -static void server_send_cb (EV_P_ ev_io *w, int revents) +static void server_send_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_send_ctx = (struct server_ctx *)w; struct server *server = server_send_ctx->server; struct remote *remote = server->remote; - if (remote == NULL) - { + if (remote == NULL) { LOGE("invalid server."); close_and_free_server(EV_A_ server); return; } - if (server->buf_len == 0) - { + if (server->buf_len == 0) { // close and free - if (verbose) - { + if (verbose) { LOGD("server_send close the connection"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(server->fd, server->buf + server->buf_idx, server->buf_len, 0); - if (s < 0) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("server_send_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < server->buf_len) - { + } else if (s < server->buf_len) { // partly sent, move memory, wait for the next time to send server->buf_len -= s; server->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading server->buf_len = 0; server->buf_idx = 0; - ev_io_stop(EV_A_ &server_send_ctx->io); - if (remote != NULL) - { - ev_io_start(EV_A_ &remote->recv_ctx->io); + ev_io_stop(EV_A_ & server_send_ctx->io); + if (remote != NULL) { + ev_io_start(EV_A_ & remote->recv_ctx->io); return; - } - else - { + } else { LOGE("invalid remote."); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -536,8 +474,8 @@ static void server_send_cb (EV_P_ ev_io *w, int revents) static void server_timeout_cb(EV_P_ ev_timer *watcher, int revents) { - struct server_ctx *server_ctx = (struct server_ctx *) (((void*)watcher) - - sizeof(ev_io)); + struct server_ctx *server_ctx = (struct server_ctx *)(((void *)watcher) + - sizeof(ev_io)); struct server *server = server_ctx->server; struct remote *remote = server->remote; @@ -555,69 +493,59 @@ static void server_resolve_cb(EV_P_ ev_io *w, int revents) asyncns_t *asyncns = listen_ctx->asyncns; err = asyncns_handle(asyncns); - if (err == ASYNCNS_HANDLE_AGAIN) - { + if (err == ASYNCNS_HANDLE_AGAIN) { // try again return; - } - else if (err == ASYNCNS_HANDLE_ERROR) - { + } else if (err == ASYNCNS_HANDLE_ERROR) { // asyncns error FATAL("asyncns exit unexpectedly."); } asyncns_query_t *query = asyncns_getnext(asyncns); - struct server *server= (struct server*) asyncns_getuserdata(asyncns, query); + struct server *server = + (struct server *)asyncns_getuserdata(asyncns, query); - if (!asyncns_isdone(asyncns, query)) - { + if (!asyncns_isdone(asyncns, query)) { // wait for reolver return; } server->query = NULL; - if (verbose) - { + if (verbose) { LOGD("asyncns resolved."); } err = asyncns_getaddrinfo_done(asyncns, query, &result); - if (err) - { + if (err) { ERROR("getaddrinfo"); close_and_free_server(EV_A_ server); - } - else - { + } else { // Use IPV4 address if possible - for (rp = result; rp != NULL; rp = rp->ai_next) - { - if (rp->ai_family == AF_INET) break; + for (rp = result; rp != NULL; rp = rp->ai_next) { + if (rp->ai_family == AF_INET) { + break; + } } - if (rp == NULL) - { + if (rp == NULL) { rp = result; } struct remote *remote = connect_to_remote(rp, server); - if (remote == NULL) - { + if (remote == NULL) { LOGE("connect error."); close_and_free_server(EV_A_ server); - } - else - { + } else { server->remote = remote; remote->server = server; // XXX: should handel buffer carefully - if (server->buf_len > 0) - { - memcpy(remote->buf, server->buf + server->buf_idx, server->buf_len); + if (server->buf_len > 0) { + memcpy(remote->buf, server->buf + server->buf_idx, + server->buf_len); remote->buf_len = server->buf_len; remote->buf_idx = 0; server->buf_len = 0; @@ -625,7 +553,7 @@ static void server_resolve_cb(EV_P_ ev_io *w, int revents) } // listen to remote connected event - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); } } @@ -633,44 +561,36 @@ static void server_resolve_cb(EV_P_ ev_io *w, int revents) asyncns_freeaddrinfo(result); } -static void remote_recv_cb (EV_P_ ev_io *w, int revents) +static void remote_recv_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_recv_ctx = (struct remote_ctx *)w; struct remote *remote = remote_recv_ctx->remote; struct server *server = remote->server; - if (server == NULL) - { + if (server == NULL) { LOGE("invalid server."); close_and_free_remote(EV_A_ remote); return; } - ev_timer_again(EV_A_ &server->recv_ctx->watcher); + ev_timer_again(EV_A_ & server->recv_ctx->watcher); ssize_t r = recv(remote->fd, server->buf, BUF_SIZE, 0); - if (r == 0) - { + if (r == 0) { // connection closed - if (verbose) - { + if (verbose) { LOGD("remote_recv close the connection"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else if (r < 0) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("remote recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -680,8 +600,7 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) server->buf = ss_encrypt(BUF_SIZE, server->buf, &r, server->e_ctx); - if (server->buf == NULL) - { + if (server->buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -690,73 +609,60 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) int s = send(server->fd, server->buf, r, 0); - if (s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send server->buf_len = r; server->buf_idx = 0; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); - } - else - { + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); + } else { ERROR("remote_recv_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < r) - { + } else if (s < r) { server->buf_len = r - s; server->buf_idx = s; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); return; } } -static void remote_send_cb (EV_P_ ev_io *w, int revents) +static void remote_send_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_send_ctx = (struct remote_ctx *)w; struct remote *remote = remote_send_ctx->remote; struct server *server = remote->server; - if (server == NULL) - { + if (server == NULL) { LOGE("invalid server."); close_and_free_remote(EV_A_ remote); return; } - if (!remote_send_ctx->connected) - { + if (!remote_send_ctx->connected) { struct sockaddr_storage addr; socklen_t len = sizeof addr; - int r = getpeername(remote->fd, (struct sockaddr*)&addr, &len); - if (r == 0) - { - if (verbose) - { + int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len); + if (r == 0) { + if (verbose) { LOGD("remote connected."); } remote_send_ctx->connected = 1; - if (remote->buf_len == 0) - { + if (remote->buf_len == 0) { server->stage = 5; - ev_io_stop(EV_A_ &remote_send_ctx->io); - ev_io_start(EV_A_ &server->recv_ctx->io); - ev_io_start(EV_A_ &remote->recv_ctx->io); + ev_io_stop(EV_A_ & remote_send_ctx->io); + ev_io_start(EV_A_ & server->recv_ctx->io); + ev_io_start(EV_A_ & remote->recv_ctx->io); return; } - } - else - { + } else { ERROR("getpeername"); // not connected close_and_free_remote(EV_A_ remote); @@ -765,57 +671,43 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) } } - if (remote->buf_len == 0) - { + if (remote->buf_len == 0) { // close and free - if (verbose) - { + if (verbose) { LOGD("remote_send close the connection"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(remote->fd, remote->buf + remote->buf_idx, remote->buf_len, 0); - if (s == -1) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s == -1) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("remote_send_send"); // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < remote->buf_len) - { + } else if (s < remote->buf_len) { // partly sent, move memory, wait for the next time to send remote->buf_len -= s; remote->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading remote->buf_len = 0; remote->buf_idx = 0; - ev_io_stop(EV_A_ &remote_send_ctx->io); - if (server != NULL) - { - ev_io_start(EV_A_ &server->recv_ctx->io); - if (server->stage == 4) - { + ev_io_stop(EV_A_ & remote_send_ctx->io); + if (server != NULL) { + ev_io_start(EV_A_ & server->recv_ctx->io); + if (server->stage == 4) { server->stage = 5; - ev_io_start(EV_A_ &remote->recv_ctx->io); + ev_io_start(EV_A_ & remote->recv_ctx->io); } - } - else - { + } else { LOGE("invalid server."); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -825,9 +717,11 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) } } -static struct remote* new_remote(int fd) +static struct remote * new_remote(int fd) { - if (verbose) remote_conn++; + if (verbose) { + remote_conn++; + } struct remote *remote; remote = malloc(sizeof(struct remote)); @@ -849,14 +743,11 @@ static struct remote* new_remote(int fd) static void free_remote(struct remote *remote) { - if (remote != NULL) - { - if (remote->server != NULL) - { + if (remote != NULL) { + if (remote->server != NULL) { remote->server->remote = NULL; } - if (remote->buf != NULL) - { + if (remote->buf != NULL) { free(remote->buf); } free(remote->recv_ctx); @@ -867,23 +758,23 @@ static void free_remote(struct remote *remote) static void close_and_free_remote(EV_P_ struct remote *remote) { - if (remote != NULL) - { - ev_io_stop(EV_A_ &remote->send_ctx->io); - ev_io_stop(EV_A_ &remote->recv_ctx->io); + if (remote != NULL) { + ev_io_stop(EV_A_ & remote->send_ctx->io); + ev_io_stop(EV_A_ & remote->recv_ctx->io); close(remote->fd); free_remote(remote); - if (verbose) - { + if (verbose) { remote_conn--; LOGD("current remote connection: %d", remote_conn); } } } -static struct server* new_server(int fd, struct listen_ctx *listener) +static struct server * new_server(int fd, struct listen_ctx *listener) { - if (verbose) server_conn++; + if (verbose) { + server_conn++; + } struct server *server; server = malloc(sizeof(struct server)); @@ -893,7 +784,8 @@ static struct server* new_server(int fd, struct listen_ctx *listener) server->fd = fd; ev_io_init(&server->recv_ctx->io, server_recv_cb, fd, EV_READ); ev_io_init(&server->send_ctx->io, server_send_cb, fd, EV_WRITE); - ev_timer_init(&server->recv_ctx->watcher, server_timeout_cb, listener->timeout, listener->timeout * 5); + ev_timer_init(&server->recv_ctx->watcher, server_timeout_cb, + listener->timeout, listener->timeout * 5); server->recv_ctx->server = server; server->recv_ctx->connected = 0; server->send_ctx->server = server; @@ -901,15 +793,12 @@ static struct server* new_server(int fd, struct listen_ctx *listener) server->stage = 0; server->query = NULL; server->listen_ctx = listener; - if (listener->method) - { + if (listener->method) { server->e_ctx = malloc(sizeof(struct enc_ctx)); server->d_ctx = malloc(sizeof(struct enc_ctx)); enc_ctx_init(listener->method, server->e_ctx, 1); enc_ctx_init(listener->method, server->d_ctx, 0); - } - else - { + } else { server->e_ctx = NULL; server->d_ctx = NULL; } @@ -921,24 +810,19 @@ static struct server* new_server(int fd, struct listen_ctx *listener) static void free_server(struct server *server) { - if (server != NULL) - { - if (server->remote != NULL) - { + if (server != NULL) { + if (server->remote != NULL) { server->remote->server = NULL; } - if (server->e_ctx != NULL) - { + if (server->e_ctx != NULL) { cipher_context_release(&server->e_ctx->evp); free(server->e_ctx); } - if (server->d_ctx != NULL) - { + if (server->d_ctx != NULL) { cipher_context_release(&server->d_ctx->evp); free(server->d_ctx); } - if (server->buf != NULL) - { + if (server->buf != NULL) { free(server->buf); } free(server->recv_ctx); @@ -949,32 +833,28 @@ static void free_server(struct server *server) static void close_and_free_server(EV_P_ struct server *server) { - if (server != NULL) - { - if (server->query != NULL) - { + if (server != NULL) { + if (server->query != NULL) { asyncns_cancel(server->listen_ctx->asyncns, server->query); server->query = NULL; } - ev_io_stop(EV_A_ &server->send_ctx->io); - ev_io_stop(EV_A_ &server->recv_ctx->io); - ev_timer_stop(EV_A_ &server->recv_ctx->watcher); + ev_io_stop(EV_A_ & server->send_ctx->io); + ev_io_stop(EV_A_ & server->recv_ctx->io); + ev_timer_stop(EV_A_ & server->recv_ctx->watcher); close(server->fd); free_server(server); - if (verbose) - { + if (verbose) { server_conn--; LOGD("current server connection: %d", server_conn); } } } -static void accept_cb (EV_P_ ev_io *w, int revents) +static void accept_cb(EV_P_ ev_io *w, int revents) { struct listen_ctx *listener = (struct listen_ctx *)w; int serverfd = accept(listener->fd, NULL, NULL); - if (serverfd == -1) - { + if (serverfd == -1) { ERROR("accept"); return; } @@ -986,17 +866,16 @@ static void accept_cb (EV_P_ ev_io *w, int revents) setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif - if (verbose) - { + if (verbose) { LOGD("accept a connection."); } struct server *server = new_server(serverfd, listener); - ev_io_start(EV_A_ &server->recv_ctx->io); - ev_timer_start(EV_A_ &server->recv_ctx->watcher); + ev_io_start(EV_A_ & server->recv_ctx->io); + ev_timer_start(EV_A_ & server->recv_ctx->watcher); } -int main (int argc, char **argv) +int main(int argc, char **argv) { int i, c; @@ -1018,20 +897,17 @@ int main (int argc, char **argv) int option_index = 0; static struct option long_options[] = { - {"fast-open", no_argument, 0, 0 }, - {0, 0, 0, 0 } + { "fast-open", no_argument, 0, 0 }, + { 0, 0, 0, 0 } }; opterr = 0; while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:i:d:a:uv", - long_options, &option_index)) != -1) - { - switch (c) - { + long_options, &option_index)) != -1) { + switch (c) { case 0: - if (option_index == 0) - { + if (option_index == 0) { #ifdef TCP_FASTOPEN fast_open = 1; LOGD("using tcp fast open"); @@ -1067,7 +943,9 @@ int main (int argc, char **argv) break; case 'd': dns_thread_num = atoi(optarg); - if (!dns_thread_num) FATAL("Invalid DNS thread number"); + if (!dns_thread_num) { + FATAL("Invalid DNS thread number"); + } break; case 'a': user = optarg; @@ -1081,40 +959,46 @@ int main (int argc, char **argv) } } - if (opterr) - { + if (opterr) { usage(); exit(EXIT_FAILURE); } - if (conf_path != NULL) - { + if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); - if (server_num == 0) - { + if (server_num == 0) { server_num = conf->remote_num; - for (i = 0; i < server_num; i++) - { + for (i = 0; i < server_num; i++) { server_host[i] = conf->remote_addr[i].host; } } - if (server_port == NULL) server_port = conf->remote_port; - if (password == NULL) password = conf->password; - if (method == NULL) method = conf->method; - if (timeout == NULL) timeout = conf->timeout; + if (server_port == NULL) { + server_port = conf->remote_port; + } + if (password == NULL) { + password = conf->password; + } + if (method == NULL) { + method = conf->method; + } + if (timeout == NULL) { + timeout = conf->timeout; + } #ifdef TCP_FASTOPEN - if (fast_open == 0) fast_open = conf->fast_open; + if (fast_open == 0) { + fast_open = conf->fast_open; + } #endif #ifdef HAVE_SETRLIMIT - if (nofile == 0) nofile = conf->nofile; + if (nofile == 0) { + nofile = conf->nofile; + } /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ - if (nofile) - { - if (verbose) - { + if (nofile) { + if (verbose) { LOGD("setting NOFILE to %d", nofile); } set_nofile(nofile); @@ -1122,16 +1006,16 @@ int main (int argc, char **argv) #endif } - if (server_num == 0 || server_port == NULL || password == NULL) - { + if (server_num == 0 || server_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } - if (timeout == NULL) timeout = "60"; + if (timeout == NULL) { + timeout = "60"; + } - if (pid_flags) - { + if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } @@ -1143,8 +1027,7 @@ int main (int argc, char **argv) // setup asyncns asyncns_t *asyncns; - if (!(asyncns = asyncns_new(dns_thread_num))) - { + if (!(asyncns = asyncns_new(dns_thread_num))) { FATAL("asyncns failed"); } @@ -1159,20 +1042,17 @@ int main (int argc, char **argv) struct listen_ctx listen_ctx_list[server_num + 1]; // bind to each interface - while (server_num > 0) - { + while (server_num > 0) { int index = --server_num; - const char* host = server_host[index]; + const char * host = server_host[index]; // Bind to port int listenfd; listenfd = create_and_bind(host, server_port); - if (listenfd < 0) - { + if (listenfd < 0) { FATAL("bind() error.."); } - if (listen(listenfd, SOMAXCONN) == -1) - { + if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error."); } setnonblocking(listenfd); @@ -1187,8 +1067,8 @@ int main (int argc, char **argv) listen_ctx->method = m; listen_ctx->iface = iface; - ev_io_init (&listen_ctx->io, accept_cb, listenfd, EV_READ); - ev_io_start (loop, &listen_ctx->io); + ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ); + ev_io_start(loop, &listen_ctx->io); } // initialize the DNS @@ -1199,22 +1079,23 @@ int main (int argc, char **argv) listen_ctx->fd = asyncnsfd; listen_ctx->method = m; listen_ctx->iface = iface; - ev_io_init (&listen_ctx->io, server_resolve_cb, asyncnsfd, EV_READ); - ev_io_start (loop, &listen_ctx->io); + ev_io_init(&listen_ctx->io, server_resolve_cb, asyncnsfd, EV_READ); + ev_io_start(loop, &listen_ctx->io); // Setup UDP - if (udprelay) - { + if (udprelay) { LOGD("udprelay enabled."); - init_udprelay(server_host[0], server_port, dns_thread_num, m, listen_ctx->timeout, iface); + init_udprelay(server_host[0], server_port, dns_thread_num, m, + listen_ctx->timeout, iface); } // setuid - if (user != NULL) + if (user != NULL) { run_as(user); + } // start ev loop - ev_run (loop, 0); + ev_run(loop, 0); return 0; } diff --git a/src/server.h b/src/server.h index bd4d2c37..86768b26 100644 --- a/src/server.h +++ b/src/server.h @@ -32,8 +32,7 @@ #include "common.h" -struct listen_ctx -{ +struct listen_ctx { ev_io io; int fd; int timeout; @@ -43,16 +42,14 @@ struct listen_ctx struct sockaddr sock; }; -struct server_ctx -{ +struct server_ctx { ev_io io; ev_timer watcher; int connected; struct server *server; }; -struct server -{ +struct server { int fd; int stage; ssize_t buf_len; @@ -67,15 +64,13 @@ struct server struct remote *remote; }; -struct remote_ctx -{ +struct remote_ctx { ev_io io; int connected; struct remote *remote; }; -struct remote -{ +struct remote { int fd; ssize_t buf_len; ssize_t buf_idx; diff --git a/src/shadowsocks.h b/src/shadowsocks.h index 29b098fb..856875e6 100644 --- a/src/shadowsocks.h +++ b/src/shadowsocks.h @@ -22,8 +22,7 @@ #ifndef _SHADOWSOCKS_H #define _SHADOWSOCKS_H -typedef struct -{ +typedef struct { /* Required */ char *remote_host; // hostname or ip of remote server char *local_addr; // local ip to bind @@ -43,7 +42,7 @@ typedef struct /* An example profile -const profile_t EXAMPLE_PROFILE = { + const profile_t EXAMPLE_PROFILE = { .remote_host = "example.com", .local_addr = "127.0.0.1", .method = "bf-cfb", @@ -56,25 +55,25 @@ const profile_t EXAMPLE_PROFILE = { .fast_open = 0, .udp_relay = 0, .verbose = 0 -}; -*/ + }; + */ #ifdef __cplusplus extern "C" { #endif - /* - * Create and start a shadowsocks local server. - * - * Calling this function will block the current thread forever if the server - * starts successfully. - * - * Make sure start the server in a seperate process to avoid any potential - * memory and socket leak. - * - * If failed, -1 is returned. Errors will output to the log file. - */ - int start_ss_local_server(profile_t profile); +/* + * Create and start a shadowsocks local server. + * + * Calling this function will block the current thread forever if the server + * starts successfully. + * + * Make sure start the server in a seperate process to avoid any potential + * memory and socket leak. + * + * If failed, -1 is returned. Errors will output to the log file. + */ +int start_ss_local_server(profile_t profile); #ifdef __cplusplus } diff --git a/src/socks5.h b/src/socks5.h index 72ec327f..490bb8b7 100644 --- a/src/socks5.h +++ b/src/socks5.h @@ -32,29 +32,25 @@ #pragma pack(1) -struct method_select_request -{ +struct method_select_request { char ver; char nmethods; char methods[255]; }; -struct method_select_response -{ +struct method_select_response { char ver; char method; }; -struct socks5_request -{ +struct socks5_request { char ver; char cmd; char rsv; char atyp; }; -struct socks5_response -{ +struct socks5_response { char ver; char rep; char rsv; diff --git a/src/tunnel.c b/src/tunnel.c index 26332de7..75a0f7a2 100644 --- a/src/tunnel.c +++ b/src/tunnel.c @@ -67,14 +67,14 @@ #define BUF_SIZE 2048 #endif -static void accept_cb (EV_P_ ev_io *w, int revents); -static void server_recv_cb (EV_P_ ev_io *w, int revents); -static void server_send_cb (EV_P_ ev_io *w, int revents); -static void remote_recv_cb (EV_P_ ev_io *w, int revents); -static void remote_send_cb (EV_P_ ev_io *w, int revents); +static void accept_cb(EV_P_ ev_io *w, int revents); +static void server_recv_cb(EV_P_ ev_io *w, int revents); +static void server_send_cb(EV_P_ ev_io *w, int revents); +static void remote_recv_cb(EV_P_ ev_io *w, int revents); +static void remote_send_cb(EV_P_ ev_io *w, int revents); -static struct remote* new_remote(int fd, int timeout); -static struct server* new_server(int fd, int method); +static struct remote * new_remote(int fd, int timeout); +static struct server * new_server(int fd, int method); static void free_remote(struct remote *remote); static void close_and_free_remote(EV_P_ struct remote *remote); @@ -88,19 +88,21 @@ int udprelay = 0; static int setnonblocking(int fd) { int flags; - if (-1 ==(flags = fcntl(fd, F_GETFL, 0))) + if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { flags = 0; + } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } #endif #ifdef SET_INTERFACE -int setinterface(int socket_fd, const char* interface_name) +int setinterface(int socket_fd, const char * interface_name) { struct ifreq interface; memset(&interface, 0, sizeof(interface)); strncpy(interface.ifr_name, interface_name, IFNAMSIZ); - int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, sizeof(struct ifreq)); + int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, + sizeof(struct ifreq)); return res; } #endif @@ -112,21 +114,20 @@ int create_and_bind(const char *addr, const char *port) int s, listen_sock; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ + hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */ s = getaddrinfo(addr, port, &hints, &result); - if (s != 0) - { + if (s != 0) { LOGD("getaddrinfo: %s", gai_strerror(s)); return -1; } - for (rp = result; rp != NULL; rp = rp->ai_next) - { + for (rp = result; rp != NULL; rp = rp->ai_next) { listen_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - if (listen_sock == -1) + if (listen_sock == -1) { continue; + } int opt = 1; setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); @@ -136,21 +137,17 @@ int create_and_bind(const char *addr, const char *port) #endif s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen); - if (s == 0) - { + if (s == 0) { /* We managed to bind successfully! */ break; - } - else - { + } else { ERROR("bind"); } close(listen_sock); } - if (rp == NULL) - { + if (rp == NULL) { LOGE("Could not bind"); return -1; } @@ -160,42 +157,34 @@ int create_and_bind(const char *addr, const char *port) return listen_sock; } -static void server_recv_cb (EV_P_ ev_io *w, int revents) +static void server_recv_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_recv_ctx = (struct server_ctx *)w; struct server *server = server_recv_ctx->server; struct remote *remote = server->remote; - if (remote == NULL) - { + if (remote == NULL) { close_and_free_server(EV_A_ server); return; } ssize_t r = recv(server->fd, remote->buf, BUF_SIZE, 0); - if (r == 0) - { + if (r == 0) { // connection closed remote->buf_len = 0; remote->buf_idx = 0; close_and_free_server(EV_A_ server); - if (remote != NULL) - { - ev_io_start(EV_A_ &remote->send_ctx->io); + if (remote != NULL) { + ev_io_start(EV_A_ & remote->send_ctx->io); } return; - } - else if(r < 0) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("server recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -205,8 +194,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) remote->buf = ss_encrypt(BUF_SIZE, remote->buf, &r, server->e_ctx); - if (remote->buf == NULL) - { + if (remote->buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -215,81 +203,63 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) int s = send(remote->fd, remote->buf, r, 0); - if(s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send remote->buf_len = r; remote->buf_idx = 0; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); return; - } - else - { + } else { ERROR("send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else if(s < r) - { + } else if (s < r) { remote->buf_len = r - s; remote->buf_idx = s; - ev_io_stop(EV_A_ &server_recv_ctx->io); - ev_io_start(EV_A_ &remote->send_ctx->io); + ev_io_stop(EV_A_ & server_recv_ctx->io); + ev_io_start(EV_A_ & remote->send_ctx->io); return; } } -static void server_send_cb (EV_P_ ev_io *w, int revents) +static void server_send_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_send_ctx = (struct server_ctx *)w; struct server *server = server_send_ctx->server; struct remote *remote = server->remote; - if (server->buf_len == 0) - { + if (server->buf_len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(server->fd, server->buf + server->buf_idx, server->buf_len, 0); - if (s < 0) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < server->buf_len) - { + } else if (s < server->buf_len) { // partly sent, move memory, wait for the next time to send server->buf_len -= s; server->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading server->buf_len = 0; server->buf_idx = 0; - ev_io_stop(EV_A_ &server_send_ctx->io); - if (remote != NULL) - { - ev_io_start(EV_A_ &remote->recv_ctx->io); - } - else - { + ev_io_stop(EV_A_ & server_send_ctx->io); + if (remote != NULL) { + ev_io_start(EV_A_ & remote->recv_ctx->io); + } else { close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; @@ -301,8 +271,8 @@ static void server_send_cb (EV_P_ ev_io *w, int revents) static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) { - struct remote_ctx *remote_ctx = (struct remote_ctx *) (((void*)watcher) - - sizeof(ev_io)); + struct remote_ctx *remote_ctx = (struct remote_ctx *)(((void *)watcher) + - sizeof(ev_io)); struct remote *remote = remote_ctx->remote; struct server *server = remote->server; @@ -310,8 +280,7 @@ static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) ev_timer_stop(EV_A_ watcher); - if (server == NULL) - { + if (server == NULL) { close_and_free_remote(EV_A_ remote); return; } @@ -319,41 +288,33 @@ static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) close_and_free_server(EV_A_ server); } -static void remote_recv_cb (EV_P_ ev_io *w, int revents) +static void remote_recv_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_recv_ctx = (struct remote_ctx *)w; struct remote *remote = remote_recv_ctx->remote; struct server *server = remote->server; - if (server == NULL) - { + if (server == NULL) { close_and_free_remote(EV_A_ remote); return; } ssize_t r = recv(remote->fd, server->buf, BUF_SIZE, 0); - if (r == 0) - { + if (r == 0) { // connection closed server->buf_len = 0; server->buf_idx = 0; close_and_free_remote(EV_A_ remote); - if (server != NULL) - { - ev_io_start(EV_A_ &server->send_ctx->io); + if (server != NULL) { + ev_io_start(EV_A_ & server->send_ctx->io); } return; - } - else if(r < 0) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + } else if (r < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; - } - else - { + } else { ERROR("remote recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -363,8 +324,7 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) server->buf = ss_decrypt(BUF_SIZE, server->buf, &r, server->d_ctx); - if (server->buf == NULL) - { + if (server->buf == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -373,52 +333,44 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) int s = send(server->fd, server->buf, r, 0); - if (s == -1) - { - if (errno == EAGAIN || errno == EWOULDBLOCK) - { + if (s == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send server->buf_len = r; server->buf_idx = 0; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); return; - } - else - { + } else { ERROR("send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else if (s < r) - { + } else if (s < r) { server->buf_len = r - s; server->buf_idx = s; - ev_io_stop(EV_A_ &remote_recv_ctx->io); - ev_io_start(EV_A_ &server->send_ctx->io); + ev_io_stop(EV_A_ & remote_recv_ctx->io); + ev_io_start(EV_A_ & server->send_ctx->io); return; } } -static void remote_send_cb (EV_P_ ev_io *w, int revents) +static void remote_send_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_send_ctx = (struct remote_ctx *)w; struct remote *remote = remote_send_ctx->remote; struct server *server = remote->server; - if (!remote_send_ctx->connected) - { + if (!remote_send_ctx->connected) { struct sockaddr_storage addr; socklen_t len = sizeof addr; - int r = getpeername(remote->fd, (struct sockaddr*)&addr, &len); - if (r == 0) - { + int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len); + if (r == 0) { remote_send_ctx->connected = 1; - ev_io_stop(EV_A_ &remote_send_ctx->io); - ev_timer_stop(EV_A_ &remote_send_ctx->watcher); + ev_io_stop(EV_A_ & remote_send_ctx->io); + ev_timer_stop(EV_A_ & remote_send_ctx->watcher); // send destaddr char *ss_addr_to_send = malloc(BUF_SIZE); @@ -435,9 +387,9 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) memcpy(ss_addr_to_send + addr_len, &port, 2); addr_len += 2; - ss_addr_to_send = ss_encrypt(BUF_SIZE, ss_addr_to_send, &addr_len, server->e_ctx); - if (ss_addr_to_send == NULL) - { + ss_addr_to_send = ss_encrypt(BUF_SIZE, ss_addr_to_send, &addr_len, + server->e_ctx); + if (ss_addr_to_send == NULL) { LOGE("invalid password or cipher"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); @@ -447,71 +399,54 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) int s = send(remote->fd, ss_addr_to_send, addr_len, 0); free(ss_addr_to_send); - if (s < addr_len) - { + if (s < addr_len) { LOGE("failed to send remote addr."); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } - ev_io_start(EV_A_ &remote->recv_ctx->io); - ev_io_start(EV_A_ &server->recv_ctx->io); + ev_io_start(EV_A_ & remote->recv_ctx->io); + ev_io_start(EV_A_ & server->recv_ctx->io); return; - } - else - { + } else { ERROR("getpeername"); // not connected close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } - } - else - { - if (remote->buf_len == 0) - { + } else { + if (remote->buf_len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; - } - else - { + } else { // has data to send ssize_t s = send(remote->fd, remote->buf + remote->buf_idx, remote->buf_len, 0); - if (s < 0) - { - if (errno != EAGAIN && errno != EWOULDBLOCK) - { + if (s < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { ERROR("send"); // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; - } - else if (s < remote->buf_len) - { + } else if (s < remote->buf_len) { // partly sent, move memory, wait for the next time to send remote->buf_len -= s; remote->buf_idx += s; return; - } - else - { + } else { // all sent out, wait for reading remote->buf_len = 0; remote->buf_idx = 0; - ev_io_stop(EV_A_ &remote_send_ctx->io); - if (server != NULL) - { - ev_io_start(EV_A_ &server->recv_ctx->io); - } - else - { + ev_io_stop(EV_A_ & remote_send_ctx->io); + if (server != NULL) { + ev_io_start(EV_A_ & server->recv_ctx->io); + } else { close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; @@ -522,7 +457,7 @@ static void remote_send_cb (EV_P_ ev_io *w, int revents) } } -static struct remote* new_remote(int fd, int timeout) +static struct remote * new_remote(int fd, int timeout) { struct remote *remote; remote = malloc(sizeof(struct remote)); @@ -544,14 +479,11 @@ static struct remote* new_remote(int fd, int timeout) static void free_remote(struct remote *remote) { - if (remote != NULL) - { - if (remote->server != NULL) - { + if (remote != NULL) { + if (remote->server != NULL) { remote->server->remote = NULL; } - if (remote->buf) - { + if (remote->buf) { free(remote->buf); } free(remote->recv_ctx); @@ -562,17 +494,16 @@ static void free_remote(struct remote *remote) static void close_and_free_remote(EV_P_ struct remote *remote) { - if (remote != NULL) - { - ev_timer_stop(EV_A_ &remote->send_ctx->watcher); - ev_io_stop(EV_A_ &remote->send_ctx->io); - ev_io_stop(EV_A_ &remote->recv_ctx->io); + if (remote != NULL) { + ev_timer_stop(EV_A_ & remote->send_ctx->watcher); + ev_io_stop(EV_A_ & remote->send_ctx->io); + ev_io_stop(EV_A_ & remote->recv_ctx->io); close(remote->fd); free_remote(remote); } } -static struct server* new_server(int fd, int method) +static struct server * new_server(int fd, int method) { struct server *server; server = malloc(sizeof(struct server)); @@ -586,15 +517,12 @@ static struct server* new_server(int fd, int method) server->recv_ctx->connected = 0; server->send_ctx->server = server; server->send_ctx->connected = 0; - if (method) - { + if (method) { server->e_ctx = malloc(sizeof(struct enc_ctx)); server->d_ctx = malloc(sizeof(struct enc_ctx)); enc_ctx_init(method, server->e_ctx, 1); enc_ctx_init(method, server->d_ctx, 0); - } - else - { + } else { server->e_ctx = NULL; server->d_ctx = NULL; } @@ -605,24 +533,19 @@ static struct server* new_server(int fd, int method) static void free_server(struct server *server) { - if (server != NULL) - { - if (server->remote != NULL) - { + if (server != NULL) { + if (server->remote != NULL) { server->remote->server = NULL; } - if (server->e_ctx != NULL) - { + if (server->e_ctx != NULL) { cipher_context_release(&server->e_ctx->evp); free(server->e_ctx); } - if (server->d_ctx != NULL) - { + if (server->d_ctx != NULL) { cipher_context_release(&server->d_ctx->evp); free(server->d_ctx); } - if (server->buf) - { + if (server->buf) { free(server->buf); } free(server->recv_ctx); @@ -633,21 +556,19 @@ static void free_server(struct server *server) static void close_and_free_server(EV_P_ struct server *server) { - if (server != NULL) - { - ev_io_stop(EV_A_ &server->send_ctx->io); - ev_io_stop(EV_A_ &server->recv_ctx->io); + if (server != NULL) { + ev_io_stop(EV_A_ & server->send_ctx->io); + ev_io_stop(EV_A_ & server->recv_ctx->io); close(server->fd); free_server(server); } } -static void accept_cb (EV_P_ ev_io *w, int revents) +static void accept_cb(EV_P_ ev_io *w, int revents) { struct listen_ctx *listener = (struct listen_ctx *)w; int serverfd = accept(listener->fd, NULL, NULL); - if (serverfd == -1) - { + if (serverfd == -1) { ERROR("accept"); return; } @@ -664,20 +585,19 @@ static void accept_cb (EV_P_ ev_io *w, int revents) hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; int index = rand() % listener->remote_num; - if (verbose) - { - LOGD("connect to %s:%s", listener->remote_addr[index].host, listener->remote_addr[index].port); + if (verbose) { + LOGD("connect to %s:%s", listener->remote_addr[index].host, + listener->remote_addr[index].port); } - int err = getaddrinfo(listener->remote_addr[index].host, listener->remote_addr[index].port, &hints, &res); - if (err) - { + int err = getaddrinfo(listener->remote_addr[index].host, + listener->remote_addr[index].port, &hints, &res); + if (err) { ERROR("getaddrinfo"); return; } sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if (sockfd < 0) - { + if (sockfd < 0) { ERROR("socket"); freeaddrinfo(res); return; @@ -691,7 +611,9 @@ static void accept_cb (EV_P_ ev_io *w, int revents) // Setup setnonblocking(sockfd); #ifdef SET_INTERFACE - if (listener->iface) setinterface(sockfd, listener->iface); + if (listener->iface) { + setinterface(sockfd, listener->iface); + } #endif struct server *server = new_server(serverfd, listener->method); @@ -702,11 +624,11 @@ static void accept_cb (EV_P_ ev_io *w, int revents) connect(sockfd, res->ai_addr, res->ai_addrlen); freeaddrinfo(res); // listen to remote connected event - ev_io_start(EV_A_ &remote->send_ctx->io); - ev_timer_start(EV_A_ &remote->send_ctx->watcher); + ev_io_start(EV_A_ & remote->send_ctx->io); + ev_timer_start(EV_A_ & remote->send_ctx->watcher); } -int main (int argc, char **argv) +int main(int argc, char **argv) { int i, c; @@ -725,15 +647,13 @@ int main (int argc, char **argv) ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port = NULL; - ss_addr_t tunnel_addr = {.host = NULL, .port = NULL}; + ss_addr_t tunnel_addr = { .host = NULL, .port = NULL }; char *tunnel_addr_str = NULL; opterr = 0; - while ((c = getopt (argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uv")) != -1) - { - switch (c) - { + while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uv")) != -1) { + switch (c) { case 's': remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; @@ -781,44 +701,54 @@ int main (int argc, char **argv) } } - if (opterr) - { + if (opterr) { usage(); exit(EXIT_FAILURE); } - if (conf_path != NULL) - { + if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); - if (remote_num == 0) - { + if (remote_num == 0) { remote_num = conf->remote_num; - for (i = 0; i < remote_num; i++) - { + for (i = 0; i < remote_num; i++) { remote_addr[i] = conf->remote_addr[i]; } } - if (remote_port == NULL) remote_port = conf->remote_port; - if (local_addr == NULL) local_addr = conf->local_addr; - if (local_port == NULL) local_port = conf->local_port; - if (password == NULL) password = conf->password; - if (method == NULL) method = conf->method; - if (timeout == NULL) timeout = conf->timeout; + if (remote_port == NULL) { + remote_port = conf->remote_port; + } + if (local_addr == NULL) { + local_addr = conf->local_addr; + } + if (local_port == NULL) { + local_port = conf->local_port; + } + if (password == NULL) { + password = conf->password; + } + if (method == NULL) { + method = conf->method; + } + if (timeout == NULL) { + timeout = conf->timeout; + } } if (remote_num == 0 || remote_port == NULL || tunnel_addr_str == NULL || - local_port == NULL || password == NULL) - { + local_port == NULL || password == NULL) { usage(); exit(EXIT_FAILURE); } - if (timeout == NULL) timeout = "10"; + if (timeout == NULL) { + timeout = "10"; + } - if (local_addr == NULL) local_addr = "0.0.0.0"; + if (local_addr == NULL) { + local_addr = "0.0.0.0"; + } - if (pid_flags) - { + if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } @@ -841,12 +771,10 @@ int main (int argc, char **argv) // Setup socket int listenfd; listenfd = create_and_bind(local_addr, local_port); - if (listenfd < 0) - { + if (listenfd < 0) { FATAL("bind() error.."); } - if (listen(listenfd, SOMAXCONN) == -1) - { + if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error."); } setnonblocking(listenfd); @@ -857,10 +785,11 @@ int main (int argc, char **argv) listen_ctx.tunnel_addr = tunnel_addr; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = malloc(sizeof(ss_addr_t) * remote_num); - while (remote_num > 0) - { + while (remote_num > 0) { int index = --remote_num; - if (remote_addr[index].port == NULL) remote_addr[index].port = remote_port; + if (remote_addr[index].port == NULL) { + remote_addr[index].port = remote_port; + } listen_ctx.remote_addr[index] = remote_addr[index]; } listen_ctx.timeout = atoi(timeout); @@ -869,26 +798,26 @@ int main (int argc, char **argv) listen_ctx.method = m; struct ev_loop *loop = ev_default_loop(0); - if (!loop) - { + if (!loop) { FATAL("ev_loop error."); } - ev_io_init (&listen_ctx.io, accept_cb, listenfd, EV_READ); - ev_io_start (loop, &listen_ctx.io); + ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); + ev_io_start(loop, &listen_ctx.io); // Setup UDP - if (udprelay) - { + if (udprelay) { LOGD("udprelay enabled."); - init_udprelay(local_addr, local_port, remote_addr[0].host, remote_addr[0].port, + init_udprelay(local_addr, local_port, remote_addr[0].host, + remote_addr[0].port, tunnel_addr, m, listen_ctx.timeout, iface); } // setuid - if (user != NULL) + if (user != NULL) { run_as(user); + } - ev_run (loop, 0); + ev_run(loop, 0); #ifdef __MINGW32__ winsock_cleanup(); diff --git a/src/tunnel.h b/src/tunnel.h index d2dced58..12f99942 100644 --- a/src/tunnel.h +++ b/src/tunnel.h @@ -29,8 +29,7 @@ #include "common.h" -struct listen_ctx -{ +struct listen_ctx { ev_io io; ss_addr_t tunnel_addr; ss_addr_t *remote_addr; @@ -42,15 +41,13 @@ struct listen_ctx struct sockaddr sock; }; -struct server_ctx -{ +struct server_ctx { ev_io io; int connected; struct server *server; }; -struct server -{ +struct server { int fd; ssize_t buf_len; ssize_t buf_idx; @@ -63,16 +60,14 @@ struct server ss_addr_t destaddr; }; -struct remote_ctx -{ +struct remote_ctx { ev_io io; ev_timer watcher; int connected; struct remote *remote; }; -struct remote -{ +struct remote { int fd; ssize_t buf_len; ssize_t buf_idx; diff --git a/src/udprelay.c b/src/udprelay.c index fbb9d614..b1ef3273 100644 --- a/src/udprelay.c +++ b/src/udprelay.c @@ -88,24 +88,27 @@ struct resolve_ctx *resolve_ctx = NULL; static int setnonblocking(int fd) { int flags; - if (-1 ==(flags = fcntl(fd, F_GETFL, 0))) + if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { flags = 0; + } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } #endif #ifdef SET_INTERFACE -static int setinterface(int socket_fd, const char* interface_name) +static int setinterface(int socket_fd, const char * interface_name) { struct ifreq interface; memset(&interface, 0, sizeof(interface)); strncpy(interface.ifr_name, interface_name, IFNAMSIZ); - int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, sizeof(struct ifreq)); + int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, + sizeof(struct ifreq)); return res; } #endif -static char *hash_key(const char *header, const int header_len, const struct sockaddr_storage *addr) +static char *hash_key(const char *header, const int header_len, + const struct sockaddr_storage *addr) { char key[384]; @@ -115,65 +118,54 @@ static char *hash_key(const char *header, const int header_len, const struct soc memcpy(key, addr, sizeof(struct sockaddr_storage)); memcpy(key + sizeof(struct sockaddr_storage), header, header_len); - return (char*) enc_md5((const uint8_t *)key, sizeof(struct sockaddr_storage) + header_len, NULL); + return (char *)enc_md5((const uint8_t *)key, + sizeof(struct sockaddr_storage) + header_len, NULL); } -static int parse_udprealy_header(const char* buf, const int buf_len, char *host, char *port) +static int parse_udprealy_header(const char * buf, const int buf_len, + char *host, char *port) { - const uint8_t atyp = *(uint8_t*)buf; + const uint8_t atyp = *(uint8_t *)buf; int offset = 1; // get remote addr and port - if (atyp == 1) - { + if (atyp == 1) { // IP V4 size_t in_addr_len = sizeof(struct in_addr); - if (buf_len > in_addr_len) - { - if (host != NULL) - { + if (buf_len > in_addr_len) { + if (host != NULL) { inet_ntop(AF_INET, (const void *)(buf + offset), host, INET_ADDRSTRLEN); } offset += in_addr_len; } - } - else if (atyp == 3) - { + } else if (atyp == 3) { // Domain name uint8_t name_len = *(uint8_t *)(buf + offset); - if (name_len < buf_len && name_len < 255 && name_len > 0) - { - if (host != NULL) - { + if (name_len < buf_len && name_len < 255 && name_len > 0) { + if (host != NULL) { memcpy(host, buf + offset + 1, name_len); } offset += name_len + 1; } - } - else if (atyp == 4) - { + } else if (atyp == 4) { // IP V6 size_t in6_addr_len = sizeof(struct in6_addr); - if (buf_len > in6_addr_len) - { - if (host != NULL) - { - inet_ntop(AF_INET6, (const void*)(buf + offset), + if (buf_len > in6_addr_len) { + if (host != NULL) { + inet_ntop(AF_INET6, (const void *)(buf + offset), host, INET6_ADDRSTRLEN); } offset += in6_addr_len; } } - if (offset == 1) - { + if (offset == 1) { LOGE("invalid header with addr type %d", atyp); return 0; } - if (port != NULL) - { + if (port != NULL) { sprintf(port, "%d", ntohs(*(uint16_t *)(buf + offset))); } offset += 2; @@ -185,12 +177,11 @@ static char *get_addr_str(const struct sockaddr *sa) { static char s[SS_ADDRSTRLEN]; memset(s, 0, SS_ADDRSTRLEN); - char addr[INET6_ADDRSTRLEN] = {0}; - char port[PORTSTRLEN] = {0}; + char addr[INET6_ADDRSTRLEN] = { 0 }; + char port[PORTSTRLEN] = { 0 }; uint16_t p; - switch(sa->sa_family) - { + switch (sa->sa_family) { case AF_INET: inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), addr, INET_ADDRSTRLEN); @@ -223,43 +214,36 @@ int create_remote_socket(int ipv6) { int remote_sock; - if (ipv6) - { + if (ipv6) { // Try to bind IPv6 first struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = in6addr_any; addr.sin6_port = 0; - remote_sock = socket(AF_INET6, SOCK_DGRAM , 0); - if (remote_sock == -1) - { + remote_sock = socket(AF_INET6, SOCK_DGRAM, 0); + if (remote_sock == -1) { ERROR("Cannot create socket."); return -1; } - if (bind(remote_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) - { + if (bind(remote_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) { FATAL("Cannot bind remote."); return -1; } - } - else - { + } else { // Or else bind to IPv4 struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = 0; - remote_sock = socket(AF_INET, SOCK_DGRAM , 0); - if (remote_sock == -1) - { + remote_sock = socket(AF_INET, SOCK_DGRAM, 0); + if (remote_sock == -1) { ERROR("Cannot create socket."); return -1; } - if (bind(remote_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) - { + if (bind(remote_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) { FATAL("Cannot bind remote."); return -1; } @@ -274,21 +258,20 @@ int create_server_socket(const char *host, const char *port) int s, server_sock; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ + hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_DGRAM; /* We want a UDP socket */ s = getaddrinfo(host, port, &hints, &result); - if (s != 0) - { + if (s != 0) { LOGE("getaddrinfo: %s", gai_strerror(s)); return -1; } - for (rp = result; rp != NULL; rp = rp->ai_next) - { + for (rp = result; rp != NULL; rp = rp->ai_next) { server_sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - if (server_sock == -1) + if (server_sock == -1) { continue; + } int opt = 1; setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); @@ -297,21 +280,17 @@ int create_server_socket(const char *host, const char *port) #endif s = bind(server_sock, rp->ai_addr, rp->ai_addrlen); - if (s == 0) - { + if (s == 0) { /* We managed to bind successfully! */ break; - } - else - { + } else { ERROR("bind"); } close(server_sock); } - if (rp == NULL) - { + if (rp == NULL) { LOGE("Could not bind"); return -1; } @@ -328,7 +307,8 @@ struct remote_ctx *new_remote(int fd, struct server_ctx *server_ctx) ctx->fd = fd; ctx->server_ctx = server_ctx; ev_io_init(&ctx->io, remote_recv_cb, fd, EV_READ); - ev_timer_init(&ctx->watcher, remote_timeout_cb, server_ctx->timeout, server_ctx->timeout); + ev_timer_init(&ctx->watcher, remote_timeout_cb, server_ctx->timeout, + server_ctx->timeout); return ctx; } @@ -356,10 +336,8 @@ struct query_ctx *new_query_ctx(asyncns_query_t *query, void close_and_free_query(EV_P_ struct query_ctx *ctx) { - if (ctx != NULL) - { - if (ctx->buf != NULL) - { + if (ctx != NULL) { + if (ctx->buf != NULL) { free(ctx->buf); } free(ctx); @@ -370,10 +348,9 @@ void close_and_free_query(EV_P_ struct query_ctx *ctx) void close_and_free_remote(EV_P_ struct remote_ctx *ctx) { - if (ctx != NULL) - { - ev_timer_stop(EV_A_ &ctx->watcher); - ev_io_stop(EV_A_ &ctx->io); + if (ctx != NULL) { + ev_timer_stop(EV_A_ & ctx->watcher); + ev_io_stop(EV_A_ & ctx->io); close(ctx->fd); free(ctx); } @@ -381,11 +358,10 @@ void close_and_free_remote(EV_P_ struct remote_ctx *ctx) static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) { - struct remote_ctx *remote_ctx = (struct remote_ctx *) (((void*)watcher) - - sizeof(ev_io)); + struct remote_ctx *remote_ctx = (struct remote_ctx *)(((void *)watcher) + - sizeof(ev_io)); - if (verbose) - { + if (verbose) { LOGD("UDP connection timeout"); } @@ -399,32 +375,28 @@ static void query_resolve_cb(EV_P_ ev_io *w, int revents) { int err; struct addrinfo *result, *rp; - struct resolve_ctx *resolve_ctx = (struct resolve_ctx*)w; + struct resolve_ctx *resolve_ctx = (struct resolve_ctx *)w; asyncns_t *asyncns = resolve_ctx->asyncns; err = asyncns_handle(asyncns); - if (err == ASYNCNS_HANDLE_AGAIN) - { + if (err == ASYNCNS_HANDLE_AGAIN) { // try again return; - } - else if (err == ASYNCNS_HANDLE_ERROR) - { + } else if (err == ASYNCNS_HANDLE_ERROR) { // asyncns error FATAL("asyncns exit unexpectedly."); } asyncns_query_t *query = asyncns_getnext(asyncns); - struct query_ctx *query_ctx= (struct query_ctx*) asyncns_getuserdata(asyncns, query); + struct query_ctx *query_ctx = (struct query_ctx *)asyncns_getuserdata( + asyncns, query); - if (!asyncns_isdone(asyncns, query)) - { + if (!asyncns_isdone(asyncns, query)) { // wait reolver return; } - if (verbose) - { + if (verbose) { LOGD("[udp] asyncns resolved."); } @@ -432,64 +404,65 @@ static void query_resolve_cb(EV_P_ ev_io *w, int revents) err = asyncns_getaddrinfo_done(asyncns, query, &result); - if (err) - { + if (err) { ERROR("getaddrinfo"); - } - else - { + } else { // Use IPV4 address if possible - for (rp = result; rp != NULL; rp = rp->ai_next) - { - if (rp->ai_family == AF_INET) break; + for (rp = result; rp != NULL; rp = rp->ai_next) { + if (rp->ai_family == AF_INET) { + break; + } } - if (rp == NULL) - { + if (rp == NULL) { rp = result; } int remotefd = create_remote_socket(rp->ai_family == AF_INET6); - if (remotefd != -1) - { + if (remotefd != -1) { setnonblocking(remotefd); #ifdef SO_NOSIGPIPE int opt = 1; setsockopt(remotefd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif #ifdef SET_INTERFACE - if (query_ctx->server_ctx->iface) + if (query_ctx->server_ctx->iface) { setinterface(remotefd, query_ctx->server_ctx->iface); + } #endif - struct remote_ctx *remote_ctx = new_remote(remotefd, query_ctx->server_ctx); + struct remote_ctx *remote_ctx = new_remote(remotefd, + query_ctx->server_ctx); remote_ctx->src_addr = query_ctx->src_addr; remote_ctx->dst_addr = *((struct sockaddr_storage *)rp->ai_addr); remote_ctx->server_ctx = query_ctx->server_ctx; remote_ctx->addr_header_len = query_ctx->addr_header_len; - memcpy(remote_ctx->addr_header, query_ctx->addr_header, query_ctx->addr_header_len); + memcpy(remote_ctx->addr_header, query_ctx->addr_header, + query_ctx->addr_header_len); // Add to conn cache char *key = hash_key(remote_ctx->addr_header, - remote_ctx->addr_header_len, &remote_ctx->src_addr); - cache_insert(query_ctx->server_ctx->conn_cache, key, (void *)remote_ctx); + remote_ctx->addr_header_len, + &remote_ctx->src_addr); + cache_insert(query_ctx->server_ctx->conn_cache, key, + (void *)remote_ctx); - ev_io_start(EV_A_ &remote_ctx->io); + ev_io_start(EV_A_ & remote_ctx->io); size_t addr_len = sizeof(struct sockaddr_in); - if (remote_ctx->dst_addr.ss_family == AF_INET6) + if (remote_ctx->dst_addr.ss_family == AF_INET6) { addr_len = sizeof(struct sockaddr_in6); - int s = sendto(remote_ctx->fd, query_ctx->buf, query_ctx->buf_len, 0, (struct sockaddr *)&remote_ctx->dst_addr, addr_len); + } + int s = sendto(remote_ctx->fd, query_ctx->buf, query_ctx->buf_len, + 0, (struct sockaddr *)&remote_ctx->dst_addr, + addr_len); - if (s == -1) - { + if (s == -1) { ERROR("udprelay_sendto_remote"); close_and_free_remote(EV_A_ remote_ctx); } - } - else - { + } else { ERROR("udprelay bind() error.."); } } @@ -500,40 +473,37 @@ static void query_resolve_cb(EV_P_ ev_io *w, int revents) } #endif -static void remote_recv_cb (EV_P_ ev_io *w, int revents) +static void remote_recv_cb(EV_P_ ev_io *w, int revents) { struct remote_ctx *remote_ctx = (struct remote_ctx *)w; struct server_ctx *server_ctx = remote_ctx->server_ctx; // server has been closed - if (server_ctx == NULL) - { + if (server_ctx == NULL) { LOGE("invalid server."); close_and_free_remote(EV_A_ remote_ctx); return; } - if (verbose) - { + if (verbose) { LOGD("[udp] remote receive a packet"); } // triger the timer - ev_timer_again(EV_A_ &remote_ctx->watcher); + ev_timer_again(EV_A_ & remote_ctx->watcher); struct sockaddr src_addr; socklen_t src_addr_len = sizeof(src_addr); char *buf = malloc(BUF_SIZE); // recv - ssize_t buf_len = recvfrom(remote_ctx->fd, buf, BUF_SIZE, 0, &src_addr, &src_addr_len); + ssize_t buf_len = recvfrom(remote_ctx->fd, buf, BUF_SIZE, 0, &src_addr, + &src_addr_len); - if (buf_len == -1) - { + if (buf_len == -1) { // error on recv // simply drop that packet - if (verbose) - { + if (verbose) { ERROR("udprelay_server_recvfrom"); } goto CLEAN_UP; @@ -541,18 +511,15 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) #ifdef UDPRELAY_LOCAL buf = ss_decrypt_all(BUF_SIZE, buf, &buf_len, server_ctx->method); - if (buf == NULL) - { - if (verbose) - { + if (buf == NULL) { + if (verbose) { ERROR("udprelay_server_ss_decrypt_all"); } goto CLEAN_UP; } int len = parse_udprealy_header(buf, buf_len, NULL, NULL); - if (len == 0) - { + if (len == 0) { LOGD("[udp] Error in parse header"); // error in parse header goto CLEAN_UP; @@ -591,21 +558,22 @@ static void remote_recv_cb (EV_P_ ev_io *w, int revents) #endif size_t addr_len = sizeof(struct sockaddr_in); - if (remote_ctx->src_addr.ss_family == AF_INET6) + if (remote_ctx->src_addr.ss_family == AF_INET6) { addr_len = sizeof(struct sockaddr_in6); - int s = sendto(server_ctx->fd, buf, buf_len, 0, (struct sockaddr *)&remote_ctx->src_addr, addr_len); + } + int s = sendto(server_ctx->fd, buf, buf_len, 0, + (struct sockaddr *)&remote_ctx->src_addr, addr_len); - if (s == -1) - { + if (s == -1) { ERROR("udprelay_sendto_local"); } -CLEAN_UP: + CLEAN_UP: free(buf); } -static void server_recv_cb (EV_P_ ev_io *w, int revents) +static void server_recv_cb(EV_P_ ev_io *w, int revents) { struct server_ctx *server_ctx = (struct server_ctx *)w; struct sockaddr_storage src_addr; @@ -614,30 +582,27 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) socklen_t src_addr_len = sizeof(struct sockaddr_storage); unsigned int offset = 0; - ssize_t buf_len = recvfrom(server_ctx->fd, buf, BUF_SIZE, 0, (struct sockaddr *)&src_addr, &src_addr_len); + ssize_t buf_len = + recvfrom(server_ctx->fd, buf, BUF_SIZE, 0, (struct sockaddr *)&src_addr, + &src_addr_len); - if (buf_len == -1) - { + if (buf_len == -1) { // error on recv // simply drop that packet - if (verbose) - { + if (verbose) { ERROR("udprelay_server_recvfrom"); } goto CLEAN_UP; } - if (verbose) - { + if (verbose) { LOGD("[udp] server receive a packet."); } #ifdef UDPRELAY_REMOTE buf = ss_decrypt_all(BUF_SIZE, buf, &buf_len, server_ctx->method); - if (buf == NULL) - { - if (verbose) - { + if (buf == NULL) { + if (verbose) { ERROR("udprelay_server_ss_decrypt_all"); } goto CLEAN_UP; @@ -646,7 +611,7 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) #ifdef UDPRELAY_LOCAL #ifndef UDPRELAY_TUNNEL - uint8_t frag = *(uint8_t*)(buf + 2); + uint8_t frag = *(uint8_t *)(buf + 2); offset += 3; #endif #endif @@ -691,9 +656,9 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) */ #ifdef UDPRELAY_TUNNEL - char addr_header[256] = {0}; - char* host = server_ctx->tunnel_addr.host; - char* port = server_ctx->tunnel_addr.port; + char addr_header[256] = { 0 }; + char * host = server_ctx->tunnel_addr.host; + char * port = server_ctx->tunnel_addr.port; int host_len = strlen(host); uint16_t port_num = (uint16_t)atoi(port); uint16_t port_net_num = htons(port_num); @@ -714,13 +679,12 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) buf_len += addr_header_len; #else - char host[256] = {0}; - char port[64] = {0}; + char host[256] = { 0 }; + char port[64] = { 0 }; int addr_header_len = parse_udprealy_header(buf + offset, - buf_len - offset, host, port); - if (addr_header_len == 0) - { + buf_len - offset, host, port); + if (addr_header_len == 0) { // error in parse header goto CLEAN_UP; } @@ -731,63 +695,54 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) struct cache *conn_cache = server_ctx->conn_cache; struct remote_ctx *remote_ctx = NULL; - cache_lookup(conn_cache, key, (void*)&remote_ctx); + cache_lookup(conn_cache, key, (void *)&remote_ctx); - if (remote_ctx != NULL) - { + if (remote_ctx != NULL) { if (memcmp(&src_addr, &remote_ctx->src_addr, sizeof(src_addr)) - || strcmp(addr_header, remote_ctx->addr_header) != 0) - { + || strcmp(addr_header, remote_ctx->addr_header) != 0) { remote_ctx = NULL; } } - if (remote_ctx == NULL) - { - if (verbose) - { - LOGD("[udp] cache missed: %s:%s <-> %s", host, port, get_addr_str((struct sockaddr *)&src_addr)); + if (remote_ctx == NULL) { + if (verbose) { + LOGD("[udp] cache missed: %s:%s <-> %s", host, port, + get_addr_str((struct sockaddr *)&src_addr)); } - } - else - { - if (verbose) - { - LOGD("[udp] cache hit: %s:%s <-> %s", host, port, get_addr_str((struct sockaddr *)&src_addr)); + } else { + if (verbose) { + LOGD("[udp] cache hit: %s:%s <-> %s", host, port, + get_addr_str((struct sockaddr *)&src_addr)); } } #ifdef UDPRELAY_LOCAL #ifndef UDPRELAY_TUNNEL - if (frag) - { + if (frag) { LOGE("drop a message since frag is not 0, but %d", frag); goto CLEAN_UP; } #endif - if (remote_ctx == NULL) - { + if (remote_ctx == NULL) { struct addrinfo hints; struct addrinfo *result; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ + hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_DGRAM; /* We want a UDP socket */ int s = getaddrinfo(server_ctx->remote_host, server_ctx->remote_port, &hints, &result); - if (s != 0 || result == NULL) - { + if (s != 0 || result == NULL) { LOGE("getaddrinfo: %s", gai_strerror(s)); goto CLEAN_UP; } // Bind to any port int remotefd = create_remote_socket(result->ai_family == AF_INET6); - if (remotefd < 0) - { + if (remotefd < 0) { ERROR("udprelay bind() error.."); // remember to free addrinfo freeaddrinfo(result); @@ -800,8 +755,9 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) setsockopt(remotefd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif #ifdef SET_INTERFACE - if (server_ctx->iface) + if (server_ctx->iface) { setinterface(remotefd, server_ctx->iface); + } #endif // Init remote_ctx @@ -815,14 +771,13 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) cache_insert(conn_cache, key, (void *)remote_ctx); // Start remote io - ev_io_start(EV_A_ &remote_ctx->io); + ev_io_start(EV_A_ & remote_ctx->io); // clean up freeaddrinfo(result); } - if (offset > 0) - { + if (offset > 0) { buf_len -= offset; memmove(buf, buf + offset, buf_len); } @@ -830,19 +785,19 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) buf = ss_encrypt_all(BUF_SIZE, buf, &buf_len, server_ctx->method); size_t addr_len = sizeof(struct sockaddr_in); - if (remote_ctx->dst_addr.ss_family == AF_INET6) + if (remote_ctx->dst_addr.ss_family == AF_INET6) { addr_len = sizeof(struct sockaddr_in6); - int s = sendto(remote_ctx->fd, buf, buf_len, 0, (struct sockaddr*)&remote_ctx->dst_addr, addr_len); + } + int s = sendto(remote_ctx->fd, buf, buf_len, 0, + (struct sockaddr *)&remote_ctx->dst_addr, addr_len); - if (s == -1) - { + if (s == -1) { ERROR("udprelay_sendto_remote"); } #else - if (remote_ctx == NULL) - { + if (remote_ctx == NULL) { struct addrinfo hints; asyncns_query_t *query; memset(&hints, 0, sizeof(hints)); @@ -852,36 +807,35 @@ static void server_recv_cb (EV_P_ ev_io *w, int revents) query = asyncns_getaddrinfo(server_ctx->asyncns, host, port, &hints); - if (query == NULL) - { + if (query == NULL) { ERROR("udp_asyncns_getaddrinfo"); goto CLEAN_UP; } - struct query_ctx *query_ctx = new_query_ctx(query, buf + addr_header_len, - buf_len - addr_header_len); + struct query_ctx *query_ctx = new_query_ctx(query, + buf + addr_header_len, + buf_len - addr_header_len); query_ctx->server_ctx = server_ctx; query_ctx->addr_header_len = addr_header_len; query_ctx->src_addr = src_addr; memcpy(query_ctx->addr_header, addr_header, addr_header_len); asyncns_setuserdata(server_ctx->asyncns, query, query_ctx); - } - else - { + } else { size_t addr_len = sizeof(struct sockaddr_in); - if (remote_ctx->dst_addr.ss_family == AF_INET6) + if (remote_ctx->dst_addr.ss_family == AF_INET6) { addr_len = sizeof(struct sockaddr_in6); + } int s = sendto(remote_ctx->fd, buf + addr_header_len, - buf_len - addr_header_len, 0, (struct sockaddr*)&remote_ctx->dst_addr, addr_len); + buf_len - addr_header_len, 0, + (struct sockaddr *)&remote_ctx->dst_addr, addr_len); - if (s == -1) - { + if (s == -1) { ERROR("udprelay_sendto_remote"); } } #endif -CLEAN_UP: + CLEAN_UP: free(buf); } @@ -890,8 +844,7 @@ void free_cb(void *element) { struct remote_ctx *remote_ctx = (struct remote_ctx *)element; - if (verbose) - { + if (verbose) { LOGD("free a remote ctx"); } @@ -923,22 +876,20 @@ int init_udprelay(const char *server_host, const char *server_port, #ifdef UDPRELAY_REMOTE // setup asyncns asyncns_t *asyncns; - if (!(asyncns = asyncns_new(dns_thread_num))) - { + if (!(asyncns = asyncns_new(dns_thread_num))) { FATAL("asyncns failed"); } resolve_ctx = malloc(sizeof(struct resolve_ctx)); resolve_ctx->asyncns = asyncns; int asyncnsfd = asyncns_fd(asyncns); - ev_io_init (&resolve_ctx->io, query_resolve_cb, asyncnsfd, EV_READ); - ev_io_start (loop, &resolve_ctx->io); + ev_io_init(&resolve_ctx->io, query_resolve_cb, asyncnsfd, EV_READ); + ev_io_start(loop, &resolve_ctx->io); #endif // Bind to port int serverfd = create_server_socket(server_host, server_port); - if (serverfd < 0) - { + if (serverfd < 0) { FATAL("udprelay bind() error.."); } setnonblocking(serverfd); @@ -968,16 +919,14 @@ void free_udprelay() { struct ev_loop *loop = EV_DEFAULT; #ifdef UDPRELAY_REMOTE - if (resolve_ctx != NULL) - { + if (resolve_ctx != NULL) { asyncns_free(resolve_ctx->asyncns); ev_io_stop(loop, &resolve_ctx->io); free(resolve_ctx); resolve_ctx = NULL; } #endif - if (server_ctx != NULL) - { + if (server_ctx != NULL) { ev_io_stop(loop, &server_ctx->io); close(server_ctx->fd); cache_delete(server_ctx->conn_cache, 0); diff --git a/src/udprelay.h b/src/udprelay.h index 83693db1..98c96489 100644 --- a/src/udprelay.h +++ b/src/udprelay.h @@ -39,8 +39,7 @@ #define MAX_UDP_PACKET_SIZE (64 * 1024) -struct server_ctx -{ +struct server_ctx { ev_io io; int fd; int method; @@ -60,14 +59,12 @@ struct server_ctx }; #ifdef UDPRELAY_REMOTE -struct resolve_ctx -{ +struct resolve_ctx { ev_io io; asyncns_t *asyncns; }; -struct query_ctx -{ +struct query_ctx { asyncns_query_t *query; struct sockaddr_storage src_addr; int buf_len; @@ -78,8 +75,7 @@ struct query_ctx }; #endif -struct remote_ctx -{ +struct remote_ctx { ev_io io; ev_timer watcher; int fd; @@ -90,15 +86,16 @@ struct remote_ctx struct server_ctx *server_ctx; }; -static void server_recv_cb (EV_P_ ev_io *w, int revents); -static void remote_recv_cb (EV_P_ ev_io *w, int revents); +static void server_recv_cb(EV_P_ ev_io *w, int revents); +static void remote_recv_cb(EV_P_ ev_io *w, int revents); static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents); -static char *hash_key(const char *header, const int header_len, const struct sockaddr_storage *addr); +static char *hash_key(const char *header, const int header_len, + const struct sockaddr_storage *addr); #ifdef UDPRELAY_REMOTE static void query_resolve_cb(EV_P_ ev_io *w, int revents); #endif static void close_and_free_remote(EV_P_ struct remote_ctx *ctx); -static struct remote_ctx* new_remote(int fd, struct server_ctx* server_ctx); +static struct remote_ctx * new_remote(int fd, struct server_ctx * server_ctx); #endif // _UDPRELAY_H diff --git a/src/uthash.h b/src/uthash.h index cf2b7a88..d136b741 100644 --- a/src/uthash.h +++ b/src/uthash.h @@ -1,25 +1,25 @@ /* -Copyright (c) 2003-2013, Troy D. Hanson http://troydhanson.github.com/uthash/ -All rights reserved. + Copyright (c) 2003-2013, Troy D. Hanson http://troydhanson.github.com/uthash/ + All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ #ifndef UTHASH_H #define UTHASH_H @@ -32,10 +32,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. As decltype is only available in newer compilers (VS2010 or gcc 4.3+ when compiling c++ source) this code uses whatever method is needed or, for VS2008 where neither is available, uses casting workarounds. */ -#ifdef _MSC_VER /* MS compiler */ -#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#ifdef _MSC_VER /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ #define DECLTYPE(x) (decltype(x)) -#else /* VS2008 or older (or VS2010 in C mode) */ +#else /* VS2008 or older (or VS2010 in C mode) */ #define NO_DECLTYPE #define DECLTYPE(x) #endif @@ -44,16 +44,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endif #ifdef NO_DECLTYPE -#define DECLTYPE_ASSIGN(dst,src) \ -do { \ - char **_da_dst = (char**)(&(dst)); \ - *_da_dst = (char*)(src); \ -} while(0) +#define DECLTYPE_ASSIGN(dst, src) \ + do { \ + char **_da_dst = (char **)(&(dst)); \ + *_da_dst = (char *)(src); \ + } while (0) #else -#define DECLTYPE_ASSIGN(dst,src) \ -do { \ - (dst) = DECLTYPE(dst)(src); \ -} while(0) +#define DECLTYPE_ASSIGN(dst, src) \ + do { \ + (dst) = DECLTYPE(dst) (src); \ + } while (0) #endif /* a number of the hash function use uint32_t which isn't defined on win32 */ @@ -64,7 +64,7 @@ typedef unsigned char uint8_t; #include /* uint32_t */ #endif -#define UTHASH_VERSION 1.9.8 +#define UTHASH_VERSION 1.9 .8 #ifndef uthash_fatal #define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ @@ -73,7 +73,7 @@ typedef unsigned char uint8_t; #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ #endif #ifndef uthash_free -#define uthash_free(ptr,sz) free(ptr) /* free fcn */ +#define uthash_free(ptr, sz) free(ptr) /* free fcn */ #endif #ifndef uthash_noexpand_fyi @@ -89,116 +89,122 @@ typedef unsigned char uint8_t; #define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ /* calculate the element whose hash handle address is hhe */ -#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) +#define ELMT_FROM_HH(tbl, hhp) ((void *)(((char *)(hhp)) - ((tbl)->hho))) -#define HASH_FIND(hh,head,keyptr,keylen,out) \ -do { \ - unsigned _hf_bkt,_hf_hashv; \ - out=NULL; \ - if (head) { \ - HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ - if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ - HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ - keyptr,keylen,out); \ - } \ - } \ -} while (0) +#define HASH_FIND(hh, head, keyptr, keylen, out) \ + do { \ + unsigned _hf_bkt, _hf_hashv; \ + out = NULL; \ + if (head) { \ + HASH_FCN(keyptr, keylen, (head)->hh.tbl->num_buckets, _hf_hashv, \ + _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, \ + (head)->hh.tbl->buckets[ _hf_bkt ], \ + keyptr, keylen, out); \ + } \ + } \ + } while (0) #ifdef HASH_BLOOM #define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) -#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) -#define HASH_BLOOM_MAKE(tbl) \ -do { \ - (tbl)->bloom_nbits = HASH_BLOOM; \ - (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ - if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ - memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ - (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ -} while (0) +#define HASH_BLOOM_BYTELEN \ + (HASH_BLOOM_BITLEN / \ + 8) + ((HASH_BLOOM_BITLEN % 8) ? 1 : 0) +#define HASH_BLOOM_MAKE(tbl) \ + do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t *)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ + memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ + } while (0) -#define HASH_BLOOM_FREE(tbl) \ -do { \ - uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ -} while (0) +#define HASH_BLOOM_FREE(tbl) \ + do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ + } while (0) -#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) -#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) +#define HASH_BLOOM_BITSET(bv, idx) (bv[(idx) / 8] |= (1U << ((idx) % 8))) +#define HASH_BLOOM_BITTEST(bv, idx) (bv[(idx) / 8] & (1U << ((idx) % 8))) -#define HASH_BLOOM_ADD(tbl,hashv) \ - HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) +#define HASH_BLOOM_ADD(tbl, hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, \ + (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) -#define HASH_BLOOM_TEST(tbl,hashv) \ - HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) +#define HASH_BLOOM_TEST(tbl, hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, \ + (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) #else #define HASH_BLOOM_MAKE(tbl) #define HASH_BLOOM_FREE(tbl) -#define HASH_BLOOM_ADD(tbl,hashv) -#define HASH_BLOOM_TEST(tbl,hashv) (1) +#define HASH_BLOOM_ADD(tbl, hashv) +#define HASH_BLOOM_TEST(tbl, hashv) (1) #define HASH_BLOOM_BYTELEN 0 #endif -#define HASH_MAKE_TABLE(hh,head) \ -do { \ - (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ - sizeof(UT_hash_table)); \ - if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ - (head)->hh.tbl->tail = &((head)->hh); \ - (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ - (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ - (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ - (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ - if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ - memset((head)->hh.tbl->buckets, 0, \ - HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ - HASH_BLOOM_MAKE((head)->hh.tbl); \ - (head)->hh.tbl->signature = HASH_SIGNATURE; \ -} while(0) +#define HASH_MAKE_TABLE(hh, head) \ + do { \ + (head)->hh.tbl = (UT_hash_table *)uthash_malloc( \ + sizeof(UT_hash_table)); \ + if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char *)(&(head)->hh) - (char *)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket *)uthash_malloc( \ + HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + if (!(head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl->buckets, 0, \ + HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ + } while (0) -#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ - HASH_ADD_KEYPTR(hh,head,&((add)->fieldname),keylen_in,add) +#define HASH_ADD(hh, head, fieldname, keylen_in, add) \ + HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) -#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ -do { \ - replaced=NULL; \ - HASH_FIND(hh,head,&((add)->fieldname),keylen_in,replaced); \ - if (replaced!=NULL) { \ - HASH_DELETE(hh,head,replaced); \ - }; \ - HASH_ADD(hh,head,fieldname,keylen_in,add); \ -} while(0) +#define HASH_REPLACE(hh, head, fieldname, keylen_in, add, replaced) \ + do { \ + replaced = NULL; \ + HASH_FIND(hh, head, &((add)->fieldname), keylen_in, replaced); \ + if (replaced != NULL) { \ + HASH_DELETE(hh, head, replaced); \ + }; \ + HASH_ADD(hh, head, fieldname, keylen_in, add); \ + } while (0) -#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ -do { \ - unsigned _ha_bkt; \ - (add)->hh.next = NULL; \ - (add)->hh.key = (char*)keyptr; \ - (add)->hh.keylen = (unsigned)keylen_in; \ - if (!(head)) { \ - head = (add); \ - (head)->hh.prev = NULL; \ - HASH_MAKE_TABLE(hh,head); \ - } else { \ - (head)->hh.tbl->tail->next = (add); \ - (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ - (head)->hh.tbl->tail = &((add)->hh); \ - } \ - (head)->hh.tbl->num_items++; \ - (add)->hh.tbl = (head)->hh.tbl; \ - HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ - (add)->hh.hashv, _ha_bkt); \ - HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ - HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ - HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ - HASH_FSCK(hh,head); \ -} while(0) +#define HASH_ADD_KEYPTR(hh, head, keyptr, keylen_in, add) \ + do { \ + unsigned _ha_bkt; \ + (add)->hh.next = NULL; \ + (add)->hh.key = (char *)keyptr; \ + (add)->hh.keylen = (unsigned)keylen_in; \ + if (!(head)) { \ + head = (add); \ + (head)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh, head); \ + } else { \ + (head)->hh.tbl->tail->next = (add); \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail = &((add)->hh); \ + } \ + (head)->hh.tbl->num_items++; \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_FCN(keyptr, keylen_in, (head)->hh.tbl->num_buckets, \ + (add)->hh.hashv, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl, (add)->hh.hashv); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + HASH_FSCK(hh, head); \ + } while (0) -#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ -do { \ - bkt = ((hashv) & ((num_bkts) - 1)); \ -} while(0) +#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ + do { \ + bkt = ((hashv) & ((num_bkts) - 1)); \ + } while (0) /* delete "delptr" from the hash table. * "the usual" patch-up process for the app-order doubly-linked-list. @@ -212,136 +218,142 @@ do { * copy the deletee pointer, then the latter references are via that * scratch pointer rather than through the repointed (users) symbol. */ -#define HASH_DELETE(hh,head,delptr) \ -do { \ - unsigned _hd_bkt; \ - struct UT_hash_handle *_hd_hh_del; \ - if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ - uthash_free((head)->hh.tbl->buckets, \ - (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ - HASH_BLOOM_FREE((head)->hh.tbl); \ - uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ - head = NULL; \ - } else { \ - _hd_hh_del = &((delptr)->hh); \ - if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ - (head)->hh.tbl->tail = \ - (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho); \ - } \ - if ((delptr)->hh.prev) { \ - ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ - (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ - } else { \ - DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ - } \ - if (_hd_hh_del->next) { \ - ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \ - (head)->hh.tbl->hho))->prev = \ - _hd_hh_del->prev; \ - } \ - HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ - HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ - (head)->hh.tbl->num_items--; \ - } \ - HASH_FSCK(hh,head); \ -} while (0) +#define HASH_DELETE(hh, head, delptr) \ + do { \ + unsigned _hd_bkt; \ + struct UT_hash_handle *_hd_hh_del; \ + if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets * \ + sizeof(struct UT_hash_bucket) ); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + head = NULL; \ + } else { \ + _hd_hh_del = &((delptr)->hh); \ + if ((delptr) == \ + ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail)) { \ + (head)->hh.tbl->tail = \ + (UT_hash_handle *)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho); \ + } \ + if ((delptr)->hh.prev) { \ + ((UT_hash_handle *)((ptrdiff_t)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho))->next = \ + (delptr)->hh.next; \ + } else { \ + DECLTYPE_ASSIGN(head, (delptr)->hh.next); \ + } \ + if (_hd_hh_del->next) { \ + ((UT_hash_handle *)((ptrdiff_t)_hd_hh_del->next + \ + (head)->hh.tbl->hho))->prev = \ + _hd_hh_del->prev; \ + } \ + HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, \ + _hd_bkt); \ + HASH_DEL_IN_BKT(hh, (head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh, head); \ + } while (0) /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ -#define HASH_FIND_STR(head,findstr,out) \ - HASH_FIND(hh,head,findstr,strlen(findstr),out) -#define HASH_ADD_STR(head,strfield,add) \ - HASH_ADD(hh,head,strfield,strlen(add->strfield),add) -#define HASH_REPLACE_STR(head,strfield,add,replaced) \ - HASH_REPLACE(hh,head,strfield,strlen(add->strfield),add,replaced) -#define HASH_FIND_INT(head,findint,out) \ - HASH_FIND(hh,head,findint,sizeof(int),out) -#define HASH_ADD_INT(head,intfield,add) \ - HASH_ADD(hh,head,intfield,sizeof(int),add) -#define HASH_REPLACE_INT(head,intfield,add,replaced) \ - HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) -#define HASH_FIND_PTR(head,findptr,out) \ - HASH_FIND(hh,head,findptr,sizeof(void *),out) -#define HASH_ADD_PTR(head,ptrfield,add) \ - HASH_ADD(hh,head,ptrfield,sizeof(void *),add) -#define HASH_REPLACE_PTR(head,ptrfield,add) \ - HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) -#define HASH_DEL(head,delptr) \ - HASH_DELETE(hh,head,delptr) +#define HASH_FIND_STR(head, findstr, out) \ + HASH_FIND(hh, head, findstr, strlen(findstr), out) +#define HASH_ADD_STR(head, strfield, add) \ + HASH_ADD(hh, head, strfield, strlen(add->strfield), add) +#define HASH_REPLACE_STR(head, strfield, add, replaced) \ + HASH_REPLACE(hh, head, strfield, strlen(add->strfield), add, replaced) +#define HASH_FIND_INT(head, findint, out) \ + HASH_FIND(hh, head, findint, sizeof(int), out) +#define HASH_ADD_INT(head, intfield, add) \ + HASH_ADD(hh, head, intfield, sizeof(int), add) +#define HASH_REPLACE_INT(head, intfield, add, replaced) \ + HASH_REPLACE(hh, head, intfield, sizeof(int), add, replaced) +#define HASH_FIND_PTR(head, findptr, out) \ + HASH_FIND(hh, head, findptr, sizeof(void *), out) +#define HASH_ADD_PTR(head, ptrfield, add) \ + HASH_ADD(hh, head, ptrfield, sizeof(void *), add) +#define HASH_REPLACE_PTR(head, ptrfield, add) \ + HASH_REPLACE(hh, head, ptrfield, sizeof(void *), add, replaced) +#define HASH_DEL(head, delptr) \ + HASH_DELETE(hh, head, delptr) /* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. */ #ifdef HASH_DEBUG -#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) -#define HASH_FSCK(hh,head) \ -do { \ - unsigned _bkt_i; \ - unsigned _count, _bkt_count; \ - char *_prev; \ - struct UT_hash_handle *_thh; \ - if (head) { \ - _count = 0; \ - for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ - _bkt_count = 0; \ - _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ +#define HASH_OOPS(...) do { fprintf(stderr, __VA_ARGS__); exit(-1); } while (0) +#define HASH_FSCK(hh, head) \ + do { \ + unsigned _bkt_i; \ + unsigned _count, _bkt_count; \ + char *_prev; \ + struct UT_hash_handle *_thh; \ + if (head) { \ + _count = 0; \ + for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ + _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char *)(_thh->hh_prev)) { \ + HASH_OOPS("invalid hh_prev %p, actual %p\n", \ + _thh->hh_prev, _prev ); \ + } \ + _bkt_count++; \ + _prev = (char *)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("invalid bucket count %d, actual %d\n", \ + (head)->hh.tbl->buckets[_bkt_i].count, \ + _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid hh item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + /* traverse hh in app order; check next/prev integrity, count */ \ + _count = 0; \ _prev = NULL; \ + _thh = &(head)->hh; \ while (_thh) { \ - if (_prev != (char*)(_thh->hh_prev)) { \ - HASH_OOPS("invalid hh_prev %p, actual %p\n", \ - _thh->hh_prev, _prev ); \ - } \ - _bkt_count++; \ - _prev = (char*)(_thh); \ - _thh = _thh->hh_next; \ + _count++; \ + if (_prev != (char *)(_thh->prev)) { \ + HASH_OOPS("invalid prev %p, actual %p\n", \ + _thh->prev, _prev ); \ + } \ + _prev = (char *)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = ( _thh->next ? (UT_hash_handle *)((char *)(_thh->next) + \ + (head)->hh.tbl->hho) : \ + NULL ); \ } \ - _count += _bkt_count; \ - if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ - HASH_OOPS("invalid bucket count %d, actual %d\n", \ - (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid app item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ } \ } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid hh item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - /* traverse hh in app order; check next/prev integrity, count */ \ - _count = 0; \ - _prev = NULL; \ - _thh = &(head)->hh; \ - while (_thh) { \ - _count++; \ - if (_prev !=(char*)(_thh->prev)) { \ - HASH_OOPS("invalid prev %p, actual %p\n", \ - _thh->prev, _prev ); \ - } \ - _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ - _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ - (head)->hh.tbl->hho) : NULL ); \ - } \ - if (_count != (head)->hh.tbl->num_items) { \ - HASH_OOPS("invalid app item count %d, actual %d\n", \ - (head)->hh.tbl->num_items, _count ); \ - } \ - } \ -} while (0) + } while (0) #else -#define HASH_FSCK(hh,head) +#define HASH_FSCK(hh, head) #endif /* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to * the descriptor to which this macro is defined for tuning the hash function. * The app can #include to get the prototype for write(2). */ #ifdef HASH_EMIT_KEYS -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ -do { \ - unsigned _klen = fieldlen; \ - write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ - write(HASH_EMIT_KEYS, keyptr, fieldlen); \ -} while (0) +#define HASH_EMIT_KEY(hh, head, keyptr, fieldlen) \ + do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, fieldlen); \ + } while (0) #else -#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#define HASH_EMIT_KEY(hh, head, keyptr, fieldlen) #endif /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ @@ -352,162 +364,163 @@ do { #endif /* The Bernstein hash function, used in Perl prior to v5.6 */ -#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hb_keylen=keylen; \ - char *_hb_key=(char*)(key); \ - (hashv) = 0; \ - while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ - bkt = (hashv) & (num_bkts-1); \ -} while (0) +#define HASH_BER(key, keylen, num_bkts, hashv, bkt) \ + do { \ + unsigned _hb_keylen = keylen; \ + char *_hb_key = (char *)(key); \ + (hashv) = 0; \ + while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ + bkt = (hashv) & (num_bkts - 1); \ + } while (0) /* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ -#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _sx_i; \ - char *_hs_key=(char*)(key); \ - hashv = 0; \ - for(_sx_i=0; _sx_i < keylen; _sx_i++) \ - hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ - bkt = hashv & (num_bkts-1); \ -} while (0) +#define HASH_SAX(key, keylen, num_bkts, hashv, bkt) \ + do { \ + unsigned _sx_i; \ + char *_hs_key = (char *)(key); \ + hashv = 0; \ + for (_sx_i = 0; _sx_i < keylen; _sx_i++) { \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; } \ + bkt = hashv & (num_bkts - 1); \ + } while (0) -#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _fn_i; \ - char *_hf_key=(char*)(key); \ - hashv = 2166136261UL; \ - for(_fn_i=0; _fn_i < keylen; _fn_i++) \ - hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ - bkt = hashv & (num_bkts-1); \ -} while(0) +#define HASH_FNV(key, keylen, num_bkts, hashv, bkt) \ + do { \ + unsigned _fn_i; \ + char *_hf_key = (char *)(key); \ + hashv = 2166136261UL; \ + for (_fn_i = 0; _fn_i < keylen; _fn_i++) { \ + hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; } \ + bkt = hashv & (num_bkts - 1); \ + } while (0) -#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _ho_i; \ - char *_ho_key=(char*)(key); \ - hashv = 0; \ - for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ - hashv += _ho_key[_ho_i]; \ - hashv += (hashv << 10); \ - hashv ^= (hashv >> 6); \ - } \ - hashv += (hashv << 3); \ - hashv ^= (hashv >> 11); \ - hashv += (hashv << 15); \ - bkt = hashv & (num_bkts-1); \ -} while(0) +#define HASH_OAT(key, keylen, num_bkts, hashv, bkt) \ + do { \ + unsigned _ho_i; \ + char *_ho_key = (char *)(key); \ + hashv = 0; \ + for (_ho_i = 0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ + bkt = hashv & (num_bkts - 1); \ + } while (0) -#define HASH_JEN_MIX(a,b,c) \ -do { \ - a -= b; a -= c; a ^= ( c >> 13 ); \ - b -= c; b -= a; b ^= ( a << 8 ); \ - c -= a; c -= b; c ^= ( b >> 13 ); \ - a -= b; a -= c; a ^= ( c >> 12 ); \ - b -= c; b -= a; b ^= ( a << 16 ); \ - c -= a; c -= b; c ^= ( b >> 5 ); \ - a -= b; a -= c; a ^= ( c >> 3 ); \ - b -= c; b -= a; b ^= ( a << 10 ); \ - c -= a; c -= b; c ^= ( b >> 15 ); \ -} while (0) +#define HASH_JEN_MIX(a, b, c) \ + do { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ + } while (0) -#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned _hj_i,_hj_j,_hj_k; \ - unsigned char *_hj_key=(unsigned char*)(key); \ - hashv = 0xfeedbeef; \ - _hj_i = _hj_j = 0x9e3779b9; \ - _hj_k = (unsigned)keylen; \ - while (_hj_k >= 12) { \ - _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ - + ( (unsigned)_hj_key[2] << 16 ) \ - + ( (unsigned)_hj_key[3] << 24 ) ); \ - _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ - + ( (unsigned)_hj_key[6] << 16 ) \ - + ( (unsigned)_hj_key[7] << 24 ) ); \ - hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ - + ( (unsigned)_hj_key[10] << 16 ) \ - + ( (unsigned)_hj_key[11] << 24 ) ); \ - \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - \ - _hj_key += 12; \ - _hj_k -= 12; \ - } \ - hashv += keylen; \ - switch ( _hj_k ) { \ - case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ - case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ - case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ - case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ - case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ - case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ - case 5: _hj_j += _hj_key[4]; \ - case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ - case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ - case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ - case 1: _hj_i += _hj_key[0]; \ - } \ - HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ - bkt = hashv & (num_bkts-1); \ -} while(0) +#define HASH_JEN(key, keylen, num_bkts, hashv, bkt) \ + do { \ + unsigned _hj_i, _hj_j, _hj_k; \ + unsigned char *_hj_key = (unsigned char *)(key); \ + hashv = 0xfeedbeef; \ + _hj_i = _hj_j = 0x9e3779b9; \ + _hj_k = (unsigned)keylen; \ + while (_hj_k >= 12) { \ + _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + + ( (unsigned)_hj_key[2] << 16 ) \ + + ( (unsigned)_hj_key[3] << 24 ) ); \ + _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + + ( (unsigned)_hj_key[6] << 16 ) \ + + ( (unsigned)_hj_key[7] << 24 ) ); \ + hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + + ( (unsigned)_hj_key[10] << 16 ) \ + + ( (unsigned)_hj_key[11] << 24 ) ); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12; \ + } \ + hashv += keylen; \ + switch (_hj_k) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ + case 5: _hj_j += _hj_key[4]; \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ + case 1: _hj_i += _hj_key[0]; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + bkt = hashv & (num_bkts - 1); \ + } while (0) /* The Paul Hsieh hash function */ #undef get16bits -#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ - || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) -#define get16bits(d) (*((const uint16_t *) (d))) +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *)(d))) #endif #if !defined (get16bits) -#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ - +(uint32_t)(((const uint8_t *)(d))[0]) ) +#define get16bits(d) \ + ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ + + (uint32_t)(((const uint8_t *)(d))[0]) ) #endif -#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ -do { \ - unsigned char *_sfh_key=(unsigned char*)(key); \ - uint32_t _sfh_tmp, _sfh_len = keylen; \ - \ - int _sfh_rem = _sfh_len & 3; \ - _sfh_len >>= 2; \ - hashv = 0xcafebabe; \ - \ - /* Main loop */ \ - for (;_sfh_len > 0; _sfh_len--) { \ - hashv += get16bits (_sfh_key); \ - _sfh_tmp = (uint32_t)(get16bits (_sfh_key+2)) << 11 ^ hashv; \ - hashv = (hashv << 16) ^ _sfh_tmp; \ - _sfh_key += 2*sizeof (uint16_t); \ - hashv += hashv >> 11; \ - } \ - \ - /* Handle end cases */ \ - switch (_sfh_rem) { \ - case 3: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 16; \ - hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)] << 18); \ - hashv += hashv >> 11; \ - break; \ - case 2: hashv += get16bits (_sfh_key); \ - hashv ^= hashv << 11; \ - hashv += hashv >> 17; \ - break; \ - case 1: hashv += *_sfh_key; \ - hashv ^= hashv << 10; \ - hashv += hashv >> 1; \ - } \ - \ - /* Force "avalanching" of final 127 bits */ \ - hashv ^= hashv << 3; \ - hashv += hashv >> 5; \ - hashv ^= hashv << 4; \ - hashv += hashv >> 17; \ - hashv ^= hashv << 25; \ - hashv += hashv >> 6; \ - bkt = hashv & (num_bkts-1); \ -} while(0) +#define HASH_SFH(key, keylen, num_bkts, hashv, bkt) \ + do { \ + unsigned char *_sfh_key = (unsigned char *)(key); \ + uint32_t _sfh_tmp, _sfh_len = keylen; \ + \ + int _sfh_rem = _sfh_len & 3; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabe; \ + \ + /* Main loop */ \ + for (; _sfh_len > 0; _sfh_len--) { \ + hashv += get16bits(_sfh_key); \ + _sfh_tmp = (uint32_t)(get16bits(_sfh_key + 2)) << 11 ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2 * sizeof(uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: hashv += get16bits(_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= (uint32_t)(_sfh_key[sizeof(uint16_t)] << 18); \ + hashv += hashv >> 11; \ + break; \ + case 2: hashv += get16bits(_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ + bkt = hashv & (num_bkts - 1); \ + } while (0) #ifdef HASH_USING_NO_STRICT_ALIASING /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. @@ -519,119 +532,139 @@ do { * gcc -m64 -dM -E - < /dev/null (on gcc) * cc -## a.c (where a.c is a simple test file) (Sun Studio) */ -#if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) -#define MUR_GETBLOCK(p,i) p[i] +#if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) +#define MUR_GETBLOCK(p, i) p[i] #else /* non intel */ #define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 0x3) == 0) #define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 0x3) == 1) #define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 0x3) == 2) #define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 0x3) == 3) -#define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) -#if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) -#define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) -#define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) -#define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) +#define WP(p) ((uint32_t *)((unsigned long)(p) & ~3UL)) +#if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || \ + defined(__ppc64__)) +#define MUR_THREE_ONE(p) \ + ((((*WP(p)) & \ + 0x00ffffff) << 8) | (((*(WP(p) + 1)) & 0xff000000) >> 24)) +#define MUR_TWO_TWO(p) \ + ((((*WP(p)) & \ + 0x0000ffff) << 16) | (((*(WP(p) + 1)) & 0xffff0000) >> 16)) +#define MUR_ONE_THREE(p) \ + ((((*WP(p)) & \ + 0x000000ff) << 24) | (((*(WP(p) + 1)) & 0xffffff00) >> 8)) #else /* assume little endian non-intel */ -#define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) -#define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) -#define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) +#define MUR_THREE_ONE(p) \ + ((((*WP(p)) & \ + 0xffffff00) >> 8) | (((*(WP(p) + 1)) & 0x000000ff) << 24)) +#define MUR_TWO_TWO(p) \ + ((((*WP(p)) & \ + 0xffff0000) >> 16) | (((*(WP(p) + 1)) & 0x0000ffff) << 16)) +#define MUR_ONE_THREE(p) \ + ((((*WP(p)) & \ + 0xff000000) >> 24) | (((*(WP(p) + 1)) & 0x00ffffff) << 8)) #endif -#define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ - (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ - (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ - MUR_ONE_THREE(p)))) +#define MUR_GETBLOCK(p, i) \ + (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ + (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ + (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ + MUR_ONE_THREE(p)))) #endif -#define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) -#define MUR_FMIX(_h) \ -do { \ - _h ^= _h >> 16; \ - _h *= 0x85ebca6b; \ - _h ^= _h >> 13; \ - _h *= 0xc2b2ae35l; \ - _h ^= _h >> 16; \ -} while(0) +#define MUR_ROTL32(x, r) (((x) << (r)) | ((x) >> (32 - (r)))) +#define MUR_FMIX(_h) \ + do { \ + _h ^= _h >> 16; \ + _h *= 0x85ebca6b; \ + _h ^= _h >> 13; \ + _h *= 0xc2b2ae35l; \ + _h ^= _h >> 16; \ + } while (0) -#define HASH_MUR(key,keylen,num_bkts,hashv,bkt) \ -do { \ - const uint8_t *_mur_data = (const uint8_t*)(key); \ - const int _mur_nblocks = (keylen) / 4; \ - uint32_t _mur_h1 = 0xf88D5353; \ - uint32_t _mur_c1 = 0xcc9e2d51; \ - uint32_t _mur_c2 = 0x1b873593; \ - uint32_t _mur_k1 = 0; \ - const uint8_t *_mur_tail; \ - const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+_mur_nblocks*4); \ - int _mur_i; \ - for(_mur_i = -_mur_nblocks; _mur_i; _mur_i++) { \ - _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ - _mur_k1 *= _mur_c1; \ - _mur_k1 = MUR_ROTL32(_mur_k1,15); \ - _mur_k1 *= _mur_c2; \ - \ - _mur_h1 ^= _mur_k1; \ - _mur_h1 = MUR_ROTL32(_mur_h1,13); \ - _mur_h1 = _mur_h1*5+0xe6546b64; \ - } \ - _mur_tail = (const uint8_t*)(_mur_data + _mur_nblocks*4); \ - _mur_k1=0; \ - switch((keylen) & 3) { \ - case 3: _mur_k1 ^= _mur_tail[2] << 16; \ - case 2: _mur_k1 ^= _mur_tail[1] << 8; \ - case 1: _mur_k1 ^= _mur_tail[0]; \ - _mur_k1 *= _mur_c1; \ - _mur_k1 = MUR_ROTL32(_mur_k1,15); \ - _mur_k1 *= _mur_c2; \ - _mur_h1 ^= _mur_k1; \ - } \ - _mur_h1 ^= (keylen); \ - MUR_FMIX(_mur_h1); \ - hashv = _mur_h1; \ - bkt = hashv & (num_bkts-1); \ -} while(0) +#define HASH_MUR(key, keylen, num_bkts, hashv, bkt) \ + do { \ + const uint8_t *_mur_data = (const uint8_t *)(key); \ + const int _mur_nblocks = (keylen) / 4; \ + uint32_t _mur_h1 = 0xf88D5353; \ + uint32_t _mur_c1 = 0xcc9e2d51; \ + uint32_t _mur_c2 = 0x1b873593; \ + uint32_t _mur_k1 = 0; \ + const uint8_t *_mur_tail; \ + const uint32_t *_mur_blocks = \ + (const uint32_t *)(_mur_data + _mur_nblocks * 4); \ + int _mur_i; \ + for (_mur_i = -_mur_nblocks; _mur_i; _mur_i++) { \ + _mur_k1 = MUR_GETBLOCK(_mur_blocks, _mur_i); \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1, 15); \ + _mur_k1 *= _mur_c2; \ + \ + _mur_h1 ^= _mur_k1; \ + _mur_h1 = MUR_ROTL32(_mur_h1, 13); \ + _mur_h1 = _mur_h1 * 5 + 0xe6546b64; \ + } \ + _mur_tail = (const uint8_t *)(_mur_data + _mur_nblocks * 4); \ + _mur_k1 = 0; \ + switch ((keylen) & 3) { \ + case 3: _mur_k1 ^= _mur_tail[2] << 16; \ + case 2: _mur_k1 ^= _mur_tail[1] << 8; \ + case 1: _mur_k1 ^= _mur_tail[0]; \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1, 15); \ + _mur_k1 *= _mur_c2; \ + _mur_h1 ^= _mur_k1; \ + } \ + _mur_h1 ^= (keylen); \ + MUR_FMIX(_mur_h1); \ + hashv = _mur_h1; \ + bkt = hashv & (num_bkts - 1); \ + } while (0) #endif /* HASH_USING_NO_STRICT_ALIASING */ /* key comparison function; return 0 if keys equal */ -#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) +#define HASH_KEYCMP(a, b, len) memcmp(a, b, len) /* iterate over items in a known bucket to find desired item */ -#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ -do { \ - if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ - else out=NULL; \ - while (out) { \ - if ((out)->hh.keylen == keylen_in) { \ - if ((HASH_KEYCMP((out)->hh.key,keyptr,keylen_in)) == 0) break; \ - } \ - if ((out)->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,(out)->hh.hh_next)); \ - else out = NULL; \ - } \ -} while(0) +#define HASH_FIND_IN_BKT(tbl, hh, head, keyptr, keylen_in, out) \ + do { \ + if (head.hh_head) { DECLTYPE_ASSIGN(out, \ + ELMT_FROM_HH(tbl, head.hh_head)); } \ + else { out = NULL; } \ + while (out) { \ + if ((out)->hh.keylen == keylen_in) { \ + if ((HASH_KEYCMP((out)->hh.key, keyptr, \ + keylen_in)) == 0) { break; } \ + } \ + if ((out)->hh.hh_next) { DECLTYPE_ASSIGN(out, \ + ELMT_FROM_HH(tbl, \ + (out)->hh. \ + hh_next)); } \ + else { out = NULL; } \ + } \ + } while (0) /* add an item to a bucket */ -#define HASH_ADD_TO_BKT(head,addhh) \ -do { \ - head.count++; \ - (addhh)->hh_next = head.hh_head; \ - (addhh)->hh_prev = NULL; \ - if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ - (head).hh_head=addhh; \ - if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ - && (addhh)->tbl->noexpand != 1) { \ - HASH_EXPAND_BUCKETS((addhh)->tbl); \ - } \ -} while(0) +#define HASH_ADD_TO_BKT(head, addhh) \ + do { \ + head.count++; \ + (addhh)->hh_next = head.hh_head; \ + (addhh)->hh_prev = NULL; \ + if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ + (head).hh_head = addhh; \ + if (head.count >= ((head.expand_mult + 1) * HASH_BKT_CAPACITY_THRESH) \ + && (addhh)->tbl->noexpand != 1) { \ + HASH_EXPAND_BUCKETS((addhh)->tbl); \ + } \ + } while (0) /* remove an item from a given bucket */ -#define HASH_DEL_IN_BKT(hh,head,hh_del) \ - (head).count--; \ - if ((head).hh_head == hh_del) { \ - (head).hh_head = hh_del->hh_next; \ - } \ - if (hh_del->hh_prev) { \ - hh_del->hh_prev->hh_next = hh_del->hh_next; \ - } \ - if (hh_del->hh_next) { \ - hh_del->hh_next->hh_prev = hh_del->hh_prev; \ +#define HASH_DEL_IN_BKT(hh, head, hh_del) \ + (head).count--; \ + if ((head).hh_head == hh_del) { \ + (head).hh_head = hh_del->hh_next; \ + } \ + if (hh_del->hh_prev) { \ + hh_del->hh_prev->hh_next = hh_del->hh_next; \ + } \ + if (hh_del->hh_next) { \ + hh_del->hh_next->hh_prev = hh_del->hh_prev; \ } /* Bucket expansion has the effect of doubling the number of buckets @@ -663,145 +696,171 @@ do { * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) * */ -#define HASH_EXPAND_BUCKETS(tbl) \ -do { \ - unsigned _he_bkt; \ - unsigned _he_bkt_i; \ - struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ - UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ - _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ - memset(_he_new_buckets, 0, \ - 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ - tbl->ideal_chain_maxlen = \ - (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ - ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ - tbl->nonideal_items = 0; \ - for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ - { \ - _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ - while (_he_thh) { \ - _he_hh_nxt = _he_thh->hh_next; \ - HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ - _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ - if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ - tbl->nonideal_items++; \ - _he_newbkt->expand_mult = _he_newbkt->count / \ - tbl->ideal_chain_maxlen; \ - } \ - _he_thh->hh_prev = NULL; \ - _he_thh->hh_next = _he_newbkt->hh_head; \ - if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ - _he_thh; \ - _he_newbkt->hh_head = _he_thh; \ - _he_thh = _he_hh_nxt; \ - } \ - } \ - uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ - tbl->num_buckets *= 2; \ - tbl->log2_num_buckets++; \ - tbl->buckets = _he_new_buckets; \ - tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ - (tbl->ineff_expands+1) : 0; \ - if (tbl->ineff_expands > 1) { \ - tbl->noexpand=1; \ - uthash_noexpand_fyi(tbl); \ - } \ - uthash_expand_fyi(tbl); \ -} while(0) +#define HASH_EXPAND_BUCKETS(tbl) \ + do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket *)uthash_malloc( \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ + memset(_he_new_buckets, 0, \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + tbl->ideal_chain_maxlen = \ + (tbl->num_items >> (tbl->log2_num_buckets + 1)) + \ + ((tbl->num_items & ((tbl->num_buckets * 2) - 1)) ? 1 : 0); \ + tbl->nonideal_items = 0; \ + for (_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ + { \ + _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ + while (_he_thh) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets * 2, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ + if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ + tbl->nonideal_items++; \ + _he_newbkt->expand_mult = _he_newbkt->count / \ + tbl->ideal_chain_maxlen; \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head) { _he_newbkt->hh_head->hh_prev = \ + _he_thh; } \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free( tbl->buckets, tbl->num_buckets * \ + sizeof(struct UT_hash_bucket) ); \ + tbl->num_buckets *= 2; \ + tbl->log2_num_buckets++; \ + tbl->buckets = _he_new_buckets; \ + tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ + (tbl->ineff_expands + 1) : 0; \ + if (tbl->ineff_expands > 1) { \ + tbl->noexpand = 1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ + } while (0) /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ /* Note that HASH_SORT assumes the hash handle name to be hh. * HASH_SRT was added to allow the hash handle name to be passed in. */ -#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) -#define HASH_SRT(hh,head,cmpfcn) \ -do { \ - unsigned _hs_i; \ - unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ - struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ - if (head) { \ - _hs_insize = 1; \ - _hs_looping = 1; \ - _hs_list = &((head)->hh); \ - while (_hs_looping) { \ - _hs_p = _hs_list; \ - _hs_list = NULL; \ - _hs_tail = NULL; \ - _hs_nmerges = 0; \ - while (_hs_p) { \ - _hs_nmerges++; \ - _hs_q = _hs_p; \ - _hs_psize = 0; \ - for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ - _hs_psize++; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - if (! (_hs_q) ) break; \ - } \ - _hs_qsize = _hs_insize; \ - while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ - if (_hs_psize == 0) { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ - _hs_e = _hs_p; \ - if (_hs_p){ \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - } \ - _hs_psize--; \ - } else if (( \ - cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ - DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ - ) <= 0) { \ - _hs_e = _hs_p; \ - if (_hs_p){ \ - _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ - ((void*)((char*)(_hs_p->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - } \ - _hs_psize--; \ - } else { \ - _hs_e = _hs_q; \ - _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ - ((void*)((char*)(_hs_q->next) + \ - (head)->hh.tbl->hho)) : NULL); \ - _hs_qsize--; \ - } \ - if ( _hs_tail ) { \ - _hs_tail->next = ((_hs_e) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ - } else { \ - _hs_list = _hs_e; \ - } \ - if (_hs_e) { \ - _hs_e->prev = ((_hs_tail) ? \ - ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ - } \ - _hs_tail = _hs_e; \ - } \ - _hs_p = _hs_q; \ - } \ - if (_hs_tail){ \ - _hs_tail->next = NULL; \ - } \ - if ( _hs_nmerges <= 1 ) { \ - _hs_looping=0; \ - (head)->hh.tbl->tail = _hs_tail; \ - DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ - } \ - _hs_insize *= 2; \ - } \ - HASH_FSCK(hh,head); \ - } \ -} while (0) +#define HASH_SORT(head, cmpfcn) HASH_SRT(hh, head, cmpfcn) +#define HASH_SRT(hh, head, cmpfcn) \ + do { \ + unsigned _hs_i; \ + unsigned _hs_looping, _hs_nmerges, _hs_insize, _hs_psize, _hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for (_hs_i = 0; _hs_i < _hs_insize; _hs_i++) { \ + _hs_psize++; \ + _hs_q = (UT_hash_handle *)((_hs_q->next) ? \ + ((void *)((char *)(_hs_q-> \ + next) + \ + (head)->hh.tbl->hho)) \ + : NULL); \ + if (!(_hs_q) ) { break; } \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ + if (_hs_psize == 0) { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle *)((_hs_q->next) ? \ + ((void *)((char *)(_hs_q \ + ->next) \ + + \ + (head)->hh.tbl \ + ->hho)) : NULL); \ + _hs_qsize--; \ + } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ + _hs_e = _hs_p; \ + if (_hs_p) { \ + _hs_p = (UT_hash_handle *)((_hs_p->next) ? \ + ((void *)((char *)( \ + _hs_p-> \ + next) + \ + (head)->hh. \ + tbl->hho)) \ + : NULL); \ + } \ + _hs_psize--; \ + } else if (( \ + cmpfcn(DECLTYPE(head) (ELMT_FROM_HH((head) \ + ->hh. \ + tbl, \ + _hs_p)), \ + DECLTYPE(head) (ELMT_FROM_HH((head) \ + ->hh. \ + tbl, \ + _hs_q))) \ + ) <= 0) { \ + _hs_e = _hs_p; \ + if (_hs_p) { \ + _hs_p = (UT_hash_handle *)((_hs_p->next) ? \ + ((void *)((char *)( \ + _hs_p-> \ + next) + \ + (head)->hh. \ + tbl->hho)) \ + : NULL); \ + } \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle *)((_hs_q->next) ? \ + ((void *)((char *)(_hs_q \ + ->next) \ + + \ + (head)->hh.tbl \ + ->hho)) : NULL); \ + _hs_qsize--; \ + } \ + if (_hs_tail) { \ + _hs_tail->next = ((_hs_e) ? \ + ELMT_FROM_HH((head)->hh.tbl, \ + _hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + if (_hs_e) { \ + _hs_e->prev = ((_hs_tail) ? \ + ELMT_FROM_HH((head)->hh.tbl, \ + _hs_tail) : NULL); \ + } \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + if (_hs_tail) { \ + _hs_tail->next = NULL; \ + } \ + if (_hs_nmerges <= 1) { \ + _hs_looping = 0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head, \ + ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2; \ + } \ + HASH_FSCK(hh, head); \ + } \ + } while (0) /* This function selects items from one hash into another hash. * The end result is that the selected items have dual presence @@ -809,76 +868,82 @@ do { * they are added into the new hash through a secondary hash * hash handle that must be present in the structure. */ #define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ -do { \ - unsigned _src_bkt, _dst_bkt; \ - void *_last_elt=NULL, *_elt; \ - UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ - ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ - if (src) { \ - for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ - for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ - _src_hh; \ - _src_hh = _src_hh->hh_next) { \ - _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ - if (cond(_elt)) { \ - _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ - _dst_hh->key = _src_hh->key; \ - _dst_hh->keylen = _src_hh->keylen; \ - _dst_hh->hashv = _src_hh->hashv; \ - _dst_hh->prev = _last_elt; \ - _dst_hh->next = NULL; \ - if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ - if (!dst) { \ - DECLTYPE_ASSIGN(dst,_elt); \ - HASH_MAKE_TABLE(hh_dst,dst); \ - } else { \ - _dst_hh->tbl = (dst)->hh_dst.tbl; \ + do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt = NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh = NULL; \ + ptrdiff_t _dst_hho = ((char *)(&(dst)->hh_dst) - (char *)(dst)); \ + if (src) { \ + for (_src_bkt = 0; _src_bkt < (src)->hh_src.tbl->num_buckets; \ + _src_bkt++) { \ + for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ + _src_hh; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + _dst_hh = (UT_hash_handle *)(((char *)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ + if (!dst) { \ + DECLTYPE_ASSIGN(dst, _elt); \ + HASH_MAKE_TABLE(hh_dst, dst); \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, \ + _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], \ + _dst_hh); \ + (dst)->hh_dst.tbl->num_items++; \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ } \ - HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ - HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ - (dst)->hh_dst.tbl->num_items++; \ - _last_elt = _elt; \ - _last_elt_hh = _dst_hh; \ - } \ - } \ - } \ - } \ - HASH_FSCK(hh_dst,dst); \ -} while (0) + } \ + HASH_FSCK(hh_dst, dst); \ + } while (0) -#define HASH_CLEAR(hh,head) \ -do { \ - if (head) { \ - uthash_free((head)->hh.tbl->buckets, \ - (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ - HASH_BLOOM_FREE((head)->hh.tbl); \ - uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ - (head)=NULL; \ - } \ -} while(0) +#define HASH_CLEAR(hh, head) \ + do { \ + if (head) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets * \ + sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head) = NULL; \ + } \ + } while (0) -#define HASH_OVERHEAD(hh,head) \ - (size_t)((((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ - ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ - (sizeof(UT_hash_table)) + \ - (HASH_BLOOM_BYTELEN))) +#define HASH_OVERHEAD(hh, head) \ + (size_t)((((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ + ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ + (sizeof(UT_hash_table)) + \ + (HASH_BLOOM_BYTELEN))) #ifdef NO_DECLTYPE -#define HASH_ITER(hh,head,el,tmp) \ -for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ - el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) +#define HASH_ITER(hh, head, el, tmp) \ + for ((el) = (head), \ + (*(char **)(&(tmp))) = (char *)((head) ? (head)->hh.next : NULL); \ + el; \ + (el) = (tmp), (*(char **)(&(tmp))) = \ + (char *)((tmp) ? (tmp)->hh.next : NULL)) #else -#define HASH_ITER(hh,head,el,tmp) \ -for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ - el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL)) +#define HASH_ITER(hh, head, el, tmp) \ + for ((el) = (head), (tmp) = DECLTYPE(el) ((head) ? (head)->hh.next : NULL); \ + el; (el) = (tmp), (tmp) = DECLTYPE(el) ((tmp) ? (tmp)->hh.next : NULL)) #endif /* obtain a count of items in the hash */ -#define HASH_COUNT(head) HASH_CNT(hh,head) -#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0) +#define HASH_COUNT(head) HASH_CNT(hh, head) +#define HASH_CNT(hh, head) ((head) ? ((head)->hh.tbl->num_items) : 0) -typedef struct UT_hash_bucket -{ +typedef struct UT_hash_bucket { struct UT_hash_handle *hh_head; unsigned count; @@ -902,13 +967,12 @@ typedef struct UT_hash_bucket #define HASH_SIGNATURE 0xa0111fe1 #define HASH_BLOOM_SIGNATURE 0xb12220f2 -typedef struct UT_hash_table -{ +typedef struct UT_hash_table { UT_hash_bucket *buckets; unsigned num_buckets, log2_num_buckets; unsigned num_items; struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ - ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ /* in an ideal situation (all buckets used equally), no bucket would have * more than ceil(#items/#buckets) items. that's the ideal chain length. */ @@ -936,8 +1000,7 @@ typedef struct UT_hash_table } UT_hash_table; -typedef struct UT_hash_handle -{ +typedef struct UT_hash_handle { struct UT_hash_table *tbl; void *prev; /* prev element in app order */ void *next; /* next element in app order */ diff --git a/src/utils.c b/src/utils.c index 82438edd..a3fcadf1 100644 --- a/src/utils.c +++ b/src/utils.c @@ -42,10 +42,10 @@ #include #endif -#define INT_DIGITS 19 /* enough for 64 bit integer */ +#define INT_DIGITS 19 /* enough for 64 bit integer */ #ifdef LIB_ONLY -FILE* logfile; +FILE * logfile; #endif #ifdef HAS_SYSLOG @@ -69,25 +69,18 @@ char *itoa(int i) { /* Room for INT_DIGITS digits, - and '\0' */ static char buf[INT_DIGITS + 2]; - char *p = buf + INT_DIGITS + 1; /* points to terminating '\0' */ - if (i >= 0) - { - do - { + char *p = buf + INT_DIGITS + 1; /* points to terminating '\0' */ + if (i >= 0) { + do { *--p = '0' + (i % 10); i /= 10; - } - while (i != 0); + } while (i != 0); return p; - } - else /* i < 0 */ - { - do - { + } else { /* i < 0 */ + do { *--p = '0' - (i % 10); i /= 10; - } - while (i != 0); + } while (i != 0); *--p = '-'; } return p; @@ -99,52 +92,49 @@ char *itoa(int i) int run_as(const char *user) { #ifndef __MINGW32__ - if (user[0]) - { + if (user[0]) { #ifdef HAVE_GETPWNAM_R struct passwd pwdbuf, *pwd; size_t buflen; int err; - for (buflen = 128;; buflen *= 2) - { + for (buflen = 128;; buflen *= 2) { char buf[buflen]; /* variable length array */ /* Note that we use getpwnam_r() instead of getpwnam(), which returns its result in a statically allocated buffer and cannot be considered thread safe. */ err = getpwnam_r(user, &pwdbuf, buf, buflen, &pwd); - if(err == 0 && pwd) - { + if (err == 0 && pwd) { /* setgid first, because we may not be allowed to do it anymore after setuid */ - if (setgid(pwd->pw_gid) != 0) - { - LOGE("Could not change group id to that of run_as user '%s': %s", - user,strerror(errno)); + if (setgid(pwd->pw_gid) != 0) { + LOGE( + "Could not change group id to that of run_as user '%s': %s", + user, strerror(errno)); return 0; } - if (setuid(pwd->pw_uid) != 0) - { - LOGE("Could not change user id to that of run_as user '%s': %s", - user,strerror(errno)); + if (setuid(pwd->pw_uid) != 0) { + LOGE( + "Could not change user id to that of run_as user '%s': %s", + user, strerror(errno)); return 0; } break; - } - else if (err != ERANGE) - { - if(err) - LOGE("run_as user '%s' could not be found: %s",user,strerror(err)); - else - LOGE("run_as user '%s' could not be found.",user); + } else if (err != ERANGE) { + if (err) { + LOGE("run_as user '%s' could not be found: %s", user, strerror( + err)); + } else { + LOGE("run_as user '%s' could not be found.", user); + } return 0; - } - else if (buflen >= 16*1024) - { + } else if (buflen >= 16 * 1024) { /* If getpwnam_r() seems defective, call it quits rather than keep on allocating ever larger buffers until we crash. */ - LOGE("getpwnam_r() requires more than %u bytes of buffer space.",(unsigned)buflen); + LOGE( + "getpwnam_r() requires more than %u bytes of buffer space.", + (unsigned)buflen); return 0; } /* Else try again with larger buffer. */ @@ -153,22 +143,19 @@ int run_as(const char *user) /* No getpwnam_r() :-( We'll use getpwnam() and hope for the best. */ struct passwd *pwd; - if (!(pwd=getpwnam(user))) - { - LOGE("run_as user %s could not be found.",user); + if (!(pwd = getpwnam(user))) { + LOGE("run_as user %s could not be found.", user); return 0; } /* setgid first, because we may not allowed to do it anymore after setuid */ - if (setgid(pwd->pw_gid) != 0) - { + if (setgid(pwd->pw_gid) != 0) { LOGE("Could not change group id to that of run_as user '%s': %s", - user,strerror(errno)); + user, strerror(errno)); return 0; } - if (setuid(pwd->pw_uid) != 0) - { + if (setuid(pwd->pw_uid) != 0) { LOGE("Could not change user id to that of run_as user '%s': %s", - user,strerror(errno)); + user, strerror(errno)); return 0; } #endif @@ -185,7 +172,9 @@ char *ss_strndup(const char *s, size_t n) size_t len = strlen(s); char *ret; - if (len <= n) return strdup(s); + if (len <= n) { + return strdup(s); + } ret = malloc(n + 1); strncpy(ret, s, n); @@ -203,21 +192,31 @@ void usage() { printf("\n"); printf("shadowsocks-libev %s\n\n", VERSION); - printf(" maintained by Max Lv and Linus Yang \n\n"); + printf( + " maintained by Max Lv and Linus Yang \n\n"); printf(" usage:\n\n"); printf(" ss-[local|redir|server|tunnel]\n"); printf("\n"); - printf(" -s host name or ip address of your remote server\n"); - printf(" -p port number of your remote server\n"); - printf(" -l port number of your local server\n"); - printf(" -k password of your remote server\n"); + printf( + " -s host name or ip address of your remote server\n"); + printf( + " -p port number of your remote server\n"); + printf( + " -l port number of your local server\n"); + printf( + " -k password of your remote server\n"); printf("\n"); printf("\n"); - printf(" [-m ] encrypt method: table, rc4, rc4-md5,\n"); - printf(" aes-128-cfb, aes-192-cfb, aes-256-cfb,\n"); - printf(" bf-cfb, camellia-128-cfb, camellia-192-cfb,\n"); - printf(" camellia-256-cfb, cast5-cfb, des-cfb,\n"); - printf(" idea-cfb, rc2-cfb and seed-cfb\n"); + printf( + " [-m ] encrypt method: table, rc4, rc4-md5,\n"); + printf( + " aes-128-cfb, aes-192-cfb, aes-256-cfb,\n"); + printf( + " bf-cfb, camellia-128-cfb, camellia-192-cfb,\n"); + printf( + " camellia-256-cfb, cast5-cfb, des-cfb,\n"); + printf( + " idea-cfb, rc2-cfb and seed-cfb\n"); printf(" [-f ] file to store the pid\n"); printf(" [-t ] socket timeout in seconds\n"); printf(" [-c ] config file in json\n"); @@ -229,18 +228,22 @@ void usage() printf(" not available in server mode\n"); printf(" [-u] enable udprelay mode\n"); printf(" not available in redir mode\n"); - printf(" [-L :] setup a local port forwarding tunnel,\n"); - printf(" only available in tunnel mode\n"); + printf( + " [-L :] setup a local port forwarding tunnel,\n"); + printf( + " only available in tunnel mode\n"); printf(" [-v] verbose mode\n"); printf("\n"); printf("\n"); printf(" [--fast-open] enable TCP fast open,\n"); - printf(" only available on Linux kernel > 3.7.0\n"); - printf(" [--acl ] config file of ACL (Access Control List)\n"); + printf( + " only available on Linux kernel > 3.7.0\n"); + printf( + " [--acl ] config file of ACL (Access Control List)\n"); printf("\n"); } -void daemonize(const char* path) +void daemonize(const char * path) { #ifndef __MINGW32__ /* Our process ID and Session ID */ @@ -248,17 +251,17 @@ void daemonize(const char* path) /* Fork off the parent process */ pid = fork(); - if (pid < 0) - { + if (pid < 0) { exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ - if (pid > 0) - { + if (pid > 0) { FILE *file = fopen(path, "w"); - if (file == NULL) FATAL("Invalid pid file\n"); + if (file == NULL) { + FATAL("Invalid pid file\n"); + } fprintf(file, "%d", pid); fclose(file); @@ -272,15 +275,13 @@ void daemonize(const char* path) /* Create a new SID for the child process */ sid = setsid(); - if (sid < 0) - { + if (sid < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Change the current working directory */ - if ((chdir("/")) < 0) - { + if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } @@ -295,27 +296,21 @@ void daemonize(const char* path) #ifdef HAVE_SETRLIMIT int set_nofile(int nofile) { - struct rlimit limit = {nofile, nofile}; /* set both soft and hard limit */ + struct rlimit limit = { nofile, nofile }; /* set both soft and hard limit */ - if (nofile <= 0) - { + if (nofile <= 0) { FATAL("nofile must be greater than 0\n"); } - if (setrlimit(RLIMIT_NOFILE, &limit) < 0) - { - if (errno == EPERM) - { - LOGE("insufficient permission to change NOFILE, not starting as root?"); + if (setrlimit(RLIMIT_NOFILE, &limit) < 0) { + if (errno == EPERM) { + LOGE( + "insufficient permission to change NOFILE, not starting as root?"); return -1; - } - else if (errno == EINVAL) - { + } else if (errno == EINVAL) { LOGE("invalid nofile, decrease nofile and try again"); return -1; - } - else - { + } else { LOGE("setrlimit failed: %s", strerror(errno)); return -1; } diff --git a/src/utils.h b/src/utils.h index 748295fd..bd794511 100644 --- a/src/utils.h +++ b/src/utils.h @@ -34,8 +34,12 @@ #include #define USE_SYSLOG(ident) -#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, "shadowsocks", __VA_ARGS__)) -#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "shadowsocks", __VA_ARGS__)) +#define LOGD(...) \ + ((void)__android_log_print(ANDROID_LOG_DEBUG, "shadowsocks", \ + __VA_ARGS__)) +#define LOGE(...) \ + ((void)__android_log_print(ANDROID_LOG_ERROR, "shadowsocks", \ + __VA_ARGS__)) #else @@ -44,39 +48,44 @@ #ifdef LIB_ONLY -extern FILE* logfile; +extern FILE * logfile; #define TIME_FORMAT "%Y-%m-%d %H:%M:%S" #define USE_SYSLOG(ident) -#define USE_LOGFILE(ident) do {\ - if (ident != NULL) logfile = fopen(ident, "w+");}\ -while(0) +#define USE_LOGFILE(ident) \ + do { \ + if (ident != NULL) { logfile = fopen(ident, "w+"); } } \ + while (0) -#define CLOSE_LOGFILE do {\ - if (logfile != NULL) fclose(logfile);}\ -while(0) +#define CLOSE_LOGFILE \ + do { \ + if (logfile != NULL) { fclose(logfile); } } \ + while (0) -#define LOGD(format, ...) do {\ - if (logfile != NULL) {\ - time_t now = time(NULL);\ - char timestr[20];\ - strftime(timestr, 20, TIME_FORMAT, localtime(&now));\ - fprintf(logfile, " %s INFO: " format "\n", timestr, ##__VA_ARGS__);\ - fflush(logfile);}\ - }\ -while(0) +#define LOGD(format, ...) \ + do { \ + if (logfile != NULL) { \ + time_t now = time(NULL); \ + char timestr[20]; \ + strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ + fprintf(logfile, " %s INFO: " format "\n", timestr, ## __VA_ARGS__); \ + fflush(logfile); } \ + } \ + while (0) -#define LOGE(format, ...) do {\ - if (logfile != NULL) {\ - time_t now = time(NULL);\ - char timestr[20];\ - strftime(timestr, 20, TIME_FORMAT, localtime(&now));\ - fprintf(logfile, " %s ERROR: " format "\n", timestr, ##__VA_ARGS__);\ - fflush(logfile);}\ - }\ -while(0) +#define LOGE(format, ...) \ + do { \ + if (logfile != NULL) { \ + time_t now = time(NULL); \ + char timestr[20]; \ + strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ + fprintf(logfile, " %s ERROR: " format "\n", timestr, \ + ## __VA_ARGS__); \ + fflush(logfile); } \ + } \ + while (0) #elif defined(_WIN32) @@ -84,19 +93,21 @@ while(0) #define USE_SYSLOG(ident) -#define LOGD(format, ...) do {\ - time_t now = time(NULL);\ - char timestr[20];\ - strftime(timestr, 20, TIME_FORMAT, localtime(&now));\ - fprintf(stderr, " %s INFO: " format "\n", timestr, ##__VA_ARGS__);}\ -while(0) +#define LOGD(format, ...) \ + do { \ + time_t now = time(NULL); \ + char timestr[20]; \ + strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ + fprintf(stderr, " %s INFO: " format "\n", timestr, ## __VA_ARGS__); } \ + while (0) -#define LOGE(format, ...) do {\ - time_t now = time(NULL);\ - char timestr[20];\ - strftime(timestr, 20, TIME_FORMAT, localtime(&now));\ - fprintf(stderr, " %s ERROR: " format "\n", timestr, ##__VA_ARGS__);}\ -while(0) +#define LOGE(format, ...) \ + do { \ + time_t now = time(NULL); \ + char timestr[20]; \ + strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ + fprintf(stderr, " %s ERROR: " format "\n", timestr, ## __VA_ARGS__); } \ + while (0) #else @@ -107,32 +118,37 @@ extern int use_syslog; #define TIME_FORMAT "%F %T" -#define USE_SYSLOG(ident) do {\ - use_syslog = 1;\ - openlog((ident), LOG_CONS | LOG_PID, 0);}\ -while(0) +#define USE_SYSLOG(ident) \ + do { \ + use_syslog = 1; \ + openlog((ident), LOG_CONS | LOG_PID, 0); } \ + while (0) -#define LOGD(format, ...) do {\ - if (use_syslog) {\ - syslog(LOG_INFO, format, ##__VA_ARGS__);\ - } else {\ - time_t now = time(NULL);\ - char timestr[20];\ - strftime(timestr, 20, TIME_FORMAT, localtime(&now));\ - fprintf(stderr, "\e[01;32m %s INFO: \e[0m" format "\n", timestr, ##__VA_ARGS__);\ - }}\ -while(0) +#define LOGD(format, ...) \ + do { \ + if (use_syslog) { \ + syslog(LOG_INFO, format, ## __VA_ARGS__); \ + } else { \ + time_t now = time(NULL); \ + char timestr[20]; \ + strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ + fprintf(stderr, "\e[01;32m %s INFO: \e[0m" format "\n", timestr, \ + ## __VA_ARGS__); \ + } } \ + while (0) -#define LOGE(format, ...) do {\ - if (use_syslog) {\ - syslog(LOG_ERR, format, ##__VA_ARGS__);\ - } else {\ - time_t now = time(NULL);\ - char timestr[20];\ - strftime(timestr, 20, TIME_FORMAT, localtime(&now));\ - fprintf(stderr, "\e[01;35m %s ERROR: \e[0m" format "\n", timestr, ##__VA_ARGS__);\ - }}\ -while(0) +#define LOGE(format, ...) \ + do { \ + if (use_syslog) { \ + syslog(LOG_ERR, format, ## __VA_ARGS__); \ + } else { \ + time_t now = time(NULL); \ + char timestr[20]; \ + strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ + fprintf(stderr, "\e[01;35m %s ERROR: \e[0m" format "\n", timestr, \ + ## __VA_ARGS__); \ + } } \ + while (0) #endif /* _WIN32 */ @@ -158,7 +174,7 @@ char *itoa(int i); int run_as(const char *user); void FATAL(const char *msg); void usage(void); -void daemonize(const char* path); +void daemonize(const char * path); char *ss_strndup(const char *s, size_t n); #ifdef HAVE_SETRLIMIT int set_nofile(int nofile); diff --git a/src/win32.c b/src/win32.c index 1aba91bd..570bd4fe 100644 --- a/src/win32.c +++ b/src/win32.c @@ -33,12 +33,10 @@ void winsock_init(void) int ret; wVersionRequested = MAKEWORD(1, 1); ret = WSAStartup(wVersionRequested, &wsaData); - if (ret != 0) - { + if (ret != 0) { FATAL("Could not initialize winsock"); } - if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) - { + if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { WSACleanup(); FATAL("Could not find a usable version of winsock"); } @@ -52,12 +50,12 @@ void winsock_cleanup(void) void ss_error(const char *s) { LPVOID *msg = NULL; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, WSAGetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR) &msg, 0, NULL); - if (msg != NULL) - { + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, WSAGetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR)&msg, 0, NULL); + if (msg != NULL) { LOGE("%s: %s", s, (char *)msg); LocalFree(msg); } @@ -68,8 +66,7 @@ int setnonblocking(int fd) u_long iMode = 0; long int iResult; iResult = ioctlsocket(fd, FIONBIO, &iMode); - if (iResult != NO_ERROR) - { + if (iResult != NO_ERROR) { LOGE("ioctlsocket failed with error: %ld\n", iResult); } return iResult; @@ -78,7 +75,7 @@ int setnonblocking(int fd) size_t strnlen(const char *s, size_t maxlen) { const char *end = memchr(s, 0, maxlen); - return end ? (size_t) (end - s) : maxlen; + return end ? (size_t)(end - s) : maxlen; } const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) @@ -87,8 +84,7 @@ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) unsigned long s = size; ZeroMemory(&ss, sizeof(ss)); ss.ss_family = af; - switch (af) - { + switch (af) { case AF_INET: ((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src; break; @@ -98,5 +94,6 @@ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) default: return NULL; } - return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst, &s) == 0) ? dst : NULL; + return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst, + &s) == 0) ? dst : NULL; } diff --git a/src/win32.h b/src/win32.h index 3508b2ff..e5a92733 100644 --- a/src/win32.h +++ b/src/win32.h @@ -49,7 +49,7 @@ #define errno WSAGetLastError() #define close(fd) closesocket(fd) #define ERROR(s) ss_error(s) -#define setsockopt(a, b, c, d, e) setsockopt(a, b, c, (char *) (d), e) +#define setsockopt(a, b, c, d, e) setsockopt(a, b, c, (char *)(d), e) void winsock_init(void); void winsock_cleanup(void);