pax_global_header00006660000000000000000000000064132032627630014516gustar00rootroot0000000000000052 comment=a9c43588e4cb038e6ac02f050e4cab81f8228dff simple-obfs-0.0.5/000077500000000000000000000000001320326276300137405ustar00rootroot00000000000000simple-obfs-0.0.5/.gitignore000066400000000000000000000016221320326276300157310ustar00rootroot00000000000000# Ignore files generated by autoconf Makefile.in aclocal.m4 auto/ config.h.in configure doc/Makefile.in m4/libtool.m4 m4/ltoptions.m4 m4/ltsugar.m4 m4/ltversion.m4 m4/lt~obsolete.m4 src/Makefile.in # Ignore files generated by configure build/ .deps/ /Makefile src/Makefile libev/Makefile libudns/Makefile libcork/Makefile libipset/Makefile doc/Makefile autom4te.cache/ /config.h config.log config.status libtool pid src/obfs-* stamp-h1 .libs .pc .dirstamp libsodium/src/libsodium/include/sodium/version.h # Ignore per-project vim config .vimrc # Ignore garbage of OS X *.DS_Store # Ignore vim cache *.swp # Documentation files doc/*.1 doc/*.8 doc/*.gz doc/*.xml doc/*.html # Do not edit the following section # Edit Compile Debug Document Distribute *~ *.bak *.bin *.dll *.exe *-ISO*.bdf *-JIS*.bdf *-KOI8*.bdf *.kld *.ko *.ko.cmd *.lai *.l[oa] *.[oa] *.obj *.patch *.so *.pcf.gz *.pdb *.tar.bz2 *.tar.gz # simple-obfs-0.0.5/.gitmodules000066400000000000000000000001531320326276300161140ustar00rootroot00000000000000[submodule "libcork"] path = libcork url = https://github.com/shadowsocks/libcork.git ignore = dirty simple-obfs-0.0.5/.travis.yml000066400000000000000000000006631320326276300160560ustar00rootroot00000000000000{ "sudo": "required", "language": "c", "dist": "trusty", "before_script": [ "sudo apt-get install --no-install-recommends -y build-essential autoconf libtool libssl-dev libpcre3-dev libc-ares-dev libev-dev asciidoc xmlto automake", "git submodule update --init --recursive", "chmod +x *.sh", "./autogen.sh", "./configure && make" ], "script": "sudo make install", "group": "stable", "os": "linux" } simple-obfs-0.0.5/.uncrustify.cfg000066400000000000000000001700131320326276300167140ustar00rootroot00000000000000# # General options # # The type of line endings newlines = lf # auto/lf/crlf/cr # The original size of tabs in the input input_tab_size = 8 # number # The size of tabs in the output (only used if align_with_tabs=true) output_tab_size = 8 # number # The ASCII value of the string escape char, usually 92 (\) or 94 (^). (Pawn) string_escape_char = 92 # number # Alternate string escape char for Pawn. Only works right before the quote char. string_escape_char2 = 0 # number # # Indenting # # The number of columns to indent per level. # Usually 2, 3, 4, or 8. indent_columns = 4 # number # The continuation indent. If non-zero, this overrides the indent of '(' and '=' continuation indents. # For FreeBSD, this is set to 4. indent_continue = 0 # number # How to use tabs when indenting code # 0=spaces only # 1=indent with tabs to brace level, align with spaces # 2=indent and align with tabs, using spaces when not on a tabstop indent_with_tabs = 0 # number # Comments that are not a brace level are indented with tabs on a tabstop. # Requires indent_with_tabs=2. If false, will use spaces. indent_cmt_with_tabs = false # false/true # Whether to indent strings broken by '\' so that they line up indent_align_string = true # false/true # The number of spaces to indent multi-line XML strings. # Requires indent_align_string=True indent_xml_string = 0 # number # Spaces to indent '{' from level indent_brace = 0 # number # Whether braces are indented to the body level indent_braces = false # false/true # Disabled indenting function braces if indent_braces is true indent_braces_no_func = false # false/true # Disabled indenting class braces if indent_braces is true indent_braces_no_class = false # false/true # Disabled indenting struct braces if indent_braces is true indent_braces_no_struct = false # false/true # Indent based on the size of the brace parent, i.e. 'if' => 3 spaces, 'for' => 4 spaces, etc. indent_brace_parent = false # false/true # Whether the 'namespace' body is indented indent_namespace = false # false/true # The number of spaces to indent a namespace block indent_namespace_level = 0 # number # If the body of the namespace is longer than this number, it won't be indented. # Requires indent_namespace=true. Default=0 (no limit) indent_namespace_limit = 0 # number # Whether the 'extern "C"' body is indented indent_extern = false # false/true # Whether the 'class' body is indented indent_class = false # false/true # Whether to indent the stuff after a leading class colon indent_class_colon = false # false/true # False=treat 'else\nif' as 'else if' for indenting purposes # True=indent the 'if' one level indent_else_if = false # false/true # Amount to indent variable declarations after a open brace. neg=relative, pos=absolute indent_var_def_blk = 0 # number # Indent continued variable declarations instead of aligning. indent_var_def_cont = false # false/true # True: indent continued function call parameters one indent level # False: align parameters under the open paren indent_func_call_param = false # false/true # Same as indent_func_call_param, but for function defs indent_func_def_param = false # false/true # Same as indent_func_call_param, but for function protos indent_func_proto_param = false # false/true # Same as indent_func_call_param, but for class declarations indent_func_class_param = false # false/true # Same as indent_func_call_param, but for class variable constructors indent_func_ctor_var_param = false # false/true # Same as indent_func_call_param, but for templates indent_template_param = false # false/true # Double the indent for indent_func_xxx_param options indent_func_param_double = false # false/true # Indentation column for standalone 'const' function decl/proto qualifier indent_func_const = 0 # number # Indentation column for standalone 'throw' function decl/proto qualifier indent_func_throw = 0 # number # The number of spaces to indent a continued '->' or '.' # Usually set to 0, 1, or indent_columns. indent_member = 0 # number # Spaces to indent single line ('//') comments on lines before code indent_sing_line_comments = 0 # number # If set, will indent trailing single line ('//') comments relative # to the code instead of trying to keep the same absolute column indent_relative_single_line_comments = false # false/true # Spaces to indent 'case' from 'switch' # Usually 0 or indent_columns. indent_switch_case = 0 # number # Spaces to shift the 'case' line, without affecting any other lines # Usually 0. indent_case_shift = 0 # number # Spaces to indent '{' from 'case'. # By default, the brace will appear under the 'c' in case. # Usually set to 0 or indent_columns. indent_case_brace = 0 # number # Whether to indent comments found in first column indent_col1_comment = false # false/true # How to indent goto labels # >0 : absolute column where 1 is the leftmost column # <=0 : subtract from brace indent indent_label = 1 # number # Same as indent_label, but for access specifiers that are followed by a colon indent_access_spec = 1 # number # Indent the code after an access specifier by one level. # If set, this option forces 'indent_access_spec=0' indent_access_spec_body = false # false/true # If an open paren is followed by a newline, indent the next line so that it lines up after the open paren (not recommended) indent_paren_nl = false # false/true # Controls the indent of a close paren after a newline. # 0: Indent to body level # 1: Align under the open paren # 2: Indent to the brace level indent_paren_close = 0 # number # Controls the indent of a comma when inside a paren.If TRUE, aligns under the open paren indent_comma_paren = false # false/true # Controls the indent of a BOOL operator when inside a paren.If TRUE, aligns under the open paren indent_bool_paren = false # false/true # If 'indent_bool_paren' is true, controls the indent of the first expression. If TRUE, aligns the first expression to the following ones indent_first_bool_expr = false # false/true # If an open square is followed by a newline, indent the next line so that it lines up after the open square (not recommended) indent_square_nl = false # false/true # Don't change the relative indent of ESQL/C 'EXEC SQL' bodies indent_preserve_sql = false # false/true # Align continued statements at the '='. Default=True # If FALSE or the '=' is followed by a newline, the next line is indent one tab. indent_align_assign = true # false/true # # Spacing options # # Add or remove space around arithmetic operator '+', '-', '/', '*', etc sp_arith = force # ignore/add/remove/force # Add or remove space around assignment operator '=', '+=', etc sp_assign = force # ignore/add/remove/force # Add or remove space around assignment operator '=' in a prototype sp_assign_default = ignore # ignore/add/remove/force # Add or remove space before assignment operator '=', '+=', etc. Overrides sp_assign. sp_before_assign = ignore # ignore/add/remove/force # Add or remove space after assignment operator '=', '+=', etc. Overrides sp_assign. sp_after_assign = ignore # ignore/add/remove/force # Add or remove space around assignment '=' in enum sp_enum_assign = force # ignore/add/remove/force # Add or remove space before assignment '=' in enum. Overrides sp_enum_assign. sp_enum_before_assign = ignore # ignore/add/remove/force # Add or remove space after assignment '=' in enum. Overrides sp_enum_assign. sp_enum_after_assign = ignore # ignore/add/remove/force # Add or remove space around preprocessor '##' concatenation operator. Default=Add sp_pp_concat = add # ignore/add/remove/force # Add or remove space after preprocessor '#' stringify operator. Also affects the '#@' charizing operator. Default=Add sp_pp_stringify = add # ignore/add/remove/force # Add or remove space around boolean operators '&&' and '||' sp_bool = force # ignore/add/remove/force # Add or remove space around compare operator '<', '>', '==', etc sp_compare = force # ignore/add/remove/force # Add or remove space inside '(' and ')' sp_inside_paren = remove # ignore/add/remove/force # Add or remove space between nested parens sp_paren_paren = remove # ignore/add/remove/force # Whether to balance spaces inside nested parens sp_balance_nested_parens = false # false/true # Add or remove space between ')' and '{' sp_paren_brace = force # ignore/add/remove/force # Add or remove space before pointer star '*' sp_before_ptr_star = add # ignore/add/remove/force # Add or remove space before pointer star '*' that isn't followed by a variable name # If set to 'ignore', sp_before_ptr_star is used instead. sp_before_unnamed_ptr_star = add # ignore/add/remove/force # Add or remove space between pointer stars '*' sp_between_ptr_star = remove # ignore/add/remove/force # Add or remove space after pointer star '*', if followed by a word. sp_after_ptr_star = remove # ignore/add/remove/force # Add or remove space after a pointer star '*', if followed by a func proto/def. sp_after_ptr_star_func = remove # ignore/add/remove/force # Add or remove space before a pointer star '*', if followed by a func proto/def. sp_before_ptr_star_func = ignore # ignore/add/remove/force # Add or remove space before a reference sign '&' sp_before_byref = force # ignore/add/remove/force # Add or remove space before a reference sign '&' that isn't followed by a variable name # If set to 'ignore', sp_before_byref is used instead. sp_before_unnamed_byref = force # ignore/add/remove/force # Add or remove space after reference sign '&', if followed by a word. sp_after_byref = ignore # ignore/add/remove/force # Add or remove space after a reference sign '&', if followed by a func proto/def. sp_after_byref_func = ignore # ignore/add/remove/force # Add or remove space before a reference sign '&', if followed by a func proto/def. sp_before_byref_func = ignore # ignore/add/remove/force # Add or remove space between type and word. Default=Force sp_after_type = force # ignore/add/remove/force # Add or remove space in 'template <' vs 'template<'. # If set to ignore, sp_before_angle is used. sp_template_angle = ignore # ignore/add/remove/force # Add or remove space before '<>' sp_before_angle = ignore # ignore/add/remove/force # Add or remove space inside '<' and '>' sp_inside_angle = ignore # ignore/add/remove/force # Add or remove space after '<>' sp_after_angle = ignore # ignore/add/remove/force # Add or remove space between '<>' and '(' as found in 'new List();' sp_angle_paren = ignore # ignore/add/remove/force # Add or remove space between '<>' and a word as in 'List m;' sp_angle_word = ignore # ignore/add/remove/force # Add or remove space between '>' and '>' in '>>' (template stuff C++/C# only). Default=Add sp_angle_shift = add # ignore/add/remove/force # Add or remove space before '(' of 'if', 'for', 'switch', and 'while' sp_before_sparen = force # ignore/add/remove/force # Add or remove space inside if-condition '(' and ')' sp_inside_sparen = remove # ignore/add/remove/force # Add or remove space before if-condition ')'. Overrides sp_inside_sparen. sp_inside_sparen_close = ignore # ignore/add/remove/force # Add or remove space after ')' of 'if', 'for', 'switch', and 'while' sp_after_sparen = ignore # ignore/add/remove/force # Add or remove space between ')' and '{' of 'if', 'for', 'switch', and 'while' sp_sparen_brace = force # ignore/add/remove/force # Add or remove space between 'invariant' and '(' in the D language. sp_invariant_paren = ignore # ignore/add/remove/force # Add or remove space after the ')' in 'invariant (C) c' in the D language. sp_after_invariant_paren = ignore # ignore/add/remove/force # Add or remove space before empty statement ';' on 'if', 'for' and 'while' sp_special_semi = ignore # ignore/add/remove/force # Add or remove space before ';'. Default=Remove sp_before_semi = remove # ignore/add/remove/force # Add or remove space before ';' in non-empty 'for' statements sp_before_semi_for = ignore # ignore/add/remove/force # Add or remove space before a semicolon of an empty part of a for statement. sp_before_semi_for_empty = ignore # ignore/add/remove/force # Add or remove space after ';', except when followed by a comment. Default=Add sp_after_semi = force # ignore/add/remove/force # Add or remove space after ';' in non-empty 'for' statements. Default=Force sp_after_semi_for = force # ignore/add/remove/force # Add or remove space after the final semicolon of an empty part of a for statement: for ( ; ; ). sp_after_semi_for_empty = remove # ignore/add/remove/force # Add or remove space before '[' (except '[]') sp_before_square = remove # ignore/add/remove/force # Add or remove space before '[]' sp_before_squares = ignore # ignore/add/remove/force # Add or remove space inside '[' and ']' sp_inside_square = remove # ignore/add/remove/force # Add or remove space after ',' sp_after_comma = force # ignore/add/remove/force # Add or remove space before ',' sp_before_comma = remove # ignore/add/remove/force # Add or remove space between an open paren and comma: '(,' vs '( ,' sp_paren_comma = force # ignore/add/remove/force # Add or remove space before the variadic '...' when preceded by a non-punctuator sp_before_ellipsis = ignore # ignore/add/remove/force # Add or remove space after class ':' sp_after_class_colon = ignore # ignore/add/remove/force # Add or remove space before class ':' sp_before_class_colon = ignore # ignore/add/remove/force # Add or remove space before case ':'. Default=Remove sp_before_case_colon = remove # ignore/add/remove/force # Add or remove space between 'operator' and operator sign sp_after_operator = ignore # ignore/add/remove/force # Add or remove space between the operator symbol and the open paren, as in 'operator ++(' sp_after_operator_sym = ignore # ignore/add/remove/force # Add or remove space after C/D cast, i.e. 'cast(int)a' vs 'cast(int) a' or '(int)a' vs '(int) a' sp_after_cast = remove # ignore/add/remove/force # Add or remove spaces inside cast parens sp_inside_paren_cast = remove # ignore/add/remove/force # Add or remove space between the type and open paren in a C++ cast, i.e. 'int(exp)' vs 'int (exp)' sp_cpp_cast_paren = ignore # ignore/add/remove/force # Add or remove space between 'sizeof' and '(' sp_sizeof_paren = remove # ignore/add/remove/force # Add or remove space after the tag keyword (Pawn) sp_after_tag = ignore # ignore/add/remove/force # Add or remove space inside enum '{' and '}' sp_inside_braces_enum = remove # ignore/add/remove/force # Add or remove space inside struct/union '{' and '}' sp_inside_braces_struct = force # ignore/add/remove/force # Add or remove space inside '{' and '}' sp_inside_braces = force # ignore/add/remove/force # Add or remove space inside '{}' sp_inside_braces_empty = remove # ignore/add/remove/force # Add or remove space between return type and function name # A minimum of 1 is forced except for pointer return types. sp_type_func = remove # ignore/add/remove/force # Add or remove space between function name and '(' on function declaration sp_func_proto_paren = remove # ignore/add/remove/force # Add or remove space between function name and '(' on function definition sp_func_def_paren = remove # ignore/add/remove/force # Add or remove space inside empty function '()' sp_inside_fparens = remove # ignore/add/remove/force # Add or remove space inside function '(' and ')' sp_inside_fparen = remove # ignore/add/remove/force # Add or remove space between ']' and '(' when part of a function call. sp_square_fparen = ignore # ignore/add/remove/force # Add or remove space between ')' and '{' of function sp_fparen_brace = ignore # ignore/add/remove/force # Add or remove space between function name and '(' on function calls sp_func_call_paren = remove # ignore/add/remove/force # Add or remove space between function name and '()' on function calls without parameters. # If set to 'ignore' (the default), sp_func_call_paren is used. sp_func_call_paren_empty = ignore # ignore/add/remove/force # Add or remove space between the user function name and '(' on function calls # You need to set a keyword to be a user function, like this: 'set func_call_user _' in the config file. sp_func_call_user_paren = ignore # ignore/add/remove/force # Add or remove space between a constructor/destructor and the open paren sp_func_class_paren = ignore # ignore/add/remove/force # Add or remove space between 'return' and '(' sp_return_paren = ignore # ignore/add/remove/force # Add or remove space between '__attribute__' and '(' sp_attribute_paren = remove # ignore/add/remove/force # Add or remove space between 'defined' and '(' in '#if defined (FOO)' sp_defined_paren = ignore # ignore/add/remove/force # Add or remove space between 'throw' and '(' in 'throw (something)' sp_throw_paren = ignore # ignore/add/remove/force # Add or remove space between macro and value sp_macro = ignore # ignore/add/remove/force # Add or remove space between macro function ')' and value sp_macro_func = ignore # ignore/add/remove/force # Add or remove space between 'else' and '{' if on the same line sp_else_brace = force # ignore/add/remove/force # Add or remove space between '}' and 'else' if on the same line sp_brace_else = force # ignore/add/remove/force # Add or remove space between '}' and the name of a typedef on the same line sp_brace_typedef = force # ignore/add/remove/force # Add or remove space between 'catch' and '{' if on the same line sp_catch_brace = ignore # ignore/add/remove/force # Add or remove space between '}' and 'catch' if on the same line sp_brace_catch = ignore # ignore/add/remove/force # Add or remove space between 'finally' and '{' if on the same line sp_finally_brace = ignore # ignore/add/remove/force # Add or remove space between '}' and 'finally' if on the same line sp_brace_finally = ignore # ignore/add/remove/force # Add or remove space between 'try' and '{' if on the same line sp_try_brace = ignore # ignore/add/remove/force # Add or remove space between get/set and '{' if on the same line sp_getset_brace = ignore # ignore/add/remove/force # Add or remove space before the '::' operator sp_before_dc = ignore # ignore/add/remove/force # Add or remove space after the '::' operator sp_after_dc = ignore # ignore/add/remove/force # Add or remove around the D named array initializer ':' operator sp_d_array_colon = ignore # ignore/add/remove/force # Add or remove space after the '!' (not) operator. Default=Remove sp_not = remove # ignore/add/remove/force # Add or remove space after the '~' (invert) operator. Default=Remove sp_inv = remove # ignore/add/remove/force # Add or remove space after the '&' (address-of) operator. Default=Remove # This does not affect the spacing after a '&' that is part of a type. sp_addr = remove # ignore/add/remove/force # Add or remove space around the '.' or '->' operators. Default=Remove sp_member = remove # ignore/add/remove/force # Add or remove space after the '*' (dereference) operator. Default=Remove # This does not affect the spacing after a '*' that is part of a type. sp_deref = remove # ignore/add/remove/force # Add or remove space after '+' or '-', as in 'x = -5' or 'y = +7'. Default=Remove sp_sign = remove # ignore/add/remove/force # Add or remove space before or after '++' and '--', as in '(--x)' or 'y++;'. Default=Remove sp_incdec = remove # ignore/add/remove/force # Add or remove space before a backslash-newline at the end of a line. Default=Add sp_before_nl_cont = add # ignore/add/remove/force # Add or remove space after the scope '+' or '-', as in '-(void) foo;' or '+(int) bar;' sp_after_oc_scope = ignore # ignore/add/remove/force # Add or remove space after the colon in message specs # '-(int) f:(int) x;' vs '-(int) f: (int) x;' sp_after_oc_colon = ignore # ignore/add/remove/force # Add or remove space before the colon in message specs # '-(int) f: (int) x;' vs '-(int) f : (int) x;' sp_before_oc_colon = ignore # ignore/add/remove/force # Add or remove space after the colon in message specs # '[object setValue:1];' vs '[object setValue: 1];' sp_after_send_oc_colon = ignore # ignore/add/remove/force # Add or remove space before the colon in message specs # '[object setValue:1];' vs '[object setValue :1];' sp_before_send_oc_colon = ignore # ignore/add/remove/force # Add or remove space after the (type) in message specs # '-(int)f: (int) x;' vs '-(int)f: (int)x;' sp_after_oc_type = ignore # ignore/add/remove/force # Add or remove space after the first (type) in message specs # '-(int) f:(int)x;' vs '-(int)f:(int)x;' sp_after_oc_return_type = ignore # ignore/add/remove/force # Add or remove space between '@selector' and '(' # '@selector(msgName)' vs '@selector (msgName)' # Also applies to @protocol() constructs sp_after_oc_at_sel = ignore # ignore/add/remove/force # Add or remove space between '@selector(x)' and the following word # '@selector(foo) a:' vs '@selector(foo)a:' sp_after_oc_at_sel_parens = ignore # ignore/add/remove/force # Add or remove space inside '@selector' parens # '@selector(foo)' vs '@selector( foo )' # Also applies to @protocol() constructs sp_inside_oc_at_sel_parens = ignore # ignore/add/remove/force # Add or remove space before a block pointer caret # '^int (int arg){...}' vs. ' ^int (int arg){...}' sp_before_oc_block_caret = ignore # ignore/add/remove/force # Add or remove space after a block pointer caret # '^int (int arg){...}' vs. '^ int (int arg){...}' sp_after_oc_block_caret = ignore # ignore/add/remove/force # Add or remove space around the ':' in 'b ? t : f' sp_cond_colon = force # ignore/add/remove/force # Add or remove space around the '?' in 'b ? t : f' sp_cond_question = force # ignore/add/remove/force # Fix the spacing between 'case' and the label. Only 'ignore' and 'force' make sense here. sp_case_label = ignore # ignore/add/remove/force # Control the space around the D '..' operator. sp_range = ignore # ignore/add/remove/force # Control the space after the opening of a C++ comment '// A' vs '//A' # MPlayer devs note: we ignore the following setting because it breaks Doxygen comments #sp_cmt_cpp_start = ignore # ignore/add/remove/force sp_cmt_cpp_start = add # ignore/add/remove/force # Controls the spaces between #else or #endif and a trailing comment sp_endif_cmt = ignore # ignore/add/remove/force # # Code alignment (not left column spaces/tabs) # # Whether to keep non-indenting tabs align_keep_tabs = false # false/true # Whether to use tabs for aligning align_with_tabs = false # false/true # Whether to bump out to the next tab when aligning align_on_tabstop = false # false/true # Whether to left-align numbers align_number_left = true # false/true # Align variable definitions in prototypes and functions align_func_params = false # false/true # Align parameters in single-line functions that have the same name. # The function names must already be aligned with each other. align_same_func_call_params = false # false/true # The span for aligning variable definitions (0=don't align) align_var_def_span = 0 # number # How to align the star in variable definitions. # 0=Part of the type 'void * foo;' # 1=Part of the variable 'void *foo;' # 2=Dangling 'void *foo;' align_var_def_star_style = 2 # number # How to align the '&' in variable definitions. # 0=Part of the type # 1=Part of the variable # 2=Dangling align_var_def_amp_style = 0 # number # The threshold for aligning variable definitions (0=no limit) align_var_def_thresh = 0 # number # The gap for aligning variable definitions align_var_def_gap = 0 # number # Whether to align the colon in struct bit fields align_var_def_colon = false # false/true # Whether to align any attribute after the variable name align_var_def_attribute = false # false/true # Whether to align inline struct/enum/union variable definitions align_var_def_inline = false # false/true # The span for aligning on '=' in assignments (0=don't align) align_assign_span = 1 # number # The threshold for aligning on '=' in assignments (0=no limit) align_assign_thresh = 0 # number # The span for aligning on '=' in enums (0=don't align) align_enum_equ_span = 1 # number # The threshold for aligning on '=' in enums (0=no limit) align_enum_equ_thresh = 0 # number # The span for aligning struct/union (0=don't align) align_var_struct_span = 0 # number # The threshold for aligning struct/union member definitions (0=no limit) align_var_struct_thresh = 0 # number # The gap for aligning struct/union member definitions align_var_struct_gap = 0 # number # The span for aligning struct initializer values (0=don't align) align_struct_init_span = 1 # number # The minimum space between the type and the synonym of a typedef align_typedef_gap = 0 # number # The span for aligning single-line typedefs (0=don't align) align_typedef_span = 0 # number # How to align typedef'd functions with other typedefs # 0: Don't mix them at all # 1: align the open paren with the types # 2: align the function type name with the other type names align_typedef_func = 0 # number # Controls the positioning of the '*' in typedefs. Just try it. # 0: Align on typedef type, ignore '*' # 1: The '*' is part of type name: typedef int *pint; # 2: The '*' is part of the type, but dangling: typedef int *pint; align_typedef_star_style = 0 # number # Controls the positioning of the '&' in typedefs. Just try it. # 0: Align on typedef type, ignore '&' # 1: The '&' is part of type name: typedef int &pint; # 2: The '&' is part of the type, but dangling: typedef int &pint; align_typedef_amp_style = 0 # number # The span for aligning comments that end lines (0=don't align) align_right_cmt_span = 0 # number # If aligning comments, mix with comments after '}' and #endif with less than 3 spaces before the comment align_right_cmt_mix = false # false/true # If a trailing comment is more than this number of columns away from the text it follows, # it will qualify for being aligned. This has to be > 0 to do anything. align_right_cmt_gap = 0 # number # Align trailing comment at or beyond column N; 'pulls in' comments as a bonus side effect (0=ignore) align_right_cmt_at_col = 0 # number # The span for aligning function prototypes (0=don't align) align_func_proto_span = 0 # number # Minimum gap between the return type and the function name. align_func_proto_gap = 0 # number # Align function protos on the 'operator' keyword instead of what follows align_on_operator = false # false/true # Whether to mix aligning prototype and variable declarations. # If true, align_var_def_XXX options are used instead of align_func_proto_XXX options. align_mix_var_proto = false # false/true # Align single-line functions with function prototypes, uses align_func_proto_span align_single_line_func = false # false/true # Aligning the open brace of single-line functions. # Requires align_single_line_func=true, uses align_func_proto_span align_single_line_brace = false # false/true # Gap for align_single_line_brace. align_single_line_brace_gap = 0 # number # The span for aligning ObjC msg spec (0=don't align) align_oc_msg_spec_span = 0 # number # Whether to align macros wrapped with a backslash and a newline. # This will not work right if the macro contains a multi-line comment. align_nl_cont = false # false/true # The minimum space between label and value of a preprocessor define align_pp_define_gap = 0 # number # The span for aligning on '#define' bodies (0=don't align) align_pp_define_span = 0 # number # Align lines that start with '<<' with previous '<<'. Default=true align_left_shift = true # false/true # Span for aligning parameters in an Obj-C message call on the ':' (0=don't align) align_oc_msg_colon_span = 0 # number # Aligning parameters in an Obj-C '+' or '-' declaration on the ':' align_oc_decl_colon = false # false/true # # Newline adding and removing options # # Whether to collapse empty blocks between '{' and '}' nl_collapse_empty_body = false # false/true # Don't split one-line braced assignments - 'foo_t f = { 1, 2 };' nl_assign_leave_one_liners = false # false/true # Don't split one-line braced statements inside a class xx { } body nl_class_leave_one_liners = false # false/true # Don't split one-line enums: 'enum foo { BAR = 15 };' nl_enum_leave_one_liners = false # false/true # Don't split one-line get or set functions nl_getset_leave_one_liners = false # false/true # Don't split one-line function definitions - 'int foo() { return 0; }' nl_func_leave_one_liners = false # false/true # Don't split one-line if/else statements - 'if(a) b++;' nl_if_leave_one_liners = false # false/true # Add or remove newlines at the start of the file nl_start_of_file = remove # ignore/add/remove/force # The number of newlines at the start of the file (only used if nl_start_of_file is 'add' or 'force' nl_start_of_file_min = 0 # number # Add or remove newline at the end of the file nl_end_of_file = force # ignore/add/remove/force # The number of newlines at the end of the file (only used if nl_end_of_file is 'add' or 'force') nl_end_of_file_min = 1 # number # Add or remove newline between '=' and '{' nl_assign_brace = remove # ignore/add/remove/force # Add or remove newline between '=' and '[' (D only) nl_assign_square = ignore # ignore/add/remove/force # Add or remove newline after '= [' (D only). Will also affect the newline before the ']' nl_after_square_assign = ignore # ignore/add/remove/force # The number of blank lines after a block of variable definitions nl_func_var_def_blk = 0 # number # Add or remove newline between a function call's ')' and '{', as in: # list_for_each(item, &list) { } nl_fcall_brace = ignore # ignore/add/remove/force # Add or remove newline between 'enum' and '{' nl_enum_brace = remove # ignore/add/remove/force # Add or remove newline between 'struct and '{' nl_struct_brace = remove # ignore/add/remove/force # Add or remove newline between 'union' and '{' nl_union_brace = remove # ignore/add/remove/force # Add or remove newline between 'if' and '{' nl_if_brace = remove # ignore/add/remove/force # Add or remove newline between '}' and 'else' nl_brace_else = remove # ignore/add/remove/force # Add or remove newline between 'else if' and '{' # If set to ignore, nl_if_brace is used instead nl_elseif_brace = ignore # ignore/add/remove/force # Add or remove newline between 'else' and '{' nl_else_brace = remove # ignore/add/remove/force # Add or remove newline between 'else' and 'if' nl_else_if = remove # ignore/add/remove/force # Add or remove newline between '}' and 'finally' nl_brace_finally = ignore # ignore/add/remove/force # Add or remove newline between 'finally' and '{' nl_finally_brace = ignore # ignore/add/remove/force # Add or remove newline between 'try' and '{' nl_try_brace = ignore # ignore/add/remove/force # Add or remove newline between get/set and '{' nl_getset_brace = ignore # ignore/add/remove/force # Add or remove newline between 'for' and '{' nl_for_brace = remove # ignore/add/remove/force # Add or remove newline between 'catch' and '{' nl_catch_brace = ignore # ignore/add/remove/force # Add or remove newline between '}' and 'catch' nl_brace_catch = ignore # ignore/add/remove/force # Add or remove newline between 'while' and '{' nl_while_brace = remove # ignore/add/remove/force # Add or remove newline between 'using' and '{' nl_using_brace = ignore # ignore/add/remove/force # Add or remove newline between two open or close braces. # Due to general newline/brace handling, REMOVE may not work. nl_brace_brace = ignore # ignore/add/remove/force # Add or remove newline between 'do' and '{' nl_do_brace = remove # ignore/add/remove/force # Add or remove newline between '}' and 'while' of 'do' statement nl_brace_while = remove # ignore/add/remove/force # Add or remove newline between 'switch' and '{' nl_switch_brace = remove # ignore/add/remove/force # Add a newline between ')' and '{' if the ')' is on a different line than the if/for/etc. # Overrides nl_for_brace, nl_if_brace, nl_switch_brace, nl_while_switch, and nl_catch_brace. nl_multi_line_cond = false # false/true # Force a newline in a define after the macro name for multi-line defines. nl_multi_line_define = false # false/true # Whether to put a newline before 'case' statement nl_before_case = false # false/true # Add or remove newline between ')' and 'throw' nl_before_throw = ignore # ignore/add/remove/force # Whether to put a newline after 'case' statement nl_after_case = true # false/true # Newline between namespace and { nl_namespace_brace = ignore # ignore/add/remove/force # Add or remove newline between 'template<>' and whatever follows. nl_template_class = ignore # ignore/add/remove/force # Add or remove newline between 'class' and '{' nl_class_brace = ignore # ignore/add/remove/force # Add or remove newline after each ',' in the constructor member initialization nl_class_init_args = ignore # ignore/add/remove/force # Add or remove newline between return type and function name in a function definition nl_func_type_name = force # ignore/add/remove/force # Add or remove newline between return type and function name inside a class {} # Uses nl_func_type_name or nl_func_proto_type_name if set to ignore. nl_func_type_name_class = ignore # ignore/add/remove/force # Add or remove newline between function scope and name in a definition # Controls the newline after '::' in 'void A::f() { }' nl_func_scope_name = ignore # ignore/add/remove/force # Add or remove newline between return type and function name in a prototype nl_func_proto_type_name = remove # ignore/add/remove/force # Add or remove newline between a function name and the opening '(' nl_func_paren = remove # ignore/add/remove/force # Add or remove newline between a function name and the opening '(' in the definition nl_func_def_paren = remove # ignore/add/remove/force # Add or remove newline after '(' in a function declaration nl_func_decl_start = remove # ignore/add/remove/force # Add or remove newline after '(' in a function definition nl_func_def_start = ignore # ignore/add/remove/force # Overrides nl_func_decl_start when there is only one parameter. nl_func_decl_start_single = ignore # ignore/add/remove/force # Overrides nl_func_def_start when there is only one parameter. nl_func_def_start_single = ignore # ignore/add/remove/force # Add or remove newline after each ',' in a function declaration nl_func_decl_args = ignore # ignore/add/remove/force # Add or remove newline after each ',' in a function definition nl_func_def_args = ignore # ignore/add/remove/force # Add or remove newline before the ')' in a function declaration nl_func_decl_end = remove # ignore/add/remove/force # Add or remove newline before the ')' in a function definition nl_func_def_end = ignore # ignore/add/remove/force # Overrides nl_func_decl_end when there is only one parameter. nl_func_decl_end_single = ignore # ignore/add/remove/force # Overrides nl_func_def_end when there is only one parameter. nl_func_def_end_single = ignore # ignore/add/remove/force # Add or remove newline between '()' in a function declaration. nl_func_decl_empty = ignore # ignore/add/remove/force # Add or remove newline between '()' in a function definition. nl_func_def_empty = ignore # ignore/add/remove/force # Add or remove newline between function signature and '{' nl_fdef_brace = force # ignore/add/remove/force # Whether to put a newline after 'return' statement nl_after_return = false # false/true # Add or remove a newline between the return keyword and return expression. nl_return_expr = ignore # ignore/add/remove/force # Whether to put a newline after semicolons, except in 'for' statements nl_after_semicolon = true # false/true # Whether to put a newline after brace open. # This also adds a newline before the matching brace close. nl_after_brace_open = false # false/true # If nl_after_brace_open and nl_after_brace_open_cmt are true, a newline is # placed between the open brace and a trailing single-line comment. nl_after_brace_open_cmt = false # false/true # Whether to put a newline after a virtual brace open with a non-empty body. # These occur in un-braced if/while/do/for statement bodies. nl_after_vbrace_open = true # false/true # Whether to put a newline after a virtual brace open with an empty body. # These occur in un-braced if/while/do/for statement bodies. nl_after_vbrace_open_empty = false # false/true # Whether to put a newline after a brace close. # Does not apply if followed by a necessary ';'. nl_after_brace_close = false # false/true # Whether to put a newline after a virtual brace close. # Would add a newline before return in: 'if (foo) a++; return;' nl_after_vbrace_close = false # false/true # Whether to alter newlines in '#define' macros nl_define_macro = false # false/true # Whether to not put blanks after '#ifxx', '#elxx', or before '#endif' nl_squeeze_ifdef = false # false/true # Add or remove blank line before 'if' nl_before_if = ignore # ignore/add/remove/force # Add or remove blank line after 'if' statement nl_after_if = ignore # ignore/add/remove/force # Add or remove blank line before 'for' nl_before_for = ignore # ignore/add/remove/force # Add or remove blank line after 'for' statement nl_after_for = ignore # ignore/add/remove/force # Add or remove blank line before 'while' nl_before_while = ignore # ignore/add/remove/force # Add or remove blank line after 'while' statement nl_after_while = ignore # ignore/add/remove/force # Add or remove blank line before 'switch' nl_before_switch = ignore # ignore/add/remove/force # Add or remove blank line after 'switch' statement nl_after_switch = ignore # ignore/add/remove/force # Add or remove blank line before 'do' nl_before_do = ignore # ignore/add/remove/force # Add or remove blank line after 'do/while' statement nl_after_do = ignore # ignore/add/remove/force # Whether to double-space commented-entries in struct/enum nl_ds_struct_enum_cmt = false # false/true # Whether to double-space before the close brace of a struct/union/enum # (lower priority than 'eat_blanks_before_close_brace') nl_ds_struct_enum_close_brace = false # false/true # Add or remove a newline around a class colon. # Related to pos_class_colon, nl_class_init_args, and pos_comma. nl_class_colon = ignore # ignore/add/remove/force # Change simple unbraced if statements into a one-liner # 'if(b)\n i++;' => 'if(b) i++;' nl_create_if_one_liner = false # false/true # Change simple unbraced for statements into a one-liner # 'for (i=0;i<5;i++)\n foo(i);' => 'for (i=0;i<5;i++) foo(i);' nl_create_for_one_liner = false # false/true # Change simple unbraced while statements into a one-liner # 'while (i<5)\n foo(i++);' => 'while (i<5) foo(i++);' nl_create_while_one_liner = false # false/true # # Positioning options # # The position of arithmetic operators in wrapped expressions pos_arith = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # The position of assignment in wrapped expressions. # Do not affect '=' followed by '{' pos_assign = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # The position of boolean operators in wrapped expressions pos_bool = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # The position of comparison operators in wrapped expressions pos_compare = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # The position of conditional (b ? t : f) operators in wrapped expressions pos_conditional = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # The position of the comma in wrapped expressions pos_comma = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # The position of the comma in the constructor initialization list pos_class_comma = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # The position of colons between constructor and member initialization pos_class_colon = ignore # ignore/lead/lead_break/lead_force/trail/trail_break/trail_force # # Line Splitting options # # Try to limit code width to N number of columns code_width = 120 # number # Whether to fully split long 'for' statements at semi-colons ls_for_split_full = false # false/true # Whether to fully split long function protos/calls at commas ls_func_split_full = false # false/true # # Blank line options # # The maximum consecutive newlines nl_max = 2 # number # The number of newlines after a function prototype, if followed by another function prototype nl_after_func_proto = 0 # number # The number of newlines after a function prototype, if not followed by another function prototype nl_after_func_proto_group = 0 # number # The number of newlines after '}' of a multi-line function body nl_after_func_body = 2 # number # The number of newlines after '}' of a single line function body nl_after_func_body_one_liner = 2 # number # The minimum number of newlines before a multi-line comment. # Doesn't apply if after a brace open or another multi-line comment. nl_before_block_comment = 0 # number # The minimum number of newlines before a single-line C comment. # Doesn't apply if after a brace open or other single-line C comments. nl_before_c_comment = 0 # number # The minimum number of newlines before a CPP comment. # Doesn't apply if after a brace open or other CPP comments. nl_before_cpp_comment = 0 # number # Whether to force a newline after a multi-line comment. nl_after_multiline_comment = false # false/true # The number of newlines before a 'private:', 'public:', 'protected:', 'signals:', or 'slots:' label. # Will not change the newline count if after a brace open. # 0 = No change. nl_before_access_spec = 0 # number # The number of newlines after a 'private:', 'public:', 'protected:', 'signals:', or 'slots:' label. # 0 = No change. nl_after_access_spec = 0 # number # The number of newlines between a function def and the function comment. # 0 = No change. nl_comment_func_def = 0 # number # The number of newlines after a try-catch-finally block that isn't followed by a brace close. # 0 = No change. nl_after_try_catch_finally = 0 # number # The number of newlines before and after a property, indexer or event decl. # 0 = No change. nl_around_cs_property = 0 # number # The number of newlines between the get/set/add/remove handlers in C#. # 0 = No change. nl_between_get_set = 0 # number # Whether to remove blank lines after '{' eat_blanks_after_open_brace = true # false/true # Whether to remove blank lines before '}' eat_blanks_before_close_brace = true # false/true # # Code modifying options (non-whitespace) # # Add or remove braces on single-line 'do' statement mod_full_brace_do = remove # ignore/add/remove/force # Add or remove braces on single-line 'for' statement mod_full_brace_for = remove # ignore/add/remove/force # Add or remove braces on single-line function definitions. (Pawn) mod_full_brace_function = ignore # ignore/add/remove/force # Add or remove braces on single-line 'if' statement. Will not remove the braces if they contain an 'else'. mod_full_brace_if = ignore # ignore/add/remove/force # Make all if/elseif/else statements in a chain be braced or not. Overrides mod_full_brace_if. # If any must be braced, they are all braced. If all can be unbraced, then the braces are removed. mod_full_brace_if_chain = false # false/true # Don't remove braces around statements that span N newlines mod_full_brace_nl = 0 # number # Add or remove braces on single-line 'while' statement mod_full_brace_while = remove # ignore/add/remove/force # Add or remove braces on single-line 'using ()' statement mod_full_brace_using = remove # ignore/add/remove/force # Add or remove unnecessary paren on 'return' statement mod_paren_on_return = remove # ignore/add/remove/force # Whether to change optional semicolons to real semicolons mod_pawn_semicolon = false # false/true # Add parens on 'while' and 'if' statement around bools mod_full_paren_if_bool = false # false/true # Whether to remove superfluous semicolons mod_remove_extra_semicolon = true # false/true # If a function body exceeds the specified number of newlines and doesn't have a comment after # the close brace, a comment will be added. mod_add_long_function_closebrace_comment = 0 # number # If a switch body exceeds the specified number of newlines and doesn't have a comment after # the close brace, a comment will be added. mod_add_long_switch_closebrace_comment = 0 # number # If an #ifdef body exceeds the specified number of newlines and doesn't have a comment after # the #else, a comment will be added. mod_add_long_ifdef_endif_comment = 0 # number # If an #ifdef or #else body exceeds the specified number of newlines and doesn't have a comment after # the #endif, a comment will be added. mod_add_long_ifdef_else_comment = 0 # number # If TRUE, will sort consecutive single-line 'import' statements [Java, D] mod_sort_import = false # false/true # If TRUE, will sort consecutive single-line 'using' statements [C#] mod_sort_using = false # false/true # If TRUE, will sort consecutive single-line '#include' statements [C/C++] and '#import' statements [Obj-C] # This is generally a bad idea, as it may break your code. mod_sort_include = false # false/true # If TRUE, it will move a 'break' that appears after a fully braced 'case' before the close brace. mod_move_case_break = false # false/true # Will add or remove the braces around a fully braced case statement. # Will only remove the braces if there are no variable declarations in the block. mod_case_brace = ignore # ignore/add/remove/force # If TRUE, it will remove a void 'return;' that appears as the last statement in a function. mod_remove_empty_return = false # false/true # # Comment modifications # # Try to wrap comments at cmt_width columns cmt_width = 0 # number # Set the comment reflow mode (default: 0) # 0: no reflowing (apart from the line wrapping due to cmt_width) # 1: no touching at all # 2: full reflow cmt_reflow_mode = 0 # number # If false, disable all multi-line comment changes, including cmt_width. keyword substitution, and leading chars. # Default is true. cmt_indent_multi = true # false/true # Whether to group c-comments that look like they are in a block cmt_c_group = false # false/true # Whether to put an empty '/*' on the first line of the combined c-comment cmt_c_nl_start = false # false/true # Whether to put a newline before the closing '*/' of the combined c-comment cmt_c_nl_end = false # false/true # Whether to group cpp-comments that look like they are in a block cmt_cpp_group = false # false/true # Whether to put an empty '/*' on the first line of the combined cpp-comment cmt_cpp_nl_start = false # false/true # Whether to put a newline before the closing '*/' of the combined cpp-comment cmt_cpp_nl_end = false # false/true # Whether to change cpp-comments into c-comments cmt_cpp_to_c = false # false/true # Whether to put a star on subsequent comment lines cmt_star_cont = true # false/true # The number of spaces to insert at the start of subsequent comment lines cmt_sp_before_star_cont = 0 # number # The number of spaces to insert after the star on subsequent comment lines cmt_sp_after_star_cont = 0 # number # For multi-line comments with a '*' lead, remove leading spaces if the first and last lines of # the comment are the same length. Default=True cmt_multi_check_last = false # false/true # The filename that contains text to insert at the head of a file if the file doesn't start with a C/C++ comment. # Will substitute $(filename) with the current file's name. cmt_insert_file_header = "" # string # The filename that contains text to insert at the end of a file if the file doesn't end with a C/C++ comment. # Will substitute $(filename) with the current file's name. cmt_insert_file_footer = "" # string # The filename that contains text to insert before a function implementation if the function isn't preceded with a C/C++ comment. # Will substitute $(function) with the function name and $(javaparam) with the javadoc @param and @return stuff. # Will also substitute $(fclass) with the class name: void CFoo::Bar() { ... } cmt_insert_func_header = "" # string # The filename that contains text to insert before a class if the class isn't preceded with a C/C++ comment. # Will substitute $(class) with the class name. cmt_insert_class_header = "" # string # If a preprocessor is encountered when stepping backwards from a function name, then # this option decides whether the comment should be inserted. # Affects cmt_insert_func_header and cmt_insert_class_header. cmt_insert_before_preproc = false # false/true # # Preprocessor options # # Control indent of preprocessors inside #if blocks at brace level 0 pp_indent = remove # ignore/add/remove/force # Whether to indent #if/#else/#endif at the brace level (true) or from column 1 (false) pp_indent_at_level = false # false/true # If pp_indent_at_level=false, specifies the number of columns to indent per level. Default=1. pp_indent_count = 1 # number # Add or remove space after # based on pp_level of #if blocks pp_space = remove # ignore/add/remove/force # Sets the number of spaces added with pp_space pp_space_count = 0 # number # The indent for #region and #endregion in C# and '#pragma region' in C/C++ pp_indent_region = 0 # number # Whether to indent the code between #region and #endregion pp_region_indent_code = false # false/true # If pp_indent_at_level=true, sets the indent for #if, #else, and #endif when not at file-level pp_indent_if = 0 # number # Control whether to indent the code between #if, #else and #endif when not at file-level pp_if_indent_code = false # false/true # Whether to indent '#define' at the brace level (true) or from column 1 (false) pp_define_at_level = false # false/true # You can force a token to be a type with the 'type' option. # Example: # type myfoo1 myfoo2 # # You can create custom macro-based indentation using macro-open, # macro-else and macro-close. # Example: # macro-open BEGIN_TEMPLATE_MESSAGE_MAP # macro-open BEGIN_MESSAGE_MAP # macro-close END_MESSAGE_MAP # # You can assign any keyword to any type with the set option. # set func_call_user _ N_ # # The full syntax description of all custom definition config entries # is shown below: # # define custom tokens as: # - embed whitespace in token using '' escape character, or # put token in quotes # - these: ' " and ` are recognized as quote delimiters # # type token1 token2 token3 ... # ^ optionally specify multiple tokens on a single line # define def_token output_token # ^ output_token is optional, then NULL is assumed # macro-open token # macro-close token # macro-else token # set id token1 token2 ... # ^ optionally specify multiple tokens on a single line # ^ id is one of the names in token_enum.h sans the CT_ prefix, # e.g. PP_PRAGMA # # all tokens are separated by any mix of ',' commas, '=' equal signs # and whitespace (space, tab) # simple-obfs-0.0.5/APKBUILD000066400000000000000000000013601320326276300150560ustar00rootroot00000000000000# Contributor: Max Lv # Maintainer: Max Lv pkgname=simple-obfs pkgver=0.0.4 pkgrel=0 pkgdesc="Simple-obfs is a simple obfusacting tool, designed as plugin server of shadowsocks." url="https://github.com/shadowsocks/simple-obfs" arch="all" license="GPLv3+" makedepends="autoconf automake libtool linux-headers libev-dev c-ares-dev asciidoc xmlto" subpackages="$pkgname-doc" builddir="$srcdir/$pkgname" prepare() { cd "$srcdir" git clone "$url" cd "$builddir" git checkout "v$pkgver" git submodule update --init --recursive } build() { cd "$builddir" ./autogen.sh ./configure --prefix=/usr make } check() { cd "$builddir" make check } package() { cd "$builddir" make DESTDIR="$pkgdir" install } simple-obfs-0.0.5/AUTHORS000066400000000000000000000003761320326276300150160ustar00rootroot00000000000000Here is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS -- people who have submitted patches, fixed bugs, added translations, and generally made simple-obfs that much better: https://github.com/shadowsocks/simple-obfs/graphs/contributors simple-obfs-0.0.5/COPYING000066400000000000000000000011451320326276300147740ustar00rootroot00000000000000This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . simple-obfs-0.0.5/Changes000066400000000000000000000011401320326276300152270ustar00rootroot00000000000000simple-obfs (0.0.5-1) unstable; urgency=medium * Fix the building issue on Windows. -- Max Lv Thu, 16 Nov 2017 18:04:07 +0800 simple-obfs (0.0.4-1) unstable; urgency=medium * Minor bug fixes. -- Max Lv Mon, 06 Nov 2017 14:52:48 +0800 simple-obfs (0.0.3-1) unstable; urgency=medium * Add failover option. * Minor bug fixes. -- Max Lv Fri, 17 Mar 2017 17:02:43 +0800 simple-obfs (0.0.2-1) UNRELEASED; urgency=low * Initial release. (Closes: #) -- Roger Shimizu Wed, 22 Feb 2017 21:55:18 +0900 simple-obfs-0.0.5/INSTALL000066400000000000000000000363321320326276300150000ustar00rootroot00000000000000Installation Instructions ************************* Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without warranty of any kind. Basic Installation ================== Briefly, the shell commands `./configure; make; make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the `README' file for instructions specific to this package. Some packages provide this `INSTALL' file but do not implement all of the features documented below. The lack of an optional feature in a given package is not necessarily a bug. More recommendations for GNU packages can be found in *note Makefile Conventions: (standards)Makefile Conventions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). It can also use an optional file (typically called `config.cache' and enabled with `--cache-file=config.cache' or simply `-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If you are using the cache, and at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.ac' (or `configure.in') is used to create `configure' by a program called `autoconf'. You need `configure.ac' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. Running `configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package, generally using the just-built uninstalled binaries. 4. Type `make install' to install the programs and any data files and documentation. When installing into a prefix owned by root, it is recommended that the package be configured and built as a regular user, and only the `make install' phase executed with root privileges. 5. Optionally, type `make installcheck' to repeat any self-tests, but this time using the binaries in their final installed location. This target does not install anything. Running this target as a regular user, particularly if the prior `make install' required root privileges, verifies that the installation completed correctly. 6. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 7. Often, you can also type `make uninstall' to remove the installed files again. In practice, not all packages have tested that uninstallation works correctly, even though it is required by the GNU Coding Standards. 8. Some packages, particularly those that use Automake, provide `make distcheck', which can by used by developers to test that all other targets like `make install' and `make uninstall' work correctly. This target is generally not run by end users. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. Run `./configure --help' for details on some of the pertinent environment variables. You can give `configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. This is known as a "VPATH" build. With a non-GNU `make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. On MacOS X 10.5 and later systems, you can create libraries and executables that work on multiple system types--known as "fat" or "universal" binaries--by specifying multiple `-arch' options to the compiler but only a single `-arch' option to the preprocessor. Like this: ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CPP="gcc -E" CXXCPP="g++ -E" This is not guaranteed to produce working output in all cases, you may have to build one architecture at a time and combine the results using the `lipo' tool if you have problems. Installation Names ================== By default, `make install' installs the package's commands under `/usr/local/bin', include files under `/usr/local/include', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PREFIX', where PREFIX must be an absolute file name. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option `--exec-prefix=PREFIX' to `configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=DIR' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. In general, the default for these options is expressed in terms of `${prefix}', so that specifying just `--prefix' will affect all of the other directory specifications that were not explicitly provided. The most portable way to affect installation locations is to pass the correct locations to `configure'; however, many packages provide one or both of the following shortcuts of passing variable assignments to the `make install' command line to change installation locations without having to reconfigure or recompile. The first method involves providing an override variable for each affected directory. For example, `make install prefix=/alternate/directory' will choose an alternate location for all directory configuration variables that were expressed in terms of `${prefix}'. Any directories that were specified during `configure', but not in terms of `${prefix}', must each be overridden at install time for the entire installation to be relocated. The approach of makefile variable overrides for each directory variable is required by the GNU Coding Standards, and ideally causes no recompilation. However, some platforms have known limitations with the semantics of shared libraries that end up requiring recompilation when using this method, particularly noticeable in packages that use GNU Libtool. The second method involves providing the `DESTDIR' variable. For example, `make install DESTDIR=/alternate/directory' will prepend `/alternate/directory' before all installation names. The approach of `DESTDIR' overrides is not required by the GNU Coding Standards, and does not work on platforms that have drive letters. On the other hand, it does better at avoiding recompilation issues, and works well even when some directory options were not specified in terms of `${prefix}' at `configure' time. Optional Features ================= If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Some packages offer the ability to configure how verbose the execution of `make' will be. For these packages, running `./configure --enable-silent-rules' sets the default to minimal output, which can be overridden with `make V=1'; while running `./configure --disable-silent-rules' sets the default to verbose, which can be overridden with `make V=0'. Particular systems ================== On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC is not installed, it is recommended to use the following options in order to use an ANSI C compiler: ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" and if that doesn't work, install pre-built binaries of GCC for HP-UX. On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot parse its `' header file. The option `-nodtk' can be used as a workaround. If GNU CC is not installed, it is therefore recommended to try ./configure CC="cc" and if that doesn't work, try ./configure CC="cc -nodtk" On Solaris, don't put `/usr/ucb' early in your `PATH'. This directory contains several dysfunctional programs; working variants of these programs are available in `/usr/bin'. So, if you need `/usr/ucb' in your `PATH', put it _after_ `/usr/bin'. On Haiku, software installed for all users goes in `/boot/common', not `/usr/local'. It is recommended to use the following options: ./configure --prefix=/boot/common Specifying the System Type ========================== There may be some features `configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, `configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the `--build=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option `--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with `--host=TYPE'. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to `configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the `configure' command line, using `VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified `gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for `CONFIG_SHELL' due to an Autoconf bug. Until the bug is fixed you can use this workaround: CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash `configure' Invocation ====================== `configure' recognizes the following options to control how it operates. `--help' `-h' Print a summary of all of the options to `configure', and exit. `--help=short' `--help=recursive' Print a summary of the options unique to this package's `configure', and exit. The `short' variant lists options used only in the top level, while the `recursive' variant lists options also present in any nested packages. `--version' `-V' Print the version of Autoconf used to generate the `configure' script, and exit. `--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally `config.cache'. FILE defaults to `/dev/null' to disable caching. `--config-cache' `-C' Alias for `--cache-file=config.cache'. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `--prefix=DIR' Use DIR as the installation prefix. *note Installation Names:: for more details, including other options available for fine-tuning the installation locations. `--no-create' `-n' Run the configure checks, but stop before creating any output files. `configure' also accepts some other, not widely useful, options. Run `configure --help' for more details. simple-obfs-0.0.5/LICENSE000066400000000000000000000773311320326276300147600ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS simple-obfs-0.0.5/Makefile.am000066400000000000000000000001351320326276300157730ustar00rootroot00000000000000SUBDIRS = libcork src if ENABLE_DOCUMENTATION SUBDIRS += doc endif ACLOCAL_AMFLAGS = -I m4 simple-obfs-0.0.5/README.md000066400000000000000000000062461320326276300152270ustar00rootroot00000000000000# simple-obfs ## Intro Simple-obfs is a simple obfusacting tool, designed as plugin server of shadowsocks. Current version: 0.0.5 | [Changelog](Changes) ## Build For Unix-like systems, especially Debian-based systems, e.g. Ubuntu, Debian or Linux Mint, you can build the binary like this: ```bash # Debian / Ubuntu sudo apt-get install --no-install-recommends build-essential autoconf libtool libssl-dev libpcre3-dev libc-ares-dev libev-dev asciidoc xmlto automake # CentOS / Fedora / RHEL sudo yum install gcc autoconf libtool automake make zlib-devel openssl-devel asciidoc xmlto c-ares-devel # Arch sudo pacman -Syu gcc autoconf libtool automake make zlib openssl asciidoc xmlto # Alpine apk add gcc autoconf make libtool automake zlib-devel openssl asciidoc xmlto libpcre32 libev-dev c-ares-dev g++ linux-headers git clone https://github.com/shadowsocks/simple-obfs.git cd simple-obfs git submodule update --init --recursive ./autogen.sh ./configure && make sudo make install ``` ## Usage For a detailed and complete list of all supported arguments, you may refer to the man pages of the applications, respectively. ### Plugin mode with shadowsocks Add respective item to `--plugin` and `--plugin-opts` arg or as value of `plugin` and `plugin_opts` in JSON. On the client: ```bash ss-local -c config.json --plugin obfs-local --plugin-opts "obfs=http;obfs-host=www.bing.com" ``` On the server: ```bash ss-server -c config.json --plugin obfs-server --plugin-opts "obfs=http" ``` ### Standalone mode On the client: ```bash obfs-local -s server_ip -p 8139 -l 1984 --obfs http --obfs-host www.bing.com ss-local -c config.json -s 127.0.0.1 -p 1984 -l 1080 ``` On the server: ```bash obfs-server -s server_ip -p 8139 --obfs http -r 127.0.0.1:8388 ss-server -c config.json -s 127.0.0.1 -p 8388 ``` ### Coexist with an actual Web server Only applicable on the server: ```bash # HTTP only with plugin mode ss-server -c config.json --plugin obfs-server --plugin-opts "obfs=http;failover=example.com" # Both HTTP and HTTPS with standalone mode obfs-server -s server_ip -p 80 --obfs http -r 127.0.0.1:8388 --failover example.com obfs-server -s server_ip -p 443 --obfs tls -r 127.0.0.1:8388 --failover example.com # suppose you have an HTTP webserver (apache/nginx/whatever) listening on localhost:8080 and HTTPS on 8443 # (you probably shouldn't expose these ports) obfs-server -s server_ip -p 80 --obfs http -r 127.0.0.1:8388 --failover 127.0.0.1:8080 obfs-server -s server_ip -p 443 --obfs tls -r 127.0.0.1:8388 --failover 127.0.0.1:8443 ``` ## License ``` Copyright (C) 2016 Max Lv This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` simple-obfs-0.0.5/autogen.sh000077500000000000000000000000501320326276300157340ustar00rootroot00000000000000#!/bin/sh autoreconf --install --force simple-obfs-0.0.5/configure.ac000077500000000000000000000146761320326276300162470ustar00rootroot00000000000000dnl -*- Autoconf -*- dnl Process this file with autoconf to produce a configure script. AC_PREREQ([2.67]) AC_INIT([simple-obfs], [0.0.5], [max.c.lv@gmail.com]) AC_CONFIG_SRCDIR([src/encrypt.c]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_AUX_DIR(auto) AC_CONFIG_MACRO_DIR([m4]) AC_USE_SYSTEM_EXTENSIONS AM_INIT_AUTOMAKE([subdir-objects foreign -Wno-gnu -Werror]) m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) AM_MAINTAINER_MODE AM_DEP_TRACK dnl Checks for lib AC_DISABLE_STATIC AC_DISABLE_SHARED LT_INIT([dlopen]) AC_ARG_ENABLE([documentation], AS_HELP_STRING([--disable-documentation], [do not build documentation]), [disable_documentation=true], [disable_documentation=false]) AM_CONDITIONAL([ENABLE_DOCUMENTATION], [test x$disable_documentation = xfalse]) AM_COND_IF([ENABLE_DOCUMENTATION], [ AC_PATH_PROG([ASCIIDOC], [asciidoc]) test x"${ASCIIDOC}" != x || AC_MSG_ERROR([Cannot find `asciidoc` in PATH.]) AC_PATH_PROG([XMLTO], [xmlto]) test x"$XMLTO" != x || AC_MSG_ERROR([Cannot find `xmlto` in PATH.]) AC_PATH_PROG([GZIP], [gzip], [gzip]) AC_PATH_PROG([MV], [mv], [mv]) AC_PROG_SED ]) dnl Checks for programs. AC_PROG_CC AM_PROG_CC_C_O AC_PROG_INSTALL AC_PROG_LN_S AC_PROG_LIBTOOL AC_PROG_MAKE_SET AC_LANG_SOURCE dnl Add library for mingw case $host in *-mingw*) CFLAGS="$CFLAGS -mno-ms-bitfields" LIBS="$LIBS -ladvapi32 -lgdi32 -lws2_32 -lcrypt32" ;; *-cygwin*) CFLAGS="$CFLAGS -mno-ms-bitfields" ;; *) ;; esac dnl Checks for TLS AX_TLS([:], [:]) dnl Checks for inet_ntop ss_FUNC_INET_NTOP dnl Checks for host. AC_MSG_CHECKING(for what kind of host) case $host in *-linux*) os_support=linux AC_MSG_RESULT(Linux) ;; *-mingw*) dnl Add custom macros for libev AC_DEFINE([FD_SETSIZE], [2048], [Reset max file descriptor size.]) AC_DEFINE([EV_FD_TO_WIN32_HANDLE(fd)], [(fd)], [Override libev default fd conversion macro.]) AC_DEFINE([EV_WIN32_HANDLE_TO_FD(handle)], [(handle)], [Override libev default handle conversion macro.]) AC_DEFINE([EV_WIN32_CLOSE_FD(fd)], [closesocket(fd)], [Override libev default fd close macro.]) os_support=mingw AC_MSG_RESULT(MinGW) ;; *) AC_MSG_RESULT(transparent proxy does not support for $host) ;; esac dnl Checks for stack protector GGL_CHECK_STACK_PROTECTOR([has_stack_protector=yes], [has_stack_protector=no]) # XXX - disable -fstack-protector due to missing libssp_nonshared case "$host_os" in *aix*) AC_MSG_NOTICE([-fstack-protector disabled on AIX]) has_stack_protector=no ;; *sunos*) AC_MSG_NOTICE([-fstack-protector disabled on SunOS]) has_stack_protector=no ;; *solaris*) AC_MSG_NOTICE([-fstack-protector disabled on Solaris]) has_stack_protector=no ;; esac AC_ARG_ENABLE(ssp, [AS_HELP_STRING(--disable-ssp,Do not compile with -fstack-protector)], [ enable_ssp="no" ], [ enable_ssp="yes" ]) if test x$has_stack_protector = xyes && test x$enable_ssp = xyes; then CFLAGS="$CFLAGS -fstack-protector" AC_MSG_NOTICE([-fstack-protector enabled in CFLAGS]) fi AM_CONDITIONAL(BUILD_REDIRECTOR, test "$os_support" = "linux") AM_CONDITIONAL(BUILD_WINCOMPAT, test "$os_support" = "mingw") dnl Checks for header files. AC_CHECK_HEADERS([limits.h stdint.h inttypes.h arpa/inet.h fcntl.h langinfo.h locale.h netdb.h netinet/in.h stdlib.h string.h strings.h unistd.h sys/ioctl.h]) dnl A special check required for on Darwin. See dnl http://www.gnu.org/software/autoconf/manual/html_node/Header-Portability.html. AC_CHECK_HEADERS([sys/socket.h]) AC_CHECK_HEADERS([net/if.h], [], [], [ #include #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_SYS_SOCKET_H # include #endif ]) case $host in *-mingw*) AC_DEFINE([CONNECT_IN_PROGRESS], [WSAEWOULDBLOCK], [errno for incomplete non-blocking connect(2)]) AC_CHECK_HEADERS([windows.h winsock2.h ws2tcpip.h], [], [AC_MSG_ERROR([Missing MinGW headers])], []) ;; *-linux*) AC_DEFINE([CONNECT_IN_PROGRESS], [EINPROGRESS], [errno for incomplete non-blocking connect(2)]) dnl Checks for netfilter headers AC_CHECK_HEADERS([linux/if.h linux/netfilter_ipv4.h linux/netfilter_ipv6/ip6_tables.h], [], [AC_MSG_ERROR([Missing netfilter headers])], [[ #if HAVE_LIMITS_H #include #endif /* Netfilter ip(6)tables v1.4.0 has broken headers */ #if HAVE_NETINET_IN_H #include #endif #if HAVE_LINUX_IF_H #include #endif #if HAVE_SYS_SOCKET_H #include #endif ]]) ;; *) # These are POSIX-like systems using BSD-like sockets API. AC_DEFINE([CONNECT_IN_PROGRESS], [EINPROGRESS], [errno for incomplete non-blocking connect(2)]) ;; esac AC_C_BIGENDIAN dnl Checks for typedefs, structures, and compiler characteristics. AC_C_INLINE AC_TYPE_SSIZE_T dnl Checks for header files. AC_HEADER_ASSERT AC_HEADER_STDC AC_HEADER_SYS_WAIT dnl Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_PID_T AC_TYPE_SIZE_T AC_TYPE_SSIZE_T AC_TYPE_UINT16_T AC_TYPE_UINT8_T AC_HEADER_TIME dnl Checks for library functions. AC_FUNC_FORK AC_FUNC_SELECT_ARGTYPES AC_TYPE_SIGNAL AC_CHECK_FUNCS([memset select setresuid setreuid strerror getpwnam_r setrlimit]) dnl Check for select() into ws2_32 for Msys/Mingw if test "$ac_cv_func_select" != "yes"; then AC_MSG_CHECKING([for select in ws2_32]) AC_TRY_LINK([ #ifdef HAVE_WINSOCK2_H #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #endif ],[ select(0,(fd_set *)NULL,(fd_set *)NULL,(fd_set *)NULL,(struct timeval *)NULL); ],[ AC_MSG_RESULT([yes]) HAVE_SELECT="1" AC_DEFINE_UNQUOTED(HAVE_SELECT, 1, [Define to 1 if you have the 'select' function.]) HAVE_SYS_SELECT_H="1" AC_DEFINE_UNQUOTED(HAVE_SYS_SELECT_H, 1, [Define to 1 if you have the header file.]) ],[ AC_MSG_ERROR([no]) ]) fi AC_CHECK_LIB(socket, connect) dnl Checks for library functions. AC_CHECK_FUNCS([malloc memset socket]) AC_CHECK_LIB([ev], [ev_loop_destroy], [LIBS="-lev $LIBS"], [AC_MSG_ERROR([Couldn't find libev. Try installing libev-dev@<:@el@:>@.])]) AM_COND_IF([ENABLE_DOCUMENTATION], [AC_CONFIG_FILES([doc/Makefile]) ]) AC_CONFIG_FILES([Makefile libcork/Makefile src/Makefile]) AC_OUTPUT simple-obfs-0.0.5/debian/000077500000000000000000000000001320326276300151625ustar00rootroot00000000000000simple-obfs-0.0.5/debian/changelog000066400000000000000000000011401320326276300170300ustar00rootroot00000000000000simple-obfs (0.0.5-1) unstable; urgency=medium * Fix the building issue on Windows. -- Max Lv Thu, 16 Nov 2017 18:04:07 +0800 simple-obfs (0.0.4-1) unstable; urgency=medium * Minor bug fixes. -- Max Lv Mon, 06 Nov 2017 14:52:48 +0800 simple-obfs (0.0.3-1) unstable; urgency=medium * Add failover option. * Minor bug fixes. -- Max Lv Fri, 17 Mar 2017 17:02:43 +0800 simple-obfs (0.0.2-1) UNRELEASED; urgency=low * Initial release. (Closes: #) -- Roger Shimizu Wed, 22 Feb 2017 21:55:18 +0900 simple-obfs-0.0.5/debian/compat000066400000000000000000000000031320326276300163610ustar00rootroot0000000000000010 simple-obfs-0.0.5/debian/control000066400000000000000000000010551320326276300165660ustar00rootroot00000000000000Source: simple-obfs Section: net Priority: extra Maintainer: Roger Shimizu Build-Depends: debhelper (>= 10), libcork-dev Standards-Version: 3.9.8 Homepage: https://github.com/shadowsocks/simple-obfs Package: simple-obfs Architecture: any Multi-Arch: foreign Depends: libcap2-bin [linux-any], ${misc:Depends}, ${shlibs:Depends} Description: simple obfusacting plugin for shadowsocks server Simple-obfs is a simple obfusacting tool, designed as plugin server of shadowsocks. . Please refer README.md and manpages for usage. simple-obfs-0.0.5/debian/copyright000066400000000000000000000140141320326276300171150ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: simple-obfs Upstream-Contact: Max Lv Source: https://github.com/shadowsocks/simple-obfs Files: * Copyright: 2013-2017 Max Lv 2014 Linus Yang License: GPL-3+ Files: debian/* Copyright: 2017 Roger Shimizu License: GPL-3+ Files: m4/ax_pthread.m4 Copyright: 2008 Steven G. Johnson 2011 Daniel Richard G. License: GPL-3+ with Autoconf exception Files: m4/ax_tls.m4 Copyright: 2008 Alan Woodland 2010 Diego Elio Petteno` License: GPL-3+ with Autoconf exception Files: m4/stack-protector.m4 Copyright: 2007 Google Inc. License: Apache-2.0 Files: src/base64.c src/base64.h Copyright: 2006 Ryan Martell License: LGPL-2.1+ Files: src/json.c src/json.h Copyright: 2012-2014 James McLaughlin et al. License: BSD-2-Clause Files: src/resolv.c src/resolv.h Copyright: 2014 Dustin Lundquist License: BSD-2-Clause License: Apache-2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at . http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. . On Debian systems, the complete text of the Apache License Version 2.0 can be found in `/usr/share/common-licenses/Apache-2.0'. License: BSD-2-Clause Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: . 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. . 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. . THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. License: GPL-3+ This file is part of the simple-obfs. . simple-obfs is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. . simple-obfs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with simple-obfs; see the file COPYING. If not, see . . On Debian systems, the complete text of the GNU General Public License Version 3 can be found in `/usr/share/common-licenses/GPL-3'. License: GPL-3+ with Autoconf exception This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with this program. If not, see . . As a special exception, the respective Autoconf Macro's copyright owner gives unlimited permission to copy, distribute and modify the configure scripts that are the output of Autoconf when processing the Macro. You need not follow the terms of the GNU General Public License when using or distributing such scripts, even though portions of the text of the Macro appear in them. The GNU General Public License (GPL) does govern all other use of the material that constitutes the Autoconf Macro. . This special exception to the GPL applies to versions of the Autoconf Macro released by the Autoconf Archive. When you make and distribute a modified version of the Autoconf Macro, you may extend this special exception to the GPL to apply to your modified version as well. License: LGPL-2.1+ This file is part of FFmpeg. . FFmpeg is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. . FFmpeg is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. . You should have received a copy of the GNU Lesser General Public License along with FFmpeg; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA simple-obfs-0.0.5/debian/docs000066400000000000000000000000221320326276300160270ustar00rootroot00000000000000AUTHORS README.md simple-obfs-0.0.5/debian/install000066400000000000000000000001011320326276300165430ustar00rootroot00000000000000src/obfs-server usr/bin/ src/obfs-local usr/bin/ #usr/share/man/ simple-obfs-0.0.5/debian/patches/000077500000000000000000000000001320326276300166115ustar00rootroot00000000000000simple-obfs-0.0.5/debian/patches/0001-Use-libcork-dev-in-system.patch000066400000000000000000000023501320326276300250710ustar00rootroot00000000000000From: Roger Shimizu Date: Tue, 21 Feb 2017 19:07:29 +0900 Subject: Use libcork-dev in system --- Makefile.am | 2 +- configure.ac | 1 - src/Makefile.am | 5 ++--- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Makefile.am b/Makefile.am index d5da3ab..a342e44 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,4 +1,4 @@ -SUBDIRS = libcork src +SUBDIRS = src if ENABLE_DOCUMENTATION SUBDIRS += doc diff --git a/configure.ac b/configure.ac index 3c03364..73d29a9 100755 --- a/configure.ac +++ b/configure.ac @@ -281,7 +281,6 @@ AM_COND_IF([ENABLE_DOCUMENTATION], ]) AC_CONFIG_FILES([Makefile - libcork/Makefile src/Makefile]) AC_OUTPUT diff --git a/src/Makefile.am b/src/Makefile.am index 6d566f9..f58b41e 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -5,9 +5,8 @@ AM_CFLAGS += $(PTHREAD_CFLAGS) AM_CFLAGS += -I$(top_srcdir)/libcork/include AM_CFLAGS += $(LIBPCRE_CFLAGS) -OBFS_COMMON_LIBS = $(top_builddir)/libcork/libcork.la \ - $(INET_NTOP_LIB) $(LIBPCRE_LIBS) -OBFS_COMMON_LIBS += -lev -lm +OBFS_COMMON_LIBS = $(INET_NTOP_LIB) $(LIBPCRE_LIBS) +OBFS_COMMON_LIBS += -lev -lm -lcork bin_PROGRAMS = obfs-local if !BUILD_WINCOMPAT simple-obfs-0.0.5/debian/patches/series000066400000000000000000000000451320326276300200250ustar00rootroot000000000000000001-Use-libcork-dev-in-system.patch simple-obfs-0.0.5/debian/postinst000066400000000000000000000011741320326276300167730ustar00rootroot00000000000000#!/bin/sh set -e # POSIX-compliant maint function recommend by devref # to check for the existence of a command # https://www.debian.org/doc/manuals/developers-reference/ch06.html#bpp-debian-maint-scripts pathfind() { OLDIFS="$IFS" IFS=: for p in $PATH; do if [ -x "$p/$*" ]; then IFS="$OLDIFS" return 0 fi done IFS="$OLDIFS" return 1 } case "$1" in configure|reconfigure) pathfind setcap && setcap \ cap_net_bind_service+ep /usr/bin/obfs-server ;; abort-upgrade|abort-remove|abort-deconfigure) exit 0 ;; *) echo "postinst called with unknown argument \`$1'" >&2 exit 0 ;; esac #DEBHELPER# exit 0 simple-obfs-0.0.5/debian/rules000077500000000000000000000001731320326276300162430ustar00rootroot00000000000000#!/usr/bin/make -f #export DH_VERBOSE = 1 # Security Hardening export DEB_BUILD_MAINT_OPTIONS = hardening=+all %: dh $@ simple-obfs-0.0.5/debian/source/000077500000000000000000000000001320326276300164625ustar00rootroot00000000000000simple-obfs-0.0.5/debian/source/format000066400000000000000000000000141320326276300176700ustar00rootroot000000000000003.0 (quilt) simple-obfs-0.0.5/debian/watch000066400000000000000000000003001320326276300162040ustar00rootroot00000000000000version=4 opts= filenamemangle=s%(?:.*?)?v?(\d[\d.]*)\.tar\.gz%simple-obfs-$1.tar.gz%" \ https://github.com/shadowsocks/simple-obfs/tags \ (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate simple-obfs-0.0.5/doc/000077500000000000000000000000001320326276300145055ustar00rootroot00000000000000simple-obfs-0.0.5/doc/Makefile.am000066400000000000000000000024601320326276300165430ustar00rootroot00000000000000ASCIIDOC = @ASCIIDOC@ ASCIIDOC_EXTRA = MANPAGE_XSL = manpage-normal.xsl XMLTO = @XMLTO@ XMLTO_EXTRA = -m manpage-bold-literal.xsl GZIPCMD = @GZIP@ INSTALL = @INSTALL@ RM = @RM@ MV = @MV@ SED = @SED@ VERSION = `$(SED) -n 's/.*PACKAGE_VERSION "\(.*\)"/\1/p'\ ../config.h` # Guard against environment variables if ENABLE_DOCUMENTATION MAN1_DOC = MAN1_DOC += obfs-local.1 MAN1_DOC += obfs-server.1 MAN8_DOC = else MAN1_DOC = MAN8_DOC = endif MAN8_XML = $(MAN8_DOC:%.8=%.xml) MAN1_XML = $(MAN1_DOC:%.1=%.xml) MAN_XML = $(MAN8_XML) $(MAN1_XML) MAN8_HTML = $(MAN8_DOC:%.8=%.html) MAN1_HTML = $(MAN1_DOC:%.1=%.html) MAN_HTML = $(MAN8_HTML) $(MAN1_HTML) MAN8_TXT = $(MAN8_DOC:%.8=%.asciidoc) MAN1_TXT = $(MAN1_DOC:%.1=%.asciidoc) MAN_TXT = $(MAN8_TXT) $(MAN1_TXT) man_MANS = $(MAN8_DOC) $(MAN1_DOC) html-local: $(MAN_HTML) %.1: %.xml $(AM_V_GEN)$(XMLTO) -m $(MANPAGE_XSL) $(XMLTO_EXTRA) man $< %.8: %.xml $(AM_V_GEN)$(XMLTO) -m $(MANPAGE_XSL) $(XMLTO_EXTRA) man $< %.xml: %.asciidoc $(AM_V_GEN)$(ASCIIDOC) -b docbook -d manpage -f asciidoc.conf \ -aversion=$(VERSION) $(ASCIIDOC_EXTRA) -o $@ $< %.html: %.asciidoc $(AM_V_GEN)$(ASCIIDOC) -b html4 -d article -f asciidoc.conf \ -aversion=$(VERSION) $(ASCIIDOC_EXTRA) -o $@ $< doc_DATA = $(MAN_HTML) CLEANFILES = $(MAN_XML) $(man_MANS) $(MAN_HTML) simple-obfs-0.0.5/doc/asciidoc.conf000066400000000000000000000014231320326276300171320ustar00rootroot00000000000000[tags] bracket-emphasis={1?[{1}]}<|> [quotes] <|>=#bracket-emphasis [attributes] asterisk=* plus=+ caret=^ startsb=[ endsb=] backslash=\ tilde=~ apostrophe=' backtick=` litdd=-- ifdef::doctype-manpage[] ifdef::backend-docbook[] [header] template::[header-declarations] {mantitle} {manvolnum} Shadowsocks-libev {version} Shadowsocks-libev Manual {manname} {manpurpose} endif::backend-docbook[] endif::doctype-manpage[] simple-obfs-0.0.5/doc/manpage-base.xsl000066400000000000000000000022501320326276300175540ustar00rootroot00000000000000 sp br simple-obfs-0.0.5/doc/manpage-bold-literal.xsl000066400000000000000000000011021320326276300212070ustar00rootroot00000000000000 fB fR simple-obfs-0.0.5/doc/manpage-normal.xsl000066400000000000000000000007331320326276300201360ustar00rootroot00000000000000 \ . simple-obfs-0.0.5/doc/obfs-local.asciidoc000066400000000000000000000044751320326276300202400ustar00rootroot00000000000000obfs-local(1) =========== NAME ---- obfs-local - simple-obfs client SYNOPSIS -------- *obfs-local* [-6] [-h|--help] [-s ] [-p ] [-l ] [-f ] [-t ] [-c ] [-i ] [-a ] [-b ] [--fast-open] [--obfs ] [--obfs-host ] DESCRIPTION ----------- *Obfs-simple* is a very simple obfuscating tunnel tool. *Obfs-simple* is written in pure C and takes advantage of libev to achieve both high performance and low resource consumption. *Obfs-simple* consists of two components. `obfs-local`(1) works as a standard tunnel on local machines to obfuscate TCP traffic. OPTIONS ------- -s :: Set the server's hostname or IP. -p :: Set the server's port number. -l :: Set the local port number. -a :: Run as a specific user. -f :: Start obfs-simple as a daemon with specific pid file. -t :: Set the socket timeout in seconds. The default value is 60. -c :: Use a configuration file. -n :: Specify max number of open files. + Only available on Linux. -i :: Send traffic through specific network interface. + For example, there are three interfaces in your device, which is lo (127.0.0.1), eth0 (192.168.0.1) and eth1 (192.168.0.2). Meanwhile, you configure `obfs-local` to listen on 0.0.0.0:8388 and bind to eth1. That results the traffic go out through eth1, but not lo nor eth0. This option is useful to control traffic in multi-interface environment. -b :: Specify local address to bind. -6:: Resovle hostname to IPv6 address first. --fast-open:: Enable TCP fast open. + Only available with Linux kernel > 3.7.0. --mptcp:: Enable Multipath TCP. + Only available with MPTCP enabled Linux kernel. --obfs :: Enable HTTP or TLS obfuscating. (Experimental) --obfs-host :: Specify the hostname for obfuscating. (Experimental) -v:: Enable verbose mode. -h|--help:: Print help message. EXAMPLE ------- `obfs-local`(1) can be started from command line and run in foreground. Here is an example: .... # Start obfs-local with given parameters obfs-local -s example.com -p 12345 -l 1080 --obfs http --obfs-host www.baidu.com .... SEE ALSO -------- `obfs-server`(1), /etc/simple-obfs/config.json simple-obfs-0.0.5/doc/obfs-server.asciidoc000066400000000000000000000047111320326276300204450ustar00rootroot00000000000000obfs-server(1) ============ NAME ---- obfs-server - simple-obfs server SYNOPSIS -------- *obfs-server* [-v] [-h|--help] [-s ] [-p ] [-l ] [-r :] [-f ] [-t ] [-c ] [-i ] [-a ] [-d ] [-n ] [-b :: Set the server's hostname or IP. -p :: Set the server's port number. -a :: Run as a specific user. -f :: Start simple-obfs as a daemon with specific pid file. -t :: Set the socket timeout in seconds. The default value is 60. -c :: Use a configuration file. -n :: Specify max number of open files. + Only available on Linux. -i :: Send traffic through specific network interface. + For example, there are three interfaces in your device, which is lo (127.0.0.1), eth0 (192.168.0.1) and eth1 (192.168.0.2). Meanwhile, you configure `obfs-server` to listen on 0.0.0.0:8388 and bind to eth1. That results the traffic go out through eth1, but not lo nor eth0. This option is useful to control traffic in multi-interface environment. -b :: Specify local address to bind. -6:: Resovle hostname to IPv6 address first. -d :: Setup name servers for internal DNS resolver (libudns). The default server is fetched from '/etc/resolv.conf'. --fast-open:: Enable TCP fast open. + Only available with Linux kernel > 3.7.0. --mptcp:: Enable Multipath TCP. + Only available with MPTCP enabled Linux kernel. --mptcp:: Enable Multipath TCP. + Only available with MPTCP enabled Linux kernel. --obfs :: Enable HTTP or TLS obfuscating. (Experimental) -v:: Enable verbose mode. -h|--help:: Print help message. EXAMPLE ------- It is recommended to use a config file when starting `obfs-server`(1). The config file is written in JSON and is easy to edit. Check out the 'SEE ALSO' section for the default path of config file. .... # Start the obfs-server obfs-server -c /etc/simple-obfs/config.json .... SEE ALSO -------- `obfs-local`(1), /etc/simple-obfs/config.json simple-obfs-0.0.5/libcork/000077500000000000000000000000001320326276300153655ustar00rootroot00000000000000simple-obfs-0.0.5/m4/000077500000000000000000000000001320326276300142605ustar00rootroot00000000000000simple-obfs-0.0.5/m4/ax_tls.m4000066400000000000000000000057001320326276300160160ustar00rootroot00000000000000# =========================================================================== # http://www.gnu.org/software/autoconf-archive/ax_tls.html # =========================================================================== # # SYNOPSIS # # AX_TLS([action-if-found], [action-if-not-found]) # # DESCRIPTION # # Provides a test for the compiler support of thread local storage (TLS) # extensions. Defines TLS if it is found. Currently knows about GCC/ICC # and MSVC. I think SunPro uses the same as GCC, and Borland apparently # supports either. # # LICENSE # # Copyright (c) 2008 Alan Woodland # Copyright (c) 2010 Diego Elio Petteno` # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # As a special exception, the respective Autoconf Macro's copyright owner # gives unlimited permission to copy, distribute and modify the configure # scripts that are the output of Autoconf when processing the Macro. You # need not follow the terms of the GNU General Public License when using # or distributing such scripts, even though portions of the text of the # Macro appear in them. The GNU General Public License (GPL) does govern # all other use of the material that constitutes the Autoconf Macro. # # This special exception to the GPL applies to versions of the Autoconf # Macro released by the Autoconf Archive. When you make and distribute a # modified version of the Autoconf Macro, you may extend this special # exception to the GPL to apply to your modified version as well. #serial 11 AC_DEFUN([AX_TLS], [ AC_MSG_CHECKING([for thread local storage (TLS) class]) AC_CACHE_VAL([ac_cv_tls], [for ax_tls_keyword in __thread '__declspec(thread)' none; do AS_CASE([$ax_tls_keyword], [none], [ac_cv_tls=none ; break], [AC_TRY_COMPILE( [#include static void foo(void) { static ] $ax_tls_keyword [ int bar; exit(1); }], [], [ac_cv_tls=$ax_tls_keyword ; break], ac_cv_tls=none )]) done ]) AC_MSG_RESULT([$ac_cv_tls]) AS_IF([test "$ac_cv_tls" != "none"], [AC_DEFINE_UNQUOTED([TLS],[$ac_cv_tls],[If the compiler supports a TLS storage class define it to that here]) m4_ifnblank([$1],[$1])], [m4_ifnblank([$2],[$2])]) ]) simple-obfs-0.0.5/m4/inet_ntop.m4000066400000000000000000000022771320326276300165310ustar00rootroot00000000000000# inet_ntop.m4 serial 19 dnl Copyright (C) 2005-2006, 2008-2013 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. AC_DEFUN([ss_FUNC_INET_NTOP], [ AC_REQUIRE([AC_C_RESTRICT]) dnl Most platforms that provide inet_ntop define it in libc. dnl Solaris 8..10 provide inet_ntop in libnsl instead. dnl Solaris 2.6..7 provide inet_ntop in libresolv instead. HAVE_INET_NTOP=1 INET_NTOP_LIB= ss_save_LIBS=$LIBS AC_SEARCH_LIBS([inet_ntop], [nsl resolv], [], [AC_CHECK_FUNCS([inet_ntop]) if test $ac_cv_func_inet_ntop = no; then HAVE_INET_NTOP=0 fi ]) LIBS=$ss_save_LIBS if test "$ac_cv_search_inet_ntop" != "no" \ && test "$ac_cv_search_inet_ntop" != "none required"; then INET_NTOP_LIB="$ac_cv_search_inet_ntop" fi AC_CHECK_HEADERS_ONCE([netdb.h]) AC_CHECK_DECLS([inet_ntop],,, [[#include #if HAVE_NETDB_H # include #endif ]]) if test $ac_cv_have_decl_inet_ntop = no; then HAVE_DECL_INET_NTOP=0 fi AC_SUBST([INET_NTOP_LIB]) ]) simple-obfs-0.0.5/m4/stack-protector.m4000066400000000000000000000034251320326276300176520ustar00rootroot00000000000000# # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # GGL_CHECK_STACK_PROTECTOR([ACTION-IF-OK], [ACTION-IF-NOT-OK]) # Check if c compiler supports -fstack-protector and -fstack-protector-all # options. AC_DEFUN([GGL_CHECK_STACK_PROTECTOR], [ ggl_check_stack_protector_save_CXXFLAGS="$CXXFLAGS" ggl_check_stack_protector_save_CFLAGS="$CFLAGS" AC_MSG_CHECKING([if -fstack-protector and -fstack-protector-all are supported.]) CXXFLAGS="$CXXFLAGS -fstack-protector" CFLAGS="$CFLAGS -fstack-protector" AC_COMPILE_IFELSE([AC_LANG_SOURCE([ int main() { return 0; } ])], [ggl_check_stack_protector_ok=yes], [ggl_check_stack_protector_ok=no]) CXXFLAGS="$ggl_check_stack_protector_save_CXXFLAGS -fstack-protector-all" CFLAGS="$ggl_check_stack_protector_save_CFLAGS -fstack-protector-all" AC_COMPILE_IFELSE([AC_LANG_SOURCE([ int main() { return 0; } ])], [ggl_check_stack_protector_all_ok=yes], [ggl_check_stack_protector_all_ok=no]) if test "x$ggl_check_stack_protector_ok" = "xyes" -a \ "x$ggl_check_stack_protector_all_ok" = "xyes"; then AC_MSG_RESULT([yes]) ifelse([$1], , :, [$1]) else AC_MSG_RESULT([no]) ifelse([$2], , :, [$2]) fi CXXFLAGS="$ggl_check_stack_protector_save_CXXFLAGS" CFLAGS="$ggl_check_stack_protector_save_CFLAGS" ]) # GGL_CHECK_STACK_PROTECTOR simple-obfs-0.0.5/src/000077500000000000000000000000001320326276300145275ustar00rootroot00000000000000simple-obfs-0.0.5/src/Makefile.am000066400000000000000000000022261320326276300165650ustar00rootroot00000000000000VERSION_INFO = 2:0:0 AM_CFLAGS = -g -O2 -Wall -Werror -Wno-deprecated-declarations -fno-strict-aliasing -std=gnu99 -D_GNU_SOURCE AM_CFLAGS += $(PTHREAD_CFLAGS) AM_CFLAGS += -I$(top_srcdir)/libcork/include AM_CFLAGS += $(LIBPCRE_CFLAGS) OBFS_COMMON_LIBS = $(top_builddir)/libcork/libcork.la \ $(INET_NTOP_LIB) $(LIBPCRE_LIBS) OBFS_COMMON_LIBS += -lev -lm bin_PROGRAMS = obfs-local if !BUILD_WINCOMPAT bin_PROGRAMS += obfs-server endif obfs_src = obfs_http.c \ obfs_tls.c \ options.c \ base64.c obfs_local_SOURCES = utils.c \ jconf.c \ json.c \ encrypt.c \ netutils.c \ local.c \ $(obfs_src) obfs_server_SOURCES = utils.c \ netutils.c \ jconf.c \ json.c \ encrypt.c \ server.c \ $(obfs_src) obfs_local_LDADD = $(OBFS_COMMON_LIBS) obfs_server_LDADD = $(OBFS_COMMON_LIBS) obfs_local_CFLAGS = $(AM_CFLAGS) -DMODULE_LOCAL obfs_server_CFLAGS = $(AM_CFLAGS) -DMODULE_REMOTE if BUILD_WINCOMPAT obfs_local_SOURCES += win32.c endif simple-obfs-0.0.5/src/android.c000066400000000000000000000045651320326276300163250ustar00rootroot00000000000000/* * android.c - Setup IPC for shadowsocks-android * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "netutils.h" #include "utils.h" int protect_socket(int fd) { int sock; struct sockaddr_un addr; if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { LOGE("[android] socket() failed: %s (socket fd = %d)\n", strerror(errno), sock); return -1; } // Set timeout to 1s struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)); setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(struct timeval)); memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, "protect_path", sizeof(addr.sun_path) - 1); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) { LOGE("[android] connect() failed for protect_path: %s (socket fd = %d)\n", strerror(errno), sock); close(sock); return -1; } if (ancil_send_fd(sock, fd)) { ERROR("[android] ancil_send_fd"); close(sock); return -1; } char ret = 0; if (recv(sock, &ret, 1, 0) == -1) { ERROR("[android] recv"); close(sock); return -1; } close(sock); return ret; } simple-obfs-0.0.5/src/base64.c000066400000000000000000000062211320326276300157600ustar00rootroot00000000000000/* * Copyright (c) 2006 Ryan Martell. (rdm4@martellventures.com) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief Base64 encode/decode * @author Ryan Martell (with lots of Michael) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "base64.h" /* ---------------- private code */ static const uint8_t map2[] = { 0x3e, 0xff, 0xff, 0xff, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33 }; int base64_decode(uint8_t *out, const char *in, int out_size) { int i, v; uint8_t *dst = out; v = 0; for (i = 0; in[i] && in[i] != '='; i++) { unsigned int index= in[i]-43; if (index >= sizeof(map2) || map2[index] == 0xff) return -1; v = (v << 6) + map2[index]; if (i & 3) { if (dst - out < out_size) { *dst++ = v >> (6 - 2 * (i & 3)); } } } return dst - out; } /***************************************************************************** * b64_encode: Stolen from VLC's http.c. * Simplified by Michael. * Fixed edge cases and made it work from data (vs. strings) by Ryan. *****************************************************************************/ char *base64_encode(char *out, int out_size, const uint8_t *in, int in_size) { static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char *ret, *dst; unsigned i_bits = 0; int i_shift = 0; int bytes_remaining = in_size; if (in_size >= UINT_MAX / 4 || out_size < BASE64_SIZE(in_size)) return NULL; ret = dst = out; while (bytes_remaining) { i_bits = (i_bits << 8) + *in++; bytes_remaining--; i_shift += 8; do { *dst++ = b64[(i_bits << 6 >> i_shift) & 0x3f]; i_shift -= 6; } while (i_shift > 6 || (bytes_remaining == 0 && i_shift > 0)); } while ((dst - ret) & 3) *dst++ = '='; *dst = '\0'; return ret; } simple-obfs-0.0.5/src/base64.h000066400000000000000000000034561320326276300157740ustar00rootroot00000000000000/* * Copyright (c) 2006 Ryan Martell. (rdm4@martellventures.com) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef BASE64_H #define BASE64_H #include /** * Decode a base64-encoded string. * * @param out buffer for decoded data * @param in null-terminated input string * @param out_size size in bytes of the out buffer, must be at * least 3/4 of the length of in * @return number of bytes written, or a negative value in case of * invalid input */ int base64_decode(uint8_t *out, const char *in, int out_size); /** * Encode data to base64 and null-terminate. * * @param out buffer for encoded data * @param out_size size in bytes of the output buffer, must be at * least BASE64_SIZE(in_size) * @param in_size size in bytes of the 'in' buffer * @return 'out' or NULL in case of error */ char *base64_encode(char *out, int out_size, const uint8_t *in, int in_size); /** * Calculate the output size needed to base64-encode x bytes. */ #define BASE64_SIZE(x) (((x)+2) / 3 * 4 + 1) #endif /* BASE64_H */ simple-obfs-0.0.5/src/common.h000066400000000000000000000036141320326276300161740ustar00rootroot00000000000000/* * common.h - Provide global definitions * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _COMMON_H #define _COMMON_H #define DEFAULT_CONF_PATH "/etc/simple-obfs/config.json" #ifndef SOL_TCP #define SOL_TCP IPPROTO_TCP #endif #if defined(MODULE_TUNNEL) || defined(MODULE_REDIR) #define MODULE_LOCAL #endif int init_udprelay(const char *server_host, const char *server_port, #ifdef MODULE_LOCAL const struct sockaddr *remote_addr, const int remote_addr_len, #ifdef MODULE_TUNNEL const ss_addr_t tunnel_addr, #endif #endif int mtu, int method, int auth, int timeout, const char *iface); void free_udprelay(void); #ifdef ANDROID int protect_socket(int fd); int send_traffic_stat(uint64_t tx, uint64_t rx); #endif #define STAGE_ERROR -1 /* Error detected */ #define STAGE_INIT 0 /* Initial stage */ #define STAGE_HANDSHAKE 1 /* Handshake with client */ #define STAGE_PARSE 2 /* Parse the header */ #define STAGE_RESOLVE 4 /* Resolve the hostname */ #define STAGE_STREAM 5 /* Stream between client and server */ #endif // _COMMON_H simple-obfs-0.0.5/src/encrypt.c000066400000000000000000000041561320326276300163650ustar00rootroot00000000000000/* * encrypt.c - Manage the global encryptor * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #include #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef __MINGW32__ #include #endif #include "encrypt.h" #include "utils.h" #define OFFSET_ROL(p, o) ((uint64_t)(*(p + o)) << (8 * o)) #ifdef DEBUG static void dump(char *tag, char *text, int len) { unsigned int i; printf("%s: ", tag); for (i = 0; i < len; i++) printf("0x%02x ", (uint8_t)text[i]); printf("\n"); } #endif int balloc(buffer_t *ptr, size_t capacity) { memset(ptr, 0, sizeof(buffer_t)); ptr->data = ss_malloc(capacity); ptr->capacity = capacity; return capacity; } int brealloc(buffer_t *ptr, size_t len, size_t capacity) { if (ptr == NULL) return -1; size_t real_capacity = max(len, capacity); if (ptr->capacity < real_capacity) { ptr->data = ss_realloc(ptr->data, real_capacity); ptr->capacity = real_capacity; } return real_capacity; } void bfree(buffer_t *ptr) { if (ptr == NULL) return; ptr->idx = 0; ptr->len = 0; ptr->capacity = 0; if (ptr->data != NULL) { ss_free(ptr->data); } } int rand_bytes(void *output, int len) { int i; int *array = (int *)output; for (i = 0; i < len / sizeof(int); i++) array[i] = rand(); // always return success return 0; } simple-obfs-0.0.5/src/encrypt.h000066400000000000000000000030371320326276300163670ustar00rootroot00000000000000/* * encrypt.h - Define the enryptor's interface * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _ENCRYPT_H #define _ENCRYPT_H #ifndef __MINGW32__ #include #else #ifdef max #undef max #endif #ifdef min #undef min #endif #endif #include #include #include #include #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) typedef struct buffer { size_t idx; size_t len; size_t capacity; char *data; } buffer_t; typedef struct chunk { uint32_t idx; uint32_t len; uint32_t counter; buffer_t *buf; } chunk_t; int balloc(buffer_t *ptr, size_t capacity); int brealloc(buffer_t *ptr, size_t len, size_t capacity); void bfree(buffer_t *ptr); int rand_bytes(void *output, int len); #endif // _ENCRYPT_H simple-obfs-0.0.5/src/jconf.c000066400000000000000000000155341320326276300160020ustar00rootroot00000000000000/* * jconf.c - Parse the JSON format config file * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #include #include #include #include #include #include "utils.h" #include "jconf.h" #include "json.h" #include "string.h" #include #define check_json_value_type(value, expected_type, message) \ do { \ if ((value)->type != (expected_type)) \ FATAL((message)); \ } while(0) static char * to_string(const json_value *value) { if (value->type == json_string) { return ss_strndup(value->u.string.ptr, value->u.string.length); } else if (value->type == json_integer) { return strdup(ss_itoa(value->u.integer)); } else if (value->type == json_null) { return "null"; } else { LOGE("%d", value->type); FATAL("Invalid config format."); } return 0; } void free_addr(ss_addr_t *addr) { ss_free(addr->host); ss_free(addr->port); } void parse_addr(const char *str, ss_addr_t *addr) { int ipv6 = 0, ret = -1, n = 0; char *pch; struct cork_ip ip; if (cork_ip_init(&ip, str) != -1) { addr->host = strdup(str); addr->port = NULL; return; } pch = strchr(str, ':'); while (pch != NULL) { n++; ret = pch - str; pch = strchr(pch + 1, ':'); } if (n > 1) { ipv6 = 1; if (str[ret - 1] != ']') { ret = -1; } } if (ret == -1) { if (ipv6) { addr->host = ss_strndup(str + 1, strlen(str) - 2); } else { addr->host = strdup(str); } addr->port = NULL; } else { if (ipv6) { addr->host = ss_strndup(str + 1, ret - 2); } else { addr->host = ss_strndup(str, ret); } addr->port = strdup(str + ret + 1); } } jconf_t * read_jconf(const char *file) { static jconf_t conf; memset(&conf, 0, sizeof(jconf_t)); char *buf; json_value *obj; FILE *f = fopen(file, "rb"); 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."); } buf = ss_malloc(pos + 1); if (buf == NULL) { FATAL("No enough memory."); } int nread = fread(buf, pos, 1, f); if (!nread) { FATAL("Failed to read the config file."); } fclose(f); buf[pos] = '\0'; // end of string json_settings settings = { 0UL, 0, NULL, NULL, NULL }; char error_buf[512]; obj = json_parse_ex(&settings, buf, pos, error_buf); if (obj == NULL) { FATAL(error_buf); } if (obj->type == json_object) { unsigned int i, j; 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; } json_value *v = value->u.array.values[j]; char *addr_str = to_string(v); parse_addr(addr_str, conf.remote_addr + j); ss_free(addr_str); conf.remote_num = j + 1; } } 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) { conf.remote_port = to_string(value); } else if (strcmp(name, "local_address") == 0) { conf.local_addr = to_string(value); } else if (strcmp(name, "local_port") == 0) { conf.local_port = to_string(value); } else if (strcmp(name, "timeout") == 0) { conf.timeout = to_string(value); } else if (strcmp(name, "user") == 0) { conf.user = to_string(value); } else if (strcmp(name, "obfs") == 0) { conf.obfs = to_string(value); } else if (strcmp(name, "obfs_host") == 0) { conf.obfs_host = to_string(value); } else if (strcmp(name, "failover") == 0) { conf.failover = to_string(value); } else if (strcmp(name, "fast_open") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'fast_open' must be a boolean"); conf.fast_open = value->u.boolean; } else if (strcmp(name, "nofile") == 0) { check_json_value_type(value, json_integer, "invalid config file: option 'nofile' must be an integer"); conf.nofile = value->u.integer; } else if (strcmp(name, "nameserver") == 0) { conf.nameserver = to_string(value); } else if (strcmp(name, "dst_addr") == 0) { conf.dst_addr = to_string(value); } else if (strcmp(name, "mptcp") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'mptcp' must be a boolean"); conf.mptcp = value->u.boolean; } else if (strcmp(name, "ipv6_first") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'ipv6_first' must be a boolean"); conf.ipv6_first = value->u.boolean; } else if (strcmp(name, "reverse_proxy") == 0) { check_json_value_type(value, json_boolean, "invalid config file: option 'reverse_proxy' must be a boolean"); conf.reverse_proxy = value->u.boolean; } } } else { FATAL("Invalid config file"); } ss_free(buf); json_value_free(obj); return &conf; } simple-obfs-0.0.5/src/jconf.h000066400000000000000000000033271320326276300160040ustar00rootroot00000000000000/* * jconf.h - Define the config data structure * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _JCONF_H #define _JCONF_H #define MAX_PORT_NUM 1024 #define MAX_REMOTE_NUM 10 #define MAX_CONF_SIZE 128 * 1024 #define MAX_DNS_NUM 4 #define MAX_CONNECT_TIMEOUT 10 #define MAX_REQUEST_TIMEOUT 60 #define MIN_UDP_TIMEOUT 10 #define UPDATE_INTERVAL 5 typedef struct { char *host; char *port; } ss_addr_t; typedef struct { char *port; char *password; } ss_port_password_t; typedef struct { int remote_num; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port; char *local_addr; char *local_port; char *timeout; char *user; char *obfs; char *obfs_host; char *failover; int fast_open; int nofile; char *nameserver; char *dst_addr; int mptcp; int ipv6_first; int reverse_proxy; } jconf_t; jconf_t *read_jconf(const char *file); void parse_addr(const char *str, ss_addr_t *addr); void free_addr(ss_addr_t *addr); #endif // _JCONF_H simple-obfs-0.0.5/src/json.c000066400000000000000000000710251320326276300156510ustar00rootroot00000000000000/* vim: set et ts=3 sw=3 sts=3 ft=c: * * Copyright (C) 2012, 2013, 2014 James McLaughlin et al. All rights reserved. * https://github.com/udp/json-parser * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ #include "json.h" #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #endif const struct _json_value json_value_none; #include #include #include #include typedef unsigned int json_uchar; static unsigned char hex_value (json_char c) { if (isdigit(c)) return c - '0'; switch (c) { case 'a': case 'A': return 0x0A; case 'b': case 'B': return 0x0B; case 'c': case 'C': return 0x0C; case 'd': case 'D': return 0x0D; case 'e': case 'E': return 0x0E; case 'f': case 'F': return 0x0F; default: return 0xFF; } } typedef struct { unsigned long used_memory; unsigned int uint_max; unsigned long ulong_max; json_settings settings; int first_pass; const json_char * ptr; unsigned int cur_line, cur_col; } json_state; static void * default_alloc (size_t size, int zero, void * user_data) { return zero ? calloc (1, size) : malloc (size); } static void default_free (void * ptr, void * user_data) { free (ptr); } 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) { 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_value * value; int values_size; if (!state->first_pass) { value = *top = *alloc; *alloc = (*alloc)->_reserved.next_alloc; if (!*root) *root = value; switch (value->type) { case json_array: if (value->u.array.length == 0) break; if (! (value->u.array.values = (json_value **) json_alloc (state, value->u.array.length * sizeof (json_value *), 0)) ) { return 0; } value->u.array.length = 0; break; case json_object: if (value->u.object.length == 0) break; values_size = sizeof (*value->u.object.values) * value->u.object.length; if (! (value->u.object.values = (json_object_entry *) json_alloc (state, values_size + ((intptr_t) value->u.object.values), 0)) ) { return 0; } 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)) ) { return 0; } value->u.string.length = 0; break; default: break; }; return 1; } if (! (value = (json_value *) json_alloc (state, sizeof (json_value) + state->settings.value_extra, 1))) { return 0; } if (!*root) *root = value; value->type = type; value->parent = *top; #ifdef JSON_TRACK_SOURCE value->line = state->cur_line; value->col = state->cur_col; #endif if (*alloc) (*alloc)->_reserved.next_alloc = value; *alloc = *top = value; return 1; } #define whitespace \ case '\n': ++ state.cur_line; state.cur_col = 0; \ case ' ': case '\t': case '\r' #define string_add(b) \ do { if (!state.first_pass) string [string_length] = b; ++ string_length; } while (0); #define line_and_col \ state.cur_line, state.cur_col 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; json_value * json_parse_ex (json_settings * settings, const json_char * json, size_t length, char * error_buf) { json_char error [json_error_max]; const json_char * end; json_value * top, * root, * alloc = 0; json_state state = { 0 }; long flags; long num_digits = 0, num_e = 0; json_int_t num_fraction = 0; /* Skip UTF-8 BOM */ if (length >= 3 && ((unsigned char) json [0]) == 0xEF && ((unsigned char) json [1]) == 0xBB && ((unsigned char) json [2]) == 0xBF) { json += 3; length -= 3; } error[0] = '\0'; end = (json + length); memcpy (&state.settings, settings, sizeof (json_settings)); if (!state.settings.mem_alloc) state.settings.mem_alloc = default_alloc; 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)); 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) { json_uchar uchar; unsigned char uc_b1, uc_b2, uc_b3, uc_b4; json_char * string = 0; unsigned int string_length = 0; top = root = 0; flags = flag_seek_value; state.cur_line = 1; for (state.ptr = json ;; ++ state.ptr) { json_char b = (state.ptr == end ? 0 : *state.ptr); if (flags & flag_string) { if (!b) { sprintf (error, "Unexpected EOF in string (at %d:%d)", line_and_col); goto e_failed; } if (string_length > state.uint_max) goto e_overflow; if (flags & flag_escaped) { flags &= ~ flag_escaped; switch (b) { case 'b': string_add ('\b'); break; case 'f': string_add ('\f'); break; case 'n': string_add ('\n'); break; case 'r': string_add ('\r'); break; case 't': string_add ('\t'); break; case 'u': if (end - state.ptr < 4 || (uc_b1 = hex_value (*++ state.ptr)) == 0xFF || (uc_b2 = hex_value (*++ state.ptr)) == 0xFF || (uc_b3 = hex_value (*++ state.ptr)) == 0xFF || (uc_b4 = hex_value (*++ state.ptr)) == 0xFF) { sprintf (error, "Invalid character value `%c` (at %d:%d)", b, line_and_col); goto e_failed; } uc_b1 = (uc_b1 << 4) | uc_b2; uc_b2 = (uc_b3 << 4) | uc_b4; uchar = (uc_b1 << 8) | uc_b2; if ((uchar & 0xF800) == 0xD800) { json_uchar uchar2; if (end - state.ptr < 6 || (*++ state.ptr) != '\\' || (*++ state.ptr) != 'u' || (uc_b1 = hex_value (*++ state.ptr)) == 0xFF || (uc_b2 = hex_value (*++ state.ptr)) == 0xFF || (uc_b3 = hex_value (*++ state.ptr)) == 0xFF || (uc_b4 = hex_value (*++ state.ptr)) == 0xFF) { sprintf (error, "Invalid character value `%c` (at %d:%d)", b, line_and_col); goto e_failed; } uc_b1 = (uc_b1 << 4) | uc_b2; uc_b2 = (uc_b3 << 4) | uc_b4; uchar2 = (uc_b1 << 8) | uc_b2; uchar = 0x010000 | ((uchar & 0x3FF) << 10) | (uchar2 & 0x3FF); } if (sizeof (json_char) >= sizeof (json_uchar) || (uchar <= 0x7F)) { string_add ((json_char) uchar); break; } if (uchar <= 0x7FF) { if (state.first_pass) string_length += 2; else { string [string_length ++] = 0xC0 | (uchar >> 6); string [string_length ++] = 0x80 | (uchar & 0x3F); } break; } if (uchar <= 0xFFFF) { if (state.first_pass) string_length += 3; else { string [string_length ++] = 0xE0 | (uchar >> 12); string [string_length ++] = 0x80 | ((uchar >> 6) & 0x3F); string [string_length ++] = 0x80 | (uchar & 0x3F); } break; } if (state.first_pass) string_length += 4; else { string [string_length ++] = 0xF0 | (uchar >> 18); string [string_length ++] = 0x80 | ((uchar >> 12) & 0x3F); string [string_length ++] = 0x80 | ((uchar >> 6) & 0x3F); string [string_length ++] = 0x80 | (uchar & 0x3F); } break; default: string_add (b); }; continue; } if (b == '\\') { flags |= flag_escaped; continue; } if (b == '"') { if (!state.first_pass) string [string_length] = 0; flags &= ~ flag_string; string = 0; switch (top->type) { case json_string: top->u.string.length = string_length; flags |= flag_next; break; case json_object: 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; top->u.object.values [top->u.object.length].name_length = string_length; (*(json_char **) &top->_reserved.object_mem) += string_length + 1; } flags |= flag_seek_value | flag_need_colon; continue; default: break; }; } 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; -- state.ptr; /* so null can be reproc'd */ } continue; } if (flags & flag_block_comment) { if (!b) { sprintf (error, "%d:%d: Unexpected EOF in block comment", line_and_col); goto e_failed; } if (b == '*' && state.ptr < (end - 1) && state.ptr [1] == '/') { flags &= ~ flag_block_comment; ++ state.ptr; /* 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", line_and_col); goto e_failed; } if (++ state.ptr == end) { sprintf (error, "%d:%d: EOF unexpected", line_and_col); goto e_failed; } switch (b = *state.ptr) { case '/': flags |= flag_line_comment; continue; case '*': flags |= flag_block_comment; continue; default: sprintf (error, "%d:%d: Unexpected `%c` in comment opening sequence", line_and_col, b); goto e_failed; }; } } if (flags & flag_done) { if (!b) break; switch (b) { whitespace: continue; default: sprintf (error, "%d:%d: Trailing garbage: `%c`", state.cur_line, state.cur_col, b); goto e_failed; }; } if (flags & flag_seek_value) { switch (b) { whitespace: continue; case ']': if (top && top->type == json_array) flags = (flags & ~ (flag_need_comma | flag_seek_value)) | flag_next; else { sprintf (error, "%d:%d: Unexpected ]", line_and_col); goto e_failed; } break; default: if (flags & flag_need_comma) { if (b == ',') { flags &= ~ flag_need_comma; continue; } else { sprintf (error, "%d:%d: Expected , before %c", state.cur_line, state.cur_col, b); goto e_failed; } } if (flags & flag_need_colon) { if (b == ':') { flags &= ~ flag_need_colon; continue; } else { sprintf (error, "%d:%d: Expected : before %c", state.cur_line, state.cur_col, b); goto e_failed; } } flags &= ~ flag_seek_value; switch (b) { case '{': if (!new_value (&state, &top, &root, &alloc, json_object)) goto e_alloc_failure; continue; case '[': 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)) goto e_alloc_failure; flags |= flag_string; string = top->u.string.ptr; string_length = 0; continue; case 't': if ((end - state.ptr) < 3 || *(++ state.ptr) != 'r' || *(++ state.ptr) != 'u' || *(++ state.ptr) != 'e') { goto e_unknown_value; } if (!new_value (&state, &top, &root, &alloc, json_boolean)) goto e_alloc_failure; top->u.boolean = 1; flags |= flag_next; break; case 'f': if ((end - state.ptr) < 4 || *(++ state.ptr) != 'a' || *(++ state.ptr) != 'l' || *(++ state.ptr) != 's' || *(++ state.ptr) != 'e') { goto e_unknown_value; } if (!new_value (&state, &top, &root, &alloc, json_boolean)) goto e_alloc_failure; flags |= flag_next; break; case 'n': if ((end - state.ptr) < 3 || *(++ state.ptr) != 'u' || *(++ state.ptr) != 'l' || *(++ state.ptr) != 'l') { goto e_unknown_value; } if (!new_value (&state, &top, &root, &alloc, json_null)) goto e_alloc_failure; flags |= flag_next; break; default: if (isdigit (b) || b == '-') { if (!new_value (&state, &top, &root, &alloc, json_integer)) goto e_alloc_failure; if (!state.first_pass) { while (isdigit (b) || b == '+' || b == '-' || b == 'e' || b == 'E' || b == '.') { if ( (++ state.ptr) == end) { b = 0; break; } b = *state.ptr; } flags |= flag_next | flag_reproc; break; } 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 != '-') { flags |= flag_reproc; break; } flags |= flag_num_negative; continue; } else { sprintf (error, "%d:%d: Unexpected %c when seeking value", line_and_col, b); goto e_failed; } }; }; } else { switch (top->type) { case json_object: switch (b) { whitespace: continue; case '"': if (flags & flag_need_comma) { sprintf (error, "%d:%d: Expected , before \"", line_and_col); goto e_failed; } flags |= flag_string; string = (json_char *) top->_reserved.object_mem; string_length = 0; break; case '}': flags = (flags & ~ flag_need_comma) | flag_next; break; case ',': if (flags & flag_need_comma) { flags &= ~ flag_need_comma; break; } default: sprintf (error, "%d:%d: Unexpected `%c` in object", line_and_col, b); goto e_failed; }; break; case json_integer: case json_double: if (isdigit (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`", line_and_col, b); goto e_failed; } if (num_digits == 1 && b == '0') flags |= flag_num_zero; } else { flags |= flag_num_e_got_sign; num_e = (num_e * 10) + (b - '0'); continue; } top->u.integer = (top->u.integer * 10) + (b - '0'); continue; } num_fraction = (num_fraction * 10) + (b - '0'); continue; } if (b == '+' || b == '-') { if ( (flags & flag_num_e) && !(flags & flag_num_e_got_sign)) { flags |= flag_num_e_got_sign; 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 `.`", line_and_col); goto e_failed; } top->type = json_double; 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 `.`", line_and_col); goto e_failed; } top->u.dbl += ((double) num_fraction) / (pow (10.0, (double) num_digits)); } if (b == 'e' || b == 'E') { flags |= flag_num_e; if (top->type == json_integer) { top->type = json_double; top->u.dbl = (double) top->u.integer; } num_digits = 0; flags &= ~ flag_num_zero; continue; } } else { if (!num_digits) { sprintf (error, "%d:%d: Expected digit after `e`", line_and_col); goto e_failed; } top->u.dbl *= pow (10.0, (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; } flags |= flag_next | flag_reproc; break; default: break; }; } if (flags & flag_reproc) { flags &= ~ flag_reproc; -- state.ptr; } if (flags & flag_next) { flags = (flags & ~ flag_next) | flag_need_comma; if (!top->parent) { /* root value done */ flags |= flag_done; continue; } if (top->parent->type == json_array) flags |= flag_seek_value; if (!state.first_pass) { json_value * parent = top->parent; switch (parent->type) { case json_object: parent->u.object.values [parent->u.object.length].value = top; break; case json_array: parent->u.array.values [parent->u.array.length] = top; break; default: break; }; } if ( (++ top->parent->u.array.length) > state.uint_max) goto e_overflow; top = top->parent; continue; } } alloc = root; } return root; e_unknown_value: sprintf (error, "%d:%d: Unknown value", line_and_col); goto e_failed; e_alloc_failure: strcpy (error, "Memory allocation failure"); goto e_failed; e_overflow: sprintf (error, "%d:%d: Too long (caught overflow)", line_and_col); goto e_failed; e_failed: if (error_buf) { if (*error) strcpy (error_buf, error); else strcpy (error_buf, "Unknown error"); } if (state.first_pass) alloc = root; while (alloc) { top = alloc->_reserved.next_alloc; state.settings.mem_free (alloc, state.settings.user_data); alloc = top; } 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_settings settings = { 0 }; return json_parse_ex (&settings, json, length, 0); } void json_value_free_ex (json_settings * settings, json_value * value) { json_value * cur_value; if (!value) return; value->parent = 0; while (value) { switch (value->type) { case json_array: 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]; continue; case json_object: 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; continue; case json_string: 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); } } void json_value_free (json_value * value) { json_settings settings = { 0 }; settings.mem_free = default_free; json_value_free_ex (&settings, value); } simple-obfs-0.0.5/src/json.h000066400000000000000000000144071320326276300156570ustar00rootroot00000000000000 /* vim: set et ts=3 sw=3 sts=3 ft=c: * * Copyright (C) 2012, 2013, 2014 James McLaughlin et al. All rights reserved. * https://github.com/udp/json-parser * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 _JSON_H #define _JSON_H #ifndef json_char #define json_char char #endif #ifndef json_int_t #ifndef _MSC_VER #include #define json_int_t int64_t #else #define json_int_t __int64 #endif #endif #include #ifdef __cplusplus #include extern "C" { #endif typedef struct { unsigned long max_memory; int settings; /* 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 * user_data; /* will be passed to mem_alloc and mem_free */ size_t value_extra; /* how much extra space to allocate for values? */ } 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 } json_type; extern const struct _json_value json_value_none; typedef struct _json_object_entry { json_char * name; unsigned int name_length; struct _json_value * value; } json_object_entry; typedef struct _json_value { struct _json_value * parent; json_type type; union { int boolean; json_int_t integer; double dbl; struct { unsigned int length; json_char * ptr; /* null terminated */ } string; struct { unsigned int length; json_object_entry * values; #if defined(__cplusplus) && __cplusplus >= 201103L decltype(values) begin () const { return values; } decltype(values) end () const { return values + length; } #endif } object; 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; } #endif } array; } u; union { struct _json_value * next_alloc; void * object_mem; } _reserved; #ifdef JSON_TRACK_SOURCE /* Location of the value in the source JSON */ unsigned int line, col; #endif /* Some C++ operator sugar */ #ifdef __cplusplus 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; return json_value_none; } 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; return u.boolean != 0; } inline operator double () const { switch (type) { case json_integer: return (double) u.integer; case json_double: return u.dbl; default: return 0; }; } #endif } json_value; 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); 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 *); #ifdef __cplusplus } /* extern "C" */ #endif #endif simple-obfs-0.0.5/src/local.c000066400000000000000000001122541320326276300157720ustar00rootroot00000000000000/* * local.c - Setup a tunneling proxy through remote simple-obfs server * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include #include #ifndef __MINGW32__ #include #include #include #include #endif #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__) #include #include #define SET_INTERFACE #endif #include #ifdef __MINGW32__ #include "win32.h" #define __ev_io_init(a, b, c, d) ev_io_init(a, b, _open_osfhandle(c, 0), d) #else #define __ev_io_init(a, b, c, d) ev_io_init(a, b, c, d) #endif #include "netutils.h" #include "utils.h" #include "obfs_http.h" #include "obfs_tls.h" #include "options.h" #include "local.h" #ifdef __APPLE__ #include #if defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10 #include #define HAVE_LAUNCHD #endif #endif #ifndef EAGAIN #define EAGAIN EWOULDBLOCK #endif #ifndef EWOULDBLOCK #define EWOULDBLOCK EAGAIN #endif #ifndef BUF_SIZE #define BUF_SIZE 2048 #endif int verbose = 0; int keep_resolving = 1; #ifdef ANDROID int vpn = 0; uint64_t tx = 0; uint64_t rx = 0; ev_tstamp last = 0; #endif static int ipv6first = 0; static int fast_open = 0; static obfs_para_t *obfs_para = NULL; #ifdef HAVE_SETRLIMIT static int nofile = 0; #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); #ifndef __MINGW32__ static void signal_cb(EV_P_ ev_signal *w, int revents); #endif static int create_and_bind(const char *addr, const char *port); #ifdef HAVE_LAUNCHD static int launch_or_create(const char *addr, const char *port); #endif static remote_t *create_remote(listen_ctx_t *listener, struct sockaddr *addr); static void free_remote(remote_t *remote); static void close_and_free_remote(EV_P_ remote_t *remote); static void free_server(server_t *server); static void close_and_free_server(EV_P_ server_t *server); static remote_t *new_remote(int fd, int timeout); static server_t *new_server(int fd); static struct cork_dllist connections; #ifndef __MINGW32__ int setnonblocking(int fd) { int flags; if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { flags = 0; } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } static void parent_watcher_cb(EV_P_ ev_timer *watcher, int revents) { static int ppid = -1; int cur_ppid = getppid(); if (ppid != -1) { if (ppid != cur_ppid) { keep_resolving = 0; ev_unloop(EV_A_ EVUNLOOP_ALL); } } ppid = cur_ppid; } #endif int create_and_bind(const char *addr, const char *port) { struct addrinfo hints; struct addrinfo *result, *rp; int s, listen_sock; memset(&hints, 0, sizeof(struct addrinfo)); 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) { LOGE("getaddrinfo (%s:%s), error %s", addr, port, gai_strerror(s)); return -1; } 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) { continue; } int opt = 1; setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); #ifdef SO_NOSIGPIPE setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif int err = set_reuseport(listen_sock); if (err == 0) { LOGI("tcp port reuse enabled"); } s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen); if (s == 0) { /* We managed to bind successfully! */ break; } else { ERROR("bind"); } close(listen_sock); } if (rp == NULL) { LOGE("Could not bind"); return -1; } freeaddrinfo(result); return listen_sock; } #ifdef HAVE_LAUNCHD int launch_or_create(const char *addr, const char *port) { int *fds; size_t cnt; int error = launch_activate_socket("Listeners", &fds, &cnt); if (error == 0) { if (cnt == 1) { return fds[0]; } else { FATAL("please don't specify multi entry"); } } else if (error == ESRCH || error == ENOENT) { /* ESRCH: The calling process is not managed by launchd(8). * ENOENT: The socket name specified does not exist * in the caller's launchd.plist(5). */ if (port == NULL) { usage(); exit(EXIT_FAILURE); } return create_and_bind(addr, port); } else { FATAL("launch_activate_socket() error"); } return -1; } #endif static void free_connections(struct ev_loop *loop) { struct cork_dllist_item *curr, *next; cork_dllist_foreach_void(&connections, curr, next) { server_t *server = cork_container_of(curr, server_t, entries); remote_t *remote = server->remote; close_and_free_server(loop, server); close_and_free_remote(loop, remote); } } static void server_recv_cb(EV_P_ ev_io *w, int revents) { server_ctx_t *server_recv_ctx = (server_ctx_t *)w; server_t *server = server_recv_ctx->server; remote_t *remote = server->remote; buffer_t *buf; ssize_t r; if (remote == NULL) { buf = server->buf; } else { buf = remote->buf; } r = recv(server->fd, buf->data + buf->len, BUF_SIZE - buf->len, 0); if (r == 0) { // connection closed close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } else if (r == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; } else { if (verbose) ERROR("server_recv_cb_recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } buf->len += r; while (1) { // local socks5 server if (server->stage == STAGE_STREAM) { if (remote == NULL) { LOGE("invalid remote"); close_and_free_server(EV_A_ server); return; } #ifdef ANDROID tx += remote->buf->len; #endif if (obfs_para) obfs_para->obfs_request(remote->buf, BUF_SIZE, server->obfs); if (!remote->send_ctx->connected) { #ifdef ANDROID if (vpn) { int not_protect = 0; if (remote->addr.ss_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *)&remote->addr; if (s->sin_addr.s_addr == inet_addr("127.0.0.1")) not_protect = 1; } if (!not_protect) { if (protect_socket(remote->fd) == -1) { ERROR("protect_socket"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } } #endif remote->buf->idx = 0; if (!fast_open) { // connecting, wait until connected int r = connect(remote->fd, (struct sockaddr *)&(remote->addr), remote->addr_len); if (r == -1 && errno != CONNECT_IN_PROGRESS) { ERROR("connect"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } // 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 { #ifdef TCP_FASTOPEN #ifdef __APPLE__ ((struct sockaddr_in *)&(remote->addr))->sin_len = sizeof(struct sockaddr_in); sa_endpoints_t endpoints; memset((char *)&endpoints, 0, sizeof(endpoints)); endpoints.sae_dstaddr = (struct sockaddr *)&(remote->addr); endpoints.sae_dstaddrlen = remote->addr_len; int s = connectx(remote->fd, &endpoints, SAE_ASSOCID_ANY, CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT, NULL, 0, NULL, NULL); if (s == 0) { s = send(remote->fd, remote->buf->data, remote->buf->len, 0); } #else int s = sendto(remote->fd, remote->buf->data, remote->buf->len, MSG_FASTOPEN, (struct sockaddr *)&(remote->addr), remote->addr_len); #endif if (s == -1) { if (errno == CONNECT_IN_PROGRESS) { // in progress, wait until connected remote->buf->idx = 0; ev_io_stop(EV_A_ & server_recv_ctx->io); ev_io_start(EV_A_ & remote->send_ctx->io); return; } else { ERROR("sendto"); if (errno == ENOTCONN) { LOGE("fast open is not supported on this platform"); // just turn it off fast_open = 0; } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } else if (s < (int)(remote->buf->len)) { remote->buf->len -= s; remote->buf->idx = s; 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); return; } else { // Just connected remote->buf->idx = 0; remote->buf->len = 0; #ifdef __APPLE__ 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 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); return; #endif } #else // if TCP_FASTOPEN is not defined, fast_open will always be 0 FATAL("can't come here"); #endif } } else { int s = send(remote->fd, remote->buf->data, remote->buf->len, 0); if (s == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send remote->buf->idx = 0; ev_io_stop(EV_A_ & server_recv_ctx->io); ev_io_start(EV_A_ & remote->send_ctx->io); return; } else { ERROR("server_recv_cb_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } else if (s < (int)(remote->buf->len)) { remote->buf->len -= s; remote->buf->idx = s; ev_io_stop(EV_A_ & server_recv_ctx->io); ev_io_start(EV_A_ & remote->send_ctx->io); return; } else { remote->buf->idx = 0; remote->buf->len = 0; } } // all processed return; } else if (server->stage == STAGE_INIT) { server->stage = STAGE_STREAM; remote = create_remote(server->listener, NULL); if (remote == NULL) { LOGE("invalid remote addr"); close_and_free_server(EV_A_ server); return; } if (buf->len > 0) { memcpy(remote->buf->data, buf->data, buf->len); remote->buf->len = buf->len; } server->remote = remote; remote->server = server; } } } static void server_send_cb(EV_P_ ev_io *w, int revents) { server_ctx_t *server_send_ctx = (server_ctx_t *)w; server_t *server = server_send_ctx->server; remote_t *remote = server->remote; if (server->buf->len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } else { // has data to send ssize_t s = send(server->fd, server->buf->data + server->buf->idx, server->buf->len, 0); if (s == -1) { 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 < (ssize_t)(server->buf->len)) { // partly sent, move memory, wait for the next time to send server->buf->len -= s; server->buf->idx += s; return; } 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); return; } } } static void remote_timeout_cb(EV_P_ ev_timer *watcher, int revents) { remote_ctx_t *remote_ctx = cork_container_of(watcher, remote_ctx_t, watcher); remote_t *remote = remote_ctx->remote; server_t *server = remote->server; if (verbose) { LOGI("TCP connection timeout"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } static void remote_recv_cb(EV_P_ ev_io *w, int revents) { remote_ctx_t *remote_recv_ctx = (remote_ctx_t *)w; remote_t *remote = remote_recv_ctx->remote; server_t *server = remote->server; ev_timer_again(EV_A_ & remote->recv_ctx->watcher); ssize_t r = recv(remote->fd, server->buf->data, BUF_SIZE, 0); if (r == 0) { // connection closed close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } else if (r == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data // continue to wait for recv return; } else { ERROR("remote_recv_cb_recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } server->buf->len = r; if (!remote->direct) { #ifdef ANDROID rx += server->buf->len; #endif if (obfs_para) { if (obfs_para->deobfs_response(server->buf, BUF_SIZE, server->obfs)) { LOGE("invalid obfuscating"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } } int s = send(server->fd, server->buf->data, server->buf->len, 0); if (s == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send server->buf->idx = 0; ev_io_stop(EV_A_ & remote_recv_ctx->io); ev_io_start(EV_A_ & server->send_ctx->io); } else { ERROR("remote_recv_cb_send"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } else if (s < (int)(server->buf->len)) { server->buf->len -= s; server->buf->idx = s; ev_io_stop(EV_A_ & remote_recv_ctx->io); ev_io_start(EV_A_ & server->send_ctx->io); } // Disable TCP_NODELAY after the first response are sent if (!remote->recv_ctx->connected) { int opt = 0; setsockopt(server->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); setsockopt(remote->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); remote->recv_ctx->connected = 1; } } static void remote_send_cb(EV_P_ ev_io *w, int revents) { remote_ctx_t *remote_send_ctx = (remote_ctx_t *)w; remote_t *remote = remote_send_ctx->remote; server_t *server = remote->server; 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) { 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); // 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); return; } } else { // not connected ERROR("getpeername"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } if (remote->buf->len == 0) { // close and free close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } else { // has data to send ssize_t s = send(remote->fd, remote->buf->data + remote->buf->idx, remote->buf->len, 0); if (s == -1) { 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 < (ssize_t)(remote->buf->len)) { // partly sent, move memory, wait for the next time to send remote->buf->len -= s; remote->buf->idx += s; return; } 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); } } } static remote_t * new_remote(int fd, int timeout) { remote_t *remote; remote = ss_malloc(sizeof(remote_t)); memset(remote, 0, sizeof(remote_t)); remote->buf = ss_malloc(sizeof(buffer_t)); remote->recv_ctx = ss_malloc(sizeof(remote_ctx_t)); remote->send_ctx = ss_malloc(sizeof(remote_ctx_t)); balloc(remote->buf, BUF_SIZE); memset(remote->recv_ctx, 0, sizeof(remote_ctx_t)); memset(remote->send_ctx, 0, sizeof(remote_ctx_t)); remote->recv_ctx->connected = 0; remote->send_ctx->connected = 0; remote->fd = fd; remote->recv_ctx->remote = remote; remote->send_ctx->remote = remote; __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, min(MAX_CONNECT_TIMEOUT, timeout), 0); ev_timer_init(&remote->recv_ctx->watcher, remote_timeout_cb, timeout, timeout); return remote; } static void free_remote(remote_t *remote) { if (remote->server != NULL) { remote->server->remote = NULL; } if (remote->buf != NULL) { bfree(remote->buf); ss_free(remote->buf); } ss_free(remote->recv_ctx); ss_free(remote->send_ctx); ss_free(remote); } static void close_and_free_remote(EV_P_ remote_t *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); close(remote->fd); free_remote(remote); } } static server_t * new_server(int fd) { server_t *server; server = ss_malloc(sizeof(server_t)); memset(server, 0, sizeof(server_t)); server->recv_ctx = ss_malloc(sizeof(server_ctx_t)); server->send_ctx = ss_malloc(sizeof(server_ctx_t)); server->buf = ss_malloc(sizeof(buffer_t)); balloc(server->buf, BUF_SIZE); memset(server->recv_ctx, 0, sizeof(server_ctx_t)); memset(server->send_ctx, 0, sizeof(server_ctx_t)); server->stage = STAGE_INIT; server->recv_ctx->connected = 0; server->send_ctx->connected = 0; server->fd = fd; server->recv_ctx->server = server; server->send_ctx->server = server; if (obfs_para != NULL) { server->obfs = (obfs_t *)ss_malloc(sizeof(obfs_t)); memset(server->obfs, 0, sizeof(obfs_t)); } __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); cork_dllist_add(&connections, &server->entries); return server; } static void free_server(server_t *server) { cork_dllist_remove(&server->entries); if (server->obfs != NULL) { bfree(server->obfs->buf); if (server->obfs->extra != NULL) ss_free(server->obfs->extra); ss_free(server->obfs); } if (server->remote != NULL) { server->remote->server = NULL; } if (server->buf != NULL) { bfree(server->buf); ss_free(server->buf); } ss_free(server->recv_ctx); ss_free(server->send_ctx); ss_free(server); } static void close_and_free_server(EV_P_ server_t *server) { 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 remote_t * create_remote(listen_ctx_t *listener, struct sockaddr *addr) { struct sockaddr *remote_addr; int index = rand() % listener->remote_num; if (addr == NULL) { remote_addr = listener->remote_addr[index]; } else { remote_addr = addr; } int remotefd = socket(remote_addr->sa_family, SOCK_STREAM, IPPROTO_TCP); if (remotefd == -1) { ERROR("socket"); return NULL; } int opt = 1; setsockopt(remotefd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); #ifdef SO_NOSIGPIPE setsockopt(remotefd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif if (listener->mptcp == 1) { int err = setsockopt(remotefd, SOL_TCP, MPTCP_ENABLED, &opt, sizeof(opt)); if (err == -1) { ERROR("failed to enable multipath TCP"); } } // Setup setnonblocking(remotefd); #ifdef SET_INTERFACE if (listener->iface) { if (setinterface(remotefd, listener->iface) == -1) ERROR("setinterface"); } #endif remote_t *remote = new_remote(remotefd, listener->timeout); remote->addr_len = get_sockaddr_len(remote_addr); memcpy(&(remote->addr), remote_addr, remote->addr_len); return remote; } #ifndef __MINGW32__ static void signal_cb(EV_P_ ev_signal *w, int revents) { if (revents & EV_SIGNAL) { switch (w->signum) { case SIGINT: case SIGTERM: case SIGUSR1: keep_resolving = 0; ev_unloop(EV_A_ EVUNLOOP_ALL); } } } #endif void accept_cb(EV_P_ ev_io *w, int revents) { listen_ctx_t *listener = (listen_ctx_t *)w; int serverfd = accept(listener->fd, NULL, NULL); if (serverfd == -1) { ERROR("accept"); return; } setnonblocking(serverfd); int opt = 1; setsockopt(serverfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); #ifdef SO_NOSIGPIPE setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif server_t *server = new_server(serverfd); server->listener = listener; ev_io_start(EV_A_ & server->recv_ctx->io); } int main(int argc, char **argv) { int i, c; int pid_flags = 0; int mptcp = 0; char *user = NULL; char *local_port = NULL; char *local_addr = NULL; char *timeout = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; char *obfs_host = NULL; srand(time(NULL)); int remote_num = 0; ss_addr_t remote_addr[MAX_REMOTE_NUM]; char *remote_port = NULL; char *ss_remote_host = getenv("SS_REMOTE_HOST"); char *ss_remote_port = getenv("SS_REMOTE_PORT"); char *ss_local_host = getenv("SS_LOCAL_HOST"); char *ss_local_port = getenv("SS_LOCAL_PORT"); char *ss_plugin_opts = getenv("SS_PLUGIN_OPTIONS"); if (ss_remote_host != NULL) { ss_remote_host = strdup(ss_remote_host); char *delim = "|"; char *p = strtok(ss_remote_host, delim); do { remote_addr[remote_num].host = p; remote_addr[remote_num++].port = NULL; } while ((p = strtok(NULL, delim))); } if (ss_remote_port != NULL) { remote_port = ss_remote_port; } if (ss_local_host != NULL) { local_addr = ss_local_host; } if (ss_local_port != NULL) { local_port = ss_local_port; } if (ss_plugin_opts != NULL) { ss_plugin_opts = strdup(ss_plugin_opts); options_t opts; int opt_num = parse_options(ss_plugin_opts, strlen(ss_plugin_opts), &opts); for (i = 0; i < opt_num; i++) { char *key = opts.keys[i]; char *value = opts.values[i]; if (key == NULL) continue; size_t key_len = strlen(key); if (key_len == 0) continue; if (key_len == 1) { char c = key[0]; switch (c) { case 't': timeout = value; break; case 'c': conf_path = value; break; case 'i': iface = value; break; case 'a': user = value; break; case 'v': verbose = 1; break; #ifdef ANDROID case 'V': vpn = 1; break; #endif case '6': ipv6first = 1; break; } } else { if (strcmp(key, "fast-open") == 0) { fast_open = 1; } else if (strcmp(key, "obfs") == 0) { if (strcmp(value, obfs_http->name) == 0) obfs_para = obfs_http; else if (strcmp(value, obfs_tls->name) == 0) obfs_para = obfs_tls; } else if (strcmp(key, "obfs-host") == 0) { obfs_host = value; #ifdef __linux__ } else if (strcmp(key, "mptcp") == 0) { mptcp = 1; LOGI("enable multipath TCP"); #endif } } } } int option_index = 0; static struct option long_options[] = { { "fast-open", no_argument, 0, 0 }, { "mptcp", no_argument, 0, 0 }, { "obfs", required_argument, 0, 0 }, { "obfs-host", required_argument, 0, 0 }, { "help", no_argument, 0, 0 }, { 0, 0, 0, 0 } }; opterr = 0; USE_TTY(); #ifdef ANDROID while ((c = getopt_long(argc, argv, "f:s:p:l:t:i:c:b:a:n:hvV6", long_options, &option_index)) != -1) { #else while ((c = getopt_long(argc, argv, "f:s:p:l:t:i:c:b:a:n:hv6", long_options, &option_index)) != -1) { #endif switch (c) { case 0: if (option_index == 0) { fast_open = 1; } else if (option_index == 1) { mptcp = 1; LOGI("enable multipath TCP"); } else if (option_index == 2) { if (strcmp(optarg, obfs_http->name) == 0) obfs_para = obfs_http; else if (strcmp(optarg, obfs_tls->name) == 0) obfs_para = obfs_tls; } else if (option_index == 3) { obfs_host = optarg; } else if (option_index == 4) { usage(); exit(EXIT_SUCCESS); } break; case 's': if (remote_num < MAX_REMOTE_NUM) { remote_addr[remote_num].host = optarg; remote_addr[remote_num++].port = NULL; } break; case 'p': remote_port = optarg; break; case 'l': local_port = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'b': local_addr = optarg; break; case 'a': user = optarg; break; #ifdef HAVE_SETRLIMIT case 'n': nofile = atoi(optarg); break; #endif case 'v': verbose = 1; break; case 'h': usage(); exit(EXIT_SUCCESS); case '6': ipv6first = 1; break; #ifdef ANDROID case 'V': vpn = 1; break; #endif case '?': // The option character is not recognized. LOGE("Unrecognized option: %s", optarg); opterr = 1; break; } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (remote_num == 0) { remote_num = conf->remote_num; 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 (timeout == NULL) { timeout = conf->timeout; } if (user == NULL) { user = conf->user; } if (obfs_para == NULL && conf->obfs != NULL) { if (strcmp(conf->obfs, obfs_http->name) == 0) obfs_para = obfs_http; else if (strcmp(conf->obfs, obfs_tls->name) == 0) obfs_para = obfs_tls; } if (obfs_host == NULL) { obfs_host = conf->obfs_host; } if (fast_open == 0) { fast_open = conf->fast_open; } if (mptcp == 0) { mptcp = conf->mptcp; } #ifdef HAVE_SETRLIMIT if (nofile == 0) { nofile = conf->nofile; } #endif } if (remote_num == 0 || remote_port == NULL || #ifndef HAVE_LAUNCHD local_port == NULL || #endif obfs_para == NULL) { usage(); exit(EXIT_FAILURE); } if (timeout == NULL) { timeout = "600"; } #ifdef HAVE_SETRLIMIT /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ if (nofile > 1024) { if (verbose) { LOGI("setting NOFILE to %d", nofile); } set_nofile(nofile); } #endif if (local_addr == NULL) { local_addr = "127.0.0.1"; } if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } if (fast_open == 1) { #ifdef TCP_FASTOPEN LOGI("using tcp fast open"); #else LOGE("tcp fast open is not supported by this environment"); fast_open = 0; #endif } if (ipv6first) { LOGI("resolving hostname to IPv6 address first"); } if (obfs_para) { if (obfs_host != NULL) obfs_para->host = obfs_host; else obfs_para->host = "cloudfront.net"; obfs_para->port = atoi(remote_port); LOGI("obfuscating enabled"); if (obfs_host) LOGI("obfuscating hostname: %s", obfs_host); } #ifdef __MINGW32__ winsock_init(); #else // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGABRT, SIG_IGN); #endif // Setup proxy context listen_ctx_t listen_ctx; listen_ctx.remote_num = remote_num; listen_ctx.remote_addr = ss_malloc(sizeof(struct sockaddr *) * remote_num); memset(listen_ctx.remote_addr, 0, sizeof(struct sockaddr *) * remote_num); for (i = 0; i < remote_num; i++) { char *host = remote_addr[i].host; char *port = remote_addr[i].port == NULL ? remote_port : remote_addr[i].port; struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage)); memset(storage, 0, sizeof(struct sockaddr_storage)); if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) { FATAL("failed to resolve the provided hostname"); } listen_ctx.remote_addr[i] = (struct sockaddr *)storage; } listen_ctx.timeout = atoi(timeout); listen_ctx.iface = iface; listen_ctx.mptcp = mptcp; #ifndef __MINGW32__ // Setup signal handler struct ev_signal sigint_watcher; struct ev_signal sigterm_watcher; ev_signal_init(&sigint_watcher, signal_cb, SIGINT); ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM); ev_signal_start(EV_DEFAULT, &sigint_watcher); ev_signal_start(EV_DEFAULT, &sigterm_watcher); #endif #ifndef __MINGW32__ ev_timer parent_watcher; ev_timer_init(&parent_watcher, parent_watcher_cb, 0, UPDATE_INTERVAL); ev_timer_start(EV_DEFAULT, &parent_watcher); #endif struct ev_loop *loop = EV_DEFAULT; // Setup socket int listenfd; #ifdef HAVE_LAUNCHD listenfd = launch_or_create(local_addr, local_port); #else listenfd = create_and_bind(local_addr, local_port); #endif if (listenfd == -1) { FATAL("bind() error"); } if (listen(listenfd, SOMAXCONN) == -1) { FATAL("listen() error"); } setnonblocking(listenfd); listen_ctx.fd = listenfd; __ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx.io); #ifdef HAVE_LAUNCHD if (local_port == NULL) LOGI("listening through launchd"); else #endif if (strcmp(local_addr, ":") > 0) LOGI("listening at [%s]:%s", local_addr, local_port); else LOGI("listening at %s:%s", local_addr, local_port); // setuid if (user != NULL && !run_as(user)) { FATAL("failed to switch user"); } #ifndef __MINGW32__ if (geteuid() == 0) { LOGI("running from root user"); } #endif // Init connections cork_dllist_init(&connections); // Enter the loop ev_run(loop, 0); if (verbose) { LOGI("closed gracefully"); } // Clean up ev_io_stop(loop, &listen_ctx.io); free_connections(loop); for (i = 0; i < remote_num; i++) ss_free(listen_ctx.remote_addr[i]); ss_free(listen_ctx.remote_addr); #ifdef __MINGW32__ winsock_cleanup(); #else ev_signal_stop(EV_DEFAULT, &sigint_watcher); ev_signal_stop(EV_DEFAULT, &sigterm_watcher); #endif return 0; } simple-obfs-0.0.5/src/local.h000066400000000000000000000036221320326276300157750ustar00rootroot00000000000000/* * local.h - Define the client's buffers and callbacks * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _LOCAL_H #define _LOCAL_H #include #include #include "encrypt.h" #include "jconf.h" #include "common.h" typedef struct listen_ctx { ev_io io; char *iface; int remote_num; int method; int timeout; int fd; int mptcp; struct sockaddr **remote_addr; } listen_ctx_t; typedef struct server_ctx { ev_io io; int connected; struct server *server; } server_ctx_t; typedef struct server { int fd; int stage; obfs_t *obfs; struct server_ctx *recv_ctx; struct server_ctx *send_ctx; struct listen_ctx *listener; struct remote *remote; buffer_t *buf; struct cork_dllist_item entries; } server_t; typedef struct remote_ctx { ev_io io; ev_timer watcher; int connected; struct remote *remote; } remote_ctx_t; typedef struct remote { int fd; int direct; int addr_len; uint32_t counter; buffer_t *buf; struct remote_ctx *recv_ctx; struct remote_ctx *send_ctx; struct server *server; struct sockaddr_storage addr; } remote_t; #endif // _LOCAL_H simple-obfs-0.0.5/src/netutils.c000066400000000000000000000223531320326276300165470ustar00rootroot00000000000000/* * netutils.c - Network utilities * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #include #include #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef __MINGW32__ #include "win32.h" #define sleep(n) Sleep(1000 * (n)) #else #include #include #include #include #include #endif #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__) #include #include #define SET_INTERFACE #endif #include "netutils.h" #include "utils.h" #ifndef SO_REUSEPORT #define SO_REUSEPORT 15 #endif extern int verbose; static const char valid_label_bytes[] = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; #if defined(MODULE_LOCAL) extern int keep_resolving; #endif int set_reuseport(int socket) { int opt = 1; return setsockopt(socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); } size_t get_sockaddr_len(struct sockaddr *addr) { if (addr->sa_family == AF_INET) { return sizeof(struct sockaddr_in); } else if (addr->sa_family == AF_INET6) { return sizeof(struct sockaddr_in6); } return 0; } #ifdef SET_INTERFACE int setinterface(int socket_fd, const char *interface_name) { struct ifreq interface; memset(&interface, 0, sizeof(struct ifreq)); strncpy(interface.ifr_name, interface_name, IFNAMSIZ); int res = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, &interface, sizeof(struct ifreq)); return res; } #endif int bind_to_address(int socket_fd, const char *host) { if (host != NULL) { struct cork_ip ip; struct sockaddr_storage storage; memset(&storage, 0, sizeof(struct sockaddr_storage)); if (cork_ip_init(&ip, host) != -1) { if (ip.version == 4) { struct sockaddr_in *addr = (struct sockaddr_in *)&storage; inet_pton(AF_INET, host, &addr->sin_addr); addr->sin_family = AF_INET; return bind(socket_fd, (struct sockaddr *)addr, sizeof(struct sockaddr_in)); } else if (ip.version == 6) { struct sockaddr_in6 *addr = (struct sockaddr_in6 *)&storage; inet_pton(AF_INET6, host, &addr->sin6_addr); addr->sin6_family = AF_INET6; return bind(socket_fd, (struct sockaddr *)addr, sizeof(struct sockaddr_in6)); } } } return -1; } ssize_t get_sockaddr(char *host, char *port, struct sockaddr_storage *storage, int block, int ipv6first) { struct cork_ip ip; if (cork_ip_init(&ip, host) != -1) { if (ip.version == 4) { struct sockaddr_in *addr = (struct sockaddr_in *)storage; addr->sin_family = AF_INET; inet_pton(AF_INET, host, &(addr->sin_addr)); if (port != NULL) { addr->sin_port = htons(atoi(port)); } } else if (ip.version == 6) { struct sockaddr_in6 *addr = (struct sockaddr_in6 *)storage; addr->sin6_family = AF_INET6; inet_pton(AF_INET6, host, &(addr->sin6_addr)); if (port != NULL) { addr->sin6_port = htons(atoi(port)); } } return 0; } else { struct addrinfo hints; struct addrinfo *result, *rp; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */ int err, i; for (i = 1; i < 8; i++) { err = getaddrinfo(host, port, &hints, &result); #if defined(MODULE_LOCAL) if (!keep_resolving) break; #endif if ((!block || !err)) { break; } else { sleep(pow(2, i)); LOGE("failed to resolve server name, wait %.0f seconds", pow(2, i)); } } if (err != 0) { LOGE("getaddrinfo: %s", gai_strerror(err)); return -1; } int prefer_af = ipv6first ? AF_INET6 : AF_INET; for (rp = result; rp != NULL; rp = rp->ai_next) if (rp->ai_family == prefer_af) { if (rp->ai_family == AF_INET) memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in)); else if (rp->ai_family == AF_INET6) memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in6)); break; } if (rp == NULL) { for (rp = result; rp != NULL; rp = rp->ai_next) { if (rp->ai_family == AF_INET) memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in)); else if (rp->ai_family == AF_INET6) memcpy(storage, rp->ai_addr, sizeof(struct sockaddr_in6)); break; } } if (rp == NULL) { LOGE("failed to resolve remote addr"); return -1; } freeaddrinfo(result); return 0; } return -1; } int sockaddr_cmp(struct sockaddr_storage *addr1, struct sockaddr_storage *addr2, socklen_t len) { struct sockaddr_in *p1_in = (struct sockaddr_in *)addr1; struct sockaddr_in *p2_in = (struct sockaddr_in *)addr2; struct sockaddr_in6 *p1_in6 = (struct sockaddr_in6 *)addr1; struct sockaddr_in6 *p2_in6 = (struct sockaddr_in6 *)addr2; if (p1_in->sin_family < p2_in->sin_family) return -1; if (p1_in->sin_family > p2_in->sin_family) return 1; if (verbose) { LOGI("sockaddr_cmp: sin_family equal? %d", p1_in->sin_family == p2_in->sin_family); } /* compare ip4 */ if (p1_in->sin_family == AF_INET) { /* just order it, ntohs not required */ if (p1_in->sin_port < p2_in->sin_port) return -1; if (p1_in->sin_port > p2_in->sin_port) return 1; if (verbose) { LOGI("sockaddr_cmp: sin_port equal? %d", p1_in->sin_port == p2_in->sin_port); } return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE); } else if (p1_in6->sin6_family == AF_INET6) { /* just order it, ntohs not required */ if (p1_in6->sin6_port < p2_in6->sin6_port) return -1; if (p1_in6->sin6_port > p2_in6->sin6_port) return 1; if (verbose) { LOGI("sockaddr_cmp: sin6_port equal? %d", p1_in6->sin6_port == p2_in6->sin6_port); } return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr, INET6_SIZE); } else { /* eek unknown type, perform this comparison for sanity. */ return memcmp(addr1, addr2, len); } } int sockaddr_cmp_addr(struct sockaddr_storage *addr1, struct sockaddr_storage *addr2, socklen_t len) { struct sockaddr_in *p1_in = (struct sockaddr_in *)addr1; struct sockaddr_in *p2_in = (struct sockaddr_in *)addr2; struct sockaddr_in6 *p1_in6 = (struct sockaddr_in6 *)addr1; struct sockaddr_in6 *p2_in6 = (struct sockaddr_in6 *)addr2; if (p1_in->sin_family < p2_in->sin_family) return -1; if (p1_in->sin_family > p2_in->sin_family) return 1; if (verbose) { LOGI("sockaddr_cmp_addr: sin_family equal? %d", p1_in->sin_family == p2_in->sin_family); } /* compare ip4 */ if (p1_in->sin_family == AF_INET) { return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE); } else if (p1_in6->sin6_family == AF_INET6) { return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr, INET6_SIZE); } else { /* eek unknown type, perform this comparison for sanity. */ return memcmp(addr1, addr2, len); } } int validate_hostname(const char *hostname, const int hostname_len) { if (hostname == NULL) return 0; if (hostname_len < 1 || hostname_len > 255) return 0; if (hostname[0] == '.') return 0; const char *label = hostname; while (label < hostname + hostname_len) { size_t label_len = hostname_len - (label - hostname); char *next_dot = strchr(label, '.'); if (next_dot != NULL) label_len = next_dot - label; if (label + label_len > hostname + hostname_len) return 0; if (label_len > 63 || label_len < 1) return 0; if (label[0] == '-' || label[label_len - 1] == '-') return 0; if (strspn(label, valid_label_bytes) < label_len) return 0; label += label_len + 1; } return 1; } simple-obfs-0.0.5/src/netutils.h000066400000000000000000000053501320326276300165520ustar00rootroot00000000000000/* * netutils.h - Network utilities * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _NETUTILS_H #define _NETUTILS_H #if defined(__linux__) #include #elif !defined(__MINGW32__) #include #endif // only enable TCP_FASTOPEN on linux #if defined(__linux__) #include /* conditional define for TCP_FASTOPEN */ #ifndef TCP_FASTOPEN #define TCP_FASTOPEN 23 #endif /* conditional define for MSG_FASTOPEN */ #ifndef MSG_FASTOPEN #define MSG_FASTOPEN 0x20000000 #endif #elif !defined(__APPLE__) #ifdef TCP_FASTOPEN #undef TCP_FASTOPEN #endif #endif /* Backward compatibility for MPTCP_ENABLED between kernel 3 & 4 */ #ifndef MPTCP_ENABLED #ifdef TCP_CC_INFO #define MPTCP_ENABLED 42 #else #define MPTCP_ENABLED 26 #endif #endif /** byte size of ip4 address */ #define INET_SIZE 4 /** byte size of ip6 address */ #define INET6_SIZE 16 size_t get_sockaddr_len(struct sockaddr *addr); ssize_t get_sockaddr(char *host, char *port, struct sockaddr_storage *storage, int block, int ipv6first); int set_reuseport(int socket); #ifdef SET_INTERFACE int setinterface(int socket_fd, const char *interface_name); #endif int bind_to_address(int socket_fd, const char *address); /** * Compare two sockaddrs. Imposes an ordering on the addresses. * Compares address and port. * @param addr1: address 1. * @param addr2: address 2. * @param len: lengths of addr. * @return: 0 if addr1 == addr2. -1 if addr1 is smaller, +1 if larger. */ int sockaddr_cmp(struct sockaddr_storage *addr1, struct sockaddr_storage *addr2, socklen_t len); /** * Compare two sockaddrs. Compares address, not the port. * @param addr1: address 1. * @param addr2: address 2. * @param len: lengths of addr. * @return: 0 if addr1 == addr2. -1 if addr1 is smaller, +1 if larger. */ int sockaddr_cmp_addr(struct sockaddr_storage *addr1, struct sockaddr_storage *addr2, socklen_t len); int validate_hostname(const char *hostname, const int hostname_len); #endif simple-obfs-0.0.5/src/obfs.h000066400000000000000000000031151320326276300156310ustar00rootroot00000000000000/* * obfs.h - Interfaces of obfuscating function * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef OBFS_H #define OBFS_H #include #include "encrypt.h" #define OBFS_OK 0 #define OBFS_NEED_MORE -1 #define OBFS_ERROR -2 typedef struct obfs { int obfs_stage; int deobfs_stage; buffer_t *buf; void *extra; } obfs_t; typedef struct obfs_para { const char *name; const char *host; uint16_t port; bool send_empty_response_upon_connection; int(*const obfs_request)(buffer_t *, size_t, obfs_t *); int(*const obfs_response)(buffer_t *, size_t, obfs_t *); int(*const deobfs_request)(buffer_t *, size_t, obfs_t *); int(*const deobfs_response)(buffer_t *, size_t, obfs_t *); int(*const check_obfs)(buffer_t *); void(*const disable)(obfs_t *); int(*const is_enable)(obfs_t *); } obfs_para_t; #endif simple-obfs-0.0.5/src/obfs_http.c000066400000000000000000000206261320326276300166710ustar00rootroot00000000000000/* * obfs_http.c - Implementation of http obfuscating * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include /* isblank() */ #include "base64.h" #include "utils.h" #include "obfs_http.h" static const char *http_request_template = "GET / HTTP/1.1\r\n" "Host: %s\r\n" "User-Agent: curl/7.%d.%d\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key: %s\r\n" "Content-Length: %lu\r\n" "\r\n"; static const char *http_response_template = "HTTP/1.1 101 Switching Protocols\r\n" "Server: nginx/1.%d.%d\r\n" "Date: %s\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %s\r\n" "\r\n"; static int obfs_http_request(buffer_t *, size_t, obfs_t *); static int obfs_http_response(buffer_t *, size_t, obfs_t *); static int deobfs_http_header(buffer_t *, size_t, obfs_t *); static int check_http_header(buffer_t *buf); static void disable_http(obfs_t *obfs); static int is_enable_http(obfs_t *obfs); static int get_header(const char *, const char *, int, char **); static int next_header(const char **, int *); static obfs_para_t obfs_http_st = { .name = "http", .port = 80, .send_empty_response_upon_connection = true, .obfs_request = &obfs_http_request, .obfs_response = &obfs_http_response, .deobfs_request = &deobfs_http_header, .deobfs_response = &deobfs_http_header, .check_obfs = &check_http_header, .disable = &disable_http, .is_enable = &is_enable_http }; obfs_para_t *obfs_http = &obfs_http_st; static int obfs_http_request(buffer_t *buf, size_t cap, obfs_t *obfs) { if (obfs == NULL || obfs->obfs_stage != 0) return 0; obfs->obfs_stage++; static int major_version = 0; static int minor_version = 0; major_version = major_version ? major_version : rand() % 51; minor_version = minor_version ? minor_version : rand() % 2; char host_port[256]; char http_header[512]; uint8_t key[16]; char b64[64]; if (obfs_http->port != 80) snprintf(host_port, sizeof(host_port), "%s:%d", obfs_http->host, obfs_http->port); else snprintf(host_port, sizeof(host_port), "%s", obfs_http->host); rand_bytes(key, 16); base64_encode(b64, 64, key, 16); size_t obfs_len = snprintf(http_header, sizeof(http_header), http_request_template, host_port, major_version, minor_version, b64, buf->len); size_t buf_len = buf->len; brealloc(buf, obfs_len + buf_len, cap); memmove(buf->data + obfs_len, buf->data, buf_len); memcpy(buf->data, http_header, obfs_len); buf->len = obfs_len + buf_len; return buf->len; } static int obfs_http_response(buffer_t *buf, size_t cap, obfs_t *obfs) { if (obfs == NULL || obfs->obfs_stage != 0) return 0; obfs->obfs_stage++; static int major_version = 0; static int minor_version = 0; major_version = major_version ? major_version : rand() % 11; minor_version = minor_version ? minor_version : rand() % 12; char http_header[512]; char datetime[64]; uint8_t key[16]; char b64[64]; time_t now; struct tm *tm_now; time(&now); tm_now = localtime(&now); strftime(datetime, 64, "%a, %d %b %Y %H:%M:%S GMT", tm_now); rand_bytes(key, 16); base64_encode(b64, 64, key, 16); size_t buf_len = buf->len; size_t obfs_len = snprintf(http_header, sizeof(http_header), http_response_template, major_version, minor_version, datetime, b64); brealloc(buf, obfs_len + buf_len, cap); memmove(buf->data + obfs_len, buf->data, buf_len); memcpy(buf->data, http_header, obfs_len); buf->len = obfs_len + buf_len; return buf->len; } static int deobfs_http_header(buffer_t *buf, size_t cap, obfs_t *obfs) { if (obfs == NULL || obfs->deobfs_stage != 0) return 0; char *data = buf->data; int len = buf->len; int err = -1; // Allow empty content while (len >= 4) { if (data[0] == '\r' && data[1] == '\n' && data[2] == '\r' && data[3] == '\n') { len -= 4; data += 4; err = 0; break; } len--; data++; } if (!err) { memmove(buf->data, data, len); buf->len = len; obfs->deobfs_stage++; } return err; } static int check_http_header(buffer_t *buf) { char *data = buf->data; int len = buf->len; if (len < 4) return OBFS_NEED_MORE; if (strncasecmp(data, "GET", 3) != 0) return OBFS_ERROR; { char *protocol; int result = get_header("Upgrade:", data, len, &protocol); if (result < 0) { if (result == -1) return OBFS_NEED_MORE; else return OBFS_ERROR; } if (strncmp(protocol, "websocket", result) != 0) { free(protocol); return OBFS_ERROR; } else { free(protocol); } } if (obfs_http->host != NULL) { char *hostname; int i; int result = get_header("Host:", data, len, &hostname); if (result < 0) { if (result == -1) return OBFS_NEED_MORE; else return OBFS_ERROR; } /* * if the user specifies the port in the request, it is included here. * Host: example.com:80 * so we trim off port portion */ for (i = result - 1; i >= 0; i--) if ((hostname)[i] == ':') { (hostname)[i] = '\0'; result = i; break; } result = OBFS_ERROR; if (strncasecmp(hostname, obfs_http->host, result) == 0) { result = OBFS_OK; } free(hostname); return result; } return OBFS_OK; } static int get_header(const char *header, const char *data, int data_len, char **value) { int len, header_len; header_len = strlen(header); /* loop through headers stopping at first blank line */ while ((len = next_header(&data, &data_len)) != 0) if (len > header_len && strncasecmp(header, data, header_len) == 0) { /* Eat leading whitespace */ while (header_len < len && isblank((unsigned char)data[header_len])) header_len++; *value = malloc(len - header_len + 1); if (*value == NULL) return -4; strncpy(*value, data + header_len, len - header_len); (*value)[len - header_len] = '\0'; return len - header_len; } /* If there is no data left after reading all the headers then we do not * have a complete HTTP request, there must be a blank line */ if (data_len == 0) return -1; return -2; } static int next_header(const char **data, int *len) { int header_len; /* perhaps we can optimize this to reuse the value of header_len, rather * than scanning twice. * Walk our data stream until the end of the header */ while (*len > 2 && (*data)[0] != '\r' && (*data)[1] != '\n') { (*len)--; (*data)++; } /* advanced past the pair */ *data += 2; *len -= 2; /* Find the length of the next header */ header_len = 0; while (*len > header_len + 1 && (*data)[header_len] != '\r' && (*data)[header_len + 1] != '\n') header_len++; return header_len; } static void disable_http(obfs_t *obfs) { obfs->obfs_stage = -1; obfs->deobfs_stage = -1; } static int is_enable_http(obfs_t *obfs) { return obfs->obfs_stage != -1 && obfs->deobfs_stage != -1; } simple-obfs-0.0.5/src/obfs_http.h000066400000000000000000000016521320326276300166740ustar00rootroot00000000000000/* * obfs_http.h - Interfaces of http obfuscating function * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef OBFS_HTTP_H #define OBFS_HTTP_H #include "obfs.h" extern obfs_para_t *obfs_http; #endif simple-obfs-0.0.5/src/obfs_tls.c000066400000000000000000000374311320326276300165160ustar00rootroot00000000000000/* * obfs_tls.c - Implementation of tls obfuscating * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #define CT_HTONS(n) CORK_UINT16_HOST_TO_BIG(n) #define CT_NTOHS(n) CORK_UINT16_BIG_TO_HOST(n) #define CT_HTONL(n) CORK_UINT32_HOST_TO_BIG(n) #define CT_NTOHL(n) CORK_UINT32_BIG_TO_HOST(n) #include "base64.h" #include "utils.h" #include "obfs_tls.h" static const struct tls_client_hello tls_client_hello_template = { .content_type = 0x16, .version = CT_HTONS(0x0301), .len = 0, .handshake_type = 1, .handshake_len_1 = 0, .handshake_len_2 = 0, .handshake_version = CT_HTONS(0x0303), .random_unix_time = 0, .random_bytes = { 0 }, .session_id_len = 32, .session_id = { 0 }, .cipher_suites_len = CT_HTONS(56), .cipher_suites = { 0xc0, 0x2c, 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f, 0x00, 0x9e, 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0x9d, 0x00, 0x9c, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x35, 0x00, 0x2f, 0x00, 0xff }, .comp_methods_len = 1, .comp_methods = { 0 }, .ext_len = 0, }; static const struct tls_ext_server_name tls_ext_server_name_template = { .ext_type = 0, .ext_len = 0, .server_name_list_len = 0, .server_name_type = 0, .server_name_len = 0, // char server_name[server_name_len]; }; static const struct tls_ext_session_ticket tls_ext_session_ticket_template = { .session_ticket_type = CT_HTONS(0x0023), .session_ticket_ext_len = 0, // char session_ticket[session_ticket_ext_len]; }; static const struct tls_ext_others tls_ext_others_template = { .ec_point_formats_ext_type = CT_HTONS(0x000B), .ec_point_formats_ext_len = CT_HTONS(4), .ec_point_formats_len = 3, .ec_point_formats = { 0x01, 0x00, 0x02 }, .elliptic_curves_type = CT_HTONS(0x000a), .elliptic_curves_ext_len = CT_HTONS(10), .elliptic_curves_len = CT_HTONS(8), .elliptic_curves = { 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19, 0x00, 0x18 }, .sig_algos_type = CT_HTONS(0x000d), .sig_algos_ext_len = CT_HTONS(32), .sig_algos_len = CT_HTONS(30), .sig_algos = { 0x06, 0x01, 0x06, 0x02, 0x06, 0x03, 0x05, 0x01, 0x05, 0x02, 0x05, 0x03, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0x03, 0x01, 0x03, 0x02, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x03 }, .encrypt_then_mac_type = CT_HTONS(0x0016), .encrypt_then_mac_ext_len = 0, .extended_master_secret_type = CT_HTONS(0x0017), .extended_master_secret_ext_len = 0, }; static const struct tls_server_hello tls_server_hello_template = { .content_type = 0x16, .version = CT_HTONS(0x0301), .len = CT_HTONS(91), .handshake_type = 2, .handshake_len_1 = 0, .handshake_len_2 = CT_HTONS(87), .handshake_version = CT_HTONS(0x0303), .random_unix_time = 0, .random_bytes = { 0 }, .session_id_len = 32, .session_id = { 0 }, .cipher_suite = CT_HTONS(0xCCA8), .comp_method = 0, .ext_len = 0, .ext_renego_info_type = CT_HTONS(0xFF01), .ext_renego_info_ext_len = CT_HTONS(1), .ext_renego_info_len = 0, .extended_master_secret_type = CT_HTONS(0x0017), .extended_master_secret_ext_len = 0, .ec_point_formats_ext_type = CT_HTONS(0x000B), .ec_point_formats_ext_len = CT_HTONS(2), .ec_point_formats_len = 1, .ec_point_formats = { 0 }, }; static const struct tls_change_cipher_spec tls_change_cipher_spec_template = { .content_type = 0x14, .version = CT_HTONS(0x0303), .len = CT_HTONS(1), .msg = 0x01, }; static const struct tls_encrypted_handshake tls_encrypted_handshake_template = { .content_type = 0x16, .version = CT_HTONS(0x0303), .len = 0, // char msg[len]; }; const char tls_data_header[3] = {0x17, 0x03, 0x03}; static int obfs_tls_request(buffer_t *, size_t, obfs_t *); static int obfs_tls_response(buffer_t *, size_t, obfs_t *); static int deobfs_tls_request(buffer_t *, size_t, obfs_t *); static int deobfs_tls_response(buffer_t *, size_t, obfs_t *); static int obfs_app_data(buffer_t *, size_t, obfs_t *); static int deobfs_app_data(buffer_t *, size_t, obfs_t *); static int check_tls_request(buffer_t *buf); static void disable_tls(obfs_t *obfs); static int is_enable_tls(obfs_t *obfs); static obfs_para_t obfs_tls_st = { .name = "tls", .port = 443, .send_empty_response_upon_connection = false, .obfs_request = &obfs_tls_request, .obfs_response = &obfs_tls_response, .deobfs_request = &deobfs_tls_request, .deobfs_response = &deobfs_tls_response, .check_obfs = &check_tls_request, .disable = &disable_tls, .is_enable = &is_enable_tls }; obfs_para_t *obfs_tls = &obfs_tls_st; static int obfs_app_data(buffer_t *buf, size_t cap, obfs_t *obfs) { size_t buf_len = buf->len; brealloc(buf, buf_len + 5, cap); memmove(buf->data + 5, buf->data, buf_len); memcpy(buf->data, tls_data_header, 3); *(uint16_t*)(buf->data + 3) = CT_HTONS(buf_len); buf->len = buf_len + 5; return 0; } static int deobfs_app_data(buffer_t *buf, size_t idx, obfs_t *obfs) { int bidx = idx, bofst = idx; frame_t *frame = (frame_t *)obfs->extra; while (bidx < buf->len) { if (frame->len == 0) { if (frame->idx >= 0 && frame->idx < 3 && buf->data[bidx] != tls_data_header[frame->idx]) { return OBFS_ERROR; } else if (frame->idx >= 3 && frame->idx < 5) { memcpy(frame->buf + frame->idx - 3, buf->data + bidx, 1); } else if (frame->idx < 0) { bofst++; } frame->idx++; bidx++; if (frame->idx == 5) { frame->len = CT_NTOHS(*(uint16_t *)(frame->buf)); frame->idx = 0; } continue; } if (frame->len > 16384) return OBFS_ERROR; int left_len = buf->len - bidx; if (left_len > frame->len) { memmove(buf->data + bofst, buf->data + bidx, frame->len); bidx += frame->len; bofst += frame->len; frame->len = 0; } else { memmove(buf->data + bofst, buf->data + bidx, left_len); bidx = buf->len; bofst += left_len; frame->len -= left_len; } } buf->len = bofst; return OBFS_OK; } static int obfs_tls_request(buffer_t *buf, size_t cap, obfs_t *obfs) { if (obfs == NULL || obfs->obfs_stage < 0) return 0; static buffer_t tmp = { 0, 0, 0, NULL }; if (obfs->obfs_stage == 0) { size_t buf_len = buf->len; size_t hello_len = sizeof(struct tls_client_hello); size_t server_name_len = sizeof(struct tls_ext_server_name); size_t host_len = strlen(obfs_tls->host); size_t ticket_len = sizeof(struct tls_ext_session_ticket); size_t other_ext_len = sizeof(struct tls_ext_others); size_t tls_len = buf_len + hello_len + server_name_len + host_len + ticket_len + other_ext_len; brealloc(&tmp, buf_len, cap); brealloc(buf, tls_len, cap); memcpy(tmp.data, buf->data, buf_len); /* Client Hello Header */ struct tls_client_hello *hello = (struct tls_client_hello *) buf->data; memcpy(hello, &tls_client_hello_template, hello_len); hello->len = CT_HTONS(tls_len - 5); hello->handshake_len_2 = CT_HTONS(tls_len - 9); hello->random_unix_time = CT_HTONL((uint32_t)time(NULL)); rand_bytes(hello->random_bytes, 28); rand_bytes(hello->session_id, 32); hello->ext_len = CT_HTONS(server_name_len + host_len + ticket_len + buf_len + other_ext_len); /* Session Ticket */ struct tls_ext_session_ticket *ticket = (struct tls_ext_session_ticket *)((char *)hello + hello_len); memcpy(ticket, &tls_ext_session_ticket_template, sizeof(struct tls_ext_session_ticket)); ticket->session_ticket_ext_len = CT_HTONS(buf_len); memcpy((char *)ticket + ticket_len, tmp.data, buf_len); /* SNI */ struct tls_ext_server_name *server_name = (struct tls_ext_server_name *)((char *)ticket + ticket_len + buf_len); memcpy(server_name, &tls_ext_server_name_template, server_name_len); server_name->ext_len = CT_HTONS(host_len + 3 + 2); server_name->server_name_list_len = CT_HTONS(host_len + 3); server_name->server_name_len = CT_HTONS(host_len); memcpy((char *)server_name + server_name_len, obfs_tls->host, host_len); /* Other Extensions */ memcpy((char *)server_name + server_name_len + host_len, &tls_ext_others_template, other_ext_len); buf->len = tls_len; obfs->obfs_stage++; } else if (obfs->obfs_stage == 1) { obfs_app_data(buf, cap, obfs); } return buf->len; } static int obfs_tls_response(buffer_t *buf, size_t cap, obfs_t *obfs) { if (obfs == NULL || obfs->obfs_stage < 0) return 0; static buffer_t tmp = { 0, 0, 0, NULL }; if (obfs->obfs_stage == 0) { size_t buf_len = buf->len; size_t hello_len = sizeof(struct tls_server_hello); size_t change_cipher_spec_len = sizeof(struct tls_change_cipher_spec); size_t encrypted_handshake_len = sizeof(struct tls_encrypted_handshake); size_t tls_len = hello_len + change_cipher_spec_len + encrypted_handshake_len + buf_len; brealloc(&tmp, buf_len, cap); brealloc(buf, tls_len, cap); memcpy(tmp.data, buf->data, buf_len); /* Server Hello */ memcpy(buf->data, &tls_server_hello_template, hello_len); struct tls_server_hello *hello = (struct tls_server_hello *)buf->data; hello->random_unix_time = CT_HTONL((uint32_t)time(NULL)); rand_bytes(hello->random_bytes, 28); if (obfs->buf != NULL) { memcpy(hello->session_id, obfs->buf->data, 32); } else { rand_bytes(hello->session_id, 32); } /* Change Cipher Spec */ memcpy(buf->data + hello_len, &tls_change_cipher_spec_template, change_cipher_spec_len); /* Encrypted Handshake */ memcpy(buf->data + hello_len + change_cipher_spec_len, &tls_encrypted_handshake_template, encrypted_handshake_len); memcpy(buf->data + hello_len + change_cipher_spec_len + encrypted_handshake_len, tmp.data, buf_len); struct tls_encrypted_handshake *encrypted_handshake = (struct tls_encrypted_handshake *)(buf->data + hello_len + change_cipher_spec_len); encrypted_handshake->len = CT_HTONS(buf_len); buf->len = tls_len; obfs->obfs_stage++; } else if (obfs->obfs_stage == 1) { obfs_app_data(buf, cap, obfs); } return buf->len; } static int deobfs_tls_request(buffer_t *buf, size_t cap, obfs_t *obfs) { if (obfs == NULL || obfs->deobfs_stage < 0) return 0; if (obfs->extra == NULL) { obfs->extra = ss_malloc(sizeof(frame_t)); memset(obfs->extra, 0, sizeof(frame_t)); } if (obfs->buf == NULL) { obfs->buf = (buffer_t *)ss_malloc(sizeof(buffer_t)); balloc(obfs->buf, 32); obfs->buf->len = 32; } if (obfs->deobfs_stage == 0) { int len = buf->len; len -= sizeof(struct tls_client_hello); if (len <= 0) return OBFS_NEED_MORE; struct tls_client_hello *hello = (struct tls_client_hello *) buf->data; if (hello->content_type != tls_client_hello_template.content_type) return OBFS_ERROR; size_t hello_len = CT_NTOHS(hello->len) + 5; memcpy(obfs->buf->data, hello->session_id, 32); len -= sizeof(struct tls_ext_session_ticket); if (len <= 0) return OBFS_NEED_MORE; struct tls_ext_session_ticket *ticket = (struct tls_ext_session_ticket *)(buf->data + sizeof(struct tls_client_hello)); if (ticket->session_ticket_type != tls_ext_session_ticket_template.session_ticket_type) return OBFS_ERROR; size_t ticket_len = CT_NTOHS(ticket->session_ticket_ext_len); if (len < ticket_len) return OBFS_NEED_MORE; memmove(buf->data, (char *)ticket + sizeof(struct tls_ext_session_ticket), ticket_len); if (buf->len > hello_len) { memmove(buf->data + ticket_len, buf->data + hello_len, buf->len - hello_len); } buf->len = ticket_len + buf->len - hello_len; obfs->deobfs_stage++; if (buf->len > ticket_len) { return deobfs_app_data(buf, ticket_len, obfs); } else { ((frame_t*)obfs->extra)->idx = buf->len - ticket_len; } } else if (obfs->deobfs_stage == 1) { return deobfs_app_data(buf, 0, obfs); } return 0; } static int deobfs_tls_response(buffer_t *buf, size_t cap, obfs_t *obfs) { if (obfs == NULL || obfs->deobfs_stage < 0) return 0; if (obfs->extra == NULL) { obfs->extra = ss_malloc(sizeof(frame_t)); memset(obfs->extra, 0, sizeof(frame_t)); } if (obfs->deobfs_stage == 0) { size_t hello_len = sizeof(struct tls_server_hello); char *data = buf->data; int len = buf->len; len -= hello_len; if (len <= 0) return OBFS_NEED_MORE; struct tls_server_hello *hello = (struct tls_server_hello*) data; if (hello->content_type != tls_server_hello_template.content_type) return OBFS_ERROR; size_t change_cipher_spec_len = sizeof(struct tls_change_cipher_spec); size_t encrypted_handshake_len = sizeof(struct tls_encrypted_handshake); len -= change_cipher_spec_len + encrypted_handshake_len; if (len <= 0) return OBFS_NEED_MORE; size_t tls_len = hello_len + change_cipher_spec_len + encrypted_handshake_len; struct tls_encrypted_handshake *encrypted_handshake = (struct tls_encrypted_handshake *)(buf->data + hello_len + change_cipher_spec_len); size_t msg_len = CT_NTOHS(encrypted_handshake->len); memmove(buf->data, buf->data + tls_len, buf->len - tls_len); buf->len = buf->len - tls_len; obfs->deobfs_stage++; if (buf->len > msg_len) { return deobfs_app_data(buf, msg_len, obfs); } else { ((frame_t*)obfs->extra)->idx = buf->len - msg_len; } } else if (obfs->deobfs_stage == 1) { return deobfs_app_data(buf, 0, obfs); } return 0; } static int check_tls_request(buffer_t *buf) { char *data = buf->data; int len = buf->len; if (len < 11) return OBFS_NEED_MORE; if (data[0] == 0x16 && data[1] == 0x03 && data[2] == 0x01 && data[5] == 0x01 && data[9] == 0x03 && data[10] == 0x03) return OBFS_OK; else return OBFS_ERROR; } static void disable_tls(obfs_t *obfs) { obfs->obfs_stage = -1; obfs->deobfs_stage = -1; } static int is_enable_tls(obfs_t *obfs) { return obfs->obfs_stage != -1 && obfs->deobfs_stage != -1; } simple-obfs-0.0.5/src/obfs_tls.h000066400000000000000000000067021320326276300165200ustar00rootroot00000000000000/* * obfs_tls.h - Interfaces of tls obfuscating * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef OBFS_TLS_H #define OBFS_TLS_H #include "obfs.h" struct tls_client_hello { char content_type; short version; short len; char handshake_type; char handshake_len_1; short handshake_len_2; short handshake_version; int random_unix_time; char random_bytes[28]; char session_id_len; char session_id[32]; short cipher_suites_len; char cipher_suites[56]; char comp_methods_len; char comp_methods[1]; short ext_len; } __attribute__((packed, aligned(1))); struct tls_ext_server_name { short ext_type; short ext_len; short server_name_list_len; char server_name_type; short server_name_len; // char server_name[server_name_len]; } __attribute__((packed, aligned(1))); struct tls_ext_session_ticket { short session_ticket_type; short session_ticket_ext_len; // char session_ticket[session_ticket_ext_len]; } __attribute__((packed, aligned(1))); struct tls_ext_others { short ec_point_formats_ext_type; short ec_point_formats_ext_len; char ec_point_formats_len; char ec_point_formats[3]; short elliptic_curves_type; short elliptic_curves_ext_len; short elliptic_curves_len; char elliptic_curves[8]; short sig_algos_type; short sig_algos_ext_len; short sig_algos_len; char sig_algos[30]; short encrypt_then_mac_type; short encrypt_then_mac_ext_len; short extended_master_secret_type; short extended_master_secret_ext_len; } __attribute__((packed, aligned(1))); struct tls_server_hello { char content_type; short version; short len; char handshake_type; char handshake_len_1; short handshake_len_2; short handshake_version; int random_unix_time; char random_bytes[28]; char session_id_len; char session_id[32]; short cipher_suite; char comp_method; short ext_len; short ext_renego_info_type; short ext_renego_info_ext_len; char ext_renego_info_len; short extended_master_secret_type; short extended_master_secret_ext_len; short ec_point_formats_ext_type; short ec_point_formats_ext_len; char ec_point_formats_len; char ec_point_formats[1]; } __attribute__((packed, aligned(1))); struct tls_change_cipher_spec { char content_type; short version; short len; char msg; } __attribute__((packed, aligned(1))); struct tls_encrypted_handshake { char content_type; short version; short len; // char msg[len]; } __attribute__((packed, aligned(1))); typedef struct frame { short idx; short len; char buf[2]; } frame_t; extern obfs_para_t *obfs_tls; #endif simple-obfs-0.0.5/src/options.c000066400000000000000000000047601320326276300163750ustar00rootroot00000000000000/* * jconf.c - Parse the JSON format config file * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "options.h" int parse_options(char *str, size_t str_len, options_t *opts) { int i, opt_idx; char p; i = 0; opt_idx = 0; p = '\0'; if (str == NULL || str_len == 0) return -1; opts->keys[0] = str; while (opt_idx < MAX_OPTION_NUM && i < str_len && str[i] != '\0') { char c = str[i]; switch (c) { case '\\': if (i + 1 == str_len) return -1; memmove(str + i, str + i + 1, str_len - i - 1); str_len--; str[str_len] = '\0'; break; case ';': if (p != '\\') { str[i] = '\0'; if (i + 1 < str_len) { opt_idx++; opts->keys[opt_idx] = str + i + 1; } } i++; break; case '=': if (p != '\\') { if (i + 1 == str_len) return -1; str[i] = '\0'; opts->values[opt_idx] = str + i + 1; } i++; break; default: i++; break; } p = c; } opts->num = opt_idx + 1; return opts->num; } const char* get_opt(const char *key, options_t *opts) { int i; for (i = 0; i < opts->num; i++) { if (strcmp(key, opts->keys[i]) == 0) { if (opts->values[i] != NULL) return opts->values[i]; else return key; } } return NULL; } simple-obfs-0.0.5/src/options.h000066400000000000000000000022241320326276300163730ustar00rootroot00000000000000/* * options.h - Define the interface for parsing SS_PLUGIN_OPTIONS * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _OPTIONS_H #define _OPTIONS_H #define MAX_OPTION_NUM 16 typedef struct options { size_t num; char *keys[MAX_OPTION_NUM]; char *values[MAX_OPTION_NUM]; } options_t; int parse_options(char *str, size_t str_len, options_t *opts); const char *get_opt(const char *key, options_t *opts); #endif // _OPTIONS_H simple-obfs-0.0.5/src/server.c000066400000000000000000001254621320326276300162130ustar00rootroot00000000000000/* * server.c - Provide simple-obfs service * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include #include #include #include #ifndef __MINGW32__ #include #include #include #include #include #endif #include #ifdef __MINGW32__ #include "win32.h" #endif #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H) && defined(__linux__) #include #include #define SET_INTERFACE #endif #include "netutils.h" #include "utils.h" #include "obfs_http.h" #include "obfs_tls.h" #include "options.h" #include "server.h" #ifndef EAGAIN #define EAGAIN EWOULDBLOCK #endif #ifndef EWOULDBLOCK #define EWOULDBLOCK EAGAIN #endif #ifndef BUF_SIZE #define BUF_SIZE 16384 #endif #ifndef SSMAXCONN #define SSMAXCONN 1024 #endif static void signal_cb(EV_P_ ev_signal *w, int revents); static void accept_cb(EV_P_ ev_io *w, int revents); static void server_send_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_send_cb(EV_P_ ev_io *w, int revents); static void server_timeout_cb(EV_P_ ev_timer *watcher, int revents); static void perform_handshake(EV_P_ server_t *server); static remote_t *new_remote(int fd); static server_t *new_server(int fd, listen_ctx_t *listener); static remote_t *connect_to_remote(EV_P_ struct addrinfo *res, server_t *server); static void free_remote(remote_t *remote); static void close_and_free_remote(EV_P_ remote_t *remote); static void free_server(server_t *server); static void close_and_free_server(EV_P_ server_t *server); int verbose = 0; static int ipv6first = 0; static int reverse_proxy = 0; static int fast_open = 0; static obfs_para_t *obfs_para = NULL; #ifdef HAVE_SETRLIMIT static int nofile = 0; #endif static int remote_conn = 0; static int server_conn = 0; static char *bind_address = NULL; static char *server_port = NULL; uint64_t tx = 0; uint64_t rx = 0; static struct cork_dllist connections; static void parent_watcher_cb(EV_P_ ev_timer *watcher, int revents) { static int ppid = -1; int cur_ppid = getppid(); if (ppid != -1) { if (ppid != cur_ppid) { ev_unloop(EV_A_ EVUNLOOP_ALL); } } ppid = cur_ppid; } static void free_connections(struct ev_loop *loop) { struct cork_dllist_item *curr, *next; cork_dllist_foreach_void(&connections, curr, next) { server_t *server = cork_container_of(curr, server_t, entries); remote_t *remote = server->remote; close_and_free_server(loop, server); close_and_free_remote(loop, remote); } } int setfastopen(int fd) { int s = 0; #ifdef TCP_FASTOPEN if (fast_open) { #ifdef __APPLE__ int opt = 1; #else int opt = 5; #endif s = setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &opt, sizeof(opt)); if (s == -1) { if (errno == EPROTONOSUPPORT || errno == ENOPROTOOPT) { LOGE("fast open is not supported on this platform"); fast_open = 0; } else { ERROR("setsockopt"); } } } #endif return s; } #ifndef __MINGW32__ int setnonblocking(int fd) { int flags; if (-1 == (flags = fcntl(fd, F_GETFL, 0))) { flags = 0; } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } #endif int create_and_bind(const char *host, const char *port, int mptcp) { struct addrinfo hints; struct addrinfo *result, *rp, *ipv4v6bindall; int s, listen_sock; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Return IPv4 and IPv6 choices */ hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */ hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; /* For wildcard IP address */ hints.ai_protocol = IPPROTO_TCP; for (int i = 1; i < 8; i++) { s = getaddrinfo(host, port, &hints, &result); if (s == 0) { break; } else { sleep(pow(2, i)); LOGE("failed to resolve server name, wait %.0f seconds", pow(2, i)); } } if (s != 0) { LOGE("getaddrinfo: %s", gai_strerror(s)); return -1; } rp = result; /* * On Linux, with net.ipv6.bindv6only = 0 (the default), getaddrinfo(NULL) with * AI_PASSIVE returns 0.0.0.0 and :: (in this order). AI_PASSIVE was meant to * return a list of addresses to listen on, but it is impossible to listen on * 0.0.0.0 and :: at the same time, if :: implies dualstack mode. */ if (!host) { ipv4v6bindall = result; /* Loop over all address infos found until a IPV6 address is found. */ while (ipv4v6bindall) { if (ipv4v6bindall->ai_family == AF_INET6) { rp = ipv4v6bindall; /* Take first IPV6 address available */ break; } ipv4v6bindall = ipv4v6bindall->ai_next; /* Get next address info, if any */ } } 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) { continue; } if (rp->ai_family == AF_INET6) { int ipv6only = host ? 1 : 0; setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6only, sizeof(ipv6only)); } int opt = 1; setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); #ifdef SO_NOSIGPIPE setsockopt(listen_sock, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif int err = set_reuseport(listen_sock); if (err == 0) { LOGI("tcp port reuse enabled"); } if (mptcp == 1) { int err = setsockopt(listen_sock, SOL_TCP, MPTCP_ENABLED, &opt, sizeof(opt)); if (err == -1) { ERROR("failed to enable multipath TCP"); } } s = bind(listen_sock, rp->ai_addr, rp->ai_addrlen); if (s == 0) { /* We managed to bind successfully! */ break; } else { ERROR("bind"); } close(listen_sock); } if (rp == NULL) { LOGE("Could not bind"); return -1; } freeaddrinfo(result); return listen_sock; } static remote_t * connect_to_remote(EV_P_ struct addrinfo *res, server_t *server) { int sockfd; #ifdef SET_INTERFACE const char *iface = server->listen_ctx->iface; #endif // initialize remote socks sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sockfd == -1) { ERROR("socket"); close(sockfd); return NULL; } int opt = 1; setsockopt(sockfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); #ifdef SO_NOSIGPIPE setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); // setup remote socks if (setnonblocking(sockfd) == -1) ERROR("setnonblocking"); if (bind_address != NULL) if (bind_to_address(sockfd, bind_address) == -1) { ERROR("bind_to_address"); close(sockfd); return NULL; } #ifdef SET_INTERFACE if (iface) { if (setinterface(sockfd, iface) == -1) { ERROR("setinterface"); close(sockfd); return NULL; } } #endif remote_t *remote = new_remote(sockfd); #ifdef TCP_FASTOPEN if (fast_open) { #ifdef __APPLE__ ((struct sockaddr_in *)(res->ai_addr))->sin_len = sizeof(struct sockaddr_in); sa_endpoints_t endpoints; memset((char *)&endpoints, 0, sizeof(endpoints)); endpoints.sae_dstaddr = res->ai_addr; endpoints.sae_dstaddrlen = res->ai_addrlen; struct iovec iov; iov.iov_base = server->buf->data + server->buf->idx; iov.iov_len = server->buf->len; size_t len; int s = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY, CONNECT_DATA_IDEMPOTENT, &iov, 1, &len, NULL); if (s == 0) { s = len; } #else ssize_t s = sendto(sockfd, server->buf->data + server->buf->idx, server->buf->len, MSG_FASTOPEN, res->ai_addr, res->ai_addrlen); #endif if (s == -1) { if (errno == CONNECT_IN_PROGRESS || 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) { // Disable fast open as it's not supported fast_open = 0; LOGE("fast open is not supported on this platform"); } else { ERROR("sendto"); } } else if (s <= server->buf->len) { server->buf->idx += s; server->buf->len -= s; } else { server->buf->idx = 0; server->buf->len = 0; } } #endif if (!fast_open) { int r = connect(sockfd, res->ai_addr, res->ai_addrlen); if (r == -1 && errno != CONNECT_IN_PROGRESS) { ERROR("connect"); close_and_free_remote(EV_A_ remote); return NULL; } } return remote; } static void perform_handshake(EV_P_ server_t *server) { // Copy back the saved first packet server->buf->len = server->header_buf->len; server->buf->idx = server->header_buf->idx; memcpy(server->buf->data, server->header_buf->data, server->header_buf->len); server->header_buf->idx = server->header_buf->len = 0; struct addrinfo info; struct sockaddr_storage storage; memset(&info, 0, sizeof(struct addrinfo)); memset(&storage, 0, sizeof(struct sockaddr_storage)); // Domain name size_t name_len = strlen(server->listen_ctx->dst_addr->host); char *host = server->listen_ctx->dst_addr->host; uint16_t port = htons((uint16_t)atoi(server->listen_ctx->dst_addr->port)); if (obfs_para == NULL || !obfs_para->is_enable(server->obfs)) { if (server->listen_ctx->failover->host != NULL && server->listen_ctx->failover->port != NULL) { name_len = strlen(server->listen_ctx->failover->host); host = server->listen_ctx->failover->host; port = htons((uint16_t)atoi(server->listen_ctx->failover->port)); } } struct cork_ip ip; if (cork_ip_init(&ip, host) != -1) { if (ip.version == 4) { struct sockaddr_in *addr = (struct sockaddr_in *)&storage; inet_pton(AF_INET, host, &(addr->sin_addr)); addr->sin_port = port; addr->sin_family = AF_INET; } else if (ip.version == 6) { struct sockaddr_in6 *addr = (struct sockaddr_in6 *)&storage; inet_pton(AF_INET6, host, &(addr->sin6_addr)); addr->sin6_port = port; addr->sin6_family = AF_INET6; } } else { if (!validate_hostname(host, name_len)) { LOGE("invalid host name"); close_and_free_server(EV_A_ server); return; } char tmp_port[16]; snprintf(tmp_port, 16, "%d", ntohs(port)); if (get_sockaddr(host, tmp_port, &storage, 0, ipv6first) == -1) { LOGE("failed to resolve the provided hostname"); close_and_free_server(EV_A_ server); return; } } info.ai_socktype = SOCK_STREAM; info.ai_protocol = IPPROTO_TCP; if (storage.ss_family == AF_INET) { info.ai_family = AF_INET; info.ai_addrlen = sizeof(struct sockaddr_in); info.ai_addr = (struct sockaddr *)&storage; } else if (storage.ss_family == AF_INET6) { info.ai_family = AF_INET6; info.ai_addrlen = sizeof(struct sockaddr_in6); info.ai_addr = (struct sockaddr *)&storage; } else { LOGE("failed to resolve the provided hostname"); close_and_free_server(EV_A_ server); return; } if (verbose) { LOGI("connect to %s:%d", host, ntohs(port)); } remote_t *remote = connect_to_remote(EV_A_ & info, server); if (remote == NULL) { LOGE("connect error"); close_and_free_server(EV_A_ server); return; } else { server->remote = remote; remote->server = server; // XXX: should handle buffer carefully if (server->buf->len > 0) { memcpy(remote->buf->data, server->buf->data, server->buf->len); remote->buf->len = server->buf->len; remote->buf->idx = 0; server->buf->len = 0; server->buf->idx = 0; } // waiting on remote connected event ev_io_start(EV_A_ & remote->send_ctx->io); } return; } static void server_recv_cb(EV_P_ ev_io *w, int revents) { server_ctx_t *server_recv_ctx = (server_ctx_t *)w; server_t *server = server_recv_ctx->server; remote_t *remote = NULL; int len = server->buf->len; buffer_t *buf = server->buf; if (server->stage > STAGE_PARSE) { remote = server->remote; buf = remote->buf; len = 0; ev_timer_again(EV_A_ & server->recv_ctx->watcher); } if (len > BUF_SIZE) { ERROR("out of recv buffer"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } ssize_t r = recv(server->fd, buf->data + len, BUF_SIZE - len, 0); if (r == 0) { // connection closed if (verbose) { LOGI("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) { // no data // continue to wait for recv return; } else { ERROR("server recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } tx += r; // handle incomplete header part 1 if (server->stage == STAGE_INIT) { buf->len += r; if (obfs_para && obfs_para->is_enable(server->obfs)) { int ret = obfs_para->check_obfs(buf); if (ret == OBFS_NEED_MORE) { return; } else if (ret == OBFS_OK) { // obfs is enabled ret = obfs_para->deobfs_request(buf, BUF_SIZE, server->obfs); if (ret == OBFS_NEED_MORE) return; else if (ret == OBFS_ERROR) obfs_para->disable(server->obfs); } else { obfs_para->disable(server->obfs); } } server->stage = STAGE_HANDSHAKE; ev_io_stop(EV_A_ & server->recv_ctx->io); // Copy the first packet to the currently unused header_buf. server->header_buf->len = server->buf->len - server->buf->idx; server->header_buf->idx = 0; memcpy(server->header_buf->data, server->buf->data + server->buf->idx, server->header_buf->len); if (reverse_proxy && obfs_para->send_empty_response_upon_connection) { // Clear the buffer to make an empty packet. server->buf->len = 0; if (obfs_para) { obfs_para->obfs_response(server->buf, BUF_SIZE, server->obfs); } int s = send(server->fd, server->buf->data, server->buf->len, 0); if (s == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send server->buf->idx = 0; ev_io_start(EV_A_ & server->send_ctx->io); return; } else { ERROR("send_inital_response"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } else if (s < server->buf->len) { server->buf->len -= s; server->buf->idx = s; ev_io_start(EV_A_ & server->send_ctx->io); return; } else { server->buf->len = 0; server->buf->idx = 0; } } perform_handshake(EV_A_ server); return; } else { buf->len = r; if (obfs_para) { int ret = obfs_para->deobfs_request(buf, BUF_SIZE, server->obfs); if (ret) LOGE("invalid obfuscating"); } } // handshake and transmit data if (server->stage == STAGE_STREAM) { int s = send(remote->fd, remote->buf->data, remote->buf->len, 0); if (s == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send remote->buf->idx = 0; 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 < remote->buf->len) { remote->buf->len -= s; remote->buf->idx = s; ev_io_stop(EV_A_ & server_recv_ctx->io); ev_io_start(EV_A_ & remote->send_ctx->io); } return; } // should not reach here FATAL("server context error"); } static void server_send_cb(EV_P_ ev_io *w, int revents) { server_ctx_t *server_send_ctx = (server_ctx_t *)w; server_t *server = server_send_ctx->server; remote_t *remote = server->remote; if (remote == NULL) { LOGE("invalid server"); close_and_free_server(EV_A_ server); return; } if (server->buf->len == 0) { // close and free if (verbose) { LOGI("server_send close the connection"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } else { // has data to send ssize_t s = send(server->fd, server->buf->data + server->buf->idx, server->buf->len, 0); if (s == -1) { 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) { // partly sent, move memory, wait for the next time to send server->buf->len -= s; server->buf->idx += s; return; } 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 handshaking if (server->stage == STAGE_HANDSHAKE) { perform_handshake(EV_A_ server); return; } else { // If streaming if (remote != NULL) { ev_io_start(EV_A_ & remote->recv_ctx->io); return; } else { LOGE("invalid remote"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } } } } static void server_timeout_cb(EV_P_ ev_timer *watcher, int revents) { server_ctx_t *server_ctx = cork_container_of(watcher, server_ctx_t, watcher); server_t *server = server_ctx->server; remote_t *remote = server->remote; if (verbose) { LOGI("TCP connection timeout"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } static void remote_recv_cb(EV_P_ ev_io *w, int revents) { remote_ctx_t *remote_recv_ctx = (remote_ctx_t *)w; remote_t *remote = remote_recv_ctx->remote; server_t *server = remote->server; if (server == NULL) { LOGE("invalid server"); close_and_free_remote(EV_A_ remote); return; } ev_timer_again(EV_A_ & server->recv_ctx->watcher); ssize_t r = recv(remote->fd, server->buf->data, BUF_SIZE, 0); if (r == 0) { // connection closed if (verbose) { LOGI("remote_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) { // no data // continue to wait for recv return; } else { ERROR("remote recv"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } rx += r; server->buf->len = r; if (obfs_para) { obfs_para->obfs_response(server->buf, BUF_SIZE, server->obfs); } int s = send(server->fd, server->buf->data, server->buf->len, 0); if (s == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // no data, wait for send server->buf->idx = 0; 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 < server->buf->len) { server->buf->len -= s; server->buf->idx = s; ev_io_stop(EV_A_ & remote_recv_ctx->io); ev_io_start(EV_A_ & server->send_ctx->io); } // Disable TCP_NODELAY after the first response are sent if (!remote->recv_ctx->connected) { int opt = 0; setsockopt(server->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); setsockopt(remote->fd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); remote->recv_ctx->connected = 1; } } static void remote_send_cb(EV_P_ ev_io *w, int revents) { remote_ctx_t *remote_send_ctx = (remote_ctx_t *)w; remote_t *remote = remote_send_ctx->remote; server_t *server = remote->server; if (server == NULL) { LOGE("invalid server"); close_and_free_remote(EV_A_ remote); return; } if (!remote_send_ctx->connected) { struct sockaddr_storage addr; socklen_t len = sizeof(struct sockaddr_storage); memset(&addr, 0, len); int r = getpeername(remote->fd, (struct sockaddr *)&addr, &len); if (r == 0) { if (verbose) { LOGI("remote connected"); } remote_send_ctx->connected = 1; if (remote->buf->len == 0) { server->stage = STAGE_STREAM; 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 { ERROR("getpeername"); // not connected close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } } if (remote->buf->len == 0) { // close and free if (verbose) { LOGI("remote_send close the connection"); } close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); return; } else { // has data to send ssize_t s = send(remote->fd, remote->buf->data + remote->buf->idx, remote->buf->len, 0); 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) { // partly sent, move memory, wait for the next time to send remote->buf->len -= s; remote->buf->idx += s; return; } 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 != STAGE_STREAM) { server->stage = STAGE_STREAM; ev_io_start(EV_A_ & remote->recv_ctx->io); } } else { LOGE("invalid server"); close_and_free_remote(EV_A_ remote); close_and_free_server(EV_A_ server); } return; } } } static remote_t * new_remote(int fd) { if (verbose) { remote_conn++; } remote_t *remote = ss_malloc(sizeof(remote_t)); memset(remote, 0, sizeof(remote_t)); remote->recv_ctx = ss_malloc(sizeof(remote_ctx_t)); remote->send_ctx = ss_malloc(sizeof(remote_ctx_t)); remote->buf = ss_malloc(sizeof(buffer_t)); balloc(remote->buf, BUF_SIZE); memset(remote->recv_ctx, 0, sizeof(remote_ctx_t)); memset(remote->send_ctx, 0, sizeof(remote_ctx_t)); remote->fd = fd; remote->recv_ctx->remote = remote; remote->recv_ctx->connected = 0; remote->send_ctx->remote = remote; remote->send_ctx->connected = 0; remote->server = NULL; 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); return remote; } static void free_remote(remote_t *remote) { if (remote->server != NULL) { remote->server->remote = NULL; } if (remote->buf != NULL) { bfree(remote->buf); ss_free(remote->buf); } ss_free(remote->recv_ctx); ss_free(remote->send_ctx); ss_free(remote); } static void close_and_free_remote(EV_P_ remote_t *remote) { 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) { remote_conn--; LOGI("current remote connection: %d", remote_conn); } } } static server_t * new_server(int fd, listen_ctx_t *listener) { if (verbose) { server_conn++; } server_t *server; server = ss_malloc(sizeof(server_t)); memset(server, 0, sizeof(server_t)); server->recv_ctx = ss_malloc(sizeof(server_ctx_t)); server->send_ctx = ss_malloc(sizeof(server_ctx_t)); server->buf = ss_malloc(sizeof(buffer_t)); server->header_buf = ss_malloc(sizeof(buffer_t)); memset(server->recv_ctx, 0, sizeof(server_ctx_t)); memset(server->send_ctx, 0, sizeof(server_ctx_t)); balloc(server->buf, BUF_SIZE); balloc(server->header_buf, BUF_SIZE); server->fd = fd; server->recv_ctx->server = server; server->recv_ctx->connected = 0; server->send_ctx->server = server; server->send_ctx->connected = 0; server->stage = STAGE_INIT; server->listen_ctx = listener; server->remote = NULL; if (obfs_para != NULL) { server->obfs = (obfs_t *)ss_malloc(sizeof(obfs_t)); memset(server->obfs, 0, sizeof(obfs_t)); } int request_timeout = min(MAX_REQUEST_TIMEOUT, listener->timeout) + rand() % MAX_REQUEST_TIMEOUT; 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, request_timeout, listener->timeout); cork_dllist_add(&connections, &server->entries); return server; } static void free_server(server_t *server) { cork_dllist_remove(&server->entries); if (server->obfs != NULL) { bfree(server->obfs->buf); if (server->obfs->extra != NULL) ss_free(server->obfs->extra); ss_free(server->obfs); } if (server->remote != NULL) { server->remote->server = NULL; } if (server->buf != NULL) { bfree(server->buf); ss_free(server->buf); } if (server->header_buf != NULL) { bfree(server->header_buf); ss_free(server->header_buf); } ss_free(server->recv_ctx); ss_free(server->send_ctx); ss_free(server); } static void close_and_free_server(EV_P_ server_t *server) { if (server != 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); close(server->fd); free_server(server); if (verbose) { server_conn--; LOGI("current server connection: %d", server_conn); } } } static void signal_cb(EV_P_ ev_signal *w, int revents) { if (revents & EV_SIGNAL) { switch (w->signum) { case SIGINT: case SIGTERM: ev_unloop(EV_A_ EVUNLOOP_ALL); } } } static void accept_cb(EV_P_ ev_io *w, int revents) { listen_ctx_t *listener = (listen_ctx_t *)w; int serverfd = accept(listener->fd, NULL, NULL); if (serverfd == -1) { ERROR("accept"); return; } int opt = 1; setsockopt(serverfd, SOL_TCP, TCP_NODELAY, &opt, sizeof(opt)); #ifdef SO_NOSIGPIPE setsockopt(serverfd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof(opt)); #endif setnonblocking(serverfd); if (verbose) { LOGI("accept a connection"); } server_t *server = new_server(serverfd, listener); 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 i, c; int pid_flags = 0; int mptcp = 0; char *user = NULL; char *timeout = NULL; char *pid_path = NULL; char *conf_path = NULL; char *iface = NULL; int server_num = 0; const char *server_host[MAX_REMOTE_NUM]; char *nameservers = NULL; ss_addr_t dst_addr = { .host = NULL, .port = NULL }; char *dst_addr_str = NULL; ss_addr_t failover = { .host = NULL, .port = NULL }; char *failover_str = NULL; char *obfs_host = NULL; char *ss_remote_host = getenv("SS_REMOTE_HOST"); char *ss_remote_port = getenv("SS_REMOTE_PORT"); char *ss_local_host = getenv("SS_LOCAL_HOST"); char *ss_local_port = getenv("SS_LOCAL_PORT"); char *ss_plugin_opts = getenv("SS_PLUGIN_OPTIONS"); if (ss_remote_host != NULL) { ss_remote_host = strdup(ss_remote_host); char *delim = "|"; char *p = strtok(ss_remote_host, delim); do { server_host[server_num++] = p; } while ((p = strtok(NULL, delim))); } if (ss_remote_port != NULL) { server_port = ss_remote_port; } if (ss_local_host != NULL) { dst_addr.host = ss_local_host; } if (ss_local_port != NULL) { dst_addr.port = ss_local_port; } if (ss_plugin_opts != NULL) { ss_plugin_opts = strdup(ss_plugin_opts); options_t opts; int opt_num = parse_options(ss_plugin_opts, strlen(ss_plugin_opts), &opts); for (i = 0; i < opt_num; i++) { char *key = opts.keys[i]; char *value = opts.values[i]; if (key == NULL) continue; size_t key_len = strlen(key); if (key_len == 0) continue; if (key_len == 1) { char c = key[0]; switch (c) { case 'b': bind_address = value; break; case 't': timeout = value; break; case 'c': conf_path = value; break; case 'i': iface = value; break; case 'a': user = value; break; case 'v': verbose = 1; break; case '6': ipv6first = 1; break; } } else { if (strcmp(key, "fast-open") == 0) { fast_open = 1; } else if (strcmp(key, "obfs") == 0) { if (strcmp(value, obfs_http->name) == 0) obfs_para = obfs_http; else if (strcmp(value, obfs_tls->name) == 0) obfs_para = obfs_tls; } else if (strcmp(key, "obfs-host") == 0) { obfs_host = value; } else if (strcmp(key, "failover") == 0) { failover_str = value; } else if (strcmp(key, "reverse_proxy") == 0) { reverse_proxy = 1; #ifdef __linux__ } else if (strcmp(key, "mptcp") == 0) { mptcp = 1; LOGI("enable multipath TCP"); #endif } } } } int option_index = 0; static struct option long_options[] = { { "fast-open", no_argument, 0, 0 }, { "help", no_argument, 0, 0 }, { "obfs", required_argument, 0, 0 }, { "obfs-host", required_argument, 0, 0 }, { "failover", required_argument, 0, 0 }, #ifdef __linux__ { "mptcp", no_argument, 0, 0 }, #endif { "reverse_proxy", no_argument, 0, 0 }, { 0, 0, 0, 0 } }; opterr = 0; USE_TTY(); while ((c = getopt_long(argc, argv, "f:s:p:l:t:b:c:i:d:r:a:n:hv6", long_options, &option_index)) != -1) { switch (c) { case 0: if (option_index == 0) { fast_open = 1; } else if (option_index == 1) { usage(); exit(EXIT_SUCCESS); } else if (option_index == 2) { if (strcmp(optarg, obfs_http->name) == 0) obfs_para = obfs_http; else if (strcmp(optarg, obfs_tls->name) == 0) obfs_para = obfs_tls; } else if (option_index == 3) { obfs_host = optarg; } else if (option_index == 4) { failover_str = optarg; } else if (option_index == 5) { mptcp = 1; LOGI("enable multipath TCP"); } else if (option_index == 6) { reverse_proxy = 1; LOGI("enable reverse proxy"); } break; case 's': if (server_num < MAX_REMOTE_NUM) { server_host[server_num++] = optarg; } break; case 'b': bind_address = optarg; break; case 'p': server_port = optarg; break; case 'r': dst_addr_str = optarg; break; case 'f': pid_flags = 1; pid_path = optarg; break; case 't': timeout = optarg; break; case 'c': conf_path = optarg; break; case 'i': iface = optarg; break; case 'd': nameservers = optarg; break; case 'a': user = optarg; break; #ifdef HAVE_SETRLIMIT case 'n': nofile = atoi(optarg); break; #endif case 'v': verbose = 1; break; case 'h': usage(); exit(EXIT_SUCCESS); case '6': ipv6first = 1; break; case '?': // The option character is not recognized. LOGE("Unrecognized option: %s", optarg); opterr = 1; break; } } if (opterr) { usage(); exit(EXIT_FAILURE); } if (conf_path != NULL) { jconf_t *conf = read_jconf(conf_path); if (server_num == 0) { server_num = conf->remote_num; 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 (timeout == NULL) { timeout = conf->timeout; } if (user == NULL) { user = conf->user; } if (dst_addr_str == NULL) { dst_addr_str = conf->dst_addr; } if (failover_str == NULL) { failover_str = conf->failover; } if (obfs_para == NULL && conf->obfs != NULL) { if (strcmp(conf->obfs, obfs_http->name) == 0) obfs_para = obfs_http; else if (strcmp(conf->obfs, obfs_tls->name) == 0) obfs_para = obfs_tls; } if (obfs_host == NULL) { obfs_host = conf->obfs_host; } if (mptcp == 0) { mptcp = conf->mptcp; } #ifdef TCP_FASTOPEN if (fast_open == 0) { fast_open = conf->fast_open; } #endif #ifdef HAVE_SETRLIMIT if (nofile == 0) { nofile = conf->nofile; } #endif if (nameservers == NULL) { nameservers = conf->nameserver; } if (ipv6first == 0) { ipv6first = conf->ipv6_first; } if (reverse_proxy == 0) { reverse_proxy = conf->reverse_proxy; } } if (server_num == 0) { server_host[server_num++] = NULL; } if (server_num == 0 || server_port == NULL) { usage(); exit(EXIT_FAILURE); } if (dst_addr_str != NULL) { // parse dst addr parse_addr(dst_addr_str, &dst_addr); } if (dst_addr.host == NULL || dst_addr.port == NULL) { FATAL("forwarding destination is not defined"); } if (failover_str != NULL) { // parse failover addr parse_addr(failover_str, &failover); } if (timeout == NULL) { timeout = "600"; } #ifdef HAVE_SETRLIMIT /* * no need to check the return value here since we will show * the user an error message if setrlimit(2) fails */ if (nofile > 1024) { if (verbose) { LOGI("setting NOFILE to %d", nofile); } set_nofile(nofile); } #endif if (pid_flags) { USE_SYSLOG(argv[0]); daemonize(pid_path); } if (ipv6first) { LOGI("resolving hostname to IPv6 address first"); } if (fast_open == 1) { #ifdef TCP_FASTOPEN LOGI("using tcp fast open"); #else LOGE("tcp fast open is not supported by this environment"); fast_open = 0; #endif } if (obfs_para) { obfs_para->host = obfs_host; LOGI("obfuscating enabled"); if (obfs_host) LOGI("obfuscating hostname: %s", obfs_host); } #ifdef __MINGW32__ winsock_init(); #else // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGCHLD, SIG_IGN); signal(SIGABRT, SIG_IGN); #endif struct ev_signal sigint_watcher; struct ev_signal sigterm_watcher; ev_signal_init(&sigint_watcher, signal_cb, SIGINT); ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM); ev_signal_start(EV_DEFAULT, &sigint_watcher); ev_signal_start(EV_DEFAULT, &sigterm_watcher); // initialize ev loop struct ev_loop *loop = EV_DEFAULT; if (nameservers != NULL) LOGI("using nameserver: %s", nameservers); // initialize listen context listen_ctx_t listen_ctx_list[server_num]; // bind to each interface while (server_num > 0) { int index = --server_num; const char *host = server_host[index]; // Bind to port int listenfd; listenfd = create_and_bind(host, server_port, mptcp); if (listenfd == -1) { FATAL("bind() error"); } if (listen(listenfd, SSMAXCONN) == -1) { FATAL("listen() error"); } setfastopen(listenfd); setnonblocking(listenfd); listen_ctx_t *listen_ctx = &listen_ctx_list[index]; // Setup proxy context listen_ctx->timeout = atoi(timeout); listen_ctx->fd = listenfd; listen_ctx->iface = iface; listen_ctx->loop = loop; listen_ctx->dst_addr = &dst_addr; listen_ctx->failover = &failover; ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ); ev_io_start(loop, &listen_ctx->io); if (host && strcmp(host, ":") > 0) LOGI("listening at [%s]:%s", host, server_port); else LOGI("listening at %s:%s", host ? host : "*", server_port); } // setuid if (user != NULL && !run_as(user)) { FATAL("failed to switch user"); } #ifndef __MINGW32__ if (geteuid() == 0) { LOGI("running from root user"); } #endif // Init connections cork_dllist_init(&connections); ev_timer parent_watcher; ev_timer_init(&parent_watcher, parent_watcher_cb, 0, UPDATE_INTERVAL); ev_timer_start(EV_DEFAULT, &parent_watcher); // start ev loop ev_run(loop, 0); if (verbose) { LOGI("closed gracefully"); } // Clean up for (int i = 0; i <= server_num; i++) { listen_ctx_t *listen_ctx = &listen_ctx_list[i]; ev_io_stop(loop, &listen_ctx->io); close(listen_ctx->fd); } free_connections(loop); #ifdef __MINGW32__ winsock_cleanup(); #endif ev_signal_stop(EV_DEFAULT, &sigint_watcher); ev_signal_stop(EV_DEFAULT, &sigterm_watcher); return 0; } simple-obfs-0.0.5/src/server.h000066400000000000000000000035701320326276300162130ustar00rootroot00000000000000/* * server.h - Define server's buffers and callbacks * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _SERVER_H #define _SERVER_H #include #include #include #include "encrypt.h" #include "jconf.h" #include "common.h" typedef struct listen_ctx { ev_io io; int fd; int timeout; int method; ss_addr_t *dst_addr; ss_addr_t *failover; char *iface; struct ev_loop *loop; } listen_ctx_t; typedef struct server_ctx { ev_io io; ev_timer watcher; int connected; struct server *server; } server_ctx_t; typedef struct server { int fd; int stage; int auth; obfs_t *obfs; buffer_t *buf; buffer_t *header_buf; struct server_ctx *recv_ctx; struct server_ctx *send_ctx; struct listen_ctx *listen_ctx; struct remote *remote; struct cork_dllist_item entries; } server_t; typedef struct remote_ctx { ev_io io; int connected; struct remote *remote; } remote_ctx_t; typedef struct remote { int fd; buffer_t *buf; struct remote_ctx *recv_ctx; struct remote_ctx *send_ctx; struct server *server; } remote_t; #endif // _SERVER_H simple-obfs-0.0.5/src/uthash.h000066400000000000000000002075541320326276300162110ustar00rootroot00000000000000/* Copyright (c) 2003-2016, 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: * 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. */ #ifndef UTHASH_H #define UTHASH_H #define UTHASH_VERSION 2.0.1 #include /* memcmp,strlen */ #include /* ptrdiff_t */ #include /* exit() */ /* These macros use decltype or the earlier __typeof GNU extension. 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. */ #if defined(_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) */ #define NO_DECLTYPE #define DECLTYPE(x) #endif #elif defined(__BORLANDC__) || defined(__LCC__) || defined(__WATCOMC__) #define NO_DECLTYPE #define DECLTYPE(x) #else /* GNU, Sun and other compilers */ #define DECLTYPE(x) (__typeof(x)) #endif #ifdef NO_DECLTYPE #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) #endif /* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */ #if defined(_WIN32) #if defined(_MSC_VER) && _MSC_VER >= 1600 #include #elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #endif #elif defined(__GNUC__) && !defined(__VXWORKS__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #endif #ifndef uthash_fatal #define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ #endif #ifndef uthash_malloc #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ #endif #ifndef uthash_free #define uthash_free(ptr,sz) free(ptr) /* free fcn */ #endif #ifndef uthash_strlen #define uthash_strlen(s) strlen(s) #endif #ifndef uthash_memcmp #define uthash_memcmp(a,b,n) memcmp(a,b,n) #endif #ifndef uthash_noexpand_fyi #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ #endif #ifndef uthash_expand_fyi #define uthash_expand_fyi(tbl) /* can be defined to log expands */ #endif /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ #define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ /* calculate the element whose hash handle address is hhp */ #define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) /* calculate the hash handle from element address elp */ #define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho))) #define HASH_VALUE(keyptr,keylen,hashv) \ do { \ HASH_FCN(keyptr, keylen, hashv); \ } while (0) #define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ do { \ (out) = NULL; \ if (head) { \ unsigned _hf_bkt; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ } \ } \ } while (0) #define HASH_FIND(hh,head,keyptr,keylen,out) \ do { \ unsigned _hf_hashv; \ HASH_VALUE(keyptr, keylen, _hf_hashv); \ HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ } while (0) #ifdef HASH_BLOOM #define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) #define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) #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_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) #define HASH_BLOOM_ADD(tbl,hashv) \ HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) #define HASH_BLOOM_TEST(tbl,hashv) \ HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) #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_BYTELEN 0U #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_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ } while (0) #define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ } while (0) #define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ } while (0) #define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ } while (0) #define HASH_APPEND_LIST(hh, head, add) \ do { \ (add)->hh.next = NULL; \ (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ (head)->hh.tbl->tail->next = (add); \ (head)->hh.tbl->tail = &((add)->hh); \ } while (0) #define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ do { \ unsigned _ha_bkt; \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ (head) = (add); \ HASH_MAKE_TABLE(hh, head); \ } else { \ struct UT_hash_handle *_hs_iter = &(head)->hh; \ (add)->hh.tbl = (head)->hh.tbl; \ do { \ if (cmpfcn(DECLTYPE(head) ELMT_FROM_HH((head)->hh.tbl, _hs_iter), add) > 0) \ break; \ } while ((_hs_iter = _hs_iter->next)); \ if (_hs_iter) { \ (add)->hh.next = _hs_iter; \ if (((add)->hh.prev = _hs_iter->prev)) { \ HH_FROM_ELMT((head)->hh.tbl, _hs_iter->prev)->next = (add); \ } else { \ (head) = (add); \ } \ _hs_iter->prev = (add); \ } else { \ HASH_APPEND_LIST(hh, head, add); \ } \ } \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ HASH_FSCK(hh, head); \ } while (0) #define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ do { \ unsigned _hs_hashv; \ HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ } while (0) #define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) #define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) #define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ do { \ unsigned _ha_bkt; \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ (head) = (add); \ HASH_MAKE_TABLE(hh, head); \ } else { \ (add)->hh.tbl = (head)->hh.tbl; \ HASH_APPEND_LIST(hh, head, add); \ } \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ 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_hashv; \ HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ } while (0) #define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) #define HASH_TO_BKT(hashv,num_bkts,bkt) \ do { \ bkt = ((hashv) & ((num_bkts) - 1U)); \ } while (0) /* delete "delptr" from the hash table. * "the usual" patch-up process for the app-order doubly-linked-list. * The use of _hd_hh_del below deserves special explanation. * These used to be expressed using (delptr) but that led to a bug * if someone used the same symbol for the head and deletee, like * HASH_DELETE(hh,users,users); * We want that to work, but by changing the head (users) below * we were forfeiting our ability to further refer to the deletee (users) * in the patch-up process. Solution: use scratch space to * 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 { \ 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 { \ unsigned _hd_bkt; \ _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 != NULL) { \ ((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 != NULL) { \ ((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,(unsigned)uthash_strlen(findstr),out) #define HASH_ADD_STR(head,strfield,add) \ HASH_ADD(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add) #define HASH_REPLACE_STR(head,strfield,add,replaced) \ HASH_REPLACE(hh,head,strfield[0],(unsigned)uthash_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,replaced) \ 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 { \ struct UT_hash_handle *_thh; \ if (head) { \ unsigned _bkt_i; \ unsigned _count; \ char *_prev; \ _count = 0; \ for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ unsigned _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 %u, actual %u\n", \ (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ } \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("invalid hh item count %u, actual %u\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 %u, actual %u\n", \ (head)->hh.tbl->num_items, _count ); \ } \ } \ } while (0) #else #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, (unsigned long)fieldlen); \ } while (0) #else #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) #endif /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ #ifdef HASH_FUNCTION #define HASH_FCN HASH_FUNCTION #else #define HASH_FCN HASH_JEN #endif /* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ #define HASH_BER(key,keylen,hashv) \ do { \ unsigned _hb_keylen=(unsigned)keylen; \ const unsigned char *_hb_key=(const unsigned char*)(key); \ (hashv) = 0; \ while (_hb_keylen-- != 0U) { \ (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ } \ } 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,hashv) \ do { \ unsigned _sx_i; \ const unsigned char *_hs_key=(const unsigned char*)(key); \ hashv = 0; \ for(_sx_i=0; _sx_i < keylen; _sx_i++) { \ hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ } \ } while (0) /* FNV-1a variation */ #define HASH_FNV(key,keylen,hashv) \ do { \ unsigned _fn_i; \ const unsigned char *_hf_key=(const unsigned char*)(key); \ hashv = 2166136261U; \ for(_fn_i=0; _fn_i < keylen; _fn_i++) { \ hashv = hashv ^ _hf_key[_fn_i]; \ hashv = hashv * 16777619U; \ } \ } while (0) #define HASH_OAT(key,keylen,hashv) \ do { \ unsigned _ho_i; \ const unsigned char *_ho_key=(const unsigned 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); \ } 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,hashv) \ do { \ unsigned _hj_i,_hj_j,_hj_k; \ unsigned const char *_hj_key=(unsigned const char*)(key); \ hashv = 0xfeedbeefu; \ _hj_i = _hj_j = 0x9e3779b9u; \ _hj_k = (unsigned)(keylen); \ while (_hj_k >= 12U) { \ _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 -= 12U; \ } \ hashv += (unsigned)(keylen); \ switch ( _hj_k ) { \ case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ case 1: _hj_i += _hj_key[0]; \ } \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ } 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))) #endif #if !defined (get16bits) #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ +(uint32_t)(((const uint8_t *)(d))[0]) ) #endif #define HASH_SFH(key,keylen,hashv) \ do { \ unsigned const char *_sfh_key=(unsigned const char*)(key); \ uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ \ unsigned _sfh_rem = _sfh_len & 3U; \ _sfh_len >>= 2; \ hashv = 0xcafebabeu; \ \ /* Main loop */ \ for (;_sfh_len > 0U; _sfh_len--) { \ hashv += get16bits (_sfh_key); \ _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ hashv = (hashv << 16) ^ _sfh_tmp; \ _sfh_key += 2U*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; \ } while (0) #ifdef HASH_USING_NO_STRICT_ALIASING /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. * MurmurHash uses the faster approach only on CPU's where we know it's safe. * * Note the preprocessor built-in defines can be emitted using: * * 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] #else /* non intel */ #define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 3UL) == 0UL) #define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL) #define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL) #define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL) #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)) #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)))) #endif #define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) #define MUR_FMIX(_h) \ do { \ _h ^= _h >> 16; \ _h *= 0x85ebca6bu; \ _h ^= _h >> 13; \ _h *= 0xc2b2ae35u; \ _h ^= _h >> 16; \ } while (0) #define HASH_MUR(key,keylen,hashv) \ do { \ const uint8_t *_mur_data = (const uint8_t*)(key); \ const int _mur_nblocks = (int)(keylen) / 4; \ uint32_t _mur_h1 = 0xf88D5353u; \ uint32_t _mur_c1 = 0xcc9e2d51u; \ uint32_t _mur_c2 = 0x1b873593u; \ 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!=0; _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*5U) + 0xe6546b64u; \ } \ _mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \ _mur_k1=0; \ switch((keylen) & 3U) { \ case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \ case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \ case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ _mur_h1 ^= _mur_k1; \ } \ _mur_h1 ^= (uint32_t)(keylen); \ MUR_FMIX(_mur_h1); \ hashv = _mur_h1; \ } while (0) #endif /* HASH_USING_NO_STRICT_ALIASING */ /* iterate over items in a known bucket to find desired item */ #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ do { \ if ((head).hh_head != NULL) { \ DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ } else { \ (out) = NULL; \ } \ while ((out) != NULL) { \ if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ if (uthash_memcmp((out)->hh.key, keyptr, keylen_in) == 0) { \ break; \ } \ } \ if ((out)->hh.hh_next != NULL) { \ 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 != NULL) { (head).hh_head->hh_prev = (addhh); } \ (head).hh_head=addhh; \ if ((head.count >= ((head.expand_mult+1U) * HASH_BKT_CAPACITY_THRESH)) \ && ((addhh)->tbl->noexpand != 1U)) { \ 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; \ } /* Bucket expansion has the effect of doubling the number of buckets * and redistributing the items into the new buckets. Ideally the * items will distribute more or less evenly into the new buckets * (the extent to which this is true is a measure of the quality of * the hash function as it applies to the key domain). * * With the items distributed into more buckets, the chain length * (item count) in each bucket is reduced. Thus by expanding buckets * the hash keeps a bound on the chain length. This bounded chain * length is the essence of how a hash provides constant time lookup. * * The calculation of tbl->ideal_chain_maxlen below deserves some * explanation. First, keep in mind that we're calculating the ideal * maximum chain length based on the *new* (doubled) bucket count. * In fractions this is just n/b (n=number of items,b=new num buckets). * Since the ideal chain length is an integer, we want to calculate * ceil(n/b). We don't depend on floating point arithmetic in this * hash, so to calculate ceil(n/b) with integers we could write * * ceil(n/b) = (n/b) + ((n%b)?1:0) * * and in fact a previous version of this hash did just that. * But now we have improved things a bit by recognizing that b is * always a power of two. We keep its base 2 log handy (call it lb), * so now we can write this with a bit shift and logical AND: * * 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( \ 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ memset(_he_new_buckets, 0, \ 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ tbl->ideal_chain_maxlen = \ (tbl->num_items >> (tbl->log2_num_buckets+1U)) + \ (((tbl->num_items & ((tbl->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ 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 != NULL) { \ _he_hh_nxt = _he_thh->hh_next; \ HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2U, _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 != NULL) { _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 *= 2U; \ tbl->log2_num_buckets++; \ tbl->buckets = _he_new_buckets; \ tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ (tbl->ineff_expands+1U) : 0U; \ if (tbl->ineff_expands > 1U) { \ 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 != NULL) { \ _hs_insize = 1; \ _hs_looping = 1; \ _hs_list = &((head)->hh); \ while (_hs_looping != 0U) { \ _hs_p = _hs_list; \ _hs_list = NULL; \ _hs_tail = NULL; \ _hs_nmerges = 0; \ while (_hs_p != NULL) { \ _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 != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ if (! (_hs_q) ) { break; } \ } \ _hs_qsize = _hs_insize; \ while ((_hs_psize > 0U) || ((_hs_qsize > 0U) && (_hs_q != NULL))) {\ if (_hs_psize == 0U) { \ _hs_e = _hs_q; \ _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } else if ( (_hs_qsize == 0U) || (_hs_q == NULL) ) { \ _hs_e = _hs_p; \ if (_hs_p != NULL){ \ _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ ((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 != NULL){ \ _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ ((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 != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } \ if ( _hs_tail != NULL ) { \ _hs_tail->next = ((_hs_e != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ } else { \ _hs_list = _hs_e; \ } \ if (_hs_e != NULL) { \ _hs_e->prev = ((_hs_tail != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ } \ _hs_tail = _hs_e; \ } \ _hs_p = _hs_q; \ } \ if (_hs_tail != NULL){ \ _hs_tail->next = NULL; \ } \ if ( _hs_nmerges <= 1U ) { \ _hs_looping=0; \ (head)->hh.tbl->tail = _hs_tail; \ DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ } \ _hs_insize *= 2U; \ } \ 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 * in both hashes. There is no copy of the items made; rather * 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 != NULL) { \ 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 != NULL; \ _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 != NULL) { _last_elt_hh->next = _elt; } \ if (dst == NULL) { \ 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_FSCK(hh_dst,dst); \ } while (0) #define HASH_CLEAR(hh,head) \ do { \ if (head != 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; \ } \ } while (0) #define HASH_OVERHEAD(hh,head) \ ((head != NULL) ? ( \ (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))) : 0U) #ifdef NO_DECLTYPE #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) #else #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(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 != NULL)?((head)->hh.tbl->num_items):0U) typedef struct UT_hash_bucket { struct UT_hash_handle *hh_head; unsigned count; /* expand_mult is normally set to 0. In this situation, the max chain length * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If * the bucket's chain exceeds this length, bucket expansion is triggered). * However, setting expand_mult to a non-zero value delays bucket expansion * (that would be triggered by additions to this particular bucket) * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. * (The multiplier is simply expand_mult+1). The whole idea of this * multiplier is to reduce bucket expansions, since they are expensive, in * situations where we know that a particular bucket tends to be overused. * It is better to let its chain length grow to a longer yet-still-bounded * value, than to do an O(n) bucket expansion too often. */ unsigned expand_mult; } UT_hash_bucket; /* random signature used only to find hash tables in external analysis */ #define HASH_SIGNATURE 0xa0111fe1u #define HASH_BLOOM_SIGNATURE 0xb12220f2u 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 */ /* in an ideal situation (all buckets used equally), no bucket would have * more than ceil(#items/#buckets) items. that's the ideal chain length. */ unsigned ideal_chain_maxlen; /* nonideal_items is the number of items in the hash whose chain position * exceeds the ideal chain maxlen. these items pay the penalty for an uneven * hash distribution; reaching them in a chain traversal takes >ideal steps */ unsigned nonideal_items; /* ineffective expands occur when a bucket doubling was performed, but * afterward, more than half the items in the hash had nonideal chain * positions. If this happens on two consecutive expansions we inhibit any * further expansion, as it's not helping; this happens when the hash * function isn't a good fit for the key domain. When expansion is inhibited * the hash will still work, albeit no longer in constant time. */ unsigned ineff_expands, noexpand; uint32_t signature; /* used only to find hash tables in external analysis */ #ifdef HASH_BLOOM uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ uint8_t *bloom_bv; uint8_t bloom_nbits; #endif } UT_hash_table; typedef struct UT_hash_handle { struct UT_hash_table *tbl; void *prev; /* prev element in app order */ void *next; /* next element in app order */ struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ struct UT_hash_handle *hh_next; /* next hh in bucket order */ void *key; /* ptr to enclosing struct's key */ unsigned keylen; /* enclosing struct's key len */ unsigned hashv; /* result of hash-fcn(key) */ } UT_hash_handle; #endif /* UTHASH_H */ simple-obfs-0.0.5/src/utils.c000066400000000000000000000244771320326276300160510ustar00rootroot00000000000000/* * utils.c - Misc utilities * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #ifndef __MINGW32__ #include #include #endif #include #include #include "utils.h" #ifdef HAVE_SETRLIMIT #include #include #endif #define INT_DIGITS 19 /* enough for 64 bit integer */ #ifdef LIB_ONLY FILE *logfile; #endif #ifdef HAS_SYSLOG int use_syslog = 0; #endif #ifndef __MINGW32__ void ERROR(const char *s) { char *msg = strerror(errno); LOGE("%s: %s", s, msg); } #endif int use_tty = 1; char * ss_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 { *--p = '0' + (i % 10); i /= 10; } while (i != 0); return p; } else { /* i < 0 */ do { *--p = '0' - (i % 10); i /= 10; } while (i != 0); *--p = '-'; } return p; } int ss_isnumeric(const char *s) { if (!s || !*s) return 0; while (isdigit(*s)) ++s; return *s == '\0'; } /* * setuid() and setgid() for a specified user. */ int run_as(const char *user) { #ifndef __MINGW32__ if (user[0]) { /* Convert user to a long integer if it is a non-negative number. * -1 means it is a user name. */ long uid = -1; if (ss_isnumeric(user)) { errno = 0; char *endptr; uid = strtol(user, &endptr, 10); if (errno || endptr == user) uid = -1; } #ifdef HAVE_GETPWNAM_R struct passwd pwdbuf, *pwd; memset(&pwdbuf, 0, sizeof(struct passwd)); size_t buflen; int err; 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 = uid >= 0 ? getpwuid_r((uid_t)uid, &pwdbuf, buf, buflen, &pwd) : getpwnam_r(user, &pwdbuf, buf, buflen, &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", pwd->pw_name, strerror(errno)); return 0; } if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) { LOGE("Could not change supplementary groups for user '%s'.", pwd->pw_name); return 0; } if (setuid(pwd->pw_uid) != 0) { LOGE( "Could not change user id to that of run_as user '%s': %s", pwd->pw_name, 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); } return 0; } 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); return 0; } /* Else try again with larger buffer. */ } #else /* No getpwnam_r() :-( We'll use getpwnam() and hope for the best. */ struct passwd *pwd; if (!(pwd = uid >=0 ? getpwuid((uid_t)uid) : 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) { LOGE("Could not change group id to that of run_as user '%s': %s", pwd->pw_name, strerror(errno)); return 0; } if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) { LOGE("Could not change supplementary groups for user '%s'.", pwd->pw_name); return 0; } if (setuid(pwd->pw_uid) != 0) { LOGE("Could not change user id to that of run_as user '%s': %s", pwd->pw_name, strerror(errno)); return 0; } #endif } #endif // __MINGW32__ return 1; } char * ss_strndup(const char *s, size_t n) { size_t len = strlen(s); char *ret; if (len <= n) { return strdup(s); } ret = ss_malloc(n + 1); strncpy(ret, s, n); ret[n] = '\0'; return ret; } void FATAL(const char *msg) { LOGE("%s", msg); exit(-1); } void * ss_malloc(size_t size) { void *tmp = malloc(size); if (tmp == NULL) exit(EXIT_FAILURE); return tmp; } void * ss_realloc(void *ptr, size_t new_size) { void *new = realloc(ptr, new_size); if (new == NULL) { free(ptr); ptr = NULL; exit(EXIT_FAILURE); } return new; } void usage() { printf("\n"); printf("simple-obfs %s\n\n", VERSION); printf( " maintained by Max Lv \n\n"); printf(" usage:\n\n"); #ifdef MODULE_LOCAL printf(" obfs-local\n"); #elif MODULE_REMOTE printf(" obfs-server\n"); #endif 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"); #ifdef MODULE_REMOTE printf( " -r : Forward traffic to this remote server address.\n"); #endif printf( " --obfs Enable obfuscating: HTTP or TLS (Experimental).\n"); #ifndef MODULE_REMOTE printf( " --obfs-host Hostname for obfuscating (Experimental).\n"); #endif printf("\n"); printf( " [-a ] Run as another user.\n"); printf( " [-f ] The file path to store pid.\n"); printf( " [-t ] Socket timeout in seconds.\n"); printf( " [-c ] The path to config file.\n"); #ifdef HAVE_SETRLIMIT printf( " [-n ] Max number of open files.\n"); #endif printf( " [-b ] Local address to bind.\n"); printf("\n"); #ifdef MODULE_REMOTE printf( " [-6] Resovle hostname to IPv6 address first.\n"); #endif printf("\n"); #ifdef MODULE_REMOTE printf( " [-d ] Name servers for internal DNS resolver.\n"); #endif #if defined(MODULE_REMOTE) || defined(MODULE_LOCAL) printf( " [--fast-open] Enable TCP fast open.\n"); printf( " with Linux kernel > 3.7.0.\n"); #endif #ifdef __linux__ printf( " [--mptcp] Enable Multipath TCP on MPTCP Kernel.\n"); #endif printf("\n"); printf( " [-v] Verbose mode.\n"); printf( " [-h, --help] Print this message.\n"); printf("\n"); fflush(stdout); } void daemonize(const char *path) { #ifndef __MINGW32__ /* Our process ID and Session ID */ pid_t pid, sid; /* Fork off the parent process */ pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } /* If we got a good PID, then * we can exit the parent process. */ if (pid > 0) { FILE *file = fopen(path, "w"); if (file == NULL) { FATAL("Invalid pid file\n"); } fprintf(file, "%d", (int)pid); fclose(file); exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); /* Open any logs here */ /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); #endif } #ifdef HAVE_SETRLIMIT int set_nofile(int nofile) { struct rlimit limit = { nofile, nofile }; /* set both soft and hard limit */ 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?"); return -1; } else if (errno == EINVAL) { LOGE("invalid nofile, decrease nofile and try again"); return -1; } else { LOGE("setrlimit failed: %s", strerror(errno)); return -1; } } return 0; } #endif simple-obfs-0.0.5/src/utils.h000066400000000000000000000216151320326276300160450ustar00rootroot00000000000000/* * utils.h - Misc utilities * * Copyright (C) 2013 - 2016, Max Lv * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #if defined(USE_CRYPTO_OPENSSL) #include #define USING_CRYPTO OPENSSL_VERSION_TEXT #elif defined(USE_CRYPTO_POLARSSL) #include #define USING_CRYPTO POLARSSL_VERSION_STRING_FULL #elif defined(USE_CRYPTO_MBEDTLS) #include #define USING_CRYPTO MBEDTLS_VERSION_STRING_FULL #endif #ifndef _UTILS_H #define _UTILS_H #include #include #include #include #define PORTSTRLEN 16 #define SS_ADDRSTRLEN (INET6_ADDRSTRLEN + PORTSTRLEN + 1) #ifdef ANDROID #include #define USE_TTY() #define USE_SYSLOG(ident) #define LOGI(...) \ ((void)__android_log_print(ANDROID_LOG_DEBUG, "simple-obfs", \ __VA_ARGS__)) #define LOGE(...) \ ((void)__android_log_print(ANDROID_LOG_ERROR, "simple-obfs", \ __VA_ARGS__)) #else #define STR(x) # x #define TOSTR(x) STR(x) #ifdef LIB_ONLY extern FILE *logfile; #define TIME_FORMAT "%Y-%m-%d %H:%M:%S" #define USE_TTY() #define USE_SYSLOG(ident) #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 LOGI(format, ...) \ do { \ if (logfile != NULL) { \ time_t now = time(NULL); \ char timestr[20]; \ strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ fprintf(logfile, " %s [simple-obfs] 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 [simple-obfs] ERROR: " format "\n", timestr, \ ## __VA_ARGS__); \ fflush(logfile); } \ } \ while (0) #elif defined(_WIN32) #define TIME_FORMAT "%Y-%m-%d %H:%M:%S" #define USE_TTY() #define USE_SYSLOG(ident) #define LOGI(format, ...) \ do { \ time_t now = time(NULL); \ char timestr[20]; \ strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ fprintf(stderr, "%s [simple-obfs] INFO: " format "\n", timestr, ## __VA_ARGS__); \ fflush(stderr); } \ while (0) #define LOGE(format, ...) \ do { \ time_t now = time(NULL); \ char timestr[20]; \ strftime(timestr, 20, TIME_FORMAT, localtime(&now)); \ fprintf(stderr, "%s [simple-obfs] ERROR: " format "\n", timestr, ## __VA_ARGS__); \ fflush(stderr); } \ while (0) #else #include extern int use_tty; #define USE_TTY() \ do { \ use_tty = isatty(STDERR_FILENO); \ } while (0) \ #define HAS_SYSLOG 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 LOGI(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)); \ if (use_tty) { \ fprintf(stderr, "\e[01;32m %s [simple-obfs] INFO: \e[0m" format "\n", timestr, \ ## __VA_ARGS__); \ } else { \ fprintf(stderr, " %s [simple-obfs] INFO: " 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)); \ if (use_tty) { \ fprintf(stderr, "\e[01;35m %s [simple-obfs] ERROR: \e[0m" format "\n", timestr, \ ## __VA_ARGS__); \ } else { \ fprintf(stderr, " %s [simple-obfs] ERROR: " format "\n", timestr, \ ## __VA_ARGS__); \ } \ } } \ while (0) #endif /* _WIN32 */ #endif #ifdef __MINGW32__ #ifdef ERROR #undef ERROR #endif #define ERROR(s) ss_error(s) #else void ERROR(const char *s); #endif char *ss_itoa(int i); int ss_isnumeric(const char *s); int run_as(const char *user); void FATAL(const char *msg); void usage(void); void daemonize(const char *path); char *ss_strndup(const char *s, size_t n); #ifdef HAVE_SETRLIMIT int set_nofile(int nofile); #endif void *ss_malloc(size_t size); void *ss_realloc(void *ptr, size_t new_size); #define ss_free(ptr) \ do { \ free(ptr); \ ptr = NULL; \ } while (0) #endif // _UTILS_H simple-obfs-0.0.5/src/win32.c000066400000000000000000000142201320326276300156340ustar00rootroot00000000000000/* * win32.c - Win32 port helpers * * Copyright (C) 2014, Linus Yang * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #include "win32.h" #include "utils.h" #include #include #ifdef setsockopt #undef setsockopt #endif void winsock_init(void) { WORD wVersionRequested; WSADATA wsaData; int ret; wVersionRequested = MAKEWORD(1, 1); ret = WSAStartup(wVersionRequested, &wsaData); if (ret != 0) { FATAL("Could not initialize winsock"); } if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { WSACleanup(); FATAL("Could not find a usable version of winsock"); } } void winsock_cleanup(void) { WSACleanup(); } 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) { LOGE("%s: %s", s, (char *)msg); LocalFree(msg); } } int setnonblocking(int fd) { u_long iMode = 1; long int iResult; iResult = ioctlsocket(fd, FIONBIO, &iMode); if (iResult != NO_ERROR) { LOGE("ioctlsocket failed with error: %ld\n", iResult); } return iResult; } size_t strnlen(const char *s, size_t maxlen) { const char *end = memchr(s, 0, maxlen); return end ? (size_t)(end - s) : maxlen; } const char * inet_ntop(int af, const void *src, char *dst, socklen_t size) { struct sockaddr_storage ss; unsigned long s = size; ZeroMemory(&ss, sizeof(ss)); ss.ss_family = af; switch (af) { case AF_INET: ((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src; break; case AF_INET6: ((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src; break; default: return NULL; } return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst, &s) == 0) ? dst : NULL; } #define NS_INADDRSZ 4 #define NS_IN6ADDRSZ 16 #define NS_INT16SZ 2 int inet_pton4(const char *src, char *dst) { uint8_t tmp[NS_INADDRSZ], *tp; int saw_digit = 0; int octets = 0; *(tp = tmp) = 0; int ch; while ((ch = *src++) != '\0') { if (ch >= '0' && ch <= '9') { uint32_t n = *tp * 10 + (ch - '0'); if (saw_digit && *tp == 0) return 0; if (n > 255) return 0; *tp = n; if (!saw_digit) { if (++octets > 4) return 0; saw_digit = 1; } } else if (ch == '.' && saw_digit) { if (octets == 4) return 0; *++tp = 0; saw_digit = 0; } else return 0; } if (octets < 4) return 0; memcpy(dst, tmp, NS_INADDRSZ); return 1; } int inet_pton6(const char *src, char *dst) { static const char xdigits[] = "0123456789abcdef"; uint8_t tmp[NS_IN6ADDRSZ]; uint8_t *tp = (uint8_t*) memset(tmp, '\0', NS_IN6ADDRSZ); uint8_t *endp = tp + NS_IN6ADDRSZ; uint8_t *colonp = NULL; /* Leading :: requires some special handling. */ if (*src == ':') { if (*++src != ':') return 0; } const char *curtok = src; int saw_xdigit = 0; uint32_t val = 0; int ch; while ((ch = tolower(*src++)) != '\0') { const char *pch = strchr(xdigits, ch); if (pch != NULL) { val <<= 4; val |= (pch - xdigits); if (val > 0xffff) return 0; saw_xdigit = 1; continue; } if (ch == ':') { curtok = src; if (!saw_xdigit) { if (colonp) return 0; colonp = tp; continue; } else if (*src == '\0') { return 0; } if (tp + NS_INT16SZ > endp) return 0; *tp++ = (uint8_t) (val >> 8) & 0xff; *tp++ = (uint8_t) val & 0xff; saw_xdigit = 0; val = 0; continue; } if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && inet_pton4(curtok, (char*) tp) > 0) { tp += NS_INADDRSZ; saw_xdigit = 0; break; /* '\0' was seen by inet_pton4(). */ } return 0; } if (saw_xdigit) { if (tp + NS_INT16SZ > endp) return 0; *tp++ = (uint8_t) (val >> 8) & 0xff; *tp++ = (uint8_t) val & 0xff; } if (colonp != NULL) { /* * Since some memmove()'s erroneously fail to handle * overlapping regions, we'll do the shift by hand. */ const int n = tp - colonp; if (tp == endp) return 0; for (int i = 1; i <= n; i++) { endp[-i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; } if (tp != endp) return 0; memcpy(dst, tmp, NS_IN6ADDRSZ); return 1; } int inet_pton(int af, const char *src, void *dst) { switch (af) { case AF_INET: return inet_pton4(src, dst); case AF_INET6: return inet_pton6(src, dst); default: return -1; } } simple-obfs-0.0.5/src/win32.h000066400000000000000000000034561320326276300156520ustar00rootroot00000000000000/* * win32.h - Win32 port helpers * * Copyright (C) 2014, Linus Yang * * This file is part of the simple-obfs. * * simple-obfs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * simple-obfs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with simple-obfs; see the file COPYING. If not, see * . */ #ifndef _WIN32_H #define _WIN32_H #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #include #include #ifdef EWOULDBLOCK #undef EWOULDBLOCK #endif #ifdef errno #undef errno #endif #ifdef ERROR #undef ERROR #endif #ifndef AI_ALL #define AI_ALL 0x00000100 #endif #ifndef AI_ADDRCONFIG #define AI_ADDRCONFIG 0x00000400 #endif #ifndef AI_V4MAPPED #define AI_V4MAPPED 0x00000800 #endif #ifndef IPV6_V6ONLY #define IPV6_V6ONLY 27 // Treat wildcard bind as AF_INET6-only. #endif #define EWOULDBLOCK WSAEWOULDBLOCK #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) void winsock_init(void); void winsock_cleanup(void); void ss_error(const char *s); size_t strnlen(const char *s, size_t maxlen); int setnonblocking(int fd); const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); int inet_pton(int af, const char *src, void *dst); #endif