From fa02368ab8e80d547ea0d331bf945ba1d5f90ca1 Mon Sep 17 00:00:00 2001 From: Georg Hopp Date: Fri, 9 Mar 2012 14:37:36 +0100 Subject: [PATCH] initial fork from server project --- .doxygen | 277 + .gitignore | 22 + AUTHORS | 1 + COPYING | 674 ++ ChangeLog | 424 ++ Makefile.am | 10 + NEWS | 0 README | 29 + TODO | 0 assets/jquery-1.7.1.js | 9266 ++++++++++++++++++++++++++ assets/jquery-1.7.1.min.js | 4 + assets/waldschrat.jpg | Bin 0 -> 79689 bytes bootstrap | 7 + certs/server.crt | 17 + certs/server.key | 15 + configure.ac | 41 + include/cbuf.h | 81 + include/class.h | 132 + include/commons.h | 10 + include/http/header.h | 50 + include/http/message.h | 58 + include/http/message/queue.h | 42 + include/http/parser.h | 67 + include/http/request.h | 45 + include/http/response.h | 57 + include/http/worker.h | 59 + include/http/writer.h | 65 + include/interface.h | 59 + include/interface/class.h | 57 + include/interface/http_intro.h | 47 + include/interface/logger.h | 45 + include/interface/observer.h | 40 + include/interface/stream_reader.h | 45 + include/interface/stream_writer.h | 45 + include/interface/subject.h | 46 + include/logger.h | 57 + include/server.h | 63 + include/session.h | 47 + include/socket.h | 47 + include/stream.h | 27 + include/utils/hash.h | 33 + include/utils/http.h | 16 + include/utils/memory.h | 34 + include/utils/signalHandling.h | 33 + src/Makefile.am | 66 + src/cbuf.c | 126 + src/cbuf/addr_index.c | 33 + src/cbuf/empty.c | 32 + src/cbuf/get_data.c | 41 + src/cbuf/get_free.c | 33 + src/cbuf/get_line.c | 49 + src/cbuf/get_read.c | 31 + src/cbuf/get_write.c | 31 + src/cbuf/inc_read.c | 36 + src/cbuf/inc_write.c | 36 + src/cbuf/is_empty.c | 31 + src/cbuf/is_locked.c | 33 + src/cbuf/lock.c | 31 + src/cbuf/memchr.c | 33 + src/cbuf/read.c | 60 + src/cbuf/release.c | 31 + src/cbuf/set_data.c | 45 + src/cbuf/skip_non_alpha.c | 34 + src/cbuf/write.c | 52 + src/http/header.c | 78 + src/http/header/add.c | 69 + src/http/header/get.c | 51 + src/http/header/to_string.c | 51 + src/http/message.c | 96 + src/http/message/get_version.c | 50 + src/http/message/has_keep_alive.c | 54 + src/http/message/has_valid_version.c | 49 + src/http/message/header_size_get.c | 55 + src/http/message/header_to_string.c | 56 + src/http/message/queue.c | 52 + src/http/parser.c | 76 + src/http/parser/body.c | 50 + src/http/parser/header.c | 67 + src/http/parser/new_message.c | 34 + src/http/parser/parse.c | 164 + src/http/request.c | 117 + src/http/request/has_valid_method.c | 53 + src/http/response.c | 110 + src/http/response/304.c | 60 + src/http/response/403.c | 52 + src/http/response/404.c | 66 + src/http/response/asset.c | 87 + src/http/response/login_form.c | 64 + src/http/response/me.c | 151 + src/http/response/randval.c | 68 + src/http/worker.c | 124 + src/http/worker/add_common_header.c | 51 + src/http/worker/get_asset.c | 38 + src/http/worker/process.c | 169 + src/http/worker/write.c | 35 + src/http/writer.c | 63 + src/http/writer/write.c | 155 + src/interface.c | 64 + src/interface/class.c | 85 + src/interface/http_intro.c | 51 + src/interface/logger.c | 60 + src/interface/observer.c | 37 + src/interface/stream_reader.c | 42 + src/interface/stream_writer.c | 42 + src/interface/subject.c | 49 + src/logger.c | 57 + src/logger/stderr.c | 38 + src/logger/syslog.c | 51 + src/server.c | 132 + src/server/close_conn.c | 48 + src/server/handle_accept.c | 100 + src/server/poll.c | 81 + src/server/read.c | 79 + src/server/run.c | 97 + src/server/write.c | 63 + src/session.c | 46 + src/session/add.c | 36 + src/session/delete.c | 23 + src/session/get.c | 29 + src/socket.c | 79 + src/socket/accept.c | 63 + src/socket/connect.c | 55 + src/socket/listen.c | 59 + src/stream.c | 41 + src/stream/read.c | 27 + src/stream/write.c | 27 + src/taskrambler.c | 196 + src/utils/daemonize.c | 47 + src/utils/hash.c | 30 + src/utils/http.c | 51 + src/utils/memory.c | 14 + src/utils/signalHandling.c | 47 + src/webgameserver.c | 196 + tests/Makefile.am | 29 + tests/cclassTest.c | 131 + tests/loggerTest.c | 94 + tests/mock/class.c | 88 + tests/mock/class.h | 49 + tests/runtest.c | 121 + tests/runtest.h | 131 + tests/serverTest.c | 122 + tests/socketTest.c | 123 + tests/tst-tsearch.c | 333 + 143 files changed, 19036 insertions(+) create mode 100644 .doxygen create mode 100644 .gitignore create mode 100644 AUTHORS create mode 100644 COPYING create mode 100644 ChangeLog create mode 100644 Makefile.am create mode 100644 NEWS create mode 100644 README create mode 100644 TODO create mode 100644 assets/jquery-1.7.1.js create mode 100644 assets/jquery-1.7.1.min.js create mode 100644 assets/waldschrat.jpg create mode 100755 bootstrap create mode 100644 certs/server.crt create mode 100644 certs/server.key create mode 100644 configure.ac create mode 100644 include/cbuf.h create mode 100644 include/class.h create mode 100644 include/commons.h create mode 100644 include/http/header.h create mode 100644 include/http/message.h create mode 100644 include/http/message/queue.h create mode 100644 include/http/parser.h create mode 100644 include/http/request.h create mode 100644 include/http/response.h create mode 100644 include/http/worker.h create mode 100644 include/http/writer.h create mode 100644 include/interface.h create mode 100644 include/interface/class.h create mode 100644 include/interface/http_intro.h create mode 100644 include/interface/logger.h create mode 100644 include/interface/observer.h create mode 100644 include/interface/stream_reader.h create mode 100644 include/interface/stream_writer.h create mode 100644 include/interface/subject.h create mode 100644 include/logger.h create mode 100644 include/server.h create mode 100644 include/session.h create mode 100644 include/socket.h create mode 100644 include/stream.h create mode 100644 include/utils/hash.h create mode 100644 include/utils/http.h create mode 100644 include/utils/memory.h create mode 100644 include/utils/signalHandling.h create mode 100644 src/Makefile.am create mode 100644 src/cbuf.c create mode 100644 src/cbuf/addr_index.c create mode 100644 src/cbuf/empty.c create mode 100644 src/cbuf/get_data.c create mode 100644 src/cbuf/get_free.c create mode 100644 src/cbuf/get_line.c create mode 100644 src/cbuf/get_read.c create mode 100644 src/cbuf/get_write.c create mode 100644 src/cbuf/inc_read.c create mode 100644 src/cbuf/inc_write.c create mode 100644 src/cbuf/is_empty.c create mode 100644 src/cbuf/is_locked.c create mode 100644 src/cbuf/lock.c create mode 100644 src/cbuf/memchr.c create mode 100644 src/cbuf/read.c create mode 100644 src/cbuf/release.c create mode 100644 src/cbuf/set_data.c create mode 100644 src/cbuf/skip_non_alpha.c create mode 100644 src/cbuf/write.c create mode 100644 src/http/header.c create mode 100644 src/http/header/add.c create mode 100644 src/http/header/get.c create mode 100644 src/http/header/to_string.c create mode 100644 src/http/message.c create mode 100644 src/http/message/get_version.c create mode 100644 src/http/message/has_keep_alive.c create mode 100644 src/http/message/has_valid_version.c create mode 100644 src/http/message/header_size_get.c create mode 100644 src/http/message/header_to_string.c create mode 100644 src/http/message/queue.c create mode 100644 src/http/parser.c create mode 100644 src/http/parser/body.c create mode 100644 src/http/parser/header.c create mode 100644 src/http/parser/new_message.c create mode 100644 src/http/parser/parse.c create mode 100644 src/http/request.c create mode 100644 src/http/request/has_valid_method.c create mode 100644 src/http/response.c create mode 100644 src/http/response/304.c create mode 100644 src/http/response/403.c create mode 100644 src/http/response/404.c create mode 100644 src/http/response/asset.c create mode 100644 src/http/response/login_form.c create mode 100644 src/http/response/me.c create mode 100644 src/http/response/randval.c create mode 100644 src/http/worker.c create mode 100644 src/http/worker/add_common_header.c create mode 100644 src/http/worker/get_asset.c create mode 100644 src/http/worker/process.c create mode 100644 src/http/worker/write.c create mode 100644 src/http/writer.c create mode 100644 src/http/writer/write.c create mode 100644 src/interface.c create mode 100644 src/interface/class.c create mode 100644 src/interface/http_intro.c create mode 100644 src/interface/logger.c create mode 100644 src/interface/observer.c create mode 100644 src/interface/stream_reader.c create mode 100644 src/interface/stream_writer.c create mode 100644 src/interface/subject.c create mode 100644 src/logger.c create mode 100644 src/logger/stderr.c create mode 100644 src/logger/syslog.c create mode 100644 src/server.c create mode 100644 src/server/close_conn.c create mode 100644 src/server/handle_accept.c create mode 100644 src/server/poll.c create mode 100644 src/server/read.c create mode 100644 src/server/run.c create mode 100644 src/server/write.c create mode 100644 src/session.c create mode 100644 src/session/add.c create mode 100644 src/session/delete.c create mode 100644 src/session/get.c create mode 100644 src/socket.c create mode 100644 src/socket/accept.c create mode 100644 src/socket/connect.c create mode 100644 src/socket/listen.c create mode 100644 src/stream.c create mode 100644 src/stream/read.c create mode 100644 src/stream/write.c create mode 100644 src/taskrambler.c create mode 100644 src/utils/daemonize.c create mode 100644 src/utils/hash.c create mode 100644 src/utils/http.c create mode 100644 src/utils/memory.c create mode 100644 src/utils/signalHandling.c create mode 100644 src/webgameserver.c create mode 100644 tests/Makefile.am create mode 100644 tests/cclassTest.c create mode 100644 tests/loggerTest.c create mode 100644 tests/mock/class.c create mode 100644 tests/mock/class.h create mode 100644 tests/runtest.c create mode 100644 tests/runtest.h create mode 100644 tests/serverTest.c create mode 100644 tests/socketTest.c create mode 100644 tests/tst-tsearch.c diff --git a/.doxygen b/.doxygen new file mode 100644 index 0000000..7d07de8 --- /dev/null +++ b/.doxygen @@ -0,0 +1,277 @@ +# Doxyfile 1.7.3 + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- +DOXYFILE_ENCODING = UTF-8 +PROJECT_NAME = Server +PROJECT_NUMBER = 0.0.1 +PROJECT_BRIEF = "HTTP/REST server implementation" +PROJECT_LOGO = +OUTPUT_DIRECTORY = docs +CREATE_SUBDIRS = NO +OUTPUT_LANGUAGE = English +BRIEF_MEMBER_DESC = YES +REPEAT_BRIEF = YES +ABBREVIATE_BRIEF = +ALWAYS_DETAILED_SEC = NO +INLINE_INHERITED_MEMB = NO +FULL_PATH_NAMES = YES +STRIP_FROM_PATH = +STRIP_FROM_INC_PATH = +SHORT_NAMES = NO +JAVADOC_AUTOBRIEF = NO +QT_AUTOBRIEF = NO +MULTILINE_CPP_IS_BRIEF = NO +INHERIT_DOCS = YES +SEPARATE_MEMBER_PAGES = NO +TAB_SIZE = 8 +ALIASES = +OPTIMIZE_OUTPUT_FOR_C = YES +OPTIMIZE_OUTPUT_JAVA = NO +OPTIMIZE_FOR_FORTRAN = NO +OPTIMIZE_OUTPUT_VHDL = NO +EXTENSION_MAPPING = +BUILTIN_STL_SUPPORT = NO +CPP_CLI_SUPPORT = YES +SIP_SUPPORT = NO +IDL_PROPERTY_SUPPORT = YES +DISTRIBUTE_GROUP_DOC = NO +SUBGROUPING = YES +TYPEDEF_HIDES_STRUCT = NO +SYMBOL_CACHE_SIZE = 0 +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- +EXTRACT_ALL = YES +EXTRACT_PRIVATE = NO +EXTRACT_STATIC = NO +EXTRACT_LOCAL_CLASSES = YES +EXTRACT_LOCAL_METHODS = YES +EXTRACT_ANON_NSPACES = YES +HIDE_UNDOC_MEMBERS = NO +HIDE_UNDOC_CLASSES = NO +HIDE_FRIEND_COMPOUNDS = NO +HIDE_IN_BODY_DOCS = NO +INTERNAL_DOCS = YES +CASE_SENSE_NAMES = YES +HIDE_SCOPE_NAMES = NO +SHOW_INCLUDE_FILES = YES +FORCE_LOCAL_INCLUDES = NO +INLINE_INFO = YES +SORT_MEMBER_DOCS = YES +SORT_BRIEF_DOCS = NO +SORT_MEMBERS_CTORS_1ST = NO +SORT_GROUP_NAMES = NO +SORT_BY_SCOPE_NAME = NO +STRICT_PROTO_MATCHING = NO +GENERATE_TODOLIST = YES +GENERATE_TESTLIST = YES +GENERATE_BUGLIST = YES +GENERATE_DEPRECATEDLIST= YES +ENABLED_SECTIONS = +MAX_INITIALIZER_LINES = 30 +SHOW_USED_FILES = YES +SHOW_DIRECTORIES = NO +SHOW_FILES = YES +SHOW_NAMESPACES = YES +FILE_VERSION_FILTER = +LAYOUT_FILE = +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_IF_DOC_ERROR = YES +WARN_NO_PARAMDOC = NO +WARN_FORMAT = "$file:$line: $text" +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = +INPUT_ENCODING = UTF-8 +FILE_PATTERNS = +RECURSIVE = YES +EXCLUDE = +EXCLUDE_SYMLINKS = NO +EXCLUDE_PATTERNS = */tests/* */doc/* */docs/* */.git/* +EXCLUDE_SYMBOLS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = +EXAMPLE_RECURSIVE = NO +IMAGE_PATH = +INPUT_FILTER = +FILTER_PATTERNS = +FILTER_SOURCE_FILES = NO +FILTER_SOURCE_PATTERNS = +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- +SOURCE_BROWSER = YES +INLINE_SOURCES = YES +STRIP_CODE_COMMENTS = YES +REFERENCED_BY_RELATION = NO +REFERENCES_RELATION = NO +REFERENCES_LINK_SOURCE = YES +USE_HTAGS = NO +VERBATIM_HEADERS = YES +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = YES +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = html +HTML_FILE_EXTENSION = .html +HTML_HEADER = +HTML_FOOTER = +HTML_STYLESHEET = +HTML_COLORSTYLE_HUE = 220 +HTML_COLORSTYLE_SAT = 100 +HTML_COLORSTYLE_GAMMA = 80 +HTML_TIMESTAMP = YES +HTML_ALIGN_MEMBERS = YES +HTML_DYNAMIC_SECTIONS = NO +GENERATE_DOCSET = NO +DOCSET_FEEDNAME = "Doxygen generated docs" +DOCSET_BUNDLE_ID = org.doxygen.Project +DOCSET_PUBLISHER_ID = org.doxygen.Publisher +DOCSET_PUBLISHER_NAME = Publisher +GENERATE_HTMLHELP = NO +CHM_FILE = +HHC_LOCATION = +GENERATE_CHI = NO +CHM_INDEX_ENCODING = +BINARY_TOC = NO +TOC_EXPAND = NO +GENERATE_QHP = NO +QCH_FILE = +QHP_NAMESPACE = org.doxygen.Project +QHP_VIRTUAL_FOLDER = doc +QHP_CUST_FILTER_NAME = +QHP_CUST_FILTER_ATTRS = +QHP_SECT_FILTER_ATTRS = +QHG_LOCATION = +GENERATE_ECLIPSEHELP = NO +ECLIPSE_DOC_ID = org.doxygen.Project +DISABLE_INDEX = NO +ENUM_VALUES_PER_LINE = 4 +GENERATE_TREEVIEW = YES +USE_INLINE_TREES = YES +TREEVIEW_WIDTH = 250 +EXT_LINKS_IN_WINDOW = NO +FORMULA_FONTSIZE = 10 +FORMULA_TRANSPARENT = YES +USE_MATHJAX = NO +MATHJAX_RELPATH = http://www.mathjax.org/mathjax +SEARCHENGINE = YES +SERVER_BASED_SEARCH = NO +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = YES +LATEX_OUTPUT = latex +LATEX_CMD_NAME = latex +MAKEINDEX_CMD_NAME = makeindex +COMPACT_LATEX = NO +PAPER_TYPE = a4 +EXTRA_PACKAGES = +LATEX_HEADER = +PDF_HYPERLINKS = YES +USE_PDFLATEX = YES +LATEX_BATCHMODE = NO +LATEX_HIDE_INDICES = NO +LATEX_SOURCE_CODE = NO +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +RTF_OUTPUT = rtf +COMPACT_RTF = NO +RTF_HYPERLINKS = NO +RTF_STYLESHEET_FILE = +RTF_EXTENSIONS_FILE = +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +MAN_OUTPUT = man +MAN_EXTENSION = .3 +MAN_LINKS = NO +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- +GENERATE_XML = NO +XML_OUTPUT = xml +XML_SCHEMA = +XML_DTD = +XML_PROGRAMLISTING = YES +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- +GENERATE_AUTOGEN_DEF = NO +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- +GENERATE_PERLMOD = NO +PERLMOD_LATEX = NO +PERLMOD_PRETTY = YES +PERLMOD_MAKEVAR_PREFIX = +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = NO +EXPAND_ONLY_PREDEF = NO +SEARCH_INCLUDES = YES +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = +EXPAND_AS_DEFINED = +SKIP_FUNCTION_MACROS = NO +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +EXTERNAL_GROUPS = YES +PERL_PATH = /usr/bin/perl +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +CLASS_DIAGRAMS = YES +MSCGEN_PATH = +HIDE_UNDOC_RELATIONS = YES +HAVE_DOT = YES +DOT_NUM_THREADS = 0 +DOT_FONTNAME = Helvetica +DOT_FONTSIZE = 10 +DOT_FONTPATH = +CLASS_GRAPH = YES +COLLABORATION_GRAPH = YES +GROUP_GRAPHS = YES +UML_LOOK = YES +TEMPLATE_RELATIONS = NO +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +CALL_GRAPH = YES +CALLER_GRAPH = YES +GRAPHICAL_HIERARCHY = YES +DIRECTORY_GRAPH = YES +DOT_IMAGE_FORMAT = png +DOT_PATH = +DOTFILE_DIRS = +MSCFILE_DIRS = +DOT_GRAPH_MAX_NODES = 50 +MAX_DOT_GRAPH_DEPTH = 0 +DOT_TRANSPARENT = YES +DOT_MULTI_TARGETS = NO +GENERATE_LEGEND = YES +DOT_CLEANUP = YES diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c79b2b --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +.*.swp +*.o +.dirstamp +.deps/ +Makefile +Makefile.in +m4/ +/docs/ +/config.* +/configure +/INSTALL +*.m4 +/autom4te.cache/ +/compile +/depcomp +/docs/ +/install-sh +/libtool +/ltmain.sh +/missing +stamp-h1 +src/taskrambler diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..354d97f --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Georg Hopp diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + 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 + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..184e80e --- /dev/null +++ b/ChangeLog @@ -0,0 +1,424 @@ +2012-02-23 17:40:00 +0100 Georg Hopp + + * add cookie header again (HEAD, origin/master, origin/HEAD, master) + +2012-02-23 16:41:36 +0100 Georg Hopp + + * optmize header search + +2012-02-23 13:02:23 +0100 Georg Hopp + + * changed all string operation within header handling with fixed length mem operations, preventing multiple iterations over these strings. In theory this should improve performance in reality it seems that it is worse...CHECK WHY + +2012-02-23 00:05:25 +0100 Georg Hopp + + * fix initialization of search value + +2012-02-22 21:50:21 +0100 Georg Hopp + + * ed + +2012-02-22 21:49:52 +0100 Georg Hopp + + * structural changes for worker/process. @TODO actually i have no idea why this happens. + +2012-02-22 12:19:40 +0100 Georg Hopp + + * fix memory problems occured with latest changes + +2012-02-22 09:03:40 +0100 Georg Hopp + + * fixed bug in keep-alive check arised by implementation if #10 + +2012-02-22 08:51:05 +0100 Georg Hopp + + * add forgotten jquery assets + +2012-02-22 08:48:43 +0100 Georg Hopp + + * closes #10: values for header ids are now stored in a char ** making multiple values for one id possible. Additionally added a jquery action that delivers the jquery java script and use it on the me action + +2012-02-21 13:01:38 +0100 Georg Hopp + + * now when a constructor returns -1 the new call will in turn call the destructor effectively freeing all resources. ATTENTION: now the destructor has to be aware that it might be called with a not completely initialized object. To make this more ease there is the FREE makro with the corresponding ffree that does NULL pointer checking and the destructor checks for NULL pointer too. Additionally the handle_accept now handles _SC_OPEN_MAX - 10 connections. The 10 are reserved for internal usage. + +2012-02-21 09:45:01 +0100 Georg Hopp + + * now a child is spawned and writes random values in a shared memory segment. These values will be shown in the me action + +2012-02-20 21:36:55 +0100 Georg Hopp + + * some code cleanups...no changes in the logic + +2012-02-20 18:08:23 +0100 Georg Hopp + + * move sdbm implementation in one file. + +2012-02-20 17:16:44 +0100 Georg Hopp + + * changed /**/ single line comments to // + +2012-02-20 14:55:46 +0100 Georg Hopp + + * start documenting this whole stuff...well at least add a copyright information in each file + +2012-02-20 10:10:29 +0100 Georg Hopp + + * first very crude, not complete, experimental 304 test implementation + +2012-02-20 07:55:06 +0100 Georg Hopp + + * disconnect on invalid request line + +2012-02-19 20:12:40 +0100 Georg Hopp + + * now incomplete requests should no longer block the complete server. Tested with \'echo -en "GET / HTTP\r\nConn" | nc -w 600 localhost 11212\' and then doing requests from my browser. @TODO: cleanup those stuff, check if a not correctly response reading would block the server. + +2012-02-19 18:28:30 +0100 Georg Hopp + + * increase writebuffer size a lot. + +2012-02-19 18:15:55 +0100 Georg Hopp + + * fixed the non keep-alive performance issue as well as i lower memory usage by using a single read and write circular buffer for every connection. @TODO: i noticed a server hang while getting large data (my image) with non keep-alive connections. Additionally an incomplete keep-alive request might stop the server now as the lock on the read buffer will not be released. + +2012-02-19 15:41:48 +0100 Georg Hopp + + * another try with the shmen trick...this time use MAP_ANONYMOUS ... as GNU extension. + +2012-02-19 14:33:42 +0100 Georg Hopp + + * Merge remote branch 'origin/master' + +2012-02-19 12:13:52 +0100 Georg Hopp + + * added missing header file to repo + +2012-02-19 11:35:15 +0100 Georg Hopp + + * another try with a shared memory based ringbuffer...this performs well for keep-alive sessions but is much slower without. actually i am not sure why but most likely the shared memory setup is quite expensive. @TODO: make a profiling. + +2012-02-18 21:08:32 +0100 Georg Hopp + + * fix inf loop. @TODO: This whole handling has to be cleaned. + +2012-02-18 20:50:01 +0100 Georg Hopp + + * this change hopefully makes the shm trick work on amd64 + +2012-02-18 20:12:27 +0100 Georg Hopp + + * lots of changes but primarily change the request parser to use a ringbuffer. The ringbuffer is implemented using the shared memory trick. + +2012-02-15 12:30:33 +0100 Georg Hopp + + * some more cleanups in the server code. Removing not needed header includes + +2012-02-15 12:17:39 +0100 Georg Hopp + + * Merge branch 'master' of 192.168.100.2:/var/lib/git/server + +2012-02-15 12:17:00 +0100 Georg Hopp + + * now the separated http worker works. Changed some size_t to ssize_t as i use -1 and -2 es error indicator in my server and fixed caculation of remainig buffer size in reader + +2012-02-15 09:38:32 +0100 Georg Hopp + + * separated the server completely from the http processing + +2012-02-15 06:19:52 +0100 Georg Hopp + + * add subject/observer interface + +2012-02-15 06:19:52 +0100 Georg Hopp + + * add subject/observer interface + +2012-02-15 04:55:46 +0100 Georg Hopp + + * fix infinite busy loop in run + +2012-02-15 04:44:38 +0100 Georg Hopp + + * dynamically get and free buffer for response write pipe now + +2012-02-14 21:32:38 +0100 Georg Hopp + + * increase write buffer + +2012-02-13 21:27:47 +0100 Georg Hopp + + * use one dynamic buffer less and save at least one write on small responses + +2012-02-13 18:25:36 +0100 Georg Hopp + + * removed generated docs + +2012-02-13 17:55:52 +0100 Georg Hopp + + * fixed bug in new response handling + +2012-02-13 17:29:35 +0100 Georg Hopp + + * better response handling but still buggy with stream piping + +2012-02-13 09:46:39 +0100 Georg Hopp + + * now load image from actual server + +2012-02-13 09:39:21 +0100 Georg Hopp + + * first working version of content delivery from file....very crude... @TODO: rewrite complete response handline. + +2012-02-12 20:39:12 +0100 Georg Hopp + + * more generalizing of response writing (implemented a response writer...now it should be possible to implement a stream writer for images + +2012-02-12 12:43:56 +0100 Georg Hopp + + * make http request and response childs of a common parent http message + +2012-02-12 04:13:54 +0100 Georg Hopp + + * remove now obsoleted header_sort + +2012-02-12 04:05:38 +0100 Georg Hopp + + * change response to tree based header storage and make everything work. + +2012-02-12 00:05:13 +0100 Georg Hopp + + * changed header hashing to use btree (GNU only). @TODO: make this conditional for other systems. Removed the qsort calls on server->fds making O(2nlogn) to O(n) + +2012-02-11 13:52:32 +0100 Georg Hopp + + * daemonize testserver now + +2012-02-11 12:47:01 +0100 Georg Hopp + + * fix seaks and hangs after adding response object (mostly not related with the response object but how i integated it into serverRun + +2012-02-10 19:57:57 +0100 Georg Hopp + + * started a response handler and changed serverRun to use it for its response + +2012-02-10 12:42:04 +0100 Georg Hopp + + * fixed bug at server destructor + +2012-02-10 09:59:41 +0100 Georg Hopp + + * reset keep_live flag on connection close + +2012-02-10 09:52:27 +0100 Georg Hopp + + * made a first cruel handling for keep-alive and non keep-alive requests. @TODO: this MUST BE cleaned + +2012-02-10 08:14:31 +0100 Georg Hopp + + * now only use keep-alive.... + +2012-02-10 06:36:43 +0100 Georg Hopp + + * moved request_parser.h and request_queue.h in separeate request subfolder + +2012-02-10 06:22:39 +0100 Georg Hopp + + * fix rather nasty reentrance bug + +2012-02-10 05:52:50 +0100 Georg Hopp + + * fix bug that arose in rewrite of header get and results in an ugly memory leak, as well as no headers would be found any more + +2012-02-10 00:27:51 +0100 Georg Hopp + + * fix memory leak created while changing things + +2012-02-09 22:39:08 +0100 Georg Hopp + + * updated docs + +2012-02-09 22:34:32 +0100 Georg Hopp + + * start split of request parser + +2012-02-09 11:44:17 +0100 Georg Hopp + + * no more request body debig output + +2012-02-09 11:32:28 +0100 Georg Hopp + + * add missing header_get to repo and build header hash only from lowercase letters now as it seems header identifier should be case insensitive + +2012-02-09 09:34:21 +0100 Georg Hopp + + * access to headers via hash, read body (actually only with content-length header should also look for content-encoding) + +2012-02-08 16:51:49 +0100 Georg Hopp + + * fix handling of remote close - i should have another eye on this...there still seems to be something wrong. + +2012-02-08 15:04:52 +0100 Georg Hopp + + * fixed some warnings + +2012-02-08 13:12:59 +0100 Georg Hopp + + * changed documentation + +2012-02-08 13:05:23 +0100 Georg Hopp + + * added first generated documentation + +2012-02-08 12:14:44 +0100 Georg Hopp + + * oops commit...forgot to add request_queue.c + +2012-02-08 11:52:30 +0100 Georg Hopp + + * found the file handle lost...made a first workaround and added an todo. + +2012-02-08 10:21:04 +0100 Georg Hopp + + * changed request handling. @TODO: I still seem to have the problem that the file handles are not closed and freed correctly as the service refuses connections after about a 1000. + +2012-02-07 14:20:00 +0100 Georg Hopp + + * now stuff seems to work correct even if read does not provide a complete request (tested with telnet) + +2012-02-07 13:41:49 +0100 Georg Hopp + + * now each HttpRequestParser initializes its own request queue and enqueus completed requests there. The server now gets the queue and prints completed requests. + +2012-02-07 11:12:30 +0100 Georg Hopp + + * started filling out a request object with the parser + +2012-02-07 09:29:59 +0100 Georg Hopp + + * porformance improvement in parsing process (no longer do alloc and free on each line) + +2012-02-07 08:52:18 +0100 Georg Hopp + + * basic request parsing (line by line) implemented + +2012-02-06 16:08:13 +0100 Georg Hopp + + * split server implementation for readability + +2012-02-06 11:35:40 +0100 Georg Hopp + + * free reader (HttpRequestParser) when connection is closed + +2012-02-06 11:20:00 +0100 Georg Hopp + + * add StreamReader interface, modify HttpRequestParser and Server to use it + +2012-02-06 11:15:00 +0100 Georg Hopp + + * add missing include to stdarg.h + +2012-02-06 10:45:33 +0100 Georg Hopp + + * implement clone selector + +2012-02-06 10:43:59 +0100 Georg Hopp + + * add ability to call interface methods with return value + +2012-02-06 02:37:55 +0100 Georg Hopp + + * make build system work again + +2012-02-06 02:37:24 +0100 Georg Hopp + + * remove inline stuff for now ... add carefully again later perhaps + +2012-02-06 00:57:26 +0100 Georg Hopp + + * and also mod conigure.ac + +2012-02-06 00:55:44 +0100 Georg Hopp + + * makefile modification for new class stuff + +2012-02-05 22:55:16 +0100 Georg Hopp + + * changed class tool. Now multiple interface per class are supported as well as simple inheritence. + +2012-02-05 22:47:10 +0100 Georg Hopp + + * some latest work + +2012-02-05 22:44:59 +0100 Georg Hopp + + * added some documentation + +2012-02-05 22:42:37 +0100 Georg Hopp + + * changes related to server code + +2012-01-19 16:41:41 +0100 Georg Hopp + + * added some valueable thought about cclass and how this structure might evolve to a real class + +2012-01-18 07:52:07 +0100 Georg Hopp + + * add testserver and did some fixes not shown by my incomplete tests + +2012-01-17 15:40:07 +0100 Georg Hopp + + * more notes + +2012-01-17 15:04:33 +0100 Georg Hopp + + * add some thought + +2012-01-17 14:49:49 +0100 Georg Hopp + + * changed from select(UNIX) to poll(POSIX) + +2012-01-16 18:39:01 +0100 Georg Hopp + + * work on server_run + +2012-01-16 17:05:57 +0100 Georg Hopp + + * move test under docs dir + +2012-01-16 17:05:08 +0100 Georg Hopp + + * simply copy signal handling code from gameserver project + +2012-01-16 16:04:11 +0100 Georg Hopp + + * more work on socket handling stuff... @TODO think about renaming it to connection as it only handles TCP sockets + +2012-01-16 13:48:05 +0100 Georg Hopp + + * add info text about file handle passing and ported more stuff from my old server structure + +2012-01-16 08:05:15 +0100 Georg Hopp + + * reflect changes in configure.ac + +2012-01-13 22:46:45 +0100 Georg Hopp + + * add daemonize code from other project. (Might be integrated in a future class but i am not sure right now + +2012-01-13 22:16:17 +0100 Georg Hopp + + * logger now works and has some basic testing + +2012-01-13 22:15:03 +0100 Georg Hopp + + * change cclass so that the internal structure is no longer visible by the rest of the code + +2012-01-13 16:06:02 +0100 Georg Hopp + + * some fixes on first logger tests + +2012-01-13 15:54:22 +0100 Georg Hopp + + * initial checkin + diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..392bb5a --- /dev/null +++ b/Makefile.am @@ -0,0 +1,10 @@ +ACLOCAL_AMFLAGS = -I m4 + +#bin_PROGRAMS = create_token +#create_token_SOURCES = base64.c createToken.c +#create_token_LDADD = src/libtoken.la $(LIBOBJS) +#create_token_CFLAGS = -Wall -I include + +EXTRA_DIST = include assets certs + +SUBDIRS = src tests diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..e69de29 diff --git a/README b/README new file mode 100644 index 0000000..fa21666 --- /dev/null +++ b/README @@ -0,0 +1,29 @@ +Actually this is some kind of server toolkit, also containing +a class and interface toolkit for C. +I use a gcc preprocessor extension to use empty variadoc +argument lists so actually this is gcc only code. + +This should become a server that has a dynamic time-sliced part +that updates an internal state all the time. +Clients might connect as they want and get some information +from the server. +The server should scale in two manners. +New instances should be able to handle connection and get +updates about the computed state. +Additionally new instances might hold their own state which +all other instances might update. + +In a first run the state might be something simple as a +matrix where every field hold a unique value. e.g. + + ------------- + |1|4|a|j|k|9| + ------------- + |1|4|a|j|k|9| + ------------- + |1|4|a|j|k|9| + ------------- + |1|4|a|j|k|9| + ------------- + +suggestion for timing: sigsuspend diff --git a/TODO b/TODO new file mode 100644 index 0000000..e69de29 diff --git a/assets/jquery-1.7.1.js b/assets/jquery-1.7.1.js new file mode 100644 index 0000000..8ccd0ea --- /dev/null +++ b/assets/jquery-1.7.1.js @@ -0,0 +1,9266 @@ +/*! + * jQuery JavaScript Library v1.7.1 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Mon Nov 21 21:11:03 2011 -0500 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document, + navigator = window.navigator, + location = window.location; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // The deferred used on DOM ready + readyList, + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = quickExpr.exec( selector ); + } + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context ? context.ownerDocument || context : document ); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.7.1", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.add( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.fireWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).off( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyList ) { + return; + } + + readyList = jQuery.Callbacks( "once memory" ); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array, i ) { + var len; + + if ( array ) { + if ( indexOf ) { + return indexOf.call( array, elem, i ); + } + + len = array.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in array && array[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function() { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return ( new Date() ).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; + }, + + browser: {} +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +return jQuery; + +})(); + + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( flags ) { + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Add one or several callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // Add if not in unique mode and callback is not in + if ( !flags.unique || !self.has( elem ) ) { + list.push( elem ); + } + } + } + }, + // Fire callbacks + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + self.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + self.disable(); + } else { + list = []; + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + var length = list.length; + add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { + firingStart = length; + fire( memory[ 0 ], memory[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } + } + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique ) { + break; + } + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory || memory === true ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( stack ) { + if ( firing ) { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { + fire( context, args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return self; +}; + + + + +var // Static reference to slice + sliceDeferred = [].slice; + +jQuery.extend({ + + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + state = "pending", + lists = { + resolve: doneList, + reject: failList, + notify: progressList + }, + promise = { + done: doneList.add, + fail: failList.add, + progress: progressList.add, + + state: function() { + return state; + }, + + // Deprecated + isResolved: doneList.fired, + isRejected: failList.fired, + + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); + return this; + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "notify" ] + }, function( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ](function() { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + }); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + }); + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + obj = promise; + } else { + for ( var key in promise ) { + obj[ key ] = promise[ key ]; + } + } + return obj; + } + }, + deferred = promise.promise({}), + key; + + for ( key in lists ) { + deferred[ key ] = lists[ key ].fire; + deferred[ key + "With" ] = lists[ key ].fireWith; + } + + // Handle state + deferred.done( function() { + state = "resolved"; + }, failList.disable, progressList.lock ).fail( function() { + state = "rejected"; + }, doneList.disable, progressList.lock ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( firstParam ) { + var args = sliceDeferred.call( arguments, 0 ), + i = 0, + length = args.length, + pValues = new Array( length ), + count = length, + pCount = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(), + promise = deferred.promise(); + function resolveFunc( i ) { + return function( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + deferred.notifyWith( promise, pValues ); + }; + } + if ( length > 1 ) { + for ( ; i < length; i++ ) { + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return promise; + } +}); + + + + +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + marginDiv, + fragment, + tds, + events, + eventName, + i, + isSupported, + div = document.createElement( "div" ), + documentElement = document.documentElement; + + // Preliminary tests + div.setAttribute("className", "t"); + div.innerHTML = "
a"; + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute("type", "radio"); + support.radioValue = input.value === "t"; + + input.setAttribute("checked", "checked"); + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + div.innerHTML = ""; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( window.getComputedStyle ) { + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.style.width = "2px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for( i in { + submit: 1, + change: 1, + focusin: 1 + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + fragment.removeChild( div ); + + // Null elements to avoid leaks in IE + fragment = select = opt = marginDiv = div = input = null; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, outer, inner, table, td, offsetSupport, + conMarginTop, ptlm, vb, style, html, + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + conMarginTop = 1; + ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; + vb = "visibility:hidden;border:0;"; + style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; + html = "
" + + "" + + "
"; + + container = document.createElement("div"); + container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
t
"; + tds = div.getElementsByTagName( "td" ); + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Figure out if the W3C box model works as expected + div.innerHTML = ""; + div.style.width = div.style.paddingLeft = "1px"; + jQuery.boxModel = support.boxModel = div.offsetWidth === 2; + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "
"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); + } + + div.style.cssText = ptlm + vb; + div.innerHTML = html; + + outer = div.firstChild; + inner = outer.firstChild; + td = outer.nextSibling.firstChild.firstChild; + + offsetSupport = { + doesNotAddBorder: ( inner.offsetTop !== 5 ), + doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) + }; + + inner.style.position = "fixed"; + inner.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); + inner.style.position = inner.style.top = ""; + + outer.style.overflow = "hidden"; + outer.style.position = "relative"; + + offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); + offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + + body.removeChild( container ); + div = container = null; + + jQuery.extend( support, offsetSupport ); + }); + + return support; +})(); + + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var privateCache, thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, + isEvents = name === "events"; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = ++jQuery.uuid; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + privateCache = thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Users should not attempt to inspect the internal events object using jQuery.data, + // it is undocumented and subject to change. But does anyone listen? No. + if ( isEvents && !thisCache[ name ] ) { + return privateCache.events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ internalKey ] : internalKey; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the cache and need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ internalKey ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + } else { + elem[ internalKey ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, attr, name, + data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { + attr = this[0].attributes; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( this[0], name, data[ name ] ); + } + } + jQuery._data( this[0], "parsedAttrs", true ); + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var self = jQuery( this ), + args = [ parts[0], value ]; + + self.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + jQuery.isNumeric( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery._data( elem, deferDataKey ); + if ( defer && + ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && + ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function() { + if ( !jQuery._data( elem, queueDataKey ) && + !jQuery._data( elem, markDataKey ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.fire(); + } + }, 0 ); + } +} + +jQuery.extend({ + + _mark: function( elem, type ) { + if ( elem ) { + type = ( type || "fx" ) + "mark"; + jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); + } + }, + + _unmark: function( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); + if ( count ) { + jQuery._data( elem, key, count ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue: function( elem, type, data ) { + var q; + if ( elem ) { + type = ( type || "fx" ) + "queue"; + q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + hooks = {}; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + jQuery._data( elem, type + ".run", hooks ); + fn.call( elem, function() { + jQuery.dequeue( elem, type ); + }, hooks ); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue " + type + ".run", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function() { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + while( i-- ) { + if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { + count++; + tmp.add( resolve ); + } + } + resolve(); + return defer.promise(); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + nodeHook, boolHook, fixSpecified; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.prop ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = ( value || "" ).split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var self = jQuery(this), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, l, + i = 0; + + if ( value && elem.nodeType === 1 ) { + attrNames = value.toLowerCase().split( rspace ); + l = attrNames.length; + + for ( ; i < l; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + + // See #9699 for explanation of this approach (setting first, then removal) + jQuery.attr( elem, name, "" ); + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( rboolean.test( name ) && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) +jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? + ret.nodeValue : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.nodeValue = value + "" ); + } + }; + + // Apply the nodeHook to tabindex + jQuery.attrHooks.tabindex.set = nodeHook.set; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); + + + + +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, + rhoverHack = /\bhover(\.\S+)?\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, + quickParse = function( selector ) { + var quick = rquickIs.exec( selector ); + if ( quick ) { + // 0 1 2 3 + // [ _, tag, id, class ] + quick[1] = ( quick[1] || "" ).toLowerCase(); + quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); + } + return quick; + }, + quickIs = function( elem, m ) { + var attrs = elem.attributes || {}; + return ( + (!m[1] || elem.nodeName.toLowerCase() === m[1]) && + (!m[2] || (attrs.id || {}).value === m[2]) && + (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) + ); + }, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, quick, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + quick: quickParse( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + t, tns, type, origType, namespaces, origCount, + j, events, special, handle, eventType, handleObj; + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, [ "events", "handle" ], true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var type = event.type || event, + namespaces = [], + cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + old = null; + for ( ; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old && old === elem.ownerDocument ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments, 0 ), + run_all = !event.exclusive && !event.namespace, + handlerQueue = [], + i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Determine handlers that should run if there are delegated events + // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { + + // Pregenerate a single jQuery object for reuse with .is() + jqcur = jQuery(this); + jqcur.context = this.ownerDocument || this; + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + selMatch = {}; + matches = []; + jqcur[0] = cur; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = ( + handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) + ); + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) + if ( event.metaKey === undefined ) { + event.metaKey = event.ctrlKey; + } + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady + }, + + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector, + ret; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !form._submit_attached ) { + jQuery.event.add( form, "submit._submit", function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + }); + form._submit_attached = true; + } + }); + // return undefined since we don't need an event listener + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + jQuery.event.simulate( "change", this, event, true ); + } + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + elem._change_attached = true; + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on.call( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( var type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); + + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + expando = "sizcache" + (Math.random() + '').replace('.', ''), + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rReturn = /\r\n/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context, seed ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set, seed ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set, i, len, match, type, left; + + if ( !expr ) { + return []; + } + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + type, found, item, filter, left, + i, pass, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + filter = Expr.filter[ type ]; + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + pass = not ^ found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Utility function for retreiving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +var getText = Sizzle.getText = function( elem ) { + var i, node, + nodeType = elem.nodeType, + ret = ""; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 ) { + // Use textContent || innerText for elements + if ( typeof elem.textContent === 'string' ) { + return elem.textContent; + } else if ( typeof elem.innerText === 'string' ) { + // Replace IE's carriage returns + return elem.innerText.replace( rReturn, '' ); + } else { + // Traverse it's children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + } else { + + // If no nodeType, this is expected to be an array + for ( i = 0; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + if ( node.nodeType !== 8 ) { + ret += getText( node ); + } + } + } + return ret; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus: function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var first, last, + doneName, parent, cache, + count, diff, + type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + first = match[2]; + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + doneName = match[0]; + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { + count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent[ expando ] = doneName; + } + + diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Sizzle.attr ? + Sizzle.attr( elem, name ) : + Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + !type && Sizzle.attr ? + result != null : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "

"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context, seed ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet, seed ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +Sizzle.selectors.attrMap = {}; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var self = this, + i, l; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + POS.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array (deprecated as of jQuery 1.7) + if ( jQuery.isArray( selectors ) ) { + var level = 1; + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( i = 0; i < selectors.length; i++ ) { + + if ( jQuery( cur ).is( selectors[ i ] ) ) { + ret.push({ selector: selectors[ i ], elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} + + + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /", "" ], + legend: [ 1, "
", "
" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + col: [ 2, "", "
" ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize and " \ + "" \ + "" \ + "" \ + "
" \ + "" \ + "Value created at:

" \ + "Next value in:
" \ + "
" \ + "Value: " \ + "
" \ + "
" \ + "

Testpage

" \ + "Welcome %s
" \ + "" \ + "
Link" \ + "
" \ + "
" \ + "" \ + "" + +HttpResponse +httpResponseMe(char * uname) +{ + HttpResponse response; + HttpMessage message; + + response = new(HttpResponse, "HTTP/1.1", 200, "OK"); + message = (HttpMessage)response; + + httpHeaderAdd(&(message->header), + new(HttpHeader, CSTRA("Content-Type"), CSTRA("text/html"))); + httpHeaderAdd(&(message->header), + new(HttpHeader, CSTRA("Set-Cookie"), CSTRA("name=Georg+Hopp"))); + httpHeaderAdd(&(message->header), + new(HttpHeader, CSTRA("Set-Cookie"), CSTRA("profession=coder"))); + + message->type = HTTP_MESSAGE_BUFFERED; + message->nbody = sizeof(RESP_DATA)-1-2+strlen(uname); //!< the two are the %s + message->body = malloc(message->nbody+1); + sprintf(message->body, RESP_DATA, uname); + //memcpy(message->body, RESP_DATA, sizeof(RESP_DATA)-1); + + return response; +} + +// vim: set ts=4 sw=4: diff --git a/src/http/response/randval.c b/src/http/response/randval.c new file mode 100644 index 0000000..059effa --- /dev/null +++ b/src/http/response/randval.c @@ -0,0 +1,68 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include +#include +#include + +#include "class.h" +#include "interface/class.h" + +#include "http/response.h" +#include "http/message.h" +#include "http/header.h" + +#include "utils/memory.h" + +#define RESP_DATA "{\"ctime\":%ld,\"vnext\":%ld,\"value\":\"%02d\"}" + +HttpResponse +httpResponseRandval(time_t ctime, int value) +{ + char buffer[200]; + HttpResponse response; + HttpMessage message; + size_t nbuf; + time_t remaining; + + response = new(HttpResponse, "HTTP/1.1", 200, "OK"); + message = (HttpMessage)response; + + httpHeaderAdd(&(message->header), + new(HttpHeader, CSTRA("Content-Type"), CSTRA("application/json"))); + + message->type = HTTP_MESSAGE_BUFFERED; + + remaining = 10 - (time(NULL) - ctime); + + nbuf = sprintf(buffer, RESP_DATA, ctime, remaining, value); + + message->nbody = nbuf; + message->body = malloc(nbuf); + memcpy(message->body, buffer, nbuf); + + return response; +} + +// vim: set ts=4 sw=4: diff --git a/src/http/worker.c b/src/http/worker.c new file mode 100644 index 0000000..b4dfc1a --- /dev/null +++ b/src/http/worker.c @@ -0,0 +1,124 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include + +#include "class.h" +#include "stream.h" +#include "http/worker.h" +#include "http/parser.h" +#include "http/writer.h" + +#include "interface/class.h" +#include "interface/stream_reader.h" +#include "interface/stream_writer.h" + +#include "utils/memory.h" + +static +int +httpWorkerCtor(void * _this, va_list * params) +{ + HttpWorker this = _this; + char * id = va_arg(*params, char *); + char cbuf_id[100]; + + this->id = malloc(strlen(id) + 1); + strcpy(this->id, id); + + this->val = va_arg(*params, struct randval *); + + sprintf(cbuf_id, "%s_%s", "parser", id); + this->pbuf = new(Cbuf, cbuf_id, PARSER_MAX_BUF); + + sprintf(cbuf_id, "%s_%s", "writer", id); + this->wbuf = new(Cbuf, cbuf_id, WRITER_MAX_BUF); + + this->parser = new(HttpParser, this->pbuf); + this->writer = new(HttpWriter, this->wbuf); + + this->sroot = &(this->session); + + return 0; +} + +static +inline +void +tDelete(void * node) +{ + delete(node); +} + +static +void +httpWorkerDtor(void * _this) +{ + HttpWorker this = _this; + + FREE(this->id); + + delete(this->parser); + delete(this->writer); + + if (NULL != this->pbuf) { + delete(this->pbuf); //!< cloned workers have NULL, so delete won't do anything + delete(this->wbuf); //!< cloned workers have NULL, so delete won't do anything + tdestroy(*(this->sroot), tDelete); + } +} + +static +void +httpWorkerClone(void * _this, void * _base) +{ + HttpWorker this = _this; + HttpWorker base = _base; + + this->val = base->val; + + this->parser = new(HttpParser, base->pbuf); + this->writer = new(HttpWriter, base->wbuf); + + this->sroot = &(base->session); +} + +ssize_t httpWorkerProcess(void *, Stream); +ssize_t httpWorkerWrite(void *, Stream); + +INIT_IFACE(Class, httpWorkerCtor, httpWorkerDtor, httpWorkerClone); +INIT_IFACE(StreamReader, httpWorkerProcess); +INIT_IFACE(StreamWriter, httpWorkerWrite); +CREATE_CLASS( + HttpWorker, + NULL, + IFACE(Class), + IFACE(StreamReader), + IFACE(StreamWriter)); + +// vim: set ts=4 sw=4: diff --git a/src/http/worker/add_common_header.c b/src/http/worker/add_common_header.c new file mode 100644 index 0000000..36fbf6d --- /dev/null +++ b/src/http/worker/add_common_header.c @@ -0,0 +1,51 @@ +#include +#include + +#include "class.h" +#include "interface/class.h" + +#include "http/message.h" +#include "http/response.h" + +#include "utils/memory.h" + +void +httpWorkerAddCommonHeader(HttpMessage request, HttpMessage response) +{ + time_t t; + struct tm * tmp; + char buffer[200]; + size_t nbuf; + + if (httpMessageHasKeepAlive(request)) { + httpHeaderAdd( + &(response->header), + new(HttpHeader, CSTRA("Connection"), CSTRA("Keep-Alive"))); + } + else { + httpHeaderAdd( + &(response->header), + new(HttpHeader, CSTRA("Connection"), CSTRA("Close"))); + } + + httpHeaderAdd(&(response->header), + new(HttpHeader, CSTRA("Server"), CSTRA("testserver"))); + + switch(((HttpResponse)response)->status) { + case 304: + break; + + default: + nbuf = sprintf(buffer, "%d", response->nbody); + httpHeaderAdd(&(response->header), + new(HttpHeader, CSTRA("Content-Length"), buffer, nbuf)); + } + + t = time(NULL); + tmp = localtime(&t); + nbuf = strftime(buffer, sizeof(buffer), "%a, %d %b %Y %T %Z", tmp); + httpHeaderAdd(&(response->header), + new(HttpHeader, CSTRA("Date"), buffer, nbuf)); +} + +// vim: set ts=4 sw=4: diff --git a/src/http/worker/get_asset.c b/src/http/worker/get_asset.c new file mode 100644 index 0000000..180729b --- /dev/null +++ b/src/http/worker/get_asset.c @@ -0,0 +1,38 @@ +#include + +#include "http/header.h" +#include "http/message.h" +#include "http/request.h" +#include "http/response.h" + +#include "utils/memory.h" + +HttpMessage +httpWorkerGetAsset( + HttpRequest request, + const char * fname, + const char * mime, + size_t nmime) +{ + char * match; + size_t nmatch; + HttpHeader header; + + header = httpHeaderGet( + &(((HttpMessage)request)->header), + CSTRA("If-None-Match")); + + if (NULL == header) { + match = ""; + nmatch = 0; + } + else { + match = (header->value)[0]; + nmatch = (header->nvalue)[0]; + } + + return (HttpMessage)httpResponseAsset( + fname, mime, nmime, match, nmatch); +} + +// vim: set ts=4 sw=4: diff --git a/src/http/worker/process.c b/src/http/worker/process.c new file mode 100644 index 0000000..f7a65e9 --- /dev/null +++ b/src/http/worker/process.c @@ -0,0 +1,169 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include +#include + +#include "class.h" +#include "interface/class.h" + +#include "http/worker.h" +#include "http/message.h" +#include "http/request.h" +#include "http/response.h" +#include "http/message/queue.h" +#include "http/parser.h" +#include "session.h" +#include "stream.h" + +#include "utils/memory.h" + +HttpMessage httpWorkerGetAsset(HttpRequest, const char *, const char *, size_t); +void httpWorkerAddCommonHeader(HttpMessage, HttpMessage); + +ssize_t +httpWorkerProcess(HttpWorker this, Stream st) +{ + ssize_t size; + + if (0 < (size = httpParserParse(this->parser, st))) { + int i; + HttpMessageQueue reqq = this->parser->queue; + HttpMessageQueue respq = this->writer->queue; + + for (i=0; inmsgs; i++) { + HttpMessage rmessage = reqq->msgs[i]; + HttpRequest request = (HttpRequest)(reqq->msgs[i]); + HttpMessage response = NULL; + HttpHeader cookie = httpHeaderGet( + &(rmessage->header), + CSTRA("cookie")); + + if (NULL == this->session && NULL != cookie) { + int i; + + for (i=0; icvalue; i++) { + char * sidstr = strstr(cookie->value[i], "sid"); + + if (NULL != sidstr) { + unsigned long sid; + + sidstr = strchr(sidstr, '=')+1; + sid = strtoul(sidstr, NULL, 10); + + this->session = sessionGet(this->sroot, sid); + break; + } + } + } + + if (NULL != this->session) { + if (time(NULL) < this->session->livetime) { + this->session->livetime = time(NULL) + SESSION_LIVETIME; + } else { + sessionDelete(this->sroot, this->session->id); + delete(this->session); + } + } + + if (0 == strcmp("POST", request->method)) { + if (0 == strcmp("/me/", request->uri)) { + char * delim = memchr(rmessage->body, '=', rmessage->nbody); + char * val; + size_t nkey, nval; + char buffer[200]; + size_t nbuf; + + nkey = delim - rmessage->body - 1; + *delim = 0; + val = delim + 1; + nval = rmessage->nbody - (val - rmessage->body); + + this->session = sessionAdd( + this->sroot, + new(Session, val, nval)); + nbuf = sprintf(buffer, "sid=%lu;Path=/", this->session->id); + + response = (HttpMessage)httpResponseMe(this->session->username); + + httpHeaderAdd( + &(response->header), + new(HttpHeader, CSTRA("Set-Cookie"), buffer, nbuf)); + } + } + + if (0 == strcmp("GET", request->method)) { + + if (0 == strcmp("/login/", request->uri)) { + response = (HttpMessage)httpResponseLoginForm(); + } + + if (0 == strcmp("/me/", request->uri)) { + char * uname = (NULL != this->session)? this->session->username : ""; + response = (HttpMessage)httpResponseMe(uname); + } + + if (0 == strcmp("/randval/", request->uri)) { + if (NULL != this->session) { + response = (HttpMessage)httpResponseRandval( + this->val->timestamp, + this->val->value); + } else { + response = (HttpMessage)httpResponse403(); + } + } + + if (0 == strcmp("/image/", request->uri)) { + response = httpWorkerGetAsset( + request, + "./assets/waldschrat.jpg", + CSTRA("image/jpeg")); + } + + if (0 == strcmp("/jquery/", request->uri)) { + response = httpWorkerGetAsset( + request, + "./assets/jquery-1.7.1.min.js", + CSTRA("text/javascript")); + } + } + + if (NULL == response) { + response = (HttpMessage)httpResponse404(); + } + + httpWorkerAddCommonHeader((HttpMessage)request, response); + + respq->msgs[(respq->nmsgs)++] = response; + response = NULL; + delete((reqq->msgs)[i]); + } + + reqq->nmsgs = 0; + } + + return size; +} + +// vim: set ts=4 sw=4: diff --git a/src/http/worker/write.c b/src/http/worker/write.c new file mode 100644 index 0000000..ca1889c --- /dev/null +++ b/src/http/worker/write.c @@ -0,0 +1,35 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include + +#include "http/worker.h" +#include "http/writer.h" +#include "stream.h" + +ssize_t +httpWorkerWrite(HttpWorker this, Stream st) +{ + return httpWriterWrite(this->writer, st); +} + +// vim: set ts=4 sw=4: diff --git a/src/http/writer.c b/src/http/writer.c new file mode 100644 index 0000000..00104e9 --- /dev/null +++ b/src/http/writer.c @@ -0,0 +1,63 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include + +#include "class.h" +#include "interface/class.h" +#include "interface/stream_writer.h" + +#include "http/message/queue.h" +#include "http/writer.h" + +static +int +httpWriterCtor(void * _this, va_list * params) +{ + HttpWriter this = _this; + + this->buffer = va_arg(*params, Cbuf); + this->queue = new(HttpMessageQueue); + + return 0; +} + +static +void +httpWriterDtor(void * _this) +{ + HttpWriter this = _this; + + delete(this->queue); + + if (TRUE == this->ourLock) + cbufRelease(this->buffer); + + if (NULL != this->current) + delete(this->current); +} + +INIT_IFACE(Class, httpWriterCtor, httpWriterDtor, NULL); +INIT_IFACE(StreamWriter, httpWriterWrite); +CREATE_CLASS(HttpWriter, NULL, IFACE(Class), IFACE(StreamWriter)); + +// vim: set ts=4 sw=4: diff --git a/src/http/writer/write.c b/src/http/writer/write.c new file mode 100644 index 0000000..abf46d8 --- /dev/null +++ b/src/http/writer/write.c @@ -0,0 +1,155 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include + +#include "class.h" +#include "interface/class.h" +#include "http/message.h" +#include "http/writer.h" +#include "cbuf.h" +#include "stream.h" + +#define MIN(x,y) ((x) < (y) ? (x) : (y)) +#define MAX(x,y) ((x) > (y) ? (x) : (y)) + +ssize_t +httpWriterWrite(void * _this, Stream st) +{ + HttpWriter this = _this; + HttpMessageQueue respq = this->queue; + int cont = 1; + + if (cbufIsLocked(this->buffer)) { + if (FALSE == this->ourLock) + return 0; + } + else { + cbufLock(this->buffer); + this->ourLock = TRUE; + } + + while (cont) { + switch (this->state) { + case HTTP_WRITER_GET: + if (NULL == this->current && 0 < respq->nmsgs) { + this->current = respq->msgs[0]; + + this->written = 0; + this->nbody = 0; + this->nheader = httpMessageHeaderSizeGet(this->current); + + httpMessageHeaderToString( + this->current, + cbufGetWrite(this->buffer)); + cbufIncWrite(this->buffer, this->nheader); + + this->state = HTTP_WRITER_WRITE; + } + else { + cbufRelease(this->buffer); + this->ourLock = FALSE; + cont = 0; + } + break; + + case HTTP_WRITER_WRITE: + /** + * read + */ + if (this->nbody < this->current->nbody) { + size_t size = MIN( + this->current->nbody - this->nbody, + cbufGetFree(this->buffer)); + + switch (this->current->type) { + case HTTP_MESSAGE_BUFFERED: + cbufSetData(this->buffer, + this->current->body + this->nbody, + size); + break; + + case HTTP_MESSAGE_PIPED: + size = cbufRead(this->buffer, this->current->handle); + break; + + default: + return -1; + } + + this->nbody += size; + } + + /** + * write + */ + { + ssize_t written = cbufWrite(this->buffer, st); + + if (0 <= written) { + this->written += written; + } + else { + return -1; + } + } + + if (this->written == this->current->nbody + this->nheader) { + this->state = HTTP_WRITER_DONE; + } + else { + cont = 0; + } + break; + + case HTTP_WRITER_DONE: + this->state = HTTP_WRITER_GET; + + memmove(respq->msgs, + &(respq->msgs[1]), + sizeof(void*) * (--respq->nmsgs + 1)); + + cbufRelease(this->buffer); + this->ourLock = FALSE; + + if (! httpMessageHasKeepAlive(this->current)) { + /** + * if the message did not have the keep-alive feature + * we don't care about further pipelined messages and + * return to the caller with a -1 indicating that the + * underlying connection should be closed at their side. + * Then we close to connection. + */ + delete(this->current); + return -1; + } + + delete(this->current); + break; + } + } + + return respq->nmsgs; +} + +// vim: set ts=4 sw=4: diff --git a/src/interface.c b/src/interface.c new file mode 100644 index 0000000..04ef14a --- /dev/null +++ b/src/interface.c @@ -0,0 +1,64 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include + +#include "interface.h" +#include "commons.h" + +static +inline +int +comp(const void * _a, const void * _b) +{ + const struct interface * a = **(const struct interface ***)_a; + const struct interface * b = **(const struct interface ***)_b; + return ((a)<(b))? -1 : ((a)>(b))? 1 : 0; +} + +/** + * this one is important in selector functions to get the correct interface + * implementation of a class. + */ +struct interface * +interfaceGet(iface_impl_ptr iface_impl, const iface_ptr _iface) +{ + const iface_ptr * iface = &_iface; + void * dummy; + + if (! iface_impl->simpl) { + qsort((void**)(iface_impl->impl), iface_impl->nimpl, sizeof(iface_ptr), comp); + iface_impl->simpl=TRUE; + } + + dummy = bsearch( + &iface, + iface_impl->impl, + iface_impl->nimpl, + sizeof(iface_ptr), + comp); + + return dummy? *(struct interface **)dummy : dummy; +} + +// vim: set ts=4 sw=4: diff --git a/src/interface/class.c b/src/interface/class.c new file mode 100644 index 0000000..8327e89 --- /dev/null +++ b/src/interface/class.c @@ -0,0 +1,85 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include + +#include "class.h" +#include "interface/class.h" + +const +struct interface i_Class = { + "class", + 3 +}; + +void * +classNew(class_ptr class, ...) +{ + void * object = calloc(1, class->object_size + sizeof(void*)); + va_list params; + int ret; + + if (class->init) class->init(); + + * (class_ptr *)object = class; + object += sizeof(void*); + + va_start(params, class); + RETCALL(object, Class, ctor, ret, ¶ms); + va_end(params); + + if (-1 == ret) { + classDelete(&object); + } + + return object; +} + +void +classDelete(void ** object) +{ + if (NULL != *object) { + CALL(*object, Class, dtor); + + free(*object - sizeof(void*)); + *object = NULL; + } +} + +void * +classClone(void * _object) +{ + class_ptr class = GET_CLASS(_object); + void * object = calloc(1, class->object_size + sizeof(void*)); + + * (class_ptr *)object = class; + object += sizeof(void*); + +#undef clone + CALL(object, Class, clone, _object); + + return object; +} + +// vim: set ts=4 sw=4: diff --git a/src/interface/http_intro.c b/src/interface/http_intro.c new file mode 100644 index 0000000..2f12eb0 --- /dev/null +++ b/src/interface/http_intro.c @@ -0,0 +1,51 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "class.h" +#include "interface/http_intro.h" + +const struct interface i_HttpIntro = { + "httpIntro", + 2 +}; + +size_t +httpIntroSizeGet(void * object) +{ + size_t ret; + + RETCALL(object, HttpIntro, sizeGet, ret); + + return ret; +} + +char * +httpIntroToString(void * object, char * string) +{ + char * ret; + + RETCALL(object, HttpIntro, toString, ret, string); + + return ret; +} + +// vim: set ts=4 sw=4: diff --git a/src/interface/logger.c b/src/interface/logger.c new file mode 100644 index 0000000..bb2a75e --- /dev/null +++ b/src/interface/logger.c @@ -0,0 +1,60 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include + +#include "logger.h" +#include "interface/logger.h" + +const struct interface i_Logger = { + "logger", + 1 +}; + +void +loggerLog(void * _object, logger_level level, const char * const fmt, ...) { + Logger object = _object; + + if (level >= object->min_level) { + char * msg = NULL; + size_t msg_size = 0; + va_list params; + + va_start(params, fmt); + msg_size = vsnprintf(msg, msg_size, fmt, params); + va_end(params); + + msg = malloc(msg_size + 1); + + va_start(params, fmt); + vsnprintf(msg, msg_size + 1, fmt, params); + va_end(params); + + CALL(_object, Logger, log, level, msg); + + free(msg); + } +} + +// vim: set ts=4 sw=4: diff --git a/src/interface/observer.c b/src/interface/observer.c new file mode 100644 index 0000000..b2424e7 --- /dev/null +++ b/src/interface/observer.c @@ -0,0 +1,37 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "class.h" +#include "interface/observer.h" + +const struct interface i_Observer = { + "observer", + 1 +}; + +void +observerNotify(void * observer, void * subject) +{ + CALL(observer, Observer, notify, subject); +} + +// vim: set ts=4 sw=4: diff --git a/src/interface/stream_reader.c b/src/interface/stream_reader.c new file mode 100644 index 0000000..c23895e --- /dev/null +++ b/src/interface/stream_reader.c @@ -0,0 +1,42 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "class.h" +#include "interface/stream_reader.h" +#include "stream.h" + +const struct interface i_StreamReader = { + "streamReader", + 1 +}; + +ssize_t +streamReaderRead(void * object, Stream st) +{ + ssize_t ret; + + RETCALL(object, StreamReader, read, ret, st); + + return ret; +} + +// vim: set ts=4 sw=4: diff --git a/src/interface/stream_writer.c b/src/interface/stream_writer.c new file mode 100644 index 0000000..8489a0d --- /dev/null +++ b/src/interface/stream_writer.c @@ -0,0 +1,42 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "class.h" +#include "interface/stream_writer.h" +#include "stream.h" + +const struct interface i_StreamWriter = { + "streamWriter", + 1 +}; + +ssize_t +streamWriterWrite(void * object, Stream st) +{ + ssize_t ret; + + RETCALL(object, StreamWriter, write, ret, st); + + return ret; +} + +// vim: set ts=4 sw=4: diff --git a/src/interface/subject.c b/src/interface/subject.c new file mode 100644 index 0000000..4ee3f4a --- /dev/null +++ b/src/interface/subject.c @@ -0,0 +1,49 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "class.h" +#include "interface/subject.h" + +const struct interface i_Subject = { + "subject", + 3 +}; + +void +subjectAttach(void * subject, void * observer) +{ + CALL(subject, Subject, attach, observer); +} + +void +subjectDetach(void * subject, void * observer) +{ + CALL(subject, Subject, detach, observer); +} + +void +subjectNotify(void * subject) +{ + CALL(subject, Subject, notify); +} + +// vim: set ts=4 sw=4: diff --git a/src/logger.c b/src/logger.c new file mode 100644 index 0000000..859ceed --- /dev/null +++ b/src/logger.c @@ -0,0 +1,57 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include + +#include "logger.h" +#include "interface/class.h" +#include "interface/logger.h" + +const +char * const +logger_level_str[] = { + "DEBUG", + "INFO", + "NOTICE", + "WARNING", + "ERR", + "CRIT", + "ALERT", + "EMERG" +}; + +static +int +loggerCtor(void * _this, va_list * params) +{ + Logger this = _this; + this->min_level = va_arg(*params, int); + + return 0; +} + +static void loggerDtor(void * _this) {} + +INIT_IFACE(Class, loggerCtor, loggerDtor, NULL); +CREATE_CLASS(Logger, NULL, IFACE(Class)); + +// vim: set ts=4 sw=4: diff --git a/src/logger/stderr.c b/src/logger/stderr.c new file mode 100644 index 0000000..dd26e1b --- /dev/null +++ b/src/logger/stderr.c @@ -0,0 +1,38 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include + +#include "logger.h" +#include "interface/logger.h" + +static +void +logStderr(void * this, logger_level level, const char * const msg) +{ + fprintf(stderr, "[%s] %s\n", logger_level_str[level], msg); +} + +INIT_IFACE(Logger, logStderr); +CREATE_CLASS(LoggerStderr, Logger, IFACE(Logger)); + +// vim: set ts=4 sw=4: diff --git a/src/logger/syslog.c b/src/logger/syslog.c new file mode 100644 index 0000000..3667606 --- /dev/null +++ b/src/logger/syslog.c @@ -0,0 +1,51 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include + +#include "logger.h" +#include "interface/logger.h" + +static +const +int syslog_priority[] = { + LOG_USER | LOG_DEBUG, + LOG_USER | LOG_INFO, + LOG_USER | LOG_NOTICE, + LOG_USER | LOG_WARNING, + LOG_USER | LOG_ERR, + LOG_USER | LOG_CRIT, + LOG_USER | LOG_ALERT, + LOG_USER | LOG_EMERG +}; + +static +void +logSyslog(void * this, logger_level level, const char * const msg) +{ + syslog(syslog_priority[level], "[%s] %s", logger_level_str[level], msg); +} + +INIT_IFACE(Logger, logSyslog); +CREATE_CLASS(LoggerSyslog, Logger, IFACE(Logger)); + +// vim: set ts=4 sw=4: diff --git a/src/server.c b/src/server.c new file mode 100644 index 0000000..a8e7951 --- /dev/null +++ b/src/server.c @@ -0,0 +1,132 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include + +#include +#include + +#include "class.h" +#include "server.h" +#include "socket.h" +#include "logger.h" +#include "interface/class.h" + +#include "utils/memory.h" + +static +int +serverCtor(void * _this, va_list * params) +{ + Server this = _this; + in_port_t port; + unsigned int backlog; + int flags; + + this->max_fds = sysconf(_SC_OPEN_MAX); + if (this->max_fds <= 10) { // reserve 10 handles for internal use. + /** + * \todo some logging would be appropriate :) + */ + return -1; + } + this->max_fds -= 10; + + this->logger = va_arg(* params, Logger); + this->worker = va_arg(* params, void *); + port = va_arg(* params, int); + backlog = va_arg(* params, unsigned int); + + this->fds = calloc(sizeof(struct pollfd), this->max_fds); + this->conns = calloc(sizeof(struct conns), this->max_fds); + + this->sock = new(Sock, this->logger, port); + flags = fcntl(this->sock->handle, F_GETFL, 0); + fcntl(this->sock->handle, F_SETFL, flags | O_NONBLOCK); + + this->sockSSL = new(Sock, this->logger, port+1); + flags = fcntl(this->sockSSL->handle, F_GETFL, 0); + fcntl(this->sockSSL->handle, F_SETFL, flags | O_NONBLOCK); + + SSL_library_init(); + SSL_load_error_strings(); + this->ctx = SSL_CTX_new(SSLv23_server_method()); + SSL_CTX_use_certificate_file( + this->ctx, + "./certs/server.crt", + SSL_FILETYPE_PEM); + + SSL_CTX_use_RSAPrivateKey_file( + this->ctx, + "./certs/server.key", + SSL_FILETYPE_PEM); + + socketListen(this->sock, backlog); + socketListen(this->sockSSL, backlog); + + (this->fds)[0].fd = this->sock->handle; + (this->fds)[0].events = POLLIN; + (this->fds)[1].fd = this->sockSSL->handle; + (this->fds)[1].events = POLLIN; + this->nfds = 2; + + return 0; +} + +static +void +serverDtor(void * _this) +{ + Server this = _this; + int i; + + for (i=0; infds; i++) { + if (this->sock->handle != (this->fds)[i].fd) { + Stream st = (this->conns[(this->fds)[i].fd]).stream; + + delete((this->conns[(this->fds)[i].fd]).sock); + delete((this->conns[(this->fds)[i].fd]).worker); + + if (NULL != st && STREAM_SSL == st->type) { + SSL_shutdown((st->handle).ssl); + SSL_free((st->handle).ssl); + } + + delete((this->conns[(this->fds)[i].fd]).stream); + } + } + + FREE(this->fds); + FREE(this->conns); + + delete(this->sock); + delete(this->sockSSL); + SSL_CTX_free(this->ctx); + ERR_free_strings(); +} + +INIT_IFACE(Class, serverCtor, serverDtor, NULL); +CREATE_CLASS(Server, NULL, IFACE(Class)); + +// vim: set ts=4 sw=4: diff --git a/src/server/close_conn.c b/src/server/close_conn.c new file mode 100644 index 0000000..dcab329 --- /dev/null +++ b/src/server/close_conn.c @@ -0,0 +1,48 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include + +#include "server.h" +#include "interface/class.h" +#include "stream.h" + +void +serverCloseConn(Server this, unsigned int i) +{ + int fd = (this->fds)[i].fd; + Stream st = (this->conns[(this->fds)[i].fd]).stream; + + delete((this->conns)[fd].sock); + delete((this->conns)[fd].worker); + + if (NULL != st && STREAM_SSL == st->type) { + SSL_shutdown((st->handle).ssl); + } + + delete((this->conns)[fd].stream); + + memset(&(this->fds[i]), 0, sizeof(struct pollfd)); +} + +// vim: set ts=4 sw=4: diff --git a/src/server/handle_accept.c b/src/server/handle_accept.c new file mode 100644 index 0000000..8235e30 --- /dev/null +++ b/src/server/handle_accept.c @@ -0,0 +1,100 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include + +#include + +#include "http/worker.h" +#include "server.h" +#include "interface/class.h" +#include "interface/logger.h" +#include "stream.h" + +int +serverHandleAccept(Server this, unsigned int i) +{ + char remoteAddr[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + Sock acc = NULL; + Stream st; + + if (this->nfds >= this->max_fds) { + return -1; + } + + switch(i) { + case 0: + // no SSL + acc = socketAccept(this->sock, &remoteAddr); + st = new(Stream, STREAM_FD, acc->handle); + break; + + case 1: + // SSL + { + SSL * ssl = SSL_new(this->ctx); + acc = socketAccept(this->sockSSL, &remoteAddr); + SSL_set_fd(ssl, acc->handle); + SSL_accept(ssl); + st = new(Stream, STREAM_SSL, ssl); + } + break; + + default: + break; + } + + if (-1 != acc->handle) { + // save the socket handle + (this->conns)[acc->handle].sock = acc; + + // clone worker + (this->conns)[acc->handle].worker = clone(this->worker); + (this->conns)[acc->handle].stream = st; + + (this->fds)[this->nfds].fd = acc->handle; + (this->fds)[this->nfds].events = POLLIN; + this->nfds++; + } else { + delete(acc); + + switch(errno) { + case EAGAIN: + loggerLog(this->logger, + LOGGER_DEBUG, + "server accept blocks"); + break; + + default: + loggerLog(this->logger, + LOGGER_DEBUG, + "server accept error"); + break; + } + } + + return (acc)? acc->handle : -1; +} + +// vim: set ts=4 sw=4: diff --git a/src/server/poll.c b/src/server/poll.c new file mode 100644 index 0000000..8c1d76c --- /dev/null +++ b/src/server/poll.c @@ -0,0 +1,81 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include + +#include "server.h" +#include "interface/logger.h" + +#include "utils/signalHandling.h" + +#define POLLFD(ptr) ((struct pollfd *)(ptr)) +#define SWAP(a, b) ((a)^=(b),(b)^=(a),(a)^=(b)) + +int +serverPoll(Server this) { + int events; + + /** + * put all closed fds to end of array in O(this->nfds) + */ + struct pollfd * fda = &(this->fds[2]); + struct pollfd * fdb = &(this->fds[this->nfds-1]); + + while (fda <= fdb) { + while (0 == fdb->fd && fda <= fdb) { + fdb--; + this->nfds--; + } + + while (0 != fda->fd && fda <= fdb) fda++; + + if (fda < fdb) { + memcpy(fda, fdb, sizeof(struct pollfd)); + fdb--; + this->nfds--; + } + } + + /* + * wait for handles to become ready + */ + if (-1 == (events = poll(this->fds, this->nfds, -1))) { + switch (errno) { + default: + case EBADF: + case EINVAL: + case ENOMEM: + doShutdown = 1; + // DROP THROUGH + + case EINTR: + loggerLog(this->logger, LOGGER_CRIT, + "poll systemcall failed: [%s] - service terminated", + strerror(errno)); + } + } + + return events; +} + +// vim: set ts=4 sw=4: diff --git a/src/server/read.c b/src/server/read.c new file mode 100644 index 0000000..0eda967 --- /dev/null +++ b/src/server/read.c @@ -0,0 +1,79 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "server.h" +#include "interface/logger.h" +#include "interface/stream_reader.h" + +void serverCloseConn(Server, unsigned int); + +ssize_t +serverRead(Server this, unsigned int i) +{ + int fd = (this->fds)[i].fd; + ssize_t size; + + if (NULL == (this->conns)[fd].worker) { + loggerLog( + this->logger, + LOGGER_INFO, + "initialization error: NULL reader"); + return -1; + } + + switch ((size = streamReaderRead( + (this->conns)[fd].worker, + (this->conns)[fd].stream))) + { + case -2: + /** + * normal close: this must be mapped to -2 within the + * underlying read call. + * + * \todo make sure all pending writes will be done before + * close. + */ + // DROP-THROUGH + + case -1: + /* + * read failure / close connection + */ + loggerLog(this->logger, LOGGER_INFO, + "connection[%d] closed...%s", + fd, + inet_ntoa((((this->conns)[fd].sock)->addr).sin_addr)); + serverCloseConn(this, i); + break; + + case 0: + break; + + default: + (this->fds)[i].events |= POLLOUT; + break; + } + + return size; +} + +// vim: set ts=4 sw=4: diff --git a/src/server/run.c b/src/server/run.c new file mode 100644 index 0000000..950a292 --- /dev/null +++ b/src/server/run.c @@ -0,0 +1,97 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "server.h" +#include "interface/logger.h" + +#include "utils/signalHandling.h" + +int serverPoll(Server); +int serverHandleAccept(Server, unsigned int); +void serverCloseConn(Server, unsigned int); +ssize_t serverRead(Server, unsigned int); +ssize_t serverWrite(Server, unsigned int); + +void +serverRun(Server this) +{ + loggerLog(this->logger, LOGGER_INFO, "service started"); + + while (!doShutdown) //! until error or signal + { + int events; + unsigned int i; + int naccs = 10; + + events = serverPoll(this); + if (doShutdown || 0 >= events) break; + + /** + * handle accept + */ + if (0 != ((this->fds)[0].revents & POLLIN)) { + events--; + while(-1 != serverHandleAccept(this, 0) && 0 < naccs) { + naccs--; + } + } + + /** + * handle accept SSL + */ + if (0 != ((this->fds)[1].revents & POLLIN)) { + events--; + while(-1 != serverHandleAccept(this, 1) && 0 < naccs) { + naccs--; + } + } + + for (i=2; i < this->nfds; i++) { + int nreads = 10, nwrites = 10; + + /** + * handle reads + */ + if (0 != ((this->fds)[i].revents & POLLIN) && 0 < nreads) { + events--; + nreads--; + + serverRead(this, i); + } + + /** + * handle writes + */ + if (0 != ((this->fds)[i].revents & POLLOUT) && 0 < nwrites) { + events--; + nwrites--; + + serverWrite(this, i); + } + + if (0 > events) + break; // no more events to handle + } + } +} + +// vim: set ts=4 sw=4: diff --git a/src/server/write.c b/src/server/write.c new file mode 100644 index 0000000..aa5e69a --- /dev/null +++ b/src/server/write.c @@ -0,0 +1,63 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include "server.h" +#include "interface/logger.h" +#include "interface/stream_writer.h" + +void serverCloseConn(Server, unsigned int); + +ssize_t +serverWrite(Server this, unsigned int i) +{ + int fd = (this->fds)[i].fd; + ssize_t remaining; + + if (NULL == (this->conns)[fd].worker) { + loggerLog( + this->logger, + LOGGER_INFO, + "initialization error: NULL worker"); + return -1; + } + + remaining = streamWriterWrite( + (this->conns)[fd].worker, + (this->conns)[fd].stream); + + switch(remaining) { + case -1: + serverCloseConn(this, i); + break; + + case 0: + (this->fds)[i].events &= ~POLLOUT; + break; + + default: + break; + } + + return remaining; +} + +// vim: set ts=4 sw=4: diff --git a/src/session.c b/src/session.c new file mode 100644 index 0000000..b3b4e37 --- /dev/null +++ b/src/session.c @@ -0,0 +1,46 @@ +#include +#include +#include +#include +#include +#include + +#include "session.h" +#include "class.h" +#include "interface/class.h" + +#include "utils/hash.h" +#include "utils/memory.h" + + +static +int +sessionCtor(void * _this, va_list * params) +{ + Session this = _this; + char * uname = va_arg(* params, char *); + size_t nuname = va_arg(* params, size_t); + + this->livetime = time(NULL) + SESSION_LIVETIME; + this->id = sdbm((unsigned char *)uname, nuname) & this->livetime; + + this->username = malloc(nuname + 1); + this->username[nuname] = 0; + memcpy(this->username, uname, nuname); + + return 0; +} + +static +void +sessionDtor(void * _this) +{ + Session this = _this; + + FREE(this->username); +} + +INIT_IFACE(Class, sessionCtor, sessionDtor, NULL); +CREATE_CLASS(Session, NULL, IFACE(Class)); + +// vim: set ts=4 sw=4: diff --git a/src/session/add.c b/src/session/add.c new file mode 100644 index 0000000..07adfa2 --- /dev/null +++ b/src/session/add.c @@ -0,0 +1,36 @@ +#include + +#include "session.h" +#include "interface/class.h" + + +static +inline +int +sessionAddComp(const void * _a, const void * _b) +{ + Session a = (Session)_a; + Session b = (Session)_b; + return (a->id < b->id)? -1 : (a->id > b->id)? 1 : 0; +} + +Session +sessionAdd(const Session * root, Session session) +{ + Session * found = tsearch(session, (void**)root, sessionAddComp); + + if (NULL == found) { + return NULL; + } + + if (*found != session) { + /** + * \todo this should not happen, so do some logging here. + */ + delete(session); + } + + return *found; +} + +// vim: set ts=4 sw=4: diff --git a/src/session/delete.c b/src/session/delete.c new file mode 100644 index 0000000..ef560ee --- /dev/null +++ b/src/session/delete.c @@ -0,0 +1,23 @@ +#include + +#include "session.h" +#include "interface/class.h" + + +static +inline +int +sessionDeleteComp(const void * _a, const void * _b) +{ + unsigned long a = *(unsigned long *)_a; + Session b = (Session)_b; + return (a < b->id)? -1 : (a > b->id)? 1 : 0; +} + +void +sessionDelete(const Session * root, const unsigned long id) +{ + tdelete(&id, (void**)root, sessionDeleteComp); +} + +// vim: set ts=4 sw=4: diff --git a/src/session/get.c b/src/session/get.c new file mode 100644 index 0000000..2b622ee --- /dev/null +++ b/src/session/get.c @@ -0,0 +1,29 @@ +#include +#include + +#include "session.h" + + +static +inline +int +sessionGetComp(const void * _a, const void * _b) +{ + unsigned long a = *(unsigned long *)_a; + Session b = (Session)_b; + return (a < b->id)? -1 : (a > b->id)? 1 : 0; +} + +Session +sessionGet(const Session * root, const unsigned long id) +{ + Session * found = tfind(&id, (void**)root, sessionGetComp); + + if (NULL == found) { + return NULL; + } + + return *found; +} + +// vim: set ts=4 sw=4: diff --git a/src/socket.c b/src/socket.c new file mode 100644 index 0000000..3603513 --- /dev/null +++ b/src/socket.c @@ -0,0 +1,79 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include + +#include "socket.h" +#include "logger.h" +#include "interface/class.h" +#include "interface/logger.h" + +static +int +socketCtor(void * _this, va_list * params) +{ + Sock this = _this; + int reUse = 1; //! \todo make this configurable + int port; + + this->log = va_arg(* params, Logger); + port = va_arg(* params, int); + + //! if port is -1 do not initialize the socket. (Used with accept) + if (-1 == port) { + return 0; + } else { + this->port = port; + } + + //! Create socket for incoming connections + if (-1 == (this->handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))) { + loggerLog(this->log, LOGGER_CRIT, + "error opening socket: %s - service terminated", + strerror(errno)); + return -1; + } + + //! Make the socket REUSE a TIME_WAIT socket + setsockopt(this->handle, SOL_SOCKET, SO_REUSEADDR, &reUse, sizeof(reUse)); + + return 0; +} + +static +void +socketDtor(void * _this) +{ + Sock this = _this; + + if (STDERR_FILENO < this->handle) { + shutdown(this->handle, SHUT_RDWR); + close(this->handle); + } +} + +INIT_IFACE(Class, socketCtor, socketDtor, NULL); +CREATE_CLASS(Sock, NULL, IFACE(Class)); + +// vim: set ts=4 sw=4: diff --git a/src/socket/accept.c b/src/socket/accept.c new file mode 100644 index 0000000..e1ff313 --- /dev/null +++ b/src/socket/accept.c @@ -0,0 +1,63 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include // for errno +#include + +#include "socket.h" +#include "interface/class.h" +#include "interface/logger.h" + +Sock +socketAccept(Sock this, char (*remoteAddr)[16]) +{ + Sock sock; // Socket for client + unsigned int len; // Length of client address data structure + + // Set the size of the in-out parameter + len = sizeof(this->addr); + + /** + * \todo Uhh, this is bad. we open a new socket additionally to + * the one we get from the accept call. + * i have to change the socket constructor to be able to create + * the data structure without creation of a socket at all. + * For now i simply close the socket here.... :D + */ + sock = new(Sock, this->log, -1); + + // Wait for a client to connect + sock->handle = accept(this->handle, (struct sockaddr *) &(sock->addr), &len); + if (-1 == sock->handle) { + loggerLog(this->log, LOGGER_WARNING, + "error accepting connection: %s", strerror(errno)); + } else { + strcpy(*remoteAddr, inet_ntoa((sock->addr).sin_addr)); + + loggerLog(this->log, LOGGER_INFO, + "handling client %s\n", inet_ntoa((sock->addr).sin_addr)); + } + + return sock; +} + +// vim: set ts=4 sw=4: diff --git a/src/socket/connect.c b/src/socket/connect.c new file mode 100644 index 0000000..66aa19c --- /dev/null +++ b/src/socket/connect.c @@ -0,0 +1,55 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include // for atoi() and exit() +#include // for errno + +#include "socket.h" +#include "interface/class.h" +#include "interface/logger.h" + + +void +socketConnect(Sock this, const char * addr, char (*remoteAddr)[16]) +{ + inet_pton(AF_INET, addr, &((this->addr).sin_addr)); + (this->addr).sin_family = AF_INET; // Internet address family + (this->addr).sin_port = htons(this->port); // Local port + + if (-1 == connect( + this->handle, + (struct sockaddr*) &(this->addr), + sizeof(this->addr))) + { + loggerLog(this->log, LOGGER_CRIT, + "error connection socket: %s - service terminated", + strerror(errno)); + exit(EXIT_FAILURE); + } else { + strcpy(*remoteAddr, inet_ntoa((this->addr).sin_addr)); + + loggerLog(this->log, LOGGER_INFO, + "handling connection %s\n", inet_ntoa((this->addr).sin_addr)); + } +} + +// vim: set ts=4 sw=4: diff --git a/src/socket/listen.c b/src/socket/listen.c new file mode 100644 index 0000000..4992058 --- /dev/null +++ b/src/socket/listen.c @@ -0,0 +1,59 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include // for atoi() and exit() +#include // for errno + +#include "socket.h" +#include "interface/class.h" +#include "interface/logger.h" + + +void +socketListen(Sock this, int backlog) +{ + (this->addr).sin_family = AF_INET; // Internet address family + (this->addr).sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface + (this->addr).sin_port = htons(this->port); // Local port + + /** + * Bind to the local address + */ + if (-1 == bind(this->handle, (struct sockaddr *) &(this->addr), sizeof(this->addr))) { + loggerLog(this->log, LOGGER_CRIT, + "error binding socket: %s - service terminated", + strerror(errno)); + exit(EXIT_FAILURE); + } + + /** + * Mark the socket so it will listen for incoming connections + */ + if (-1 == listen(this->handle, backlog)) { + loggerLog(this->log, LOGGER_CRIT, + "error binding socket: %s - service terminated", + strerror(errno)); + exit(EXIT_FAILURE); + } +} + +// vim: set ts=4 sw=4: diff --git a/src/stream.c b/src/stream.c new file mode 100644 index 0000000..49cf067 --- /dev/null +++ b/src/stream.c @@ -0,0 +1,41 @@ +#include +#include + +#include "class.h" +#include "interface/class.h" +#include "stream.h" + + +static +int +streamCtor(void * _this, va_list * params) +{ + Stream this = _this; + this->type = va_arg(* params, StreamHandleType); + + switch(this->type) { + case STREAM_FD: + (this->handle).fd = va_arg(* params, int); + break; + + case STREAM_SSL: + (this->handle).ssl = va_arg(* params, SSL*); + break; + + default: + return -1; + } + + return 0; +} + +static +void +streamDtor(void * _this) +{ +} + +INIT_IFACE(Class, streamCtor, streamDtor, NULL); +CREATE_CLASS(Stream, NULL, IFACE(Class)); + +// vim: set ts=4 sw=4: diff --git a/src/stream/read.c b/src/stream/read.c new file mode 100644 index 0000000..b7bb058 --- /dev/null +++ b/src/stream/read.c @@ -0,0 +1,27 @@ +#include +#include + +#include "stream.h" + +ssize_t +streamRead(Stream this, void * buf, size_t count) +{ + ssize_t done; + + switch(this->type) { + case STREAM_FD: + done = read((this->handle).fd, buf, count); + break; + + case STREAM_SSL: + done = SSL_read((this->handle).ssl, buf, count); + break; + + default: + break; + } + + return done; +} + +// vim: set ts=4 sw=4: diff --git a/src/stream/write.c b/src/stream/write.c new file mode 100644 index 0000000..475e9e9 --- /dev/null +++ b/src/stream/write.c @@ -0,0 +1,27 @@ +#include +#include + +#include "stream.h" + +ssize_t +streamWrite(Stream this, void * buf, size_t count) +{ + ssize_t done; + + switch(this->type) { + case STREAM_FD: + done = write((this->handle).fd, buf, count); + break; + + case STREAM_SSL: + done = SSL_write((this->handle).ssl, buf, count); + break; + + default: + break; + } + + return done; +} + +// vim: set ts=4 sw=4: diff --git a/src/taskrambler.c b/src/taskrambler.c new file mode 100644 index 0000000..5125956 --- /dev/null +++ b/src/taskrambler.c @@ -0,0 +1,196 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "server.h" +#include "logger.h" +#include "http/worker.h" + +#include "interface/class.h" +#include "interface/logger.h" + +#include "utils/signalHandling.h" + +#define DEFAULT_SECS 10 +//#define DEFAULT_USECS (1000000 / HZ * 2) +//#define DEFAULT_SECS 1 +#define DEFAULT_USECS 0 + +void nullhandler() {} + +void daemonize(void); + +int +main() +{ + pid_t pid; + long psize = sysconf(_SC_PAGESIZE); + int status; + int shm; + struct randval * value; + + struct rlimit limit = {RLIM_INFINITY, RLIM_INFINITY}; + setrlimit(RLIMIT_CPU, &limit); + + getrlimit(RLIMIT_NOFILE, &limit); + limit.rlim_cur = limit.rlim_max; + setrlimit(RLIMIT_NOFILE, &limit); + + init_signals(); + + shm = shm_open("/fooshm", O_RDWR|O_CREAT, S_IRWXU); + ftruncate(shm, psize); + + switch((pid = fork())) { + case -1: + break; + + case 0: + { + sigset_t block_these, pause_mask; + struct sigaction s; + struct itimerval interval; + + value = mmap (0, sizeof(struct randval), PROT_READ|PROT_WRITE, + MAP_SHARED, shm, 0); + value->timestamp = 0; + value->value = 0; + + close(shm); + + // Block SIGALRM + sigemptyset(&block_these); + sigaddset(&block_these, SIGALRM); + sigprocmask(SIG_BLOCK, &block_these, &pause_mask); + + // Set up handler for SIGALRM + sigemptyset(&s.sa_mask); + sigaddset(&s.sa_mask, SIGINT); + s.sa_flags = 0; + s.sa_handler = nullhandler; + if (sigaction(SIGALRM, &s, NULL) < 0) { + perror("sigaction SIGALRM"); + exit (1); + } + + interval.it_value.tv_sec = DEFAULT_SECS; + interval.it_value.tv_usec = DEFAULT_USECS; + interval.it_interval.tv_sec = DEFAULT_SECS; + interval.it_interval.tv_usec = DEFAULT_USECS; + + setitimer(ITIMER_REAL, &interval, NULL); + + // child + while(!doShutdown) { + value->timestamp = time(NULL); + value->value = rand() % 100; + sigsuspend(&pause_mask); + } + + _exit(EXIT_SUCCESS); + } + + default: + { + Logger logger; + HttpWorker worker; + Server server; + + value = mmap (0, sizeof(int), PROT_READ|PROT_WRITE, + MAP_SHARED, shm, 0); + + shm_unlink("/fooshm"); + close(shm); + + logger = new(LoggerStderr, LOGGER_DEBUG); + worker = new(HttpWorker, "testserver", value); + server = new(Server, logger, worker, 11212, SOMAXCONN); + + //daemonize(); + if (NULL != server) { + serverRun(server); + } + else { + doShutdown = 1; + kill(pid, SIGINT); + } + + do { + pid_t w; + + w = waitpid(pid, &status, 0); + + while (w == -1) { + switch(errno) { + case EINTR: w = waitpid(pid, &status, 0); + break; + case ECHILD: perror("no child"); + // DROP THROUGH + default: w = 0; + } + } + + if (0 < w) { + if (WIFEXITED(status)) { + loggerLog(logger, LOGGER_INFO, + "child exited, status=%d\n", + WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + loggerLog(logger, LOGGER_INFO, + "killed by signal %d\n", + WTERMSIG(status)); + } else if (WIFSTOPPED(status)) { + loggerLog(logger, LOGGER_INFO, + "stopped by signal %d\n", + WSTOPSIG(status)); + } else if (WIFCONTINUED(status)) { + loggerLog(logger, LOGGER_INFO, "continued\n"); + } + } + } while (!WIFEXITED(status) && !WIFSIGNALED(status)); + + if (NULL != server) delete(server); + if (NULL != worker) delete(worker); + if (NULL != logger) delete(logger); + } + + break; + } + + return 0; +} + +// vim: set ts=4 sw=4: diff --git a/src/utils/daemonize.c b/src/utils/daemonize.c new file mode 100644 index 0000000..bdd61f5 --- /dev/null +++ b/src/utils/daemonize.c @@ -0,0 +1,47 @@ +/** + * \file + * Disconnect from parent process and let all standard file handles + * point to /dev/null. + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include // for printf() and fprintf() +#include // for getopt +#include + + +void daemonize(void) { + pid_t pid; + + if (0 > ((pid = fork()))) { + perror("deamoinze[fork]"); + exit(EXIT_FAILURE); + } else if (0 != pid) { + exit(EXIT_SUCCESS); + } + + // make new child session leader + setsid(); + + // connect all standard streams to /dev/null + stderr = freopen("/dev/null", "w", stderr); + stdin = freopen("/dev/null", "r", stdin); + stdout = freopen("/dev/null", "w", stdout); +} diff --git a/src/utils/hash.c b/src/utils/hash.c new file mode 100644 index 0000000..dc6dcea --- /dev/null +++ b/src/utils/hash.c @@ -0,0 +1,30 @@ +#include +#include + +#include "utils/hash.h" + +/** + * SDBM hashing algorithm: + * + * this algorithm was created for sdbm (a public-domain reimplementation of + * ndbm) database library. it was found to do well in scrambling bits, + * causing better distribution of the keys and fewer splits. it also happens + * to be a good general hashing function with good distribution. the actual + * function is hash(i) = hash(i - 1) * 65599 + str[i]; what is included below + * is the faster version used in gawk. [there is even a faster, duff-device + * version] the magic constant 65599 was picked out of thin air while + * experimenting with different constants, and turns out to be a prime. this + * is one of the algorithms used in berkeley db (see sleepycat) and elsewhere. + */ +unsigned long +sdbm(const unsigned char * str, size_t len) +{ + unsigned long hash = 0; + + for(; 0 < len; str++, len--) + hash = tolower(*str) + (hash << 6) + (hash << 16) - hash; + + return hash; +} + +// vim: set ts=4 sw=4: diff --git a/src/utils/http.c b/src/utils/http.c new file mode 100644 index 0000000..61e833b --- /dev/null +++ b/src/utils/http.c @@ -0,0 +1,51 @@ +#include +#include +#include + +#include "http/message.h" +#include "http/request.h" +#include "http/response.h" + +#include "interface/class.h" + +#include "commons.h" + +char +isHttpVersion(const char * str, size_t len) +{ + if (NULL == str) + return FALSE; + + if (8 > len) + return FALSE; + + if (0 != memcmp("HTTP/", str, sizeof("HTTP/")-1)) + return FALSE; + + return TRUE; +} + +HttpMessage +httpGetMessage( + const char * part1, size_t len1, + const char * part2, size_t len2, + const char * part3, size_t len3) +{ + if (isHttpVersion(part1, len1)) { + return new(HttpResponse, + part1, len1, + strtoul(part2, NULL, 10), + part3, len3); + } + + if (isHttpVersion(part3, len3)) { + return new(HttpRequest, + part1, len1, + part2, len2, + part3, len3); + } + + return NULL; +} + +// vim: set ts=4 sw=4: diff --git a/src/utils/memory.c b/src/utils/memory.c new file mode 100644 index 0000000..853b613 --- /dev/null +++ b/src/utils/memory.c @@ -0,0 +1,14 @@ +#include + +#include "utils/memory.h" + +void +ffree(void ** data) +{ + if (NULL != *data) { + free(*data); + *data = NULL; + } +} + +// vim: set ts=4 sw=4: diff --git a/src/utils/signalHandling.c b/src/utils/signalHandling.c new file mode 100644 index 0000000..4771fa0 --- /dev/null +++ b/src/utils/signalHandling.c @@ -0,0 +1,47 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include // for signal() and signal names + +volatile int doShutdown; + +void terminate(int signum) +{ + signal(signum, SIG_IGN); + /* + * \todo do logging here + */ + doShutdown = 1; +} + +void init_signals(void) +{ + signal(SIGTERM, terminate); + signal(SIGHUP, SIG_IGN); + signal(SIGINT, terminate); + signal(SIGQUIT, terminate); + signal(SIGABRT, terminate); + signal(SIGALRM, SIG_IGN); + signal(SIGURG, SIG_IGN); + + signal(SIGPIPE, SIG_IGN); +} diff --git a/src/webgameserver.c b/src/webgameserver.c new file mode 100644 index 0000000..5125956 --- /dev/null +++ b/src/webgameserver.c @@ -0,0 +1,196 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "server.h" +#include "logger.h" +#include "http/worker.h" + +#include "interface/class.h" +#include "interface/logger.h" + +#include "utils/signalHandling.h" + +#define DEFAULT_SECS 10 +//#define DEFAULT_USECS (1000000 / HZ * 2) +//#define DEFAULT_SECS 1 +#define DEFAULT_USECS 0 + +void nullhandler() {} + +void daemonize(void); + +int +main() +{ + pid_t pid; + long psize = sysconf(_SC_PAGESIZE); + int status; + int shm; + struct randval * value; + + struct rlimit limit = {RLIM_INFINITY, RLIM_INFINITY}; + setrlimit(RLIMIT_CPU, &limit); + + getrlimit(RLIMIT_NOFILE, &limit); + limit.rlim_cur = limit.rlim_max; + setrlimit(RLIMIT_NOFILE, &limit); + + init_signals(); + + shm = shm_open("/fooshm", O_RDWR|O_CREAT, S_IRWXU); + ftruncate(shm, psize); + + switch((pid = fork())) { + case -1: + break; + + case 0: + { + sigset_t block_these, pause_mask; + struct sigaction s; + struct itimerval interval; + + value = mmap (0, sizeof(struct randval), PROT_READ|PROT_WRITE, + MAP_SHARED, shm, 0); + value->timestamp = 0; + value->value = 0; + + close(shm); + + // Block SIGALRM + sigemptyset(&block_these); + sigaddset(&block_these, SIGALRM); + sigprocmask(SIG_BLOCK, &block_these, &pause_mask); + + // Set up handler for SIGALRM + sigemptyset(&s.sa_mask); + sigaddset(&s.sa_mask, SIGINT); + s.sa_flags = 0; + s.sa_handler = nullhandler; + if (sigaction(SIGALRM, &s, NULL) < 0) { + perror("sigaction SIGALRM"); + exit (1); + } + + interval.it_value.tv_sec = DEFAULT_SECS; + interval.it_value.tv_usec = DEFAULT_USECS; + interval.it_interval.tv_sec = DEFAULT_SECS; + interval.it_interval.tv_usec = DEFAULT_USECS; + + setitimer(ITIMER_REAL, &interval, NULL); + + // child + while(!doShutdown) { + value->timestamp = time(NULL); + value->value = rand() % 100; + sigsuspend(&pause_mask); + } + + _exit(EXIT_SUCCESS); + } + + default: + { + Logger logger; + HttpWorker worker; + Server server; + + value = mmap (0, sizeof(int), PROT_READ|PROT_WRITE, + MAP_SHARED, shm, 0); + + shm_unlink("/fooshm"); + close(shm); + + logger = new(LoggerStderr, LOGGER_DEBUG); + worker = new(HttpWorker, "testserver", value); + server = new(Server, logger, worker, 11212, SOMAXCONN); + + //daemonize(); + if (NULL != server) { + serverRun(server); + } + else { + doShutdown = 1; + kill(pid, SIGINT); + } + + do { + pid_t w; + + w = waitpid(pid, &status, 0); + + while (w == -1) { + switch(errno) { + case EINTR: w = waitpid(pid, &status, 0); + break; + case ECHILD: perror("no child"); + // DROP THROUGH + default: w = 0; + } + } + + if (0 < w) { + if (WIFEXITED(status)) { + loggerLog(logger, LOGGER_INFO, + "child exited, status=%d\n", + WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + loggerLog(logger, LOGGER_INFO, + "killed by signal %d\n", + WTERMSIG(status)); + } else if (WIFSTOPPED(status)) { + loggerLog(logger, LOGGER_INFO, + "stopped by signal %d\n", + WSTOPSIG(status)); + } else if (WIFCONTINUED(status)) { + loggerLog(logger, LOGGER_INFO, "continued\n"); + } + } + } while (!WIFEXITED(status) && !WIFSIGNALED(status)); + + if (NULL != server) delete(server); + if (NULL != worker) delete(worker); + if (NULL != logger) delete(logger); + } + + break; + } + + return 0; +} + +// vim: set ts=4 sw=4: diff --git a/tests/Makefile.am b/tests/Makefile.am new file mode 100644 index 0000000..d3c0391 --- /dev/null +++ b/tests/Makefile.am @@ -0,0 +1,29 @@ +ACLOCAL_AMFLAGS = -I m4 +AUTOMAKE_OPTIONS = subdir-objects + +TESTS_ENVIRONMENT = valgrind --error-exitcode=123 --leak-check=full --quiet +TESTS = cclassTest loggerTest socketTest serverTest +check_PROGRAMS = cclassTest loggerTest socketTest serverTest + +COMMON = runtest.c ../src/interface/class.c +CCLASS = $(COMMON) mock/class.c +LOGGER = $(COMMON) ../src/logger.c ../src/interface/logger.c \ + ../src/logger/stderr.c ../src/logger/syslog.c +SOCKET = $(LOGGER) ../src/socket.c ../src/socket/listen.c \ + ../src/socket/accept.c ../src/socket/connect.c +SERVER = $(SOCKET) ../src/server.c ../src/server/run.c \ + ../src/server/close_conn.c ../src/utils/signalHandling.c + +cclassTest_SOURCES = $(CCLASS) cclassTest.c +cclassTest_CFLAGS = -Wall -ggdb -O0 -finline-functions -I ../include -I .. -I . + +loggerTest_SOURCES = $(LOGGER) loggerTest.c +loggerTest_CFLAGS = -Wall -ggdb -O0 -I ../include -I .. -I . + +socketTest_SOURCES = $(SOCKET) socketTest.c +socketTest_CFLAGS = -Wall -ggdb -O0 -I ../include -I .. -I . + +serverTest_SOURCES = $(SERVER) serverTest.c +serverTest_CFLAGS = -Wall -ggdb -O0 -I ../include -I .. -I . + +EXTRA_DIST = runtest.h mock/class.h diff --git a/tests/cclassTest.c b/tests/cclassTest.c new file mode 100644 index 0000000..45f92a0 --- /dev/null +++ b/tests/cclassTest.c @@ -0,0 +1,131 @@ +/** + * \file + * cclassTest.c: tests for my oop C stuff + * Copyright (C) 2011 Georg Hopp + * + * 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 . + */ +#include +#include +#include + +#include "runtest.h" +#include "mock/class.h" +#include "cclass.h" + +const char testname[] = "cclassTest"; + +MOCK_CLASS mock = NULL; + +static +int +__setUp() +{ + mock = NULL; + _reset(); + + return TEST_OK; +} +int (* const setUp)() = __setUp; + +static +int +__tearDown() +{ + if (NULL != mock) { + ASSERT_OBJECT(mock); + delete(&mock); + } + + return TEST_OK; +} +int (* const tearDown)() = __tearDown; + +static +int +testNew(void) +{ + mock = new(MOCK_CLASS, 123); + + ASSERT_OBJECT_NOT_NULL(mock); + ASSERT_EQUAL(1, _called); + ASSERT_EQUAL(123, mock_class_getValue(mock)); + + return TEST_OK; +} + +static +int +testNewFromJson(void) +{ + struct json_object * json = json_object_new_int(123); + + mock = newFromJson(MOCK_CLASS, json); + json_object_put(json); + + ASSERT_OBJECT_NOT_NULL(mock); + ASSERT_EQUAL(1, _called); + ASSERT_EQUAL(123, mock_class_getValue(mock)); + + return TEST_OK; +} + +static +int +testDelete(void) +{ + mock = new(MOCK_CLASS, 123); + + ASSERT_NOT_NULL(mock); + + _reset(); + delete(&mock); + + ASSERT_NULL(mock); + ASSERT_EQUAL(1, _called); + + return TEST_OK; +} + +static +int +testToJson(void) +{ + struct json_object * json = NULL; + mock = new(MOCK_CLASS, 123); + int value; + + _reset(); + toJson(mock, &json); + + ASSERT_NOT_NULL(json); + + value = json_object_get_int(json); + json_object_put(json); + + ASSERT_EQUAL(123, value); + ASSERT_EQUAL(1, _called); + + return TEST_OK; +} + +const testfunc tests[] = { + testNew, + testNewFromJson, + testDelete, + testToJson +}; +const size_t count = FUNCS_COUNT(tests); + +// vim: set et ts=4 sw=4: diff --git a/tests/loggerTest.c b/tests/loggerTest.c new file mode 100644 index 0000000..2727a47 --- /dev/null +++ b/tests/loggerTest.c @@ -0,0 +1,94 @@ +/** + * \file + * loggerTest.c: tests for my logger class + * Copyright (C) 2012 Georg Hopp + * + * 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 . + */ + +#include +#include + +#include "runtest.h" +#include "cclass.h" +#include "logger.h" + + +int level = -1; +char * msg = NULL; + +static void +logfnct_mock(int _level, const char * _msg) +{ + level = _level; + msg = malloc(strlen(_msg) + 1); + strcpy(msg, _msg); +} + +const char testname[] = "loggerTest"; +LOGGER logger = NULL; + + +static +int +__setUp() +{ + logger = new(LOGGER, NULL); + + ASSERT_INSTANCE_OF(LOGGER, logger); + + logger_add(logger, logfnct_mock); + + return TEST_OK; +} +int (* const setUp)() = __setUp; + +static +int +__tearDown() +{ + level = -1; + + if (NULL != msg) { + free(msg); + msg = NULL; + } + + if (NULL != logger) { + ASSERT_OBJECT(logger); + delete(&logger); + } + + return TEST_OK; +} +int (* const tearDown)() = __tearDown; + +static +int +testLogger() +{ + logger_log(logger, LOGGER_ERR, "foo %d %s", 123, "bar"); + + ASSERT_EQUAL(LOGGER_ERR, level); + ASSERT_STRING_EQUAL("foo 123 bar", msg); + + return TEST_OK; +} + +const testfunc tests[] = { + testLogger +}; +const size_t count = FUNCS_COUNT(tests); + +// vim: set et ts=4 sw=4: diff --git a/tests/mock/class.c b/tests/mock/class.c new file mode 100644 index 0000000..8a9da0a --- /dev/null +++ b/tests/mock/class.c @@ -0,0 +1,88 @@ +/** + * \file + * mock/class.c: a mock to test my oop stuff + * Copyright (C) 2011 Georg Hopp + * + * 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 . + */ + +#include +#include + +#include "cclass.h" +#include "class.h" + +char _called; + +INIT_CLASS(MOCK_CLASS); + +__construct(MOCK_CLASS) +{ + _called = 1; + this->value = va_arg(* params, int); +} + +__jsonConst(MOCK_CLASS) +{ + _called = 1; + assert(json_type_int == json_object_get_type(json)); + + this->value = json_object_get_int(json); +} + +__clear(MOCK_CLASS) {} + +__destruct(MOCK_CLASS) +{ + _called = 1; +} + +__toJson(MOCK_CLASS) +{ + *json = json_object_new_int(this->value); + _called = 1; +} + +/** + * ~~~ method implementations ~~~~~~~~ + */ + +int +mock_class_getValue(MOCK_CLASS this) +{ + return this->value; +} + +void +mock_class_setValue(MOCK_CLASS this, int value) +{ + this->value = value; +} + +/** + * ~~~ helper for mock assertions ~~~~~~~~ + */ +void * +getConstruct() +{ + return __construct; +} + +void * +getJsonConst() +{ + return __jsonConst; +} + +// vim: set et ts=4 sw=4: diff --git a/tests/mock/class.h b/tests/mock/class.h new file mode 100644 index 0000000..e439bb1 --- /dev/null +++ b/tests/mock/class.h @@ -0,0 +1,49 @@ +/** + * \file + * mock/class.h: definitions for my mock to test my oop stuff + * Copyright (C) 2011 Georg Hopp + * + * 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 . + */ +#ifndef __MOCK_CLASS_H__ +#define __MOCK_CLASS_H__ + +#include "cclass.h" + +extern char _called; + +#ifndef _RESET +#define _RESET +void +inline +_reset() +{ + _called = 0; +} +#endif//_RESET + + +CLASS(MOCK_CLASS) { + int value; +}; + +/** + * ~~~ method declarations ~~~~~~~~ + */ + +int mock_class_getValue(MOCK_CLASS this); +void mock_class_setValue(MOCK_CLASS this, int value); + +#endif//__MOCK_CLASS_H__ +// vim: set et ts=4 sw=4: diff --git a/tests/runtest.c b/tests/runtest.c new file mode 100644 index 0000000..b363cc8 --- /dev/null +++ b/tests/runtest.c @@ -0,0 +1,121 @@ +/** + * \file + * runtest.c: the main runner for my tests + * Copyright (C) 2011 Georg Hopp + * + * 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 . + */ +#include +#include +#include +#include + +#include "runtest.h" +#include "cclass.h" + + +#define TEST_OK_CHAR '.' +#define TEST_FAILED_CHAR 'F' +#define TEST_ERROR_CHAR 'E' + + +const char results[3] = { + TEST_OK_CHAR, + TEST_FAILED_CHAR, + TEST_ERROR_CHAR +}; + +int +isObjectNull(void * _object) +{ + const CCLASS * class = _object - sizeof(CCLASS); + + if (! isObject(_object)) { + return 0; + } + + return isMemNull(_object, (*class)->size); +} + +int +isMemNull(void * _mem, size_t size) +{ + size_t index; + + if (NULL == _mem) { + return 0; + } + + for(index=0; index. + */ +#ifndef __RUNTEST_h__ +#define __RUNTEST_h__ + +#include +#include + + +enum RESULT_TYPES { + TEST_OK=0, + TEST_FAILED, + TEST_ERROR +}; + +#define ASSERT_NULL(value) \ + if (NULL != (value)) { \ + printf("%s[%d]: Assertion failed that %s is NULL\n", \ + __FILE__, __LINE__, #value); \ + return TEST_FAILED; } + +#define ASSERT_NOT_NULL(value) \ + if (NULL == (value)) { \ + printf("%s[%d]: Assertion failed that %s is NOT NULL\n", \ + __FILE__, __LINE__, #value); \ + return TEST_FAILED; } + +#define ASSERT_EQUAL(val1,val2) \ + if ((val1) != (val2)) { \ + printf("%s[%d]: Assertion failed that %s EQUALS %s\n", \ + __FILE__, __LINE__, #val1, #val2); \ + return TEST_FAILED; } + +#define ASSERT_NOT_EQUAL(val1,val2) \ + if ((val1) == (val2)) { \ + printf("%s[%d]: Assertion failed that %s NOT EQUALS %s\n", \ + __FILE__, __LINE__, #val1, #val2); \ + return TEST_FAILED; } + +#define ASSERT_MEM_EQUAL(val1,val2,size) \ + if(0 != memcmp((val1), (val2), (size))) { \ + printf("%s[%d]: Assertion failed that memory at %s EQUALS %s for %lu bytes\n", \ + __FILE__, __LINE__, #val1, #val2, size); \ + return TEST_FAILED; } + +#define ASSERT_MEM_NOT_EQUAL(val1,val2,size) \ + if(0 == memcmp((val1), (val2), (size))) { \ + printf("%s[%d]: Assertion failed that memory at %s NOT EQUALS %s for %lu bytes\n", \ + __FILE__, __LINE__, #val1, #val2, size); \ + return TEST_FAILED; } + +#define ASSERT_MEM_NULL(val, size) \ + if (! isMemNull((val), (size))) { \ + printf("%s[%d]: Assertion failed that memory at %s is NULL for %lu bytes\n", \ + __FILE__, __LINE__, #val, size); \ + return TEST_FAILED; } + +#define ASSERT_MEM_NOT_NULL(val, size) \ + if (isMemNull((val), (size))) { \ + printf("%s[%d]: Assertion failed that memory at %s is NOT NULL for %lu bytes\n", \ + __FILE__, __LINE__, #val, size); \ + return TEST_FAILED; } + +#define ASSERT_STRING_EQUAL(val1, val2) \ + if(0 != strcmp((val1), (val2))) { \ + printf("%s[%d]: Assertion failed that string %s EQUALS %s\n", \ + __FILE__, __LINE__, val1, val2); \ + return TEST_FAILED; } + +#define ASSERT_STRING_NOT_EQUAL(val1, val2) \ + if(0 == strcmp((val1), (val2))) { \ + printf("%s[%d]: Assertion failed that string %s NOT EQUALS %s\n", \ + __FILE__, __LINE__, val1, val2); \ + return TEST_FAILED; } + +#define ASSERT_OBJECT(val) \ + if (! isObject((val))) { \ + printf("%s[%d]: Assertion failed that %s IS an object\n", \ + __FILE__, __LINE__, #val); \ + return TEST_FAILED; } + +#define ASSERT_OBJECT_NULL(val) \ + if (! isObjectNull((val))) { \ + printf("%s[%d]: Assertion failed that %s IS an UNINITIALIZED object\n", \ + __FILE__, __LINE__, #val); \ + return TEST_FAILED; } + +#define ASSERT_OBJECT_NOT_NULL(val) \ + if (isObjectNull((val))) { \ + printf("%s[%d]: Assertion failed that %s IS an INITIALIZED object\n", \ + __FILE__, __LINE__, #val); \ + return TEST_FAILED; } + +#define ASSERT_INSTANCE_OF(class, val) \ + if (! instanceOf(class, val)) { \ + printf("%s[%d]: Assertion failed that %s is instance of %s\n", \ + __FILE__, __LINE__, #val, #class); \ + return TEST_FAILED; } + + +typedef int (* const testfunc)(void); +#define FUNCS_COUNT(array) (sizeof((array)) / sizeof(testfunc)) + +extern const char testname[]; +extern testfunc tests[]; +extern const size_t count; + +extern int (* const setUp)(); +extern int (* const tearDown)(); + +int isMemNull(void * _mem, size_t size); +int isObjectNull(void * _object); + +#endif//__RUNTEST_h__ +// vim: set et ts=4 sw=4: diff --git a/tests/serverTest.c b/tests/serverTest.c new file mode 100644 index 0000000..3eae940 --- /dev/null +++ b/tests/serverTest.c @@ -0,0 +1,122 @@ +#include +#include +#include +#include +#include + +#include "runtest.h" +#include "logger.h" +#include "cclass.h" +#include "server.h" +#include "signalHandling.h" + + +#define TEST_PORT 11212 +#define TEST_DATA "test" + + +int level = -1; +char msg[1024]; +char buffer[1025]; + +static void +read_hook(const char * _buffer, size_t size) +{ + memset(buffer, 0, 1025); + + if (NULL != _buffer) { + strncpy(buffer, _buffer, 1024>size? size : 1024); + } + + doShutdown = 1; +} + +static void +logfnct_mock(int _level, const char * _msg) +{ + level = _level; + strncpy(msg, _msg, 1023); +} + +const char testname[] = "serverTest"; +LOGGER logger = NULL; +SERVER server = NULL; + +static +int +__setUp() +{ + logger = new(LOGGER, NULL); + logger_add(logger, logfnct_mock); + + server = new(SERVER, logger, TEST_PORT, SOMAXCONN); + + ASSERT_INSTANCE_OF(SERVER, server); + ASSERT_INSTANCE_OF(LOGGER, server->logger); + ASSERT_INSTANCE_OF(SOCK, server->sock); + ASSERT_EQUAL(TEST_PORT, server->sock->port); + + server->read_hook = read_hook; + + return TEST_OK; +} +int (* const setUp)() = __setUp; + +static +int +__tearDown() +{ + level = -1; + + if (NULL != server) { + ASSERT_OBJECT(server); + delete(&server); + } + + if (NULL != logger) { + ASSERT_OBJECT(logger); + delete(&logger); + } + + return TEST_OK; +} +int (* const tearDown)() = __tearDown; + +static +int +testDummy() +{ + SOCK con; + pid_t pid; + + pid = fork(); + + switch(pid) { + case 0: + con = new(SOCK, logger, TEST_PORT); + sleep(1); + sock_connect(con, "127.0.0.1"); + write(con->handle, TEST_DATA, strlen(TEST_DATA)+1); + delete(&con); + __tearDown(); + exit(EXIT_SUCCESS); + + case -1: + return TEST_FAILED; + + default: + init_signals(); + server_run(server); + } + + ASSERT_STRING_EQUAL(TEST_DATA, buffer); + + return TEST_OK; +} + +const testfunc tests[] = { + testDummy +}; +const size_t count = FUNCS_COUNT(tests); + +// vim: set ts=4 sw=4: diff --git a/tests/socketTest.c b/tests/socketTest.c new file mode 100644 index 0000000..64447da --- /dev/null +++ b/tests/socketTest.c @@ -0,0 +1,123 @@ +#include +#include +#include + +#include "runtest.h" +#include "logger.h" +#include "cclass.h" +#include "socket.h" + + +#define TEST_PORT 11212 + + +int level = -1; +char * msg = NULL; + +static void +logfnct_mock(int _level, const char * _msg) +{ + level = _level; + msg = malloc(strlen(_msg) + 1); + strcpy(msg, _msg); +} + +const char testname[] = "socketTest"; +LOGGER logger = NULL; +SOCK sock = NULL; + +static +int +__setUp() +{ + logger = new(LOGGER, NULL); + logger_add(logger, logfnct_mock); + + sock = new(SOCK, logger, TEST_PORT); + + ASSERT_INSTANCE_OF(SOCK, sock); + ASSERT_INSTANCE_OF(LOGGER, sock->logger); + ASSERT_EQUAL(TEST_PORT, sock->port); + ASSERT_NOT_EQUAL(0, sock->handle); + + return TEST_OK; +} +int (* const setUp)() = __setUp; + +static +int +__tearDown() +{ + level = -1; + + if (NULL != msg) { + free(msg); + msg = NULL; + } + + if (NULL != logger) { + ASSERT_OBJECT(logger); + delete(&logger); + } + + if (NULL != sock) { + ASSERT_OBJECT(sock); + delete(&sock); + } + + return TEST_OK; +} +int (* const tearDown)() = __tearDown; + +static +int +testListen() +{ + sock_listen(sock, 10); + + return TEST_OK; +} + +static +int +testAccept() +{ + SOCK acc, con; + char addr[16]; + pid_t pid; + + sock_listen(sock, 10); + + pid = fork(); + + switch(pid) { + case 0: + con = new(SOCK, logger, TEST_PORT); + sleep(1); + sock_connect(con, "127.0.0.1"); + delete(&con); + __tearDown(); + exit(EXIT_SUCCESS); + + case -1: + return TEST_FAILED; + + default: + acc = sock_accept(sock, addr); + } + + if (NULL != acc) { + ASSERT_OBJECT(acc); + delete(&acc); + } + + return TEST_OK; +} + +const testfunc tests[] = { + testListen, + testAccept +}; +const size_t count = FUNCS_COUNT(tests); + +// vim: set ts=4 sw=4: diff --git a/tests/tst-tsearch.c b/tests/tst-tsearch.c new file mode 100644 index 0000000..722b6d7 --- /dev/null +++ b/tests/tst-tsearch.c @@ -0,0 +1,333 @@ +/* Test program for tsearch et al. + Copyright (C) 1997, 2000, 2001 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library 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. + + The GNU C Library 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 the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#ifndef _GNU_SOURCE +# define _GNU_SOURCE 1 +#endif + +#include +#include +#include +#include + +#define SEED 0 +#define BALANCED 1 +#define PASSES 100 + +#if BALANCED +#include +#define SIZE 1000 +#else +#define SIZE 100 +#endif + +enum order +{ + ascending, + descending, + randomorder +}; + +enum action +{ + build, + build_and_del, + delete, + find +}; + +/* Set to 1 if a test is flunked. */ +static int error = 0; + +/* The keys we add to the tree. */ +static int x[SIZE]; + +/* Pointers into the key array, possibly permutated, to define an order + for insertion/removal. */ +static int y[SIZE]; + +/* Flags set for each element visited during a tree walk. */ +static int z[SIZE]; + +/* Depths for all the elements, to check that the depth is constant for + all three visits. */ +static int depths[SIZE]; + +/* Maximum depth during a tree walk. */ +static int max_depth; + +/* Compare two keys. */ +static int +cmp_fn (const void *a, const void *b) +{ + return *(const int *) a - *(const int *) b; +} + +/* Permute an array of integers. */ +static void +memfry (int *string) +{ + int i; + + for (i = 0; i < SIZE; ++i) + { + int32_t j; + int c; + + j = random () % SIZE; + + c = string[i]; + string[i] = string[j]; + string[j] = c; + } +} + +static void +walk_action (const void *nodep, const VISIT which, const int depth) +{ + int key = **(int **) nodep; + + if (depth > max_depth) + max_depth = depth; + if (which == leaf || which == preorder) + { + ++z[key]; + depths[key] = depth; + } + else + { + if (depths[key] != depth) + { + fputs ("Depth for one element is not constant during tree walk.\n", + stdout); + } + } +} + +static void +walk_tree (void *root, int expected_count) +{ + int i; + + memset (z, 0, sizeof z); + max_depth = 0; + + twalk (root, walk_action); + for (i = 0; i < expected_count; ++i) + if (z[i] != 1) + { + fputs ("Node was not visited.\n", stdout); + error = 1; + } + +#if BALANCED + if (max_depth > log (expected_count) * 2 + 2) +#else + if (max_depth > expected_count) +#endif + { + fputs ("Depth too large during tree walk.\n", stdout); + error = 1; + } +} + +/* Perform an operation on a tree. */ +static void +mangle_tree (enum order how, enum action what, void **root, int lag) +{ + int i; + + if (how == randomorder) + { + for (i = 0; i < SIZE; ++i) + y[i] = i; + memfry (y); + } + + for (i = 0; i < SIZE + lag; ++i) + { + void *elem; + int j, k; + + switch (how) + { + case randomorder: + if (i >= lag) + k = y[i - lag]; + else + /* Ensure that the array index is within bounds. */ + k = y[(SIZE - i - 1 + lag) % SIZE]; + j = y[i % SIZE]; + break; + + case ascending: + k = i - lag; + j = i; + break; + + case descending: + k = SIZE - i - 1 + lag; + j = SIZE - i - 1; + break; + + default: + /* This never should happen, but gcc isn't smart enough to + recognize it. */ + abort (); + } + + switch (what) + { + case build_and_del: + case build: + if (i < SIZE) + { + if (tfind (x + j, (void *const *) root, cmp_fn) != NULL) + { + fputs ("Found element which is not in tree yet.\n", stdout); + error = 1; + } + elem = tsearch (x + j, root, cmp_fn); + if (elem == 0 + || tfind (x + j, (void *const *) root, cmp_fn) == NULL) + { + fputs ("Couldn't find element after it was added.\n", + stdout); + error = 1; + } + } + + if (what == build || i < lag) + break; + + j = k; + /* fall through */ + + case delete: + elem = tfind (x + j, (void *const *) root, cmp_fn); + if (elem == NULL || tdelete (x + j, root, cmp_fn) == NULL) + { + fputs ("Error deleting element.\n", stdout); + error = 1; + } + break; + + case find: + if (tfind (x + j, (void *const *) root, cmp_fn) == NULL) + { + fputs ("Couldn't find element after it was added.\n", stdout); + error = 1; + } + break; + + } + } +} + + +int +main (int argc, char **argv) +{ + int total_error = 0; + static char state[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + void *root = NULL; + int i, j; + + initstate (SEED, state, 8); + + for (i = 0; i < SIZE; ++i) + x[i] = i; + + /* Do this loop several times to get different permutations for the + random case. */ + fputs ("Series I\n", stdout); + for (i = 0; i < PASSES; ++i) + { + fprintf (stdout, "Pass %d... ", i + 1); + fflush (stdout); + error = 0; + + mangle_tree (ascending, build, &root, 0); + mangle_tree (ascending, find, &root, 0); + mangle_tree (descending, find, &root, 0); + mangle_tree (randomorder, find, &root, 0); + walk_tree (root, SIZE); + mangle_tree (ascending, delete, &root, 0); + + mangle_tree (ascending, build, &root, 0); + walk_tree (root, SIZE); + mangle_tree (descending, delete, &root, 0); + + mangle_tree (ascending, build, &root, 0); + walk_tree (root, SIZE); + mangle_tree (randomorder, delete, &root, 0); + + mangle_tree (descending, build, &root, 0); + mangle_tree (ascending, find, &root, 0); + mangle_tree (descending, find, &root, 0); + mangle_tree (randomorder, find, &root, 0); + walk_tree (root, SIZE); + mangle_tree (descending, delete, &root, 0); + + mangle_tree (descending, build, &root, 0); + walk_tree (root, SIZE); + mangle_tree (descending, delete, &root, 0); + + mangle_tree (descending, build, &root, 0); + walk_tree (root, SIZE); + mangle_tree (randomorder, delete, &root, 0); + + mangle_tree (randomorder, build, &root, 0); + mangle_tree (ascending, find, &root, 0); + mangle_tree (descending, find, &root, 0); + mangle_tree (randomorder, find, &root, 0); + walk_tree (root, SIZE); + mangle_tree (randomorder, delete, &root, 0); + + for (j = 1; j < SIZE; j *= 2) + { + mangle_tree (randomorder, build_and_del, &root, j); + } + + fputs (error ? " failed!\n" : " ok.\n", stdout); + total_error |= error; + } + + fputs ("Series II\n", stdout); + for (i = 1; i < SIZE; i *= 2) + { + fprintf (stdout, "For size %d... ", i); + fflush (stdout); + error = 0; + + mangle_tree (ascending, build_and_del, &root, i); + mangle_tree (descending, build_and_del, &root, i); + mangle_tree (ascending, build_and_del, &root, i); + mangle_tree (descending, build_and_del, &root, i); + mangle_tree (ascending, build_and_del, &root, i); + mangle_tree (descending, build_and_del, &root, i); + mangle_tree (ascending, build_and_del, &root, i); + mangle_tree (descending, build_and_del, &root, i); + + fputs (error ? " failed!\n" : " ok.\n", stdout); + total_error |= error; + } + + return total_error; +}