Browse Source

Initial public commit of Plex Media Player

Tobias Hieta 8 years ago
commit
3d4859f1b1
100 changed files with 13593 additions and 0 deletions
  1. 47 0
      .clang-format
  2. 11 0
      .gitignore
  3. 0 0
      .gitmodules
  4. 41 0
      BuildQT5-windows.md
  5. 59 0
      CMakeLists.txt
  6. 21 0
      CMakeModules/AppleConfiguration.cmake
  7. 35 0
      CMakeModules/BreakpadSymbols.cmake
  8. 63 0
      CMakeModules/CPackConfiguration.cmake
  9. 3 0
      CMakeModules/CPackGeneratedConfig.cmake.in
  10. 17 0
      CMakeModules/CompleteBundle.cmake
  11. 69 0
      CMakeModules/CompleteBundleOSX.cmake.in
  12. 10 0
      CMakeModules/CompleteBundleWin.cmake.in
  13. 28 0
      CMakeModules/DependencyConfiguration.cmake
  14. 69 0
      CMakeModules/FindBreakpad.cmake
  15. 26 0
      CMakeModules/FindCEC.cmake
  16. 17 0
      CMakeModules/FindDL.cmake
  17. 73 0
      CMakeModules/FindGLES2.cmake
  18. 311 0
      CMakeModules/FindICU.cmake
  19. 57 0
      CMakeModules/FindIconv.cmake
  20. 80 0
      CMakeModules/FindMPV.cmake
  21. 69 0
      CMakeModules/FindSDL2.cmake
  22. 0 0
      CMakeModules/GCCConfiguration.cmake
  23. 13 0
      CMakeModules/GetDate.cmake
  24. 123 0
      CMakeModules/GetGitRevisionDescription.cmake
  25. 38 0
      CMakeModules/GetGitRevisionDescription.cmake.in
  26. 71 0
      CMakeModules/InputConfiguration.cmake
  27. 14 0
      CMakeModules/LinuxConfiguration.cmake
  28. 16 0
      CMakeModules/NameConfiguration.cmake
  29. 16 0
      CMakeModules/PlayerConfiguration.cmake
  30. 57 0
      CMakeModules/QtConfiguration.cmake
  31. 30 0
      CMakeModules/VersionConfiguration.cmake
  32. 36 0
      CMakeModules/WebClientResources.cmake
  33. 2 0
      CMakeModules/WebClientVariables.cmake
  34. 14 0
      CMakeModules/Win32Configuration.cmake
  35. 70 0
      CMakeModules/utils.cmake
  36. 52 0
      README.md
  37. 40 0
      bundle/osx/Info.plist.in
  38. 12 0
      bundle/osx/Konvergo.entitlements
  39. BIN
      bundle/osx/Plex.icns
  40. 10 0
      bundle/osx/WebEngine.entitlements
  41. 4 0
      bundle/osx/qt.conf
  42. BIN
      bundle/win/Plex.ico
  43. 2 0
      bundle/win/PlexMediaPlayer-angle.bat
  44. 1 0
      bundle/win/iconres.rc
  45. 7 0
      bundle/win/qt.conf
  46. 15 0
      bundle/win/shortcut.qs
  47. 7 0
      external/CMakeLists.txt
  48. 9 0
      external/SPMediaKeyTap/CMakeLists.txt
  49. 8 0
      external/SPMediaKeyTap/LICENSE
  50. 12 0
      external/SPMediaKeyTap/README.md
  51. 30 0
      external/SPMediaKeyTap/SPInvocationGrabbing/NSObject+SPInvocationGrabbing.h
  52. 127 0
      external/SPMediaKeyTap/SPInvocationGrabbing/NSObject+SPInvocationGrabbing.m
  53. 43 0
      external/SPMediaKeyTap/SPMediaKeyTap.h
  54. 346 0
      external/SPMediaKeyTap/SPMediaKeyTap.m
  55. 8 0
      external/plistparser/CMakeLists.txt
  56. 22 0
      external/plistparser/LICENSE
  57. 98 0
      external/plistparser/plistparser.cpp
  58. 18 0
      external/plistparser/plistparser.h
  59. 83 0
      external/plistparser/plistserializer.cpp
  60. 20 0
      external/plistparser/plistserializer.h
  61. 30 0
      external/qhttpserver/.gitignore
  62. 8 0
      external/qhttpserver/CMakeLists.txt
  63. 19 0
      external/qhttpserver/LICENSE
  64. 72 0
      external/qhttpserver/README.md
  65. 7 0
      external/qhttpserver/TODO
  66. 2314 0
      external/qhttpserver/docs/Doxyfile
  67. 10 0
      external/qhttpserver/docs/pages/examples.dox
  68. 105 0
      external/qhttpserver/docs/pages/main-page.dox
  69. 76 0
      external/qhttpserver/examples/bodydata/bodydata.cpp
  70. 39 0
      external/qhttpserver/examples/bodydata/bodydata.h
  71. 19 0
      external/qhttpserver/examples/bodydata/bodydata.pro
  72. 5 0
      external/qhttpserver/examples/examples.pro
  73. 48 0
      external/qhttpserver/examples/greeting/greeting.cpp
  74. 16 0
      external/qhttpserver/examples/greeting/greeting.h
  75. 19 0
      external/qhttpserver/examples/greeting/greeting.pro
  76. 37 0
      external/qhttpserver/examples/helloworld/helloworld.cpp
  77. 16 0
      external/qhttpserver/examples/helloworld/helloworld.h
  78. 19 0
      external/qhttpserver/examples/helloworld/helloworld.pro
  79. 28 0
      external/qhttpserver/http-parser/.gitignore
  80. 8 0
      external/qhttpserver/http-parser/.mailmap
  81. 13 0
      external/qhttpserver/http-parser/.travis.yml
  82. 67 0
      external/qhttpserver/http-parser/AUTHORS
  83. 4 0
      external/qhttpserver/http-parser/CONTRIBUTIONS
  84. 23 0
      external/qhttpserver/http-parser/LICENSE-MIT
  85. 183 0
      external/qhttpserver/http-parser/README.md
  86. 111 0
      external/qhttpserver/http-parser/bench.c
  87. 160 0
      external/qhttpserver/http-parser/contrib/parsertrace.c
  88. 46 0
      external/qhttpserver/http-parser/contrib/url_parser.c
  89. 2429 0
      external/qhttpserver/http-parser/http_parser.c
  90. 111 0
      external/qhttpserver/http-parser/http_parser.gyp
  91. 342 0
      external/qhttpserver/http-parser/http_parser.h
  92. 3852 0
      external/qhttpserver/http-parser/test.c
  93. 44 0
      external/qhttpserver/http-parser/url_parser.c
  94. 46 0
      external/qhttpserver/konvergo-error.patch
  95. 3 0
      external/qhttpserver/qhttpserver.pri
  96. 8 0
      external/qhttpserver/qhttpserver.pro
  97. 293 0
      external/qhttpserver/src/qhttpconnection.cpp
  98. 85 0
      external/qhttpserver/src/qhttpconnection.h
  99. 96 0
      external/qhttpserver/src/qhttprequest.cpp
  100. 202 0
      external/qhttpserver/src/qhttprequest.h

+ 47 - 0
.clang-format

@@ -0,0 +1,47 @@
+---
+# BasedOnStyle:  LLVM
+AccessModifierOffset: -2
+ConstructorInitializerIndentWidth: 2
+AlignEscapedNewlinesLeft: false
+AlignTrailingComments: true
+AllowAllParametersOfDeclarationOnNextLine: true
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AlwaysBreakTemplateDeclarations: false
+AlwaysBreakBeforeMultilineStrings: false
+BreakBeforeBinaryOperators: false
+BreakBeforeTernaryOperators: false
+BreakConstructorInitializersBeforeComma: false
+BinPackParameters: true
+ColumnLimit:     100
+ConstructorInitializerAllOnOneLineOrOnePerLine: true
+DerivePointerBinding: false
+ExperimentalAutoDetectBinPacking: false
+IndentCaseLabels: true
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: All
+ObjCSpaceBeforeProtocolList: true
+PenaltyBreakBeforeFirstCallParameter: 19
+PenaltyBreakComment: 60
+PenaltyBreakString: 1000
+PenaltyBreakFirstLessLess: 120
+PenaltyExcessCharacter: 1000000
+PenaltyReturnTypeOnItsOwnLine: 1000
+PointerBindsToType: true
+SpacesBeforeTrailingComments: 1
+Cpp11BracedListStyle: false
+Standard:        Cpp03
+IndentWidth:     2
+TabWidth:        2
+UseTab:          Never
+BreakBeforeBraces: Allman
+IndentFunctionDeclarationAfterType: false
+SpacesInParentheses: false
+SpacesInAngles:  false
+SpaceInEmptyParentheses: false
+SpacesInCStyleCastParentheses: false
+SpaceAfterControlStatementKeyword: true
+SpaceBeforeAssignmentOperators: true
+ContinuationIndentWidth: 0
+...
+

+ 11 - 0
.gitignore

@@ -0,0 +1,11 @@
+*.pro.user*
+dependencies/*
+CMakeLists.txt.user
+CMakeLists.txt.user.*
+build/*
+.idea
+.install_pkg
+.openelec-unpack
+QtCreatorDeployment.txt
+vagrant/ubuntu-x86_64/.vagrant
+vagrant/windows-x86_64/.vagrant

+ 0 - 0
.gitmodules


+ 41 - 0
BuildQT5-windows.md

@@ -0,0 +1,41 @@
+# How-To build Qt 5.5.0 on Windows
+This procedure was ran on a freshly installed Win7 64 bits.
+
+This procedure assumes that the build root is `C:\qt\` but it can be changed in the beginning of each `.bat` file
+
+1. Install Visual Studio 2013
+- Install [Visual Studio 2013 Update 4](http://www.microsoft.com/fr-fr/download/details.aspx?id=44921) 
+- Install [Windows SDK 8](https://msdn.microsoft.com/en-us/windows/desktop/hh852363.aspx)
+- Install [ActivePerl](http://www.activestate.com/activeperl/downloads)
+- Install [Python 2.7.10](https://www.python.org/downloads/release/python-2710)
+- Install the following gnutools:
+  - [Bison](http://gnuwin32.sourceforge.net/downlinks/bison.php)
+  - [GPerf](http://gnuwin32.sourceforge.net/downlinks/gperf.php)
+  - [Flex](http://gnuwin32.sourceforge.net/downlinks/flex.php)
+- Grab [ICU sources](http://download.icu-project.org/files/icu4c/55.1/icu4c-55_1-src.zip) and unpack them in `C:\qt\icu`
+- Grab [Openssl 1.0.2d](https://www.openssl.org/source/) and unpack them in `C:\qt\openssl`
+- Grab [Qt Sources](http://download.qt.io/official_releases/qt/5.5/5.5.0/single/qt-everywhere-opensource-src-5.5.0.zip) and unpack them in  `C:\qt\qt5`
+- drop the three `.bat` files in the steps below in `C:\qt\` 
+- Open `C:\qt\icu\source\allionone\allinone.sln` with VS2013, you will be prompted for project conversion. Once the project is converted, just close it.
+- run `c:\qt\buildicu.bat`
+- run `c:\qt\buildopenssl.bat`
+- run `c:\qt\buildqt.bat`
+
+The qt build will land in `C:\qt\qt5\build`
+
+
+# buildicu.bat
+```
+set BUILD_ROOT=C:\qt

REM Set up \Microsoft Visual Studio 2013, where <arch> is \c amd64, \c x86, etc.
CALL "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86_amd64

REM set compiler to multicore
set CL=/MP

REM Build icu
cd %BUILD_ROOT%\icu
msbuild source\allinone\allinone.sln /m /target:Build /property:Configuration=Release;Platform=x64
msbuild source\allinone\allinone.sln /m /target:Build /property:Configuration=Debug;Platform=x64
+cd ..
+```
+
+# buildopenssl.bat
+```
+set BUILD_ROOT=C:\qt

CALL "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86_amd64

cd openssl
set CL=/MP
perl Configure VC-WIN64A --prefix=%BUILD_ROOT%\openssl\build
call ms\do_win64a
nmake -f ms\ntdll.mak
nmake -f ms\ntdll.mak install
cd ..
+```
+
+# buildqt.bat
+```
+set BUILD_ROOT=C:\qt


REM Set up \Microsoft Visual Studio 2013, where <arch> is \c amd64, \c x86, etc.
CALL "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86_amd64

REM set compiler to multicore
set CL=/MP

REM Add ICU dirs to the proper path (include, libs , bin)
set INCLUDE=%INCLUDE%;%BUILD_ROOT%\icu\include
set LIB=%LIB%;%BUILD_ROOT%\icu\lib64
set PATH=%PATH%;%BUILD_ROOT%\icu\bin64


REM Add OpenSSL dirs to the proper path (include, libs , bin)
set INCLUDE=%INCLUDE%;%BUILD_ROOT%\openssl\build\include
set LIB=%LIB%;%BUILD_ROOT%\openssl\build\lib
set PATH=%PATH%;%BUILD_ROOT%\openssl\build\bin

REM Add Pyhton dirs to the proper path (include, libs , bin)
set PATH=%PATH%;c:\Python27\


REM Add GunWindirs to the proper path (include, libs , bin)
set INCLUDE=%INCLUDE%;%BUILD_ROOT%\GnuWin32\include
set LIB=%LIB%;%BUILD_ROOT%\GnuWin32\lib
set PATH=%PATH%;=%BUILD_ROOT%\GnuWin32\bin


SET QT_ROOT=%BUILD_ROOT%\qt5
SET PATH=%QT_ROOT%\qtbase\bin;%PATH%
SET QMAKESPEC=win32-msvc2013

cd %QT_ROOT%

CALL configure -prefix %QT_ROOT%\build -icu -opengl dynamic -release -nomake examples -opensource -confirm-license  -no-gif  -qt-libpng -qt-libjpeg -openssl -qt-pcre -no-cups -no-dbus -skip qtwebkit -skip qtconnectivity -skip qtdoc -skip qtgraphicaleffects -skip qtmultimedia -skip qtsensors -skip qtserialport -skip qtwebkit-examples -skip qtquick1 -skip qt3d

nmake
nmake install
cd ..
+```

+ 59 - 0
CMakeLists.txt

@@ -0,0 +1,59 @@
+project(PlexMediaPlayer CXX C)
+cmake_minimum_required(VERSION 3.0.0 FATAL_ERROR)
+
+cmake_policy(SET CMP0020 NEW)
+if (POLICY CMP0058)
+cmake_policy(SET CMP0058 NEW)
+endif()
+cmake_policy(SET CMP0017 NEW)
+
+option(OPENELEC "Make an OpenELEC build" OFF)
+
+if (OPENELEC)
+  add_definitions(-DKONVERGO_OPENELEC=1)
+  Message(STATUS "Making an OpenELEC build")
+endif(OPENELEC)
+
+option(BUILD_TARGET "Destination target for the build" "")
+
+if (BUILD_TARGET STREQUAL "RPI")
+  add_definitions(-DTARGET_RPI=1)
+  set(RPI_LIBS bcm_host)
+  Message(STATUS "Build for Raspberry PI target")
+endif(BUILD_TARGET STREQUAL "RPI")
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMakeModules/")
+set(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME Core)
+
+add_definitions(-DQS_LOG_LINE_NUMBERS -DQHTTPSERVER_EXPORT)
+
+include(DependencyConfiguration)
+include(VersionConfiguration)
+include(NameConfiguration)
+include(utils)
+include(QtConfiguration)
+include(PlayerConfiguration)
+include(InputConfiguration)
+include(FindBreakpad)
+include(BreakpadSymbols)
+
+if(APPLE)
+  include(AppleConfiguration)
+elseif(WIN32)
+  include(Win32Configuration)
+elseif(UNIX AND (NOT APPLE))
+  include(LinuxConfiguration)
+endif(APPLE)
+
+if(CMAKE_COMPILER_IS_GNUCC)
+  include(GCCConfiguration)
+endif(CMAKE_COMPILER_IS_GNUCC)
+
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WARNINGS}")
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${WARNINGS}")
+
+add_subdirectory(external)
+add_subdirectory(src)
+
+include(CPackConfiguration)

+ 21 - 0
CMakeModules/AppleConfiguration.cmake

@@ -0,0 +1,21 @@
+find_library(FOUNDATION Foundation)
+find_library(APPKIT AppKit)
+find_library(IOKIT IOKit)
+find_library(COCOA Cocoa)
+find_Library(CARBON Carbon)
+find_library(SECURITY Security)
+
+set(OS_LIBS ${FOUNDATION} ${APPKIT} ${IOKIT} ${COCOA} ${SECURITY} ${CARBON} spmediakeytap)
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mmacosx-version-min=10.9")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mmacosx-version-min=10.9")
+set(WARNINGS "-Wall")
+
+set(HAVE_UPDATER 1)
+find_program(UPDATER_PATH updater HINTS ${CMAKE_FIND_ROOT_PATH}/update_installer/ NO_DEFAULT_PATH)
+if(${UPDATER_PATH} MATCHES "UPDATER_PATH-NOTFOUND")
+  set(HAVE_UPDATER 0)
+  message(STATUS "will build without the updater")
+endif(${UPDATER_PATH} MATCHES "UPDATER_PATH-NOTFOUND")
+
+set(INSTALL_BIN_DIR .)
+set(INSTALL_RESOURCE_DIR Contents/Resources)

+ 35 - 0
CMakeModules/BreakpadSymbols.cmake

@@ -0,0 +1,35 @@
+OPTION(GENERATE_SYMBOLS "Should we generate symbols for binaries?" ON)
+function(dumpsyms target symfile)
+  find_program(DUMP_SYMS dump_syms HINTS /usr/bin/ ${DEPENDENCY_ROOT}/bin)
+  if(GENERATE_SYMBOLS AND NOT DUMP_SYMS)
+    message(STATUS "dump_syms not found")
+  endif()
+  if(GENERATE_SYMBOLS AND DUMP_SYMS)
+
+    if(APPLE)
+      add_custom_command(TARGET ${target} POST_BUILD
+        COMMAND dsymutil -o ${MAIN_NAME}.dSYM $<TARGET_FILE:${MAIN_TARGET}>
+        COMMENT Generating ${MAIN_NAME}.dSYM
+        BYPRODUCTS ${MAIN_NAME}.dSYM/Contents/Resources/DWARF/${target} ${MAIN_NAME}.dSYM/Contents/Info.plist
+      )
+    endif(APPLE)
+
+    unset(COMPRESS)
+    find_program(COMPRESS_XZ xz)
+    find_program(COMPRESS_BZ bzip2)
+    if(COMPRESS_XZ)
+      set(COMPRESS_EXT xz)
+      set(COMPRESS ${COMPRESS_XZ})
+    elseif(COMPRESS_BZ)
+      set(COMPRESS_EXT bz2)
+      set(COMPRESS ${COMPRESS_BZ})
+    endif(COMPRESS_XZ)
+
+    add_custom_command(
+      TARGET ${target} POST_BUILD
+      BYPRODUCTS ${symfile}.${COMPRESS_EXT}
+      COMMAND ${CMAKE_SOURCE_DIR}/scripts/dump-syms.sh "${DUMP_SYMS}" "${COMPRESS}" "$<TARGET_FILE:${target}>" "${symfile}.${COMPRESS_EXT}"
+    )
+    install(FILES ${symfile}.${COMPRESS_EXT} DESTINATION ${CMAKE_BINARY_DIR})
+  endif(GENERATE_SYMBOLS AND DUMP_SYMS)
+endfunction()

+ 63 - 0
CMakeModules/CPackConfiguration.cmake

@@ -0,0 +1,63 @@
+set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Plex Media Player")
+set(CPACK_PACKAGE_VENDOR "Plex")
+set(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR})
+set(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR})
+set(CPACK_PACKAGE_VERSION_PATCH ${VERSION_NANO})
+
+if(APPLE)
+  set(CPACK_SYSTEM_NAME "macosx-x86_64")
+elseif(WIN32)
+  set(CPACK_SYSTEM_NAME "windows-x86")
+else()
+  set(CPACK_SYSTEM_NAME linux-${CMAKE_HOST_SYSTEM_PROCESSOR})
+endif()
+set(CPACK_PACKAGE_FILE_NAME "PlexMediaPlayer-${VERSION_STRING}-${CPACK_SYSTEM_NAME}")
+set(CPACK_SOURCE_PACKAGE_FILE_NAME "PlexMediaPlayer-${VERSION_STRING}-src")
+
+set(CPACK_PACKAGE_INSTALL_DIRECTORY "PlexMediaPlayer")
+set(CPACK_STRIP_FILES 1)
+
+set(CPACK_GENERATOR "ZIP")
+
+if(WIN32)
+	list(APPEND CPACK_GENERATOR "IFW")
+endif(WIN32)
+
+# config IFW
+set(CPACK_IFW_FRAMEWORK_VERSION 2.0.1)
+set(CPACK_IFW_PACKAGE_NAME "Plex Media Player")
+set(CPACK_IFW_PACKAGE_START_MENU_DIRECTORY "Plex Media Player")
+set(CPACK_IFW_PACKAGE_TITLE "Plex Media Player Installer")
+set(CPACK_IFW_PACKAGE_PUBLISHER "Plex")
+set(CPACK_IFW_PRODUCT_URL "https://plex.tv")
+set(CPACK_IFW_PACKAGE_ICON ${CMAKE_SOURCE_DIR}/bundle/win/Plex.ico)
+set(CPACK_IFW_PACKAGE_WINDOW_ICON ${CMAKE_SOURCE_DIR}/resources/images/icon.png)
+
+if(APPLE)
+  set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 0)
+endif(APPLE)
+
+configure_file(${CMAKE_SOURCE_DIR}/CMakeModules/CPackGeneratedConfig.cmake.in ${CMAKE_BINARY_DIR}/CPackGeneratedConfig.cmake)
+set(CPACK_PROJECT_CONFIG_FILE ${CMAKE_BINARY_DIR}/CPackGeneratedConfig.cmake)
+
+include(CPack)
+
+cpack_add_component(Core DISPLAY_NAME "Plex Media Player" DESCRIPTION "Plex Media Player (Core Application)" REQUIRED)
+
+if(WIN32)
+  FILE(TO_CMAKE_PATH ${DEPENDENCY_ROOT} tmp)
+  install(FILES ${tmp}/bin/mpv-1.dll DESTINATION .)
+  install(FILES ${tmp}/lib/SDL2.dll DESTINATION .)
+  install(FILES ${tmp}/lib/libcec.dll DESTINATION .)
+  if(IS_DIRECTORY ${CMAKE_BINARY_DIR}/extradlls)
+    file(GLOB EXTRADLLS ${CMAKE_BINARY_DIR}/extradlls/*.dll)
+    install(FILES ${EXTRADLLS} DESTINATION .)
+  endif()
+  install(FILES ${CMAKE_SOURCE_DIR}/bundle/win/qt.conf DESTINATION .)
+  install(FILES ${CMAKE_SOURCE_DIR}/bundle/win/PlexMediaPlayer-angle.bat DESTINATION .)
+  #add_custom_command(TARGET package POST_BUILD COMMAND ${CMAKE_SOURCE_DIR}/scripts/WindowsSign.cmd  ${CPACK_PACKAGE_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}.exe WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} )
+  # group/component configuration
+  message(STATUS configure IFW)
+  include(CPackIFW)
+  cpack_ifw_configure_component(Core PRIORITY 1 SCRIPT ${CMAKE_SOURCE_DIR}/bundle/win/shortcut.qs)
+endif(WIN32)

+ 3 - 0
CMakeModules/CPackGeneratedConfig.cmake.in

@@ -0,0 +1,3 @@
+if(CPACK_GENERATOR MATCHES "IFW")
+  set(CMAKE_EXECUTABLE_SUFFIX ".exe")
+endif()

+ 17 - 0
CMakeModules/CompleteBundle.cmake

@@ -0,0 +1,17 @@
+if(APPLE)
+  set(SCRIPT CompleteBundleOSX)
+elseif(WIN32)
+  set(SCRIPT CompleteBundleWin)
+endif(APPLE)
+
+option(CODE_SIGN "code sign the app" OFF)
+if(CODE_SIGN)
+  set(DO_SIGN 1)
+else(CODE_SIGN)
+  set(DO_SIGN 0)
+endif(CODE_SIGN)
+
+if(SCRIPT)
+  configure_file(${CMAKE_SOURCE_DIR}/CMakeModules/${SCRIPT}.cmake.in ${SCRIPT}.cmake @ONLY)
+  install(SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/${SCRIPT}.cmake)
+endif(SCRIPT)

+ 69 - 0
CMakeModules/CompleteBundleOSX.cmake.in

@@ -0,0 +1,69 @@
+set(app "@EXE@")
+
+list(APPEND BINS "Contents/Resources/updater")
+list(APPEND BINS "Contents/Resources/@HELPER_NAME@")
+
+set(args ${app})
+list(APPEND args "-verbose=2")
+list(APPEND args "-qmldir=@SOURCE_ROOT@/src/ui")
+foreach(BIN ${BINS})
+  list(APPEND args "-executable=${app}/${BIN}")
+endforeach(BIN ${BINS})
+
+execute_process(
+  COMMAND @QTROOT@/bin/macdeployqt ${args}
+  WORKING_DIRECTORY ${CMAKE_INSTALL_PREFIX}
+)
+
+#set(ENTITLEMENTS --entitlements @SOURCE_ROOT@/bundle/osx/Konvergo.entitlements)
+set(CODESIGN codesign ${ENTITLEMENTS} --force --sign "Developer ID Application: Plex Inc.")
+
+macro(sign_binary BIN)
+  message(STATUS "Signing: ${BIN}")
+  execute_process(
+    COMMAND ${CODESIGN} "${BIN}"
+    RESULT_VARIABLE result
+  )
+  if(NOT ${result} EQUAL 0)
+    message(FATAL_ERROR "Failed to sign ${BIN}")
+  endif(NOT ${result} EQUAL 0)
+endmacro(sign_binary BIN)
+
+if(@DO_SIGN@)
+
+  # we need to sign the webengine helper before the framework
+  # add --entitlements @SOURCE_ROOT@/bundle/osx/WebEngine.entitlements when we want to sandbox
+  set(WEB_PROC "${CMAKE_INSTALL_PREFIX}/${app}/Contents/Frameworks/QtWebEngineCore.framework/Versions/Current/Helpers/QtWebEngineProcess.app")
+  sign_binary(${WEB_PROC})
+
+  file(GLOB_RECURSE LIBS
+    FOLLOW_SYMLINKS
+    "${CMAKE_INSTALL_PREFIX}/${app}/*.dylib"
+  )
+  file(GLOB FRAMEWORKS FOLLOW_SYMLINKS LIST_DIRECTORIES true "${CMAKE_INSTALL_PREFIX}/${app}/Contents/Frameworks/*")
+  foreach(LIB ${LIBS} ${FRAMEWORKS})
+    sign_binary(${LIB})
+  endforeach(LIB ${LIBS})
+
+  foreach(BIN ${BINS})
+    sign_binary(${CMAKE_INSTALL_PREFIX}/${app}/${BIN})
+  endforeach(BIN ${BINS})
+
+  sign_binary(${CMAKE_INSTALL_PREFIX}/${app})
+
+  message("Verifing signature")
+  execute_process(
+    COMMAND codesign --verbose=4 --verify "${CMAKE_INSTALL_PREFIX}/@EXE@"
+    RESULT_VARIABLE result
+  )
+  if(NOT ${result} EQUAL 0)
+    message(FATAL_ERROR "Failed to verify binary!")
+  endif(NOT ${result} EQUAL 0)
+  execute_process(
+    COMMAND spctl --verbose=4 --assess --type execute "${CMAKE_INSTALL_PREFIX}/@EXE@"
+    RESULT_VARIABLE result
+  )
+  if(NOT ${result} EQUAL 0)
+    message(FATAL_ERROR "Failed to verify binary!")
+  endif(NOT ${result} EQUAL 0)
+endif(@DO_SIGN@)

+ 10 - 0
CMakeModules/CompleteBundleWin.cmake.in

@@ -0,0 +1,10 @@
+execute_process(COMMAND @QTROOT@/bin/windeployqt.exe --qmldir @SOURCE_ROOT@/src/ui ${CMAKE_INSTALL_PREFIX}/PlexMediaPlayer.exe)
+
+if(@DO_SIGN@)
+  file(GLOB_RECURSE EXES ${CMAKE_INSTALL_PREFIX}/*.exe ${CMAKE_INSTALL_PREFIX}/*.dll)
+  set(ENV{errorlevel} 1)
+  foreach(e ${EXES})
+    message("-- Signing: ${CMAKE_SOURCE_DIR}/scripts/WindowsSign.cmd ${e}")
+    execute_process(COMMAND ${CMAKE_SOURCE_DIR}/scripts/WindowsSign.cmd "${e}" RESULT_VARIABLE RES)
+  endforeach()
+endif()

+ 28 - 0
CMakeModules/DependencyConfiguration.cmake

@@ -0,0 +1,28 @@
+find_package(PkgConfig)
+option(DISABLE_BUNDLED_DEPS "Disable the bundled deps on certain platforms" OFF)
+
+if(APPLE AND NOT DISABLE_BUNDLED_DEPS)
+  set(DEFAULT_ROOT "${CMAKE_SOURCE_DIR}/dependencies/konvergo-depends-darwin-x86_64-release")
+  set(DEPENDENCY_ROOT ${DEFAULT_ROOT} CACHE PATH "Path where the deps are located")
+endif(APPLE AND NOT DISABLE_BUNDLED_DEPS)
+
+if(DEPENDENCY_ROOT)
+  message(STATUS "Going to use bundled deps in directory: ${DEPENDENCY_ROOT}")
+  set(CMAKE_FIND_ROOT_PATH ${DEPENDENCY_ROOT})
+  set(CMAKE_PREFIX_PATH ${DEPENDENCY_ROOT})
+  set(ENV{PKG_CONFIG_LIBDIR} ${CMAKE_FIND_ROOT_PATH}/lib/pkgconfig)
+  set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH TRUE)
+  include_directories(${CMAKE_FIND_ROOT_PATH}/include)
+else(DEPENDENCY_ROOT)
+  message(STATUS "Not using bundled deps")
+endif(DEPENDENCY_ROOT)
+
+find_package(Threads)
+
+# on windows we need to download the updater binary seperately
+if(WIN32)
+  file(DOWNLOAD https://nightlies.plex.tv/directdl/plex-dependencies/konvergo-qt/updater.exe ${CMAKE_BINARY_DIR}/updater.exe
+       SHOW_PROGRESS
+       EXPECTED_HASH SHA1=d3b4f70d6542fa42c8edd2b9b93fd0916bf20f07
+       TLS_VERIFY OFF)
+endif(WIN32)

+ 69 - 0
CMakeModules/FindBreakpad.cmake

@@ -0,0 +1,69 @@
+###############################################################################
+# CMake module to search for the mpv libraries.
+#
+# WARNING: This module is experimental work in progress.
+#
+# Based one FindVLC.cmake by:
+# Copyright (c) 2011 Michael Jansen <info@michael-jansen.biz>
+# Modified by Tobias Hieta <tobias@hieta.se>
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+#
+###############################################################################
+
+#
+### Global Configuration Section
+#
+SET(_BREAKPAD_REQUIRED_VARS BREAKPAD_INCLUDE_DIR BREAKPAD_LIBRARY)
+
+#
+### BREAKPAD uses pkgconfig.
+#
+if(PKG_CONFIG_FOUND)
+    pkg_check_modules(PC_BREAKPAD QUIET breakpad-client)
+endif(PKG_CONFIG_FOUND)
+
+#
+### Look for the include files.
+#
+find_path(
+    BREAKPAD_INCLUDE_DIR
+    NAMES google_breakpad/common/breakpad_types.h
+    PATH_SUFFIXES breakpad
+    HINTS
+        ${PC_BREAKPAD_INCLUDEDIR}
+        ${PC_BREAKPAD_INCLUDE_DIRS} # Unused for BREAKPAD but anyway
+    DOC "BREAKPAD include directory"
+    )
+mark_as_advanced(BREAKPAD_INCLUDE_DIR)
+set(BREAKPAD_INCLUDE_DIRS ${BREAKPAD_INCLUDE_DIR})
+
+#
+### Look for the libraries (BREAKPAD and BREAKPADsore)
+#
+find_library(
+    BREAKPAD_LIBRARY
+    NAMES breakpad_client
+    HINTS
+        ${PC_BREAKPAD_LIBDIR}
+        ${PC_BREAKPAD_LIBRARY_DIRS} # Unused for BREAKPAD but anyway
+    PATH_SUFFIXES lib${LIB_SUFFIX}
+    )
+get_filename_component(_BREAKPAD_LIBRARY_DIR ${BREAKPAD_LIBRARY} PATH)
+mark_as_advanced(BREAKPAD_LIBRARY)
+
+set(BREAKPAD_LIBRARY_DIRS _BREAKPAD_CORE_LIBRARY_DIR _BREAKPAD_LIBRARY_DIR)
+list(REMOVE_DUPLICATES BREAKPAD_LIBRARY_DIRS)
+mark_as_advanced(BREAKPAD_LIBRARY_DIRS)
+
+#
+### Check if everything was found and if the version is sufficient.
+#
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(
+    BREAKPAD
+    REQUIRED_VARS ${_BREAKPAD_REQUIRED_VARS}
+    VERSION_VAR BREAKPAD_VERSION_STRING
+    )
+

+ 26 - 0
CMakeModules/FindCEC.cmake

@@ -0,0 +1,26 @@
+if(CEC_INCLUDE_DIR)
+  # Already in cache, be silent
+  set(CEC_FIND_QUIETLY TRUE)
+endif(CEC_INCLUDE_DIR)
+
+if (PKG_CONFIG_FOUND)
+  pkg_check_modules(_CEC QUIET libcec>=2.0)
+endif (PKG_CONFIG_FOUND)
+
+Find_Path(CEC_INCLUDE_DIR
+  NAMES cec.h
+  PATHS /usr/include usr/local/include 
+  PATH_SUFFIXES libcec
+  HINTS ${_CEC_INCLUDEDIR}
+)
+
+Find_Library(CEC_LIBRARY
+  NAMES cec
+  PATHS /usr/lib usr/local/lib
+  HINTS ${_CEC_LIBDIR}
+)
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(CEC DEFAULT_MSG CEC_LIBRARY CEC_INCLUDE_DIR)
+
+

+ 17 - 0
CMakeModules/FindDL.cmake

@@ -0,0 +1,17 @@
+# - find where dlopen and friends are located.
+# DL_FOUND - system has dynamic linking interface available
+# DL_INCLUDE_DIR - where dlfcn.h is located.
+# DL_LIBRARIES - libraries needed to use dlopen
+
+include(CheckFunctionExists)
+
+find_path(DL_INCLUDE_DIR NAMES dlfcn.h)
+find_library(DL_LIBRARIES NAMES dl)
+if(DL_LIBRARIES)
+  set(DL_FOUND)
+else(DL_LIBRARIES)
+  check_function_exists(dlopen DL_FOUND)
+  # If dlopen can be found without linking in dl then dlopen is part
+  # of libc, so don't need to link extra libs.
+  set(DL_LIBRARIES "")
+endif(DL_LIBRARIES)

+ 73 - 0
CMakeModules/FindGLES2.cmake

@@ -0,0 +1,73 @@
+# Copyright (c) 2012, Guillermo A. Amaral B. (gamaral) <g@maral.me>.
+# All rights reserved.
+#
+# This file is part of Marshmallow Game Engine.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#    1. Redistributions of source code must retain the above copyright notice,
+#       this list of conditions and the following disclaimer.
+#
+#    2. Redistributions in binary form must reproduce the above copyright
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+# EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# The views and conclusions contained in the software and documentation are
+# those of the authors and should not be interpreted as representing official
+# policies, either expressed or implied, of the project as a whole.
+#
+###############################################################################
+# Find GLES2
+###############################################################################
+#
+#  GLES2_FOUND
+#  GLES2_INCLUDE_DIR
+#  GLES2_LIBRARY
+#
+###############################################################################
+
+find_path(GLES2_INCLUDE_DIR GLES2/gl2.h
+	HINTS $ENV{GLES2DIR}
+	PATH_SUFFIXES include
+	PATHS ~/Library/Frameworks
+	      /Library/Frameworks
+	      /usr/local
+	      /usr
+	      /usr/X11R6
+	      /opt/local
+	      /opt/vc
+	      /opt
+)
+
+find_library(GLES2_LIBRARY
+	GLESv2
+	HINTS $ENV{GLES2DIR}
+	PATH_SUFFIXES lib64 lib
+	PATHS ~/Library/Frameworks
+	      /Library/Frameworks
+	      /usr/local
+	      /usr
+	      /usr/X11R6
+	      /opt/local
+	      /opt/vc
+	      /opt
+)
+
+include(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(GLES2 DEFAULT_MSG GLES2_LIBRARY)
+
+mark_as_advanced(GLES2_LIBRARY GLES2_INCLUDE_DIR)
+
+set(OPENGL_FOUND ${GLES2_FOUND})

+ 311 - 0
CMakeModules/FindICU.cmake

@@ -0,0 +1,311 @@
+# This module can find the International Components for Unicode (ICU) Library
+#
+# Requirements:
+# - CMake >= 2.8.3 (for new version of find_package_handle_standard_args)
+#
+# The following variables will be defined for your use:
+#   - ICU_FOUND             : were all of your specified components found (include dependencies)?
+#   - ICU_INCLUDE_DIRS      : ICU include directory
+#   - ICU_LIBRARIES         : ICU libraries
+#   - ICU_VERSION           : complete version of ICU (x.y.z)
+#   - ICU_MAJOR_VERSION     : major version of ICU
+#   - ICU_MINOR_VERSION     : minor version of ICU
+#   - ICU_PATCH_VERSION     : patch version of ICU
+#   - ICU_<COMPONENT>_FOUND : were <COMPONENT> found? (FALSE for non specified component if it is not a dependency)
+#
+# For windows or non standard installation, define ICU_ROOT variable to point to the root installation of ICU. Two ways:
+#   - run cmake with -DICU_ROOT=<PATH>
+#   - define an environment variable with the same name before running cmake
+# With cmake-gui, before pressing "Configure":
+#   1) Press "Add Entry" button
+#   2) Add a new entry defined as:
+#     - Name: ICU_ROOT
+#     - Type: choose PATH in the selection list
+#     - Press "..." button and select the root installation of ICU
+#
+# Example Usage:
+#
+#   1. Copy this file in the root of your project source directory
+#   2. Then, tell CMake to search this non-standard module in your project directory by adding to your CMakeLists.txt:
+#     set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR})
+#   3. Finally call find_package() once, here are some examples to pick from
+#
+#   Require ICU 4.4 or later
+#     find_package(ICU 4.4 REQUIRED)
+#
+#   if(ICU_FOUND)
+#      include_directories(${ICU_INCLUDE_DIRS})
+#      add_executable(myapp myapp.c)
+#      target_link_libraries(myapp ${ICU_LIBRARIES})
+#   endif(ICU_FOUND)
+
+#=============================================================================
+# Copyright (c) 2011-2013, julp
+#
+# Distributed under the OSI-approved BSD License
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+#=============================================================================
+
+########## Private ##########
+if(NOT DEFINED ICU_PUBLIC_VAR_NS)
+    set(ICU_PUBLIC_VAR_NS "ICU")                          # Prefix for all ICU relative public variables
+endif(NOT DEFINED ICU_PUBLIC_VAR_NS)
+if(NOT DEFINED ICU_PRIVATE_VAR_NS)
+    set(ICU_PRIVATE_VAR_NS "_${ICU_PUBLIC_VAR_NS}")       # Prefix for all ICU relative internal variables
+endif(NOT DEFINED ICU_PRIVATE_VAR_NS)
+if(NOT DEFINED PC_ICU_PRIVATE_VAR_NS)
+    set(PC_ICU_PRIVATE_VAR_NS "_PC${ICU_PRIVATE_VAR_NS}") # Prefix for all pkg-config relative internal variables
+endif(NOT DEFINED PC_ICU_PRIVATE_VAR_NS)
+
+function(icudebug _VARNAME)
+    if(${ICU_PUBLIC_VAR_NS}_DEBUG)
+        if(DEFINED ${ICU_PUBLIC_VAR_NS}_${_VARNAME})
+            message("${ICU_PUBLIC_VAR_NS}_${_VARNAME} = ${${ICU_PUBLIC_VAR_NS}_${_VARNAME}}")
+        else(DEFINED ${ICU_PUBLIC_VAR_NS}_${_VARNAME})
+            message("${ICU_PUBLIC_VAR_NS}_${_VARNAME} = <UNDEFINED>")
+        endif(DEFINED ${ICU_PUBLIC_VAR_NS}_${_VARNAME})
+    endif(${ICU_PUBLIC_VAR_NS}_DEBUG)
+endfunction(icudebug)
+
+set(${ICU_PRIVATE_VAR_NS}_ROOT "")
+if(DEFINED ENV{ICU_ROOT})
+    set(${ICU_PRIVATE_VAR_NS}_ROOT "$ENV{ICU_ROOT}")
+endif(DEFINED ENV{ICU_ROOT})
+if (DEFINED ICU_ROOT)
+    set(${ICU_PRIVATE_VAR_NS}_ROOT "${ICU_ROOT}")
+endif(DEFINED ICU_ROOT)
+
+set(${ICU_PRIVATE_VAR_NS}_BIN_SUFFIXES )
+set(${ICU_PRIVATE_VAR_NS}_LIB_SUFFIXES )
+if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+    list(APPEND ${ICU_PRIVATE_VAR_NS}_BIN_SUFFIXES "bin64")
+    list(APPEND ${ICU_PRIVATE_VAR_NS}_LIB_SUFFIXES "lib64")
+endif(CMAKE_SIZEOF_VOID_P EQUAL 8)
+list(APPEND ${ICU_PRIVATE_VAR_NS}_BIN_SUFFIXES "bin")
+list(APPEND ${ICU_PRIVATE_VAR_NS}_LIB_SUFFIXES "lib")
+
+set(${ICU_PRIVATE_VAR_NS}_COMPONENTS )
+# <icu component name> <library name 1> ... <library name N>
+macro(icu_declare_component _NAME)
+    list(APPEND ${ICU_PRIVATE_VAR_NS}_COMPONENTS ${_NAME})
+    set("${ICU_PRIVATE_VAR_NS}_COMPONENTS_${_NAME}" ${ARGN})
+endmacro(icu_declare_component)
+
+icu_declare_component(data icudata)
+icu_declare_component(uc   icuuc)         # Common and Data libraries
+icu_declare_component(i18n icui18n icuin) # Internationalization library
+icu_declare_component(io   icuio ustdio)  # Stream and I/O Library
+icu_declare_component(le   icule)         # Layout library
+icu_declare_component(lx   iculx)         # Paragraph Layout library
+
+########## Public ##########
+set(${ICU_PUBLIC_VAR_NS}_FOUND TRUE)
+set(${ICU_PUBLIC_VAR_NS}_LIBRARIES )
+set(${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS )
+set(${ICU_PUBLIC_VAR_NS}_C_FLAGS "")
+set(${ICU_PUBLIC_VAR_NS}_CXX_FLAGS "")
+set(${ICU_PUBLIC_VAR_NS}_CPP_FLAGS "")
+set(${ICU_PUBLIC_VAR_NS}_C_SHARED_FLAGS "")
+set(${ICU_PUBLIC_VAR_NS}_CXX_SHARED_FLAGS "")
+set(${ICU_PUBLIC_VAR_NS}_CPP_SHARED_FLAGS "")
+foreach(${ICU_PRIVATE_VAR_NS}_COMPONENT ${${ICU_PRIVATE_VAR_NS}_COMPONENTS})
+    string(TOUPPER "${${ICU_PRIVATE_VAR_NS}_COMPONENT}" ${ICU_PRIVATE_VAR_NS}_UPPER_COMPONENT)
+    set("${ICU_PUBLIC_VAR_NS}_${${ICU_PRIVATE_VAR_NS}_UPPER_COMPONENT}_FOUND" FALSE) # may be done in the icu_declare_component macro
+endforeach(${ICU_PRIVATE_VAR_NS}_COMPONENT)
+
+# Check components
+if(NOT ${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS) # uc required at least
+    set(${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS uc)
+else(NOT ${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS)
+    list(APPEND ${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS uc)
+    list(REMOVE_DUPLICATES ${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS)
+    foreach(${ICU_PRIVATE_VAR_NS}_COMPONENT ${${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS})
+        if(NOT DEFINED ${ICU_PRIVATE_VAR_NS}_COMPONENTS_${${ICU_PRIVATE_VAR_NS}_COMPONENT})
+            message(FATAL_ERROR "Unknown ICU component: ${${ICU_PRIVATE_VAR_NS}_COMPONENT}")
+        endif(NOT DEFINED ${ICU_PRIVATE_VAR_NS}_COMPONENTS_${${ICU_PRIVATE_VAR_NS}_COMPONENT})
+    endforeach(${ICU_PRIVATE_VAR_NS}_COMPONENT)
+endif(NOT ${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS)
+
+# Includes
+find_path(
+    ${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS
+    NAMES unicode/utypes.h utypes.h
+    HINTS ${${ICU_PRIVATE_VAR_NS}_ROOT}
+    PATH_SUFFIXES "include"
+    DOC "Include directories for ICU"
+)
+
+if(${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS)
+    ########## <part to keep synced with tests/version/CMakeLists.txt> ##########
+    if(EXISTS "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/unicode/uvernum.h") # ICU >= 4
+        file(READ "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/unicode/uvernum.h" ${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS)
+    elseif(EXISTS "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/unicode/uversion.h") # ICU [2;4[
+        file(READ "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/unicode/uversion.h" ${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS)
+    elseif(EXISTS "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/unicode/utypes.h") # ICU [1.4;2[
+        file(READ "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/unicode/utypes.h" ${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS)
+    elseif(EXISTS "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/utypes.h") # ICU 1.3
+        file(READ "${${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS}/utypes.h" ${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS)
+    else()
+        message(FATAL_ERROR "ICU version header not found")
+    endif()
+
+    if(${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS MATCHES ".*# *define *ICU_VERSION *\"([0-9]+)\".*") # ICU 1.3
+        # [1.3;1.4[ as #define ICU_VERSION "3" (no patch version, ie all 1.3.X versions will be detected as 1.3.0)
+        set(${ICU_PUBLIC_VAR_NS}_MAJOR_VERSION "1")
+        set(${ICU_PUBLIC_VAR_NS}_MINOR_VERSION "${CMAKE_MATCH_1}")
+        set(${ICU_PUBLIC_VAR_NS}_PATCH_VERSION "0")
+    elseif(${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS MATCHES ".*# *define *U_ICU_VERSION_MAJOR_NUM *([0-9]+).*")
+        #
+        # Since version 4.9.1, ICU release version numbering was totaly changed, see:
+        # - http://site.icu-project.org/download/49
+        # - http://userguide.icu-project.org/design#TOC-Version-Numbers-in-ICU
+        #
+        set(${ICU_PUBLIC_VAR_NS}_MAJOR_VERSION "${CMAKE_MATCH_1}")
+        string(REGEX REPLACE ".*# *define *U_ICU_VERSION_MINOR_NUM *([0-9]+).*" "\\1" ${ICU_PUBLIC_VAR_NS}_MINOR_VERSION "${${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS}")
+        string(REGEX REPLACE ".*# *define *U_ICU_VERSION_PATCHLEVEL_NUM *([0-9]+).*" "\\1" ${ICU_PUBLIC_VAR_NS}_PATCH_VERSION "${${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS}")
+    elseif(${ICU_PRIVATE_VAR_NS}_VERSION_HEADER_CONTENTS MATCHES ".*# *define *U_ICU_VERSION *\"(([0-9]+)(\\.[0-9]+)*)\".*") # ICU [1.4;1.8[
+        # [1.4;1.8[ as #define U_ICU_VERSION "1.4.1.2" but it seems that some 1.4.1(?:\.\d)? have releasing error and appears as 1.4.0
+        set(${ICU_PRIVATE_VAR_NS}_FULL_VERSION "${CMAKE_MATCH_1}") # copy CMAKE_MATCH_1, no longer valid on the following if
+        if(${ICU_PRIVATE_VAR_NS}_FULL_VERSION MATCHES "^([0-9]+)\\.([0-9]+)$")
+            set(${ICU_PUBLIC_VAR_NS}_MAJOR_VERSION "${CMAKE_MATCH_1}")
+            set(${ICU_PUBLIC_VAR_NS}_MINOR_VERSION "${CMAKE_MATCH_2}")
+            set(${ICU_PUBLIC_VAR_NS}_PATCH_VERSION "0")
+        elseif(${ICU_PRIVATE_VAR_NS}_FULL_VERSION MATCHES "^([0-9]+)\\.([0-9]+)\\.([0-9]+)")
+            set(${ICU_PUBLIC_VAR_NS}_MAJOR_VERSION "${CMAKE_MATCH_1}")
+            set(${ICU_PUBLIC_VAR_NS}_MINOR_VERSION "${CMAKE_MATCH_2}")
+            set(${ICU_PUBLIC_VAR_NS}_PATCH_VERSION "${CMAKE_MATCH_3}")
+        endif()
+    else()
+        message(FATAL_ERROR "failed to detect ICU version")
+    endif()
+    set(${ICU_PUBLIC_VAR_NS}_VERSION "${${ICU_PUBLIC_VAR_NS}_MAJOR_VERSION}.${${ICU_PUBLIC_VAR_NS}_MINOR_VERSION}.${${ICU_PUBLIC_VAR_NS}_PATCH_VERSION}")
+    ########## </part to keep synced with tests/version/CMakeLists.txt> ##########
+
+    # Check dependencies (implies pkg-config)
+    if(PKG_CONFIG_FOUND)
+        set(${ICU_PRIVATE_VAR_NS}_COMPONENTS_DUP ${${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS})
+        foreach(${ICU_PRIVATE_VAR_NS}_COMPONENT ${${ICU_PRIVATE_VAR_NS}_COMPONENTS_DUP})
+            pkg_check_modules(PC_ICU_PRIVATE_VAR_NS "icu-${${ICU_PRIVATE_VAR_NS}_COMPONENT}" QUIET)
+
+            if(${PC_ICU_PRIVATE_VAR_NS}_FOUND)
+                foreach(${PC_ICU_PRIVATE_VAR_NS}_LIBRARY ${PC_ICU_LIBRARIES})
+                    string(REGEX REPLACE "^icu" "" ${PC_ICU_PRIVATE_VAR_NS}_STRIPPED_LIBRARY ${${PC_ICU_PRIVATE_VAR_NS}_LIBRARY})
+                    list(APPEND ${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS ${${PC_ICU_PRIVATE_VAR_NS}_STRIPPED_LIBRARY})
+                endforeach(${PC_ICU_PRIVATE_VAR_NS}_LIBRARY)
+            endif(${PC_ICU_PRIVATE_VAR_NS}_FOUND)
+        endforeach(${ICU_PRIVATE_VAR_NS}_COMPONENT)
+        list(REMOVE_DUPLICATES ${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS)
+    endif(PKG_CONFIG_FOUND)
+
+    # Check libraries
+    foreach(${ICU_PRIVATE_VAR_NS}_COMPONENT ${${ICU_PUBLIC_VAR_NS}_FIND_COMPONENTS})
+        set(${ICU_PRIVATE_VAR_NS}_POSSIBLE_RELEASE_NAMES )
+        set(${ICU_PRIVATE_VAR_NS}_POSSIBLE_DEBUG_NAMES )
+        foreach(${ICU_PRIVATE_VAR_NS}_BASE_NAME ${${ICU_PRIVATE_VAR_NS}_COMPONENTS_${${ICU_PRIVATE_VAR_NS}_COMPONENT}})
+            list(APPEND ${ICU_PRIVATE_VAR_NS}_POSSIBLE_RELEASE_NAMES "${${ICU_PRIVATE_VAR_NS}_BASE_NAME}")
+            list(APPEND ${ICU_PRIVATE_VAR_NS}_POSSIBLE_DEBUG_NAMES "${${ICU_PRIVATE_VAR_NS}_BASE_NAME}d")
+            list(APPEND ${ICU_PRIVATE_VAR_NS}_POSSIBLE_RELEASE_NAMES "${${ICU_PRIVATE_VAR_NS}_BASE_NAME}${ICU_MAJOR_VERSION}${ICU_MINOR_VERSION}")
+            list(APPEND ${ICU_PRIVATE_VAR_NS}_POSSIBLE_DEBUG_NAMES "${${ICU_PRIVATE_VAR_NS}_BASE_NAME}${ICU_MAJOR_VERSION}${ICU_MINOR_VERSION}d")
+        endforeach(${ICU_PRIVATE_VAR_NS}_BASE_NAME)
+
+        find_library(
+            ${ICU_PRIVATE_VAR_NS}_LIB_RELEASE_${${ICU_PRIVATE_VAR_NS}_COMPONENT}
+            NAMES ${${ICU_PRIVATE_VAR_NS}_POSSIBLE_RELEASE_NAMES}
+            HINTS ${${ICU_PRIVATE_VAR_NS}_ROOT}
+            PATH_SUFFIXES ${_ICU_LIB_SUFFIXES}
+            DOC "Release libraries for ICU"
+        )
+        find_library(
+            ${ICU_PRIVATE_VAR_NS}_LIB_DEBUG_${${ICU_PRIVATE_VAR_NS}_COMPONENT}
+            NAMES ${${ICU_PRIVATE_VAR_NS}_POSSIBLE_DEBUG_NAMES}
+            HINTS ${${ICU_PRIVATE_VAR_NS}_ROOT}
+            PATH_SUFFIXES ${_ICU_LIB_SUFFIXES}
+            DOC "Debug libraries for ICU"
+        )
+
+        string(TOUPPER "${${ICU_PRIVATE_VAR_NS}_COMPONENT}" ${ICU_PRIVATE_VAR_NS}_UPPER_COMPONENT)
+        if(NOT ${ICU_PRIVATE_VAR_NS}_LIB_RELEASE_${${ICU_PRIVATE_VAR_NS}_COMPONENT} AND NOT ${ICU_PRIVATE_VAR_NS}_LIB_DEBUG_${${ICU_PRIVATE_VAR_NS}_COMPONENT}) # both not found
+            set("${ICU_PUBLIC_VAR_NS}_${${ICU_PRIVATE_VAR_NS}_UPPER_COMPONENT}_FOUND" FALSE)
+            set("${ICU_PUBLIC_VAR_NS}_FOUND" FALSE)
+        else(NOT ${ICU_PRIVATE_VAR_NS}_LIB_RELEASE_${${ICU_PRIVATE_VAR_NS}_COMPONENT} AND NOT ${ICU_PRIVATE_VAR_NS}_LIB_DEBUG_${${ICU_PRIVATE_VAR_NS}_COMPONENT}) # one or both found
+            set("${ICU_PUBLIC_VAR_NS}_${${ICU_PRIVATE_VAR_NS}_UPPER_COMPONENT}_FOUND" TRUE)
+            if(NOT ${ICU_PRIVATE_VAR_NS}_LIB_RELEASE_${${ICU_PRIVATE_VAR_NS}_COMPONENT}) # release not found => we are in debug
+                set(${ICU_PRIVATE_VAR_NS}_LIB_${${ICU_PRIVATE_VAR_NS}_COMPONENT} "${${ICU_PRIVATE_VAR_NS}_LIB_DEBUG_${${ICU_PRIVATE_VAR_NS}_COMPONENT}}")
+            elseif(NOT ${ICU_PRIVATE_VAR_NS}_LIB_DEBUG_${${ICU_PRIVATE_VAR_NS}_COMPONENT}) # debug not found => we are in release
+                set(${ICU_PRIVATE_VAR_NS}_LIB_${${ICU_PRIVATE_VAR_NS}_COMPONENT} "${${ICU_PRIVATE_VAR_NS}_LIB_RELEASE_${${ICU_PRIVATE_VAR_NS}_COMPONENT}}")
+            else() # both found
+                set(
+                    ${ICU_PRIVATE_VAR_NS}_LIB_${${ICU_PRIVATE_VAR_NS}_COMPONENT}
+                    optimized ${${ICU_PRIVATE_VAR_NS}_LIB_RELEASE_${${ICU_PRIVATE_VAR_NS}_COMPONENT}}
+                    debug ${${ICU_PRIVATE_VAR_NS}_LIB_DEBUG_${${ICU_PRIVATE_VAR_NS}_COMPONENT}}
+                )
+            endif()
+            list(APPEND ${ICU_PUBLIC_VAR_NS}_LIBRARIES ${${ICU_PRIVATE_VAR_NS}_LIB_${${ICU_PRIVATE_VAR_NS}_COMPONENT}})
+        endif(NOT ${ICU_PRIVATE_VAR_NS}_LIB_RELEASE_${${ICU_PRIVATE_VAR_NS}_COMPONENT} AND NOT ${ICU_PRIVATE_VAR_NS}_LIB_DEBUG_${${ICU_PRIVATE_VAR_NS}_COMPONENT})
+    endforeach(${ICU_PRIVATE_VAR_NS}_COMPONENT)
+
+    # Try to find out compiler flags
+    find_program(${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE icu-config HINTS ${${ICU_PRIVATE_VAR_NS}_ROOT})
+    if(${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE)
+        execute_process(COMMAND ${${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE} --cflags OUTPUT_VARIABLE ${ICU_PUBLIC_VAR_NS}_C_FLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
+        execute_process(COMMAND ${${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE} --cxxflags OUTPUT_VARIABLE ${ICU_PUBLIC_VAR_NS}_CXX_FLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
+        execute_process(COMMAND ${${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE} --cppflags OUTPUT_VARIABLE ${ICU_PUBLIC_VAR_NS}_CPP_FLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+        execute_process(COMMAND ${${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE} --cflags-dynamic OUTPUT_VARIABLE ${ICU_PUBLIC_VAR_NS}_C_SHARED_FLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
+        execute_process(COMMAND ${${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE} --cxxflags-dynamic OUTPUT_VARIABLE ${ICU_PUBLIC_VAR_NS}_CXX_SHARED_FLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
+        execute_process(COMMAND ${${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE} --cppflags-dynamic OUTPUT_VARIABLE ${ICU_PUBLIC_VAR_NS}_CPP_SHARED_FLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
+    endif(${ICU_PUBLIC_VAR_NS}_CONFIG_EXECUTABLE)
+
+    # Check find_package arguments
+    include(FindPackageHandleStandardArgs)
+    if(${ICU_PUBLIC_VAR_NS}_FIND_REQUIRED AND NOT ${ICU_PUBLIC_VAR_NS}_FIND_QUIETLY)
+        find_package_handle_standard_args(
+            ${ICU_PUBLIC_VAR_NS}
+            REQUIRED_VARS ${ICU_PUBLIC_VAR_NS}_LIBRARIES ${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS
+            VERSION_VAR ${ICU_PUBLIC_VAR_NS}_VERSION
+        )
+    else(${ICU_PUBLIC_VAR_NS}_FIND_REQUIRED AND NOT ${ICU_PUBLIC_VAR_NS}_FIND_QUIETLY)
+        find_package_handle_standard_args(${ICU_PUBLIC_VAR_NS} "ICU not found" ${ICU_PUBLIC_VAR_NS}_LIBRARIES ${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS)
+    endif(${ICU_PUBLIC_VAR_NS}_FIND_REQUIRED AND NOT ${ICU_PUBLIC_VAR_NS}_FIND_QUIETLY)
+else(${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS)
+    if(${ICU_PUBLIC_VAR_NS}_FIND_REQUIRED AND NOT ${ICU_PUBLIC_VAR_NS}_FIND_QUIETLY)
+        message(FATAL_ERROR "Could not find ICU include directory")
+    endif(${ICU_PUBLIC_VAR_NS}_FIND_REQUIRED AND NOT ${ICU_PUBLIC_VAR_NS}_FIND_QUIETLY)
+endif(${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS)
+
+mark_as_advanced(
+    ${ICU_PUBLIC_VAR_NS}_INCLUDE_DIRS
+    ${ICU_PUBLIC_VAR_NS}_LIBRARIES
+)
+
+# IN (args)
+icudebug("FIND_COMPONENTS")
+icudebug("FIND_REQUIRED")
+icudebug("FIND_QUIETLY")
+icudebug("FIND_VERSION")
+# OUT
+# Found
+icudebug("FOUND")
+icudebug("UC_FOUND")
+icudebug("I18N_FOUND")
+icudebug("IO_FOUND")
+icudebug("LE_FOUND")
+icudebug("LX_FOUND")
+icudebug("DATA_FOUND")
+# Flags
+icudebug("C_FLAGS")
+icudebug("CPP_FLAGS")
+icudebug("CXX_FLAGS")
+icudebug("C_SHARED_FLAGS")
+icudebug("CPP_SHARED_FLAGS")
+icudebug("CXX_SHARED_FLAGS")
+# Linking
+icudebug("INCLUDE_DIRS")
+icudebug("LIBRARIES")
+# Version
+icudebug("MAJOR_VERSION")
+icudebug("MINOR_VERSION")
+icudebug("PATCH_VERSION")
+icudebug("VERSION")

+ 57 - 0
CMakeModules/FindIconv.cmake

@@ -0,0 +1,57 @@
+# - Try to find Iconv 
+# Once done this will define 
+# 
+#  ICONV_FOUND - system has Iconv 
+#  ICONV_INCLUDE_DIR - the Iconv include directory 
+#  ICONV_LIBRARIES - Link these to use Iconv 
+#  ICONV_SECOND_ARGUMENT_IS_CONST - the second argument for iconv() is const
+# 
+include(CheckCXXSourceCompiles)
+
+IF (ICONV_INCLUDE_DIR AND ICONV_LIBRARIES)
+  # Already in cache, be silent
+  SET(ICONV_FIND_QUIETLY TRUE)
+ENDIF (ICONV_INCLUDE_DIR AND ICONV_LIBRARIES)
+
+FIND_PATH(ICONV_INCLUDE_DIR iconv.h) 
+ 
+FIND_LIBRARY(ICONV_LIBRARIES NAMES iconv libiconv libiconv-2 c)
+ 
+IF(ICONV_INCLUDE_DIR AND ICONV_LIBRARIES) 
+   SET(ICONV_FOUND TRUE) 
+ENDIF(ICONV_INCLUDE_DIR AND ICONV_LIBRARIES) 
+
+set(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
+set(CMAKE_REQUIRED_LIBRARIES ${ICONV_LIBRARIES})
+IF(ICONV_FOUND)
+  check_cxx_source_compiles("
+  #include <iconv.h>
+  int main(){
+    iconv_t conv = 0;
+    const char* in = 0;
+    size_t ilen = 0;
+    char* out = 0;
+    size_t olen = 0;
+    iconv(conv, &in, &ilen, &out, &olen);
+    return 0;
+  }
+" ICONV_SECOND_ARGUMENT_IS_CONST )
+ENDIF(ICONV_FOUND)
+set(CMAKE_REQUIRED_INCLUDES)
+set(CMAKE_REQUIRED_LIBRARIES)
+
+IF(ICONV_FOUND) 
+  IF(NOT ICONV_FIND_QUIETLY) 
+    MESSAGE(STATUS "Found Iconv: ${ICONV_LIBRARIES}") 
+  ENDIF(NOT ICONV_FIND_QUIETLY) 
+ELSE(ICONV_FOUND) 
+  IF(Iconv_FIND_REQUIRED) 
+    MESSAGE(FATAL_ERROR "Could not find Iconv") 
+  ENDIF(Iconv_FIND_REQUIRED) 
+ENDIF(ICONV_FOUND)
+
+MARK_AS_ADVANCED(
+  ICONV_INCLUDE_DIR
+  ICONV_LIBRARIES
+  ICONV_SECOND_ARGUMENT_IS_CONST
+)

+ 80 - 0
CMakeModules/FindMPV.cmake

@@ -0,0 +1,80 @@
+###############################################################################
+# CMake module to search for the mpv libraries.
+#
+# WARNING: This module is experimental work in progress.
+#
+# Based one FindVLC.cmake by:
+# Copyright (c) 2011 Michael Jansen <info@michael-jansen.biz>
+# Modified by Tobias Hieta <tobias@hieta.se>
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+#
+###############################################################################
+
+#
+### Global Configuration Section
+#
+SET(_MPV_REQUIRED_VARS MPV_INCLUDE_DIR MPV_LIBRARY)
+
+#
+### MPV uses pkgconfig.
+#
+if(PKG_CONFIG_FOUND)
+    pkg_check_modules(PC_MPV QUIET mpv)
+endif(PKG_CONFIG_FOUND)
+
+if(PC_MPV_FOUND)
+  #
+  ### Look for the include files.
+  #
+  find_path(
+      MPV_INCLUDE_DIR
+      NAMES mpv/client.h
+      HINTS
+          ${PC_MPV_INCLUDEDIR}
+          ${PC_MPV_INCLUDE_DIRS} # Unused for MPV but anyway
+      DOC "MPV include directory"
+      )
+
+  #
+  ### Look for the libraries
+  #
+  set(_MPV_LIBRARY_NAMES mpv)
+  if(PC_MPV_LIBRARIES)
+    set(_MPV_LIBRARY_NAMES ${PC_MPV_LIBRARIES})
+  endif(PC_MPV_LIBRARIES)
+
+  foreach(l ${_MPV_LIBRARY_NAMES})
+    find_library(
+        MPV_LIBRARY_${l}
+        NAMES ${l}
+        HINTS
+            ${PC_MPV_LIBDIR}
+            ${PC_MPV_LIBRARY_DIRS} # Unused for MPV but anyway
+        PATH_SUFFIXES lib${LIB_SUFFIX}
+    )
+    list(APPEND MPV_LIBRARY ${MPV_LIBRARY_${l}})
+  endforeach()
+  get_filename_component(_MPV_LIBRARY_DIR ${MPV_LIBRARY_mpv} PATH)
+  mark_as_advanced(MPV_LIBRARY)
+
+  set(MPV_LIBRARY_DIRS _MPV_LIBRARY_DIR)
+  list(REMOVE_DUPLICATES MPV_LIBRARY_DIRS)
+
+endif()
+
+mark_as_advanced(MPV_INCLUDE_DIR)
+mark_as_advanced(MPV_LIBRARY_DIRS)
+set(MPV_INCLUDE_DIRS ${MPV_INCLUDE_DIR})
+
+#
+### Check if everything was found and if the version is sufficient.
+#
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(
+    MPV
+    REQUIRED_VARS ${_MPV_REQUIRED_VARS}
+    VERSION_VAR MPV_VERSION_STRING
+    )
+

+ 69 - 0
CMakeModules/FindSDL2.cmake

@@ -0,0 +1,69 @@
+###############################################################################
+# CMake module to search for the SDL libraries.
+#
+# WARNING: This module is experimental work in progress.
+#
+# Based one FindVLC.cmake by:
+# Copyright (c) 2011 Michael Jansen <info@michael-jansen.biz>
+# Modified by Tobias Hieta <tobias@hieta.se>
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+#
+###############################################################################
+
+#
+### Global Configuration Section
+#
+SET(_SDL2_REQUIRED_VARS SDL2_INCLUDE_DIR SDL2_LIBRARY)
+
+#
+### SDL uses pkgconfig.
+#
+if(PKG_CONFIG_FOUND)
+    pkg_check_modules(PC_SDL QUIET sdl2)
+endif(PKG_CONFIG_FOUND)
+
+#
+### Look for the include files.
+#
+find_path(
+    SDL2_INCLUDE_DIR
+    NAMES SDL.h
+    PATH_SUFFIXES SDL2
+    HINTS
+        ${PC_SDL2_INCLUDEDIR}
+        ${PC_SDL2_INCLUDE_DIRS} # Unused for SDL but anyway
+    DOC "SDL2 include directory"
+    )
+mark_as_advanced(SDL2_INCLUDE_DIR)
+set(SDL2_INCLUDE_DIRS ${SDL_INCLUDE_DIR})
+
+#
+### Look for the libraries (SDL and SDLsore)
+#
+find_library(
+    SDL2_LIBRARY
+    NAMES SDL2
+    HINTS
+        ${PC_SDL2_LIBDIR}
+        ${PC_SDL2_LIBRARY_DIRS} # Unused for SDL but anyway
+    PATH_SUFFIXES lib${LIB_SUFFIX}
+    )
+get_filename_component(_SDL2_LIBRARY_DIR "${SDL2_LIBRARY}" PATH)
+mark_as_advanced(SDL2_LIBRARY)
+
+set(SDL2_LIBRARY_DIRS _SDL2_LIBRARY_DIR)
+list(REMOVE_DUPLICATES SDL2_LIBRARY_DIRS)
+mark_as_advanced(SDL2_LIBRARY_DIRS)
+
+#
+### Check if everything was found and if the version is sufficient.
+#
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(
+    SDL2
+    REQUIRED_VARS ${_SDL2_REQUIRED_VARS}
+    VERSION_VAR SDL2_VERSION_STRING
+    )
+

+ 0 - 0
CMakeModules/GCCConfiguration.cmake


+ 13 - 0
CMakeModules/GetDate.cmake

@@ -0,0 +1,13 @@
+MACRO (TODAY RESULT) 
+    IF (WIN32) 
+        #EXECUTE_PROCESS(COMMAND "cmd" " /C date /T" OUTPUT_VARIABLE ${RESULT})
+        #string(REGEX REPLACE "(..)/(..)/(....).*" "\\3\\2\\1" ${RESULT} ${${RESULT}})
+        set(${RESULT})
+    ELSEIF(UNIX) 
+        EXECUTE_PROCESS(COMMAND "date" "+%d/%m/%Y" OUTPUT_VARIABLE ${RESULT}) 
+        string(REGEX REPLACE "(..)/(..)/(....).*" "\\3\\2\\1" ${RESULT} ${${RESULT}}) 
+    ELSE (WIN32) 
+        MESSAGE(SEND_ERROR "date not implemented") 
+        SET(${RESULT} 000000) 
+    ENDIF (WIN32) 
+ENDMACRO (TODAY) 

+ 123 - 0
CMakeModules/GetGitRevisionDescription.cmake

@@ -0,0 +1,123 @@
+# - Returns a version string from Git
+#
+# These functions force a re-configure on each git commit so that you can
+# trust the values of the variables in your build system.
+#
+#  get_git_head_revision(<refspecvar> <hashvar> [<additional arguments to git describe> ...])
+#
+# Returns the refspec and sha hash of the current head revision
+#
+#  git_describe(<var> [<additional arguments to git describe> ...])
+#
+# Returns the results of git describe on the source tree, and adjusting
+# the output so that it tests false if an error occurs.
+#
+#  git_get_exact_tag(<var> [<additional arguments to git describe> ...])
+#
+# Returns the results of git describe --exact-match on the source tree,
+# and adjusting the output so that it tests false if there was no exact
+# matching tag.
+#
+# Requires CMake 2.6 or newer (uses the 'function' command)
+#
+# Original Author:
+# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net>
+# http://academic.cleardefinition.com
+# Iowa State University HCI Graduate Program/VRAC
+#
+# Copyright Iowa State University 2009-2010.
+# Distributed under the Boost Software License, Version 1.0.
+# (See accompanying file LICENSE_1_0.txt or copy at
+# http://www.boost.org/LICENSE_1_0.txt)
+
+if(__get_git_revision_description)
+	return()
+endif()
+set(__get_git_revision_description YES)
+
+# We must run the following at "include" time, not at function call time,
+# to find the path to this module rather than the path to a calling list file
+get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
+
+function(get_git_head_revision _refspecvar _hashvar)
+	set(GIT_PARENT_DIR "${CMAKE_SOURCE_DIR}")
+	set(GIT_DIR "${GIT_PARENT_DIR}/.git")
+	while(NOT EXISTS "${GIT_DIR}")	# .git dir not found, search parent directories
+		set(GIT_PREVIOUS_PARENT "${GIT_PARENT_DIR}")
+		get_filename_component(GIT_PARENT_DIR ${GIT_PARENT_DIR} PATH)
+		if(GIT_PARENT_DIR STREQUAL GIT_PREVIOUS_PARENT)
+			# We have reached the root directory, we are not in git
+			set(${_refspecvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
+			set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
+			return()
+		endif()
+		set(GIT_DIR "${GIT_PARENT_DIR}/.git")
+	endwhile()
+	set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data")
+	if(NOT EXISTS "${GIT_DATA}")
+		file(MAKE_DIRECTORY "${GIT_DATA}")
+	endif()
+
+	if(NOT EXISTS "${GIT_DIR}/HEAD")
+		return()
+	endif()
+	set(HEAD_FILE "${GIT_DATA}/HEAD")
+	configure_file("${GIT_DIR}/HEAD" "${HEAD_FILE}" COPYONLY)
+
+	configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in"
+		"${GIT_DATA}/grabRef.cmake"
+		@ONLY)
+	include("${GIT_DATA}/grabRef.cmake")
+
+	set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE)
+	set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE)
+endfunction()
+
+function(git_describe _var)
+	if(NOT GIT_FOUND)
+		find_package(Git QUIET)
+	endif()
+	get_git_head_revision(refspec hash)
+	if(NOT GIT_FOUND)
+		set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
+		return()
+	endif()
+	if(NOT hash)
+		set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
+		return()
+	endif()
+
+	# TODO sanitize
+	#if((${ARGN}" MATCHES "&&") OR
+	#	(ARGN MATCHES "||") OR
+	#	(ARGN MATCHES "\\;"))
+	#	message("Please report the following error to the project!")
+	#	message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
+	#endif()
+
+	#message(STATUS "Arguments to execute_process: ${ARGN}")
+
+	execute_process(COMMAND
+		"${GIT_EXECUTABLE}"
+		describe
+		${hash}
+		${ARGN}
+		WORKING_DIRECTORY
+		"${CMAKE_SOURCE_DIR}"
+		RESULT_VARIABLE
+		res
+		OUTPUT_VARIABLE
+		out
+		ERROR_QUIET
+		OUTPUT_STRIP_TRAILING_WHITESPACE)
+	if(NOT res EQUAL 0)
+		set(out "${out}-${res}-NOTFOUND")
+	endif()
+
+	set(${_var} "${out}" PARENT_SCOPE)
+endfunction()
+
+function(git_get_exact_tag _var)
+	git_describe(out --exact-match ${ARGN})
+	set(${_var} "${out}" PARENT_SCOPE)
+endfunction()

+ 38 - 0
CMakeModules/GetGitRevisionDescription.cmake.in

@@ -0,0 +1,38 @@
+# 
+# Internal file for GetGitRevisionDescription.cmake
+#
+# Requires CMake 2.6 or newer (uses the 'function' command)
+#
+# Original Author:
+# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net>
+# http://academic.cleardefinition.com
+# Iowa State University HCI Graduate Program/VRAC
+#
+# Copyright Iowa State University 2009-2010.
+# Distributed under the Boost Software License, Version 1.0.
+# (See accompanying file LICENSE_1_0.txt or copy at
+# http://www.boost.org/LICENSE_1_0.txt)
+
+set(HEAD_HASH)
+
+file(READ "@HEAD_FILE@" HEAD_CONTENTS LIMIT 1024)
+
+string(STRIP "${HEAD_CONTENTS}" HEAD_CONTENTS)
+if(HEAD_CONTENTS MATCHES "ref")
+	# named branch
+	string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}")
+	if(EXISTS "@GIT_DIR@/${HEAD_REF}")
+		configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY)
+	elseif(EXISTS "@GIT_DIR@/logs/${HEAD_REF}")
+		configure_file("@GIT_DIR@/logs/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY)
+		set(HEAD_HASH "${HEAD_REF}")
+	endif()
+else()
+	# detached HEAD
+	configure_file("@GIT_DIR@/HEAD" "@GIT_DATA@/head-ref" COPYONLY)
+endif()
+
+if(NOT HEAD_HASH)
+	file(READ "@GIT_DATA@/head-ref" HEAD_HASH LIMIT 1024)
+	string(STRIP "${HEAD_HASH}" HEAD_HASH)
+endif()

+ 71 - 0
CMakeModules/InputConfiguration.cmake

@@ -0,0 +1,71 @@
+OPTION(ENABLE_SDL2 "Enable SDL2 for joystick handling" ON)
+if(ENABLE_SDL2)
+  find_package(SDL2)
+  if(SDL2_FOUND)
+    list(APPEND ENABLED_INPUTS SDL2)
+
+    if(NOT WIN32)
+      find_package(Iconv)
+
+      if(NOT ICONV_FOUND)
+        unset(SDL2_FOUND)
+      endif(NOT ICONV_FOUND)
+
+      find_package(DL)
+
+      if(NOT DL_FOUND)
+        unset(SDL2_FOUND)
+      endif(NOT DL_FOUND)
+
+      list(APPEND SDL2_LIBRARY ${ICONV_LIBRARIES} ${DL_LIBRARIES})
+    endif()
+
+    if(APPLE)
+      find_package(Iconv)
+
+      if(NOT ICONV_FOUND)
+        unset(SDL2_FOUND)
+      endif(NOT ICONV_FOUND)
+
+      list(APPEND SDL2_LIBRARY ${ICONV_LIBRARIES})
+      find_library(FORCEFEEDBACK ForceFeedback)
+      find_library(CARBON Carbon)
+      list(APPEND SDL2_LIBRARY ${FORCEFEEDBACK} ${CARBON})
+    endif(APPLE)
+
+    if(SDL2_FOUND)
+      add_definitions(-DHAVE_SDL)
+      include_directories(${SDL2_INCLUDE_DIR})
+      set(EXTRA_LIBS ${SDL2_LIBRARY})
+    endif(SDL2_FOUND)
+
+  endif(SDL2_FOUND)
+
+endif(ENABLE_SDL2)
+
+OPTION(ENABLE_CEC "Enable HDMI/CEC support with libCEC" ON)
+if(ENABLE_CEC)
+  find_package(CEC)
+  if(CEC_FOUND)
+    list(APPEND ENABLED_INPUTS CEC)
+    add_definitions(-DHAVE_CEC)
+    include_directories(${CEC_INCLUDE_DIR})
+    set(EXTRA_LIBS ${EXTRA_LIBS} ${CEC_LIBRARY})
+  endif(CEC_FOUND)
+
+endif(ENABLE_CEC)
+
+if(UNIX AND NOT APPLE)
+  OPTION(ENABLE_LIRC "Enable LIRC for Linux IR handling" ON)
+  if(ENABLE_LIRC)
+    list(APPEND ENABLED_INPUTS LIRC)
+    add_definitions(-DHAVE_LIRC)
+  endif(ENABLE_LIRC)
+endif(UNIX AND NOT APPLE)
+
+if(APPLE)
+  list(APPEND ENABLED_INPUTS "AppleRemote")
+endif(APPLE)
+
+string(REPLACE ";" " " _STR "${ENABLED_INPUTS}")
+message(STATUS "Enabled Inputs: " ${_STR})

+ 14 - 0
CMakeModules/LinuxConfiguration.cmake

@@ -0,0 +1,14 @@
+find_package(X11)
+if(X11_FOUND AND X11_Xrandr_FOUND)
+  include_directories(X11_X11_INCLUDE_PATH X11_Xrandr_INCLUDE_PATH)
+  set(X11XRANDR_FOUND 1)
+  add_definitions(-DUSE_X11XRANDR)
+endif()
+
+if (NOT BUILD_TARGET STREQUAL "RPI")
+  set(USE_X11POWER ON)
+  add_definitions(-DUSE_X11POWER)
+endif()
+
+set(INSTALL_BIN_DIR bin)
+set(INSTALL_RESOURCE_DIR share)

+ 16 - 0
CMakeModules/NameConfiguration.cmake

@@ -0,0 +1,16 @@
+set(HELPER_TARGET PMPHelper)
+set(MAIN_TARGET PlexMediaPlayer)
+
+# Name of the output binary, defaults are only used on Linux
+set(HELPER_NAME pmphelper)
+set(MAIN_NAME plexmediaplayer)
+
+if(APPLE)
+  set(HELPER_NAME "PMP Helper")
+  set(MAIN_NAME "Plex Media Player")
+elseif(WIN32)
+  set(HELPER_NAME "PMPHelper")
+  set(MAIN_NAME "PlexMediaPlayer")
+endif(APPLE)
+
+configure_file(src/shared/Names.cpp.in src/shared/Names.cpp @ONLY)

+ 16 - 0
CMakeModules/PlayerConfiguration.cmake

@@ -0,0 +1,16 @@
+# We want OpenGL or OpenGLES2
+find_package(OpenGL)
+if(NOT OPENGL_FOUND)
+  find_package(GLES2)
+  if(NOT GLES2_FOUND)
+    message(FATAL_ERROR "OpenGL or GLES2 is required")
+  else(NOT GLES2_FOUND)
+    set(OPENGL_LIBS ${GLES2_LIBRARY})
+  endif(NOT GLES2_FOUND)
+else(NOT OPENGL_FOUND)
+  set(OPENGL_LIBS ${OPENGL_gl_LIBRARY})
+endif(NOT OPENGL_FOUND)
+
+find_package(MPV REQUIRED)
+
+include_directories(${MPV_INCLUDE_DIR})

+ 57 - 0
CMakeModules/QtConfiguration.cmake

@@ -0,0 +1,57 @@
+set(QTROOT "/usr/local/Qt/Qt5.5" CACHE PATH "Root of the QT binaries.")
+set(REQUIRED_QT_VERSION "5.5.0")
+
+set(QTCONFIGROOT ${QTROOT}/lib/cmake/Qt5)
+set(components Core Network WebChannel Qml Quick Xml WebEngine)
+
+if(OPENELEC)
+  set(components ${components} DBus)
+endif(OPENELEC)
+
+foreach(COMP ${components})
+	set(mod Qt5${COMP})
+	
+	# look for the config files in the QtConfigRoot defined above
+	set(${mod}_DIR ${QTCONFIGROOT}${COMP})
+
+	# look for the actual package
+	find_package(${mod} ${REQUIRED_QT_VERSION} REQUIRED)
+
+	include_directories(${${mod}_INCLUDE_DIRS})
+	if(OPENELEC)
+		include_directories(${${mod}_PRIVATE_INCLUDE_DIRS})
+	endif(OPENELEC)
+
+	list(APPEND QT5_LIBRARIES ${${mod}_LIBRARIES})
+	list(APPEND QT5_CFLAGS ${${mod}_EXECUTABLE_COMPILE_FLAGS})
+endforeach(COMP ${components})
+
+list(REMOVE_DUPLICATES QT5_CFLAGS)
+
+message(STATUS "Qt version: ${Qt5Core_VERSION_STRING}")
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${QT5_CFLAGS}")
+
+set(CMAKE_REQUIRED_INCLUDES ${Qt5WebEngine_INCLUDE_DIRS};${Qt5WebEngine_PRIVATE_INCLUDE_DIRS})
+set(CMAKE_REQUIRED_LIBRARIES ${QT5_LIBRARIES})
+
+OPTION(SKIP_QT_TEST "Skip tests for required Qt features" OFF)
+
+if(NOT SKIP_QT_TEST)
+	include(CheckCXXSourceCompiles)
+        check_cxx_source_compiles("
+                #include <private/qquickwebengineview_p.h>
+                #include <QColor>
+                int main()
+                {
+                QQuickWebEngineView* view = new QQuickWebEngineView(NULL);
+                view->setBackgroundColor(QColor(\"transparent\"));
+                }
+	" WebEngineBackgroundProperty)
+
+	if(NOT WebEngineBackgroundProperty)
+		message(FATAL_ERROR "QQuickWebEngineView doesn't have the background property."
+			"This will break video playback. As of Qt 5.5 you need to manually patch and build Qt to get this property."
+			"With the release of Qt5.6 it will no longer be required. See qt-patches/README for more details.")
+	endif(NOT WebEngineBackgroundProperty)
+
+endif(NOT SKIP_QT_TEST)

+ 30 - 0
CMakeModules/VersionConfiguration.cmake

@@ -0,0 +1,30 @@
+# Get the current date.
+include(GetDate)
+include(WebClientVariables)
+today(CURRENT_DATE)
+
+# Get git revision version
+include(GetGitRevisionDescription)
+get_git_head_revision(REFSPEC FULL_GIT_REVISION)
+if(FULL_GIT_REVISION STREQUAL "GITDIR-NOTFOUND")
+  set(GIT_REVISION "git")
+else(FULL_GIT_REVISION STREQUAL "GITDIR-NOTFOUND")
+  string(SUBSTRING ${FULL_GIT_REVISION} 0 8 GIT_REVISION)
+endif(FULL_GIT_REVISION STREQUAL "GITDIR-NOTFOUND")
+
+# Get the build number if available
+if(DEFINED ENV{BUILD_NUMBER})
+  set(VERSION_BUILD "$ENV{BUILD_NUMBER}")
+  set(VERSION_BUILD_NR "$ENV{BUILD_NUMBER}")
+else()
+  set(VERSION_BUILD "dev")
+  set(VERSION_BUILD_NR "0")
+endif()
+
+set(VERSION_MAJOR 1)
+set(VERSION_MINOR 0)
+set(VERSION_NANO 0)
+
+set(VERSION_STRING "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_NANO}.${VERSION_BUILD}-${GIT_REVISION}")
+set(CANONICAL_VERSION_STRING "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_NANO}-${GIT_REVISION}")
+configure_file(src/Version.cpp.in src/Version.cpp)

+ 36 - 0
CMakeModules/WebClientResources.cmake

@@ -0,0 +1,36 @@
+include(WebClientVariables)
+
+option(SKIP_WEB_CLIENT "Skip downloading the web client" OFF)
+
+if(NOT SKIP_WEB_CLIENT)
+  set(WEB_CLIENT_CPP web-client-${WEB_CLIENT_VERSION}.cpp)
+  set(WEB_CLIENT_URL https://nightlies.plex.tv/directdl/plex-web-client-plexmediaplayer/master/plex-web-client-konvergo-${WEB_CLIENT_VERSION}.cpp.bz2)
+
+  message(STATUS "web-client version: ${WEB_CLIENT_VERSION}")
+
+  file(
+    DOWNLOAD ${WEB_CLIENT_URL} ${CMAKE_CURRENT_BINARY_DIR}/${WEB_CLIENT_CPP}.bz2
+    EXPECTED_HASH SHA1=${WEB_CLIENT_HASH}
+    TIMEOUT 100
+    SHOW_PROGRESS
+    TLS_VERIFY ON
+  )
+
+  find_program(BUNZIP2 bunzip2${CMAKE_EXECUTABLE_SUFFIX})
+  if(${BUNZIP2} MATCHES NOT_FOUND)
+    message(FATAL_ERROR "Can't fid bunzip2")
+  endif(${BUNZIP2} MATCHES NOT_FOUND)
+
+  add_custom_command(
+    OUTPUT ${WEB_CLIENT_CPP}
+    COMMAND ${BUNZIP2} -k -f ${CMAKE_CURRENT_BINARY_DIR}/${WEB_CLIENT_CPP}.bz2
+    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${WEB_CLIENT_CPP}.bz2
+    COMMENT "Unpacking: ${WEB_CLIENT_CPP}.bz2"
+  )
+
+  add_custom_target(UnpackWebClientResource
+    DEPENDS ${WEB_CLIENT_CPP}
+  )
+else(NOT SKIP_WEB_CLIENT)
+  message(WARNING "Skipping web-client, you will not a functioning end product")
+endif(NOT SKIP_WEB_CLIENT)

+ 2 - 0
CMakeModules/WebClientVariables.cmake

@@ -0,0 +1,2 @@
+set(WEB_CLIENT_VERSION a1def70)
+set(WEB_CLIENT_HASH 16d2ef0a5b46fb6746aed6d3f3f7234d463f2c36)

+ 14 - 0
CMakeModules/Win32Configuration.cmake

@@ -0,0 +1,14 @@
+set(INSTALL_BIN_DIR .)
+set(INSTALL_RESOURCE_DIR resources)
+set(HAVE_UPDATER 1)
+
+
+# Add install rules for required system runtimes such as MSVCRxx.dll
+SET (CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_SKIP ON)
+INCLUDE(InstallRequiredSystemLibraries)
+IF (CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS)
+  INSTALL(FILES ${CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS}
+    DESTINATION ${INSTALL_BIN_DIR}
+    PERMISSIONS OWNER_WRITE OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ
+    COMPONENT Runtime)
+ENDIF (CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS)

+ 70 - 0
CMakeModules/utils.cmake

@@ -0,0 +1,70 @@
+#############################################################
+function(set_bundle_dir)
+  set(args SOURCES DEST EXCLUDE)
+  include(CMakeParseArguments)
+  cmake_parse_arguments(BD "" "" "${args}" ${ARGN})
+
+  foreach(_BDIR ${BD_SOURCES}) 
+    file(GLOB _DIRCONTENTS ${_BDIR}/*)
+    foreach(_BDFILE ${_DIRCONTENTS})
+      get_filename_component(_BDFILE_NAME ${_BDFILE} NAME)
+
+      set(PROCESS_FILE 1)
+      foreach(EX_FILE ${BD_EXCLUDE})
+        string(REGEX MATCH ${EX_FILE} DID_MATCH ${_BDFILE})
+        if(NOT "${DID_MATCH}" STREQUAL "")
+          set(PROCESS_FILE 0)
+        endif(NOT "${DID_MATCH}" STREQUAL "")
+      endforeach(EX_FILE ${BD_EXCLUDE})
+      
+      if(PROCESS_FILE STREQUAL "1")
+        if(IS_DIRECTORY ${_BDFILE})
+          set_bundle_dir(SOURCES ${_BDFILE} DEST ${BD_DEST}/${_BDFILE_NAME} EXCLUDE ${BD_EXCLUDE})
+        else(IS_DIRECTORY ${_BDFILE})
+          #message("set_bundle_dir : setting package_location ${_BDFILE} = ${BD_DEST}")
+          set_source_files_properties(${_BDFILE} PROPERTIES MACOSX_PACKAGE_LOCATION ${BD_DEST})
+          get_property(BUNDLED_FILES GLOBAL PROPERTY CONFIG_BUNDLED_FILES)
+          set_property(GLOBAL PROPERTY CONFIG_BUNDLED_FILES ${BUNDLED_FILES} ${_BDFILE})
+
+          string(REPLACE "/" "\\\\" GNAME ${BD_DEST})
+          source_group(${GNAME} FILES ${_BDFILE})
+        endif(IS_DIRECTORY ${_BDFILE})
+      endif()
+    endforeach(_BDFILE ${_DIRCONTENTS})
+  endforeach(_BDIR ${BD_SOURCES})
+endfunction(set_bundle_dir)
+
+#############################################################
+macro(find_all_sources DIRECTORY VARIABLE)
+  aux_source_directory(${DIRECTORY} ${VARIABLE})
+  file(GLOB headers ${DIRECTORY}/*h)
+  list(APPEND ${VARIABLE} ${headers})
+endmacro()
+
+#############################################################
+# function to collect all the sources from sub-directories
+# into a single list
+function(add_sources)
+  get_property(is_defined GLOBAL PROPERTY SRCS_LIST DEFINED)
+  if(NOT is_defined)
+    define_property(GLOBAL PROPERTY SRCS_LIST
+      BRIEF_DOCS "List of source files"
+      FULL_DOCS "List of source files to be compiled in one library")
+  endif()
+  # make absolute paths
+  set(SRCS)
+  foreach(s IN LISTS ARGN)
+    if(NOT IS_ABSOLUTE "${s}")
+      get_filename_component(s "${s}" ABSOLUTE)
+    endif()
+    list(APPEND SRCS "${s}")
+  endforeach()
+
+  string(REPLACE ${CMAKE_SOURCE_DIR}/src/ "" SUBDIR ${CMAKE_CURRENT_SOURCE_DIR})
+  string(TOLOWER ${SUBDIR} SUBDIR)
+  string(REPLACE "/" "\\\\" LIBNAME ${SUBDIR})
+  source_group(${LIBNAME} FILES ${SRCS})
+
+  # add it to the global list.
+  set_property(GLOBAL APPEND PROPERTY SRCS_LIST ${SRCS})
+endfunction(add_sources)

+ 52 - 0
README.md

@@ -0,0 +1,52 @@
+## Building
+
+You need:
+
+* Qt 5.6 alpha
+* cmake 3.0 or newer
+* ninja is recommended for building
+
+Special Qt requirements:
+
+* On Windows, you must apply qt-patches/0003-Always-enable-viewport-stuff.patch for
+  correct window scaling. Applying the patches in qt-patches/qt-5.6-alpha/ fixes
+  some stability issues.
+* On OSX, you should apply qt-patches/0002-qtbase-Don-t-show-the-menu-bar-at-all-in-lion-style-fullscr.patch
+  to improve the user experience in fullscreen.
+* You can try to use Qt 5.5, but then you also need to apply the following patches:
+    qt-patches/0001-qtwebengine-Add-a-backgroundColor-property.patch
+    qt-patches/0004-qtwebengine-transparency-window-creation.patch
+  Without them, video playback will not work.
+
+Get dependencies:
+
+* scripts/fetch-binaries.py -p darwin-x86_64
+
+If you're happy just building from the command line then run CMake for the ninja build tool:
+
+* mkdir build ; cd build
+* cmake -GNinja -DCMAKE_BUILD_TYPE=Debug -DQTROOT=/path/to/qt -DCMAKE_INSTALL_PREFIX=output ..
+
+Build (ninja):
+
+* ninja
+
+Make a distributable package:
+
+* ninja install (be patient, it's slow)
+
+Or if you prefer working in Xcode, run CMake for the xcode build):
+
+* mkdir build ; cd build
+* cmake -GXcode -DQTROOT=/path/to/qt ..
+
+
+### Debugging Web Client
+
+You can run a locally hosted development version of the web app within the Konvergo application. If the main app window is open you can also run Chrome side by side to debug.
+
+* Run the `grunt server:konvergo` from the `web-client` submodule. This will run a dev version of the web client
+* Update the `starturl` in `~/Library/Application Support/Plex Media Player/Plex Media Player.conf` to point to `http://localhost:3333/app/dev-konvergo.html`
+* Run the `Plex Media Player.app`
+* Tail the `~/Library/Logs/Plex Media Player/Plex Media Player.log`, optionally grepped with `WebClient` to see `console.log`s
+* Open Chrome and point to `http://localhost:3333/app/dev-konvergo.html`. This should open a Qt channel to the main `Plex Media Player.app` and function as normal - but with the ability to add breakpoints and inspect code

+ 40 - 0
bundle/osx/Info.plist.in

@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>English</string>
+	<key>CFBundleExecutable</key>
+	<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
+	<key>CFBundleGetInfoString</key>
+	<string>${MACOSX_BUNDLE_INFO_STRING}</string>
+	<key>CFBundleIconFile</key>
+	<string>${MACOSX_BUNDLE_ICON_FILE}</string>
+	<key>CFBundleIdentifier</key>
+	<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleLongVersionString</key>
+	<string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>
+	<key>CFBundleName</key>
+	<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
+	<key>CFBundleSignature</key>
+	<string>????</string>
+	<key>CFBundleVersion</key>
+	<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
+	<key>CSResourcesFileMapped</key>
+	<true/>
+	<key>NSHumanReadableCopyright</key>
+	<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
+	<key>NSPrincipalClass</key>
+	<string>NSApplication</string>
+	<key>NSHighResolutionCapable</key>
+	<string>True</string>
+	<key>LSMinimumSystemVersion</key>
+	<string>10.9</string>
+</dict>
+</plist>

+ 12 - 0
bundle/osx/Konvergo.entitlements

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>com.apple.security.app-sandbox</key>
+	<true/>
+	<key>com.apple.security.network.client</key>
+	<true/>
+	<key>com.apple.security.network.server</key>
+	<true/>
+</dict>
+</plist>

BIN
bundle/osx/Plex.icns


+ 10 - 0
bundle/osx/WebEngine.entitlements

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>com.apple.security.app-sandbox</key>
+	<true/>
+	<key>com.apple.security.inherit</key>
+	<true/>
+</dict>
+</plist>

+ 4 - 0
bundle/osx/qt.conf

@@ -0,0 +1,4 @@
+[Paths]
+Plugins = ../PlugIns
+Imports = ../Resources/qml
+Qml2Imports = ../Resources/qml

BIN
bundle/win/Plex.ico


+ 2 - 0
bundle/win/PlexMediaPlayer-angle.bat

@@ -0,0 +1,2 @@
+set QT_OPENGL=angle
+start PlexMediaPlayer.exe

+ 1 - 0
bundle/win/iconres.rc

@@ -0,0 +1 @@
+IDI_ICON ICON Plex.ico

+ 7 - 0
bundle/win/qt.conf

@@ -0,0 +1,7 @@
+[Paths]
+Prefix = .
+Plugins = .
+Binaries = .
+Imports = .
+Qml2Imports = .
+LibraryExecutables = .

+ 15 - 0
bundle/win/shortcut.qs

@@ -0,0 +1,15 @@
+function Component()
+{
+  // default constructor
+}
+
+Component.prototype.createOperations = function()
+{
+  component.createOperations();
+
+  if (systemInfo.productType === "windows") {
+    component.addOperation("CreateShortcut", "@TargetDir@/PlexMediaPlayer.exe", "@StartMenuDir@/Plex Media Player.lnk");
+    component.addOperation("CreateShortcut", "@TargetDir@/PlexMediaPlayer-angle.bat", "@StartMenuDir@/Plex Media Player (DirectX).lnk");
+    component.addOperation("CreateShortcut", "@TargetDir@/maintenancetool.exe", "@StartMenuDir@/Maintain Plex Media Player.lnk");
+  }
+}

+ 7 - 0
external/CMakeLists.txt

@@ -0,0 +1,7 @@
+add_subdirectory(qhttpserver)
+add_subdirectory(qslog)
+
+if(APPLE)
+  add_subdirectory(plistparser)
+  add_subdirectory(SPMediaKeyTap)
+endif(APPLE)

+ 9 - 0
external/SPMediaKeyTap/CMakeLists.txt

@@ -0,0 +1,9 @@
+
+# SPMediaKeyTap uses some deprecated methods, no need to fix that right now, so let's supress the warnings.
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-deprecated-declarations")
+
+add_library(spmediakeytap STATIC
+  SPMediaKeyTap.h SPMediaKeyTap.m
+  SPInvocationGrabbing/NSObject+SPInvocationGrabbing.m
+  SPInvocationGrabbing/NSObject+SPInvocationGrabbing.h
+)

+ 8 - 0
external/SPMediaKeyTap/LICENSE

@@ -0,0 +1,8 @@
+Copyright (c) 2011, Joachim Bengtsson
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Neither the name of the organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 12 - 0
external/SPMediaKeyTap/README.md

@@ -0,0 +1,12 @@
+SPMediaKeyTap
+=============
+
+`SPMediaKeyTap` abstracts a `CGEventHook` and other nastiness in order to give you a relatively simple API to receive media key events (prev/next/playpause, on F7 to F9 on modern MacBook Pros) exclusively, without them reaching other applications like iTunes. `SPMediaKeyTap` is clever enough to resign its exclusive lock on media keys by looking for which application was active most recently: if that application is in `SPMediaKeyTap`'s whitelist, it will resign the keys. This is similar to the behavior of Apple's applications collaborating on media key handling exclusivity, but unfortunately, Apple is not exposing any APIs allowing third-parties to join in on this collaboration.
+
+For now, the whitelist is just a hardcoded array in `+[SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers]`. If your app starts using `SPMediaKeyTap`, please [mail me](mailto:nevyn@spotify.com) your bundle ID, and I'll include it in the canonical repository. This is a bad solution; a better solution would be to use distributed notifications to collaborate in creating this whitelist at runtime. Hopefully someone'll have the time and energy to write this soon. 
+
+In `Example/SPMediaKeyTapExampleAppDelegate.m` is an example of both how you use `SPMediaKeyTap`, and how you handle the semi-private `NSEvent` subtypes involved in media keys, including on how to fall back to non-event tap handling of these events.
+
+`SPMediaKeyTap` and other `CGEventHook`s on the event type `NSSystemDefined` is known to interfere with each other and applications doing weird stuff with mouse input, because mouse clicks are also part of the `NSSystemDefined` category. The single issue we have had reported here at Spotify is Adobe Fireworks, in which item selection stops working with `SPMediaKeyTap` is active.
+
+`SPMediaKeyTap` requires 10.5 to work, and disables itself on 10.4.

+ 30 - 0
external/SPMediaKeyTap/SPInvocationGrabbing/NSObject+SPInvocationGrabbing.h

@@ -0,0 +1,30 @@
+#import <Foundation/Foundation.h>
+
+@interface SPInvocationGrabber : NSObject {
+    id _object;
+    NSInvocation *_invocation;
+    int frameCount;
+    char **frameStrings;
+    BOOL backgroundAfterForward;
+    BOOL onMainAfterForward;
+    BOOL waitUntilDone;
+}
+-(id)initWithObject:(id)obj;
+-(id)initWithObject:(id)obj stacktraceSaving:(BOOL)saveStack;
+@property (readonly, retain, nonatomic) id object;
+@property (readonly, retain, nonatomic) NSInvocation *invocation;
+@property BOOL backgroundAfterForward;
+@property BOOL onMainAfterForward;
+@property BOOL waitUntilDone;
+-(void)invoke; // will release object and invocation
+-(void)printBacktrace;
+-(void)saveBacktrace;
+@end
+
+@interface NSObject (SPInvocationGrabbing)
+-(id)grab;
+-(id)invokeAfter:(NSTimeInterval)delta;
+-(id)nextRunloop;
+-(id)inBackground;
+-(id)onMainAsync:(BOOL)async;
+@end

+ 127 - 0
external/SPMediaKeyTap/SPInvocationGrabbing/NSObject+SPInvocationGrabbing.m

@@ -0,0 +1,127 @@
+#import "NSObject+SPInvocationGrabbing.h"
+#import <execinfo.h>
+
+#pragma mark Invocation grabbing
+@interface SPInvocationGrabber ()
+@property (readwrite, retain, nonatomic) id object;
+@property (readwrite, retain, nonatomic) NSInvocation *invocation;
+
+@end
+
+@implementation SPInvocationGrabber
+- (id)initWithObject:(id)obj;
+{
+	return [self initWithObject:obj stacktraceSaving:YES];
+}
+
+-(id)initWithObject:(id)obj stacktraceSaving:(BOOL)saveStack;
+{
+	self.object = obj;
+
+	if(saveStack)
+		[self saveBacktrace];
+
+	return self;
+}
+-(void)dealloc;
+{
+	free(frameStrings);
+	self.object = nil;
+	self.invocation = nil;
+	[super dealloc];
+}
+@synthesize invocation = _invocation, object = _object;
+
+@synthesize backgroundAfterForward, onMainAfterForward, waitUntilDone;
+- (void)runInBackground;
+{
+	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+	@try {
+		[self invoke];
+	}
+	@finally {
+		[pool drain];
+	}
+}
+
+
+- (void)forwardInvocation:(NSInvocation *)anInvocation {
+	[anInvocation retainArguments];
+	anInvocation.target = _object;
+	self.invocation = anInvocation;
+	
+	if(backgroundAfterForward)
+		[NSThread detachNewThreadSelector:@selector(runInBackground) toTarget:self withObject:nil];
+	else if(onMainAfterForward)
+        [self performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:waitUntilDone];
+}
+- (NSMethodSignature *)methodSignatureForSelector:(SEL)inSelector {
+	NSMethodSignature *signature = [super methodSignatureForSelector:inSelector];
+	if (signature == NULL)
+		signature = [_object methodSignatureForSelector:inSelector];
+    
+	return signature;
+}
+
+- (void)invoke;
+{
+
+	@try {
+		[_invocation invoke];
+	}
+	@catch (NSException * e) {
+		NSLog(@"SPInvocationGrabber's target raised %@:\n\t%@\nInvocation was originally scheduled at:", e.name, e);
+		[self printBacktrace];
+		printf("\n");
+		[e raise];
+	}
+
+	self.invocation = nil;
+	self.object = nil;
+}
+
+-(void)saveBacktrace;
+{
+  void *backtraceFrames[128];
+  frameCount = backtrace(&backtraceFrames[0], 128);
+  frameStrings = backtrace_symbols(&backtraceFrames[0], frameCount);
+}
+-(void)printBacktrace;
+{
+	for(int x = 3; x < frameCount; x++) {
+		if(frameStrings[x] == NULL) { break; }
+		printf("%s\n", frameStrings[x]);
+	}
+}
+@end
+
+@implementation NSObject (SPInvocationGrabbing)
+-(id)grab;
+{
+	return [[[SPInvocationGrabber alloc] initWithObject:self] autorelease];
+}
+-(id)invokeAfter:(NSTimeInterval)delta;
+{
+	id grabber = [self grab];
+	[NSTimer scheduledTimerWithTimeInterval:delta target:grabber selector:@selector(invoke) userInfo:nil repeats:NO];
+	return grabber;
+}
+- (id)nextRunloop;
+{
+	return [self invokeAfter:0];
+}
+-(id)inBackground;
+{
+    SPInvocationGrabber *grabber = [self grab];
+	grabber.backgroundAfterForward = YES;
+	return grabber;
+}
+-(id)onMainAsync:(BOOL)async;
+{
+    SPInvocationGrabber *grabber = [self grab];
+	grabber.onMainAfterForward = YES;
+    grabber.waitUntilDone = !async;
+	return grabber;
+}
+
+@end

+ 43 - 0
external/SPMediaKeyTap/SPMediaKeyTap.h

@@ -0,0 +1,43 @@
+#include <Cocoa/Cocoa.h>
+#import <IOKit/hidsystem/ev_keymap.h>
+#import <Carbon/Carbon.h>
+
+// http://overooped.com/post/2593597587/mediakeys
+
+#define SPSystemDefinedEventMediaKeys 8
+
+@interface SPMediaKeyTap : NSObject {
+	EventHandlerRef _app_switching_ref;
+	EventHandlerRef _app_terminating_ref;
+	CFMachPortRef _eventPort;
+	CFRunLoopSourceRef _eventPortSource;
+	CFRunLoopRef _tapThreadRL;
+	BOOL _shouldInterceptMediaKeyEvents;
+	id _delegate;
+	// The app that is frontmost in this list owns media keys
+	NSMutableArray *_mediaKeyAppList;
+}
++ (NSArray*)defaultMediaKeyUserBundleIdentifiers;
+
+-(id)initWithDelegate:(id)delegate;
+
++(BOOL)usesGlobalMediaKeyTap;
+-(void)startWatchingMediaKeys;
+-(void)stopWatchingMediaKeys;
+-(void)handleAndReleaseMediaKeyEvent:(NSEvent *)event;
+@end
+
+@interface NSObject (SPMediaKeyTapDelegate)
+-(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event;
+@end
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern NSString *kMediaKeyUsingBundleIdentifiersDefaultsKey;
+extern NSString *kIgnoreMediaKeysDefaultsKey;
+
+#ifdef __cplusplus
+}
+#endif

+ 346 - 0
external/SPMediaKeyTap/SPMediaKeyTap.m

@@ -0,0 +1,346 @@
+// Copyright (c) 2010 Spotify AB
+#import "SPMediaKeyTap.h"
+#import "SPInvocationGrabbing/NSObject+SPInvocationGrabbing.h" // https://gist.github.com/511181, in submodule
+
+@interface SPMediaKeyTap ()
+-(BOOL)shouldInterceptMediaKeyEvents;
+-(void)setShouldInterceptMediaKeyEvents:(BOOL)newSetting;
+-(void)startWatchingAppSwitching;
+-(void)stopWatchingAppSwitching;
+-(void)eventTapThread;
+@end
+static SPMediaKeyTap *singleton = nil;
+
+static pascal OSStatus appSwitched (EventHandlerCallRef nextHandler, EventRef evt, void* userData);
+static pascal OSStatus appTerminated (EventHandlerCallRef nextHandler, EventRef evt, void* userData);
+static CGEventRef tapEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon);
+
+
+// Inspired by http://gist.github.com/546311
+
+@implementation SPMediaKeyTap
+
+#pragma mark -
+#pragma mark Setup and teardown
+-(id)initWithDelegate:(id)delegate;
+{
+	_delegate = delegate;
+	[self startWatchingAppSwitching];
+	singleton = self;
+	_mediaKeyAppList = [NSMutableArray new];
+    _tapThreadRL=nil;
+    _eventPort=nil;
+    _eventPortSource=nil;
+	return self;
+}
+-(void)dealloc;
+{
+	[self stopWatchingMediaKeys];
+	[self stopWatchingAppSwitching];
+	[_mediaKeyAppList release];
+	[super dealloc];
+}
+
+-(void)startWatchingAppSwitching;
+{
+	// Listen to "app switched" event, so that we don't intercept media keys if we
+	// weren't the last "media key listening" app to be active
+	EventTypeSpec eventType = { kEventClassApplication, kEventAppFrontSwitched };
+    OSStatus err = InstallApplicationEventHandler(NewEventHandlerUPP(appSwitched), 1, &eventType, self, &_app_switching_ref);
+	assert(err == noErr);
+	
+	eventType.eventKind = kEventAppTerminated;
+    err = InstallApplicationEventHandler(NewEventHandlerUPP(appTerminated), 1, &eventType, self, &_app_terminating_ref);
+	assert(err == noErr);
+}
+-(void)stopWatchingAppSwitching;
+{
+	if(!_app_switching_ref) return;
+	RemoveEventHandler(_app_switching_ref);
+	_app_switching_ref = NULL;
+}
+
+-(void)startWatchingMediaKeys;{
+    // Prevent having multiple mediaKeys threads
+    [self stopWatchingMediaKeys];
+    
+	[self setShouldInterceptMediaKeyEvents:YES];
+	
+	// Add an event tap to intercept the system defined media key events
+	_eventPort = CGEventTapCreate(kCGSessionEventTap,
+								  kCGHeadInsertEventTap,
+								  kCGEventTapOptionDefault,
+								  CGEventMaskBit(NX_SYSDEFINED),
+								  tapEventCallback,
+								  self);
+	assert(_eventPort != NULL);
+	
+    _eventPortSource = CFMachPortCreateRunLoopSource(kCFAllocatorSystemDefault, _eventPort, 0);
+	assert(_eventPortSource != NULL);
+	
+	// Let's do this in a separate thread so that a slow app doesn't lag the event tap
+	[NSThread detachNewThreadSelector:@selector(eventTapThread) toTarget:self withObject:nil];
+}
+-(void)stopWatchingMediaKeys;
+{
+	// TODO<nevyn>: Shut down thread, remove event tap port and source
+    
+    if(_tapThreadRL){
+        CFRunLoopStop(_tapThreadRL);
+        _tapThreadRL=nil;
+    }
+    
+    if(_eventPort){
+        CFMachPortInvalidate(_eventPort);
+        CFRelease(_eventPort);
+        _eventPort=nil;
+    }
+    
+    if(_eventPortSource){
+        CFRelease(_eventPortSource);
+        _eventPortSource=nil;
+    }
+}
+
+#pragma mark -
+#pragma mark Accessors
+
++(BOOL)usesGlobalMediaKeyTap
+{
+#ifdef _DEBUG
+	// breaking in gdb with a key tap inserted sometimes locks up all mouse and keyboard input forever, forcing reboot
+	return NO;
+#else
+	// XXX(nevyn): MediaKey event tap doesn't work on 10.4, feel free to figure out why if you have the energy.
+	return 
+		![[NSUserDefaults standardUserDefaults] boolForKey:kIgnoreMediaKeysDefaultsKey]
+		&& floor(NSAppKitVersionNumber) >= 949/*NSAppKitVersionNumber10_5*/;
+#endif
+}
+
++ (NSArray*)defaultMediaKeyUserBundleIdentifiers;
+{
+	return [NSArray arrayWithObjects:
+		[[NSBundle mainBundle] bundleIdentifier], // your app
+		@"com.spotify.client",
+		@"com.apple.iTunes",
+		@"com.apple.QuickTimePlayerX",
+		@"com.apple.quicktimeplayer",
+		@"com.apple.iWork.Keynote",
+		@"com.apple.iPhoto",
+		@"org.videolan.vlc",
+		@"com.apple.Aperture",
+		@"com.plexsquared.Plex",
+		@"com.soundcloud.desktop",
+		@"org.niltsh.MPlayerX",
+		@"com.ilabs.PandorasHelper",
+		@"com.mahasoftware.pandabar",
+		@"com.bitcartel.pandorajam",
+		@"org.clementine-player.clementine",
+		@"fm.last.Last.fm",
+		@"fm.last.Scrobbler",
+		@"com.beatport.BeatportPro",
+		@"com.Timenut.SongKey",
+		@"com.macromedia.fireworks", // the tap messes up their mouse input
+		@"at.justp.Theremin",
+		@"ru.ya.themblsha.YandexMusic",
+		@"com.jriver.MediaCenter18",
+		@"com.jriver.MediaCenter19",
+		@"com.jriver.MediaCenter20",
+		@"co.rackit.mate",
+		@"com.ttitt.b-music",
+		@"com.beardedspice.BeardedSpice",
+		@"com.plug.Plug",
+		@"com.plug.Plug2",
+    @"com.netease.163music",
+		nil
+	];
+}
+
+
+-(BOOL)shouldInterceptMediaKeyEvents;
+{
+	BOOL shouldIntercept = NO;
+	@synchronized(self) {
+		shouldIntercept = _shouldInterceptMediaKeyEvents;
+	}
+	return shouldIntercept;
+}
+
+-(void)pauseTapOnTapThread:(BOOL)yeahno;
+{
+	CGEventTapEnable(self->_eventPort, yeahno);
+}
+-(void)setShouldInterceptMediaKeyEvents:(BOOL)newSetting;
+{
+	BOOL oldSetting;
+	@synchronized(self) {
+		oldSetting = _shouldInterceptMediaKeyEvents;
+		_shouldInterceptMediaKeyEvents = newSetting;
+	}
+	if(_tapThreadRL && oldSetting != newSetting) {
+		id grab = [self grab];
+		[grab pauseTapOnTapThread:newSetting];
+		NSTimer *timer = [NSTimer timerWithTimeInterval:0 invocation:[grab invocation] repeats:NO];
+		CFRunLoopAddTimer(_tapThreadRL, (CFRunLoopTimerRef)timer, kCFRunLoopCommonModes);
+	}
+}
+
+#pragma mark 
+#pragma mark -
+#pragma mark Event tap callbacks
+
+// Note: method called on background thread
+
+static CGEventRef tapEventCallback2(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
+{
+	SPMediaKeyTap *self = refcon;
+
+    if(type == kCGEventTapDisabledByTimeout) {
+		NSLog(@"Media key event tap was disabled by timeout");
+		CGEventTapEnable(self->_eventPort, TRUE);
+		return event;
+	} else if(type == kCGEventTapDisabledByUserInput) {
+		// Was disabled manually by -[pauseTapOnTapThread]
+		return event;
+	}
+	NSEvent *nsEvent = nil;
+	@try {
+		nsEvent = [NSEvent eventWithCGEvent:event];
+	}
+	@catch (NSException * e) {
+		NSLog(@"Strange CGEventType: %d: %@", type, e);
+		assert(0);
+		return event;
+	}
+
+	if (type != NX_SYSDEFINED || [nsEvent subtype] != SPSystemDefinedEventMediaKeys)
+		return event;
+
+	int keyCode = (([nsEvent data1] & 0xFFFF0000) >> 16);
+    if (keyCode != NX_KEYTYPE_PLAY && keyCode != NX_KEYTYPE_FAST && keyCode != NX_KEYTYPE_REWIND && keyCode != NX_KEYTYPE_PREVIOUS && keyCode != NX_KEYTYPE_NEXT)
+		return event;
+
+	if (![self shouldInterceptMediaKeyEvents])
+		return event;
+	
+	[nsEvent retain]; // matched in handleAndReleaseMediaKeyEvent:
+	[self performSelectorOnMainThread:@selector(handleAndReleaseMediaKeyEvent:) withObject:nsEvent waitUntilDone:NO];
+	
+	return NULL;
+}
+
+static CGEventRef tapEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
+{
+	NSAutoreleasePool *pool = [NSAutoreleasePool new];
+	CGEventRef ret = tapEventCallback2(proxy, type, event, refcon);
+	[pool drain];
+	return ret;
+}
+
+
+// event will have been retained in the other thread
+-(void)handleAndReleaseMediaKeyEvent:(NSEvent *)event {
+	[event autorelease];
+	
+	[_delegate mediaKeyTap:self receivedMediaKeyEvent:event];
+}
+
+
+-(void)eventTapThread;
+{
+	_tapThreadRL = CFRunLoopGetCurrent();
+	CFRunLoopAddSource(_tapThreadRL, _eventPortSource, kCFRunLoopCommonModes);
+	CFRunLoopRun();
+}
+
+#pragma mark Task switching callbacks
+
+NSString *kMediaKeyUsingBundleIdentifiersDefaultsKey = @"SPApplicationsNeedingMediaKeys";
+NSString *kIgnoreMediaKeysDefaultsKey = @"SPIgnoreMediaKeys";
+
+
+
+-(void)mediaKeyAppListChanged;
+{
+	if([_mediaKeyAppList count] == 0) return;
+	
+	/*NSLog(@"--");
+	int i = 0;
+	for (NSValue *psnv in _mediaKeyAppList) {
+		ProcessSerialNumber psn; [psnv getValue:&psn];
+		NSDictionary *processInfo = [(id)ProcessInformationCopyDictionary(
+			&psn,
+			kProcessDictionaryIncludeAllInformationMask
+		) autorelease];
+		NSString *bundleIdentifier = [processInfo objectForKey:(id)kCFBundleIdentifierKey];
+		NSLog(@"%d: %@", i++, bundleIdentifier);
+	}*/
+	
+    ProcessSerialNumber mySerial, topSerial;
+	GetCurrentProcess(&mySerial);
+	[[_mediaKeyAppList objectAtIndex:0] getValue:&topSerial];
+
+	Boolean same;
+	OSErr err = SameProcess(&mySerial, &topSerial, &same);
+	[self setShouldInterceptMediaKeyEvents:(err == noErr && same)];	
+
+}
+-(void)appIsNowFrontmost:(ProcessSerialNumber)psn;
+{
+	NSValue *psnv = [NSValue valueWithBytes:&psn objCType:@encode(ProcessSerialNumber)];
+	
+	NSDictionary *processInfo = [(id)ProcessInformationCopyDictionary(
+		&psn,
+		kProcessDictionaryIncludeAllInformationMask
+	) autorelease];
+	NSString *bundleIdentifier = [processInfo objectForKey:(id)kCFBundleIdentifierKey];
+
+	NSArray *whitelistIdentifiers = [[NSUserDefaults standardUserDefaults] arrayForKey:kMediaKeyUsingBundleIdentifiersDefaultsKey];
+	if(![whitelistIdentifiers containsObject:bundleIdentifier]) return;
+
+	[_mediaKeyAppList removeObject:psnv];
+	[_mediaKeyAppList insertObject:psnv atIndex:0];
+	[self mediaKeyAppListChanged];
+}
+-(void)appTerminated:(ProcessSerialNumber)psn;
+{
+	NSValue *psnv = [NSValue valueWithBytes:&psn objCType:@encode(ProcessSerialNumber)];
+	[_mediaKeyAppList removeObject:psnv];
+	[self mediaKeyAppListChanged];
+}
+
+static pascal OSStatus appSwitched (EventHandlerCallRef nextHandler, EventRef evt, void* userData)
+{
+	SPMediaKeyTap *self = (id)userData;
+
+    ProcessSerialNumber newSerial;
+    GetFrontProcess(&newSerial);
+	
+	[self appIsNowFrontmost:newSerial];
+		
+    return CallNextEventHandler(nextHandler, evt);
+}
+
+static pascal OSStatus appTerminated (EventHandlerCallRef nextHandler, EventRef evt, void* userData)
+{
+	SPMediaKeyTap *self = (id)userData;
+	
+	ProcessSerialNumber deadPSN;
+
+	GetEventParameter(
+		evt, 
+		kEventParamProcessID, 
+		typeProcessSerialNumber, 
+		NULL, 
+		sizeof(deadPSN), 
+		NULL, 
+		&deadPSN
+	);
+
+	
+	[self appTerminated:deadPSN];
+    return CallNextEventHandler(nextHandler, evt);
+}
+
+@end

+ 8 - 0
external/plistparser/CMakeLists.txt

@@ -0,0 +1,8 @@
+include_directories(.)
+
+add_library(plistparser STATIC
+  plistparser.cpp
+  plistparser.h
+  plistserializer.cpp
+  plistserializer.h
+)

+ 22 - 0
external/plistparser/LICENSE

@@ -0,0 +1,22 @@
+Gist: this is an MIT license.  Act accordingly (basically, do whatever you want).
+It would be nice to get an email from you if you use this, but if not that's also cool.
+
+Copyright (c) 2010 Reilly Watson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 98 - 0
external/plistparser/plistparser.cpp

@@ -0,0 +1,98 @@
+// Own includes
+#include "plistparser.h"
+
+// Qt includes
+#include <QDomNode>
+#include <QDomDocument>
+#include <QDateTime>
+#include <QDebug>
+
+QVariant PListParser::parsePList(QIODevice *device) {
+	QVariantMap result;
+	QDomDocument doc;
+	QString errorMessage;
+	int errorLine;
+	int errorColumn;
+	bool success = doc.setContent(device, false, &errorMessage, &errorLine, &errorColumn);
+	if (!success) {
+		qDebug() << "PListParser Warning: Could not parse PList file!";
+		qDebug() << "Error message: " << errorMessage;
+		qDebug() << "Error line: " << errorLine;
+		qDebug() << "Error column: " << errorColumn;
+		return result;
+	}
+	QDomElement root = doc.documentElement();
+	if (root.attribute(QStringLiteral("version"), QStringLiteral("1.0")) != QLatin1String("1.0")) {
+		qDebug() << "PListParser Warning: plist is using an unknown format version, parsing might fail unexpectedly";
+	}
+	return parseElement(root.firstChild().toElement());
+}
+
+QVariant PListParser::parseElement(const QDomElement &e) {
+	QString tagName = e.tagName();
+	QVariant result;
+	if (tagName == QLatin1String("dict")) {
+		result = parseDictElement(e);
+	}
+	else if (tagName == QLatin1String("array")) {
+		result = parseArrayElement(e);
+	}
+	else if (tagName == QLatin1String("string")) {
+		result = e.text();
+	}
+	else if (tagName == QLatin1String("data")) {
+		result = QByteArray::fromBase64(e.text().toUtf8());
+	}
+	else if (tagName == QLatin1String("integer")) {
+		result = e.text().toInt();
+	}
+	else if (tagName == QLatin1String("real")) {
+		result = e.text().toFloat();
+	}
+	else if (tagName == QLatin1String("true")) {
+		result = true;
+	}
+	else if (tagName == QLatin1String("false")) {
+		result = false;
+	}
+	else if (tagName == QLatin1String("date")) {
+		result = QDateTime::fromString(e.text(), Qt::ISODate);
+	}
+	else {
+		qDebug() << "PListParser Warning: Invalid tag found: " << e.tagName() << e.text();
+	}
+	return result;
+}
+
+QVariantList PListParser::parseArrayElement(const QDomElement& element) {
+	QVariantList result;
+	QDomNodeList children = element.childNodes();
+	for (int i = 0; i < children.count(); i++) {
+		QDomNode child = children.at(i);
+		QDomElement e = child.toElement();
+		if (!e.isNull()) {
+			result.append(parseElement(e));
+		}
+	}
+	return result;
+}
+
+QVariantMap PListParser::parseDictElement(const QDomElement& element) {
+	QVariantMap result;
+	QDomNodeList children = element.childNodes();
+	QString currentKey;
+	for (int i = 0; i < children.count(); i++) {
+		QDomNode child = children.at(i);
+		QDomElement e = child.toElement();
+		if (!e.isNull()) {
+			QString tagName = e.tagName();
+			if (tagName == QLatin1String("key")) {
+				currentKey = e.text();
+			}
+			else if (!currentKey.isEmpty()) {
+				result[currentKey] = parseElement(e);
+			}
+		}
+	}
+	return result;
+}

+ 18 - 0
external/plistparser/plistparser.h

@@ -0,0 +1,18 @@
+#pragma once
+
+// Qt includes
+#include <QIODevice>
+#include <QVariant>
+#include <QVariantList>
+#include <QVariantMap>
+#include <QDomElement>
+
+class PListParser {
+public:
+	static QVariant parsePList(QIODevice *device);
+private:
+	static QVariant parseElement(const QDomElement &e);
+	static QVariantList parseArrayElement(const QDomElement& node);
+	static QVariantMap parseDictElement(const QDomElement& element);
+};
+

+ 83 - 0
external/plistparser/plistserializer.cpp

@@ -0,0 +1,83 @@
+// Own includes
+#include "plistserializer.h"
+
+// Qt includes
+#include <QDomElement>
+#include <QDomDocument>
+#include <QDate>
+#include <QDateTime>
+
+static QDomElement textElement(QDomDocument& doc, const char *tagName, QString contents) {
+	QDomElement tag = doc.createElement(QString::fromLatin1(tagName));
+	tag.appendChild(doc.createTextNode(contents));
+	return tag;
+}
+
+static QDomElement serializePrimitive(QDomDocument &doc, const QVariant &variant) {
+	QDomElement result;
+	if (variant.type() == QVariant::Bool) {
+        result = doc.createElement(variant.toBool() ? QStringLiteral("true") : QStringLiteral("false"));
+	}
+	else if (variant.type() == QVariant::Date) {
+		result = textElement(doc, "date", variant.toDate().toString(Qt::ISODate));
+	}
+	else if (variant.type() == QVariant::DateTime) {
+		result = textElement(doc, "date", variant.toDateTime().toString(Qt::ISODate));
+	}
+	else if (variant.type() == QVariant::ByteArray) {
+		result = textElement(doc, "data", QString::fromLatin1(variant.toByteArray().toBase64()));
+	}
+	else if (variant.type() == QVariant::String) {
+		result = textElement(doc, "string", variant.toString());
+	}
+	else if (variant.type() == QVariant::Int) {
+		result = textElement(doc, "integer", QString::number(variant.toInt()));
+	}
+	else if (variant.canConvert(QVariant::Double)) {
+		QString num;
+		num.setNum(variant.toDouble());
+		result = textElement(doc, "real", num);
+	}
+	return result;
+}
+
+QDomElement PListSerializer::serializeElement(QDomDocument &doc, const QVariant &variant) {
+	if (variant.type() == QVariant::Map) {
+		return serializeMap(doc, variant.toMap());
+	}
+	else if (variant.type() == QVariant::List) {
+		 return serializeList(doc, variant.toList());
+	}
+	else {
+		return serializePrimitive(doc, variant);
+	}
+}
+
+QDomElement PListSerializer::serializeList(QDomDocument &doc, const QVariantList &list) {
+	QDomElement element = doc.createElement(QStringLiteral("array"));
+	foreach(QVariant item, list) {
+		element.appendChild(serializeElement(doc, item));
+	}
+	return element;
+}
+
+QDomElement PListSerializer::serializeMap(QDomDocument &doc, const QVariantMap &map) {
+	QDomElement element = doc.createElement(QStringLiteral("dict"));
+	QList<QString> keys = map.keys();
+	foreach(QString key, keys) {
+		QDomElement keyElement = textElement(doc, "key", key);
+		element.appendChild(keyElement);
+		element.appendChild(serializeElement(doc, map[key]));
+	}
+	return element;
+}
+
+QString PListSerializer::toPList(const QVariant &variant) {
+	QDomDocument document(QStringLiteral("plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\""));
+	document.appendChild(document.createProcessingInstruction(QStringLiteral("xml"), QStringLiteral("version=\"1.0\" encoding=\"UTF-8\"")));
+	QDomElement plist = document.createElement(QStringLiteral("plist"));
+	plist.setAttribute(QStringLiteral("version"), QStringLiteral("1.0"));
+	document.appendChild(plist);
+	plist.appendChild(serializeElement(document, variant));
+	return document.toString();
+}

+ 20 - 0
external/plistparser/plistserializer.h

@@ -0,0 +1,20 @@
+#pragma once
+
+// Qt includes
+#include <QIODevice>
+#include <QVariant>
+#include <QVariantList>
+#include <QVariantMap>
+#include <QDomElement>
+#include <QDomDocument>
+#include <QString>
+
+class PListSerializer {
+public:
+	static QString toPList(const QVariant &variant);
+private:
+	static QDomElement serializeElement(QDomDocument &doc, const QVariant &variant);
+	static QDomElement serializeMap(QDomDocument &doc, const QVariantMap &map);
+	static QDomElement serializeList(QDomDocument &doc, const QVariantList &list);
+};
+

+ 30 - 0
external/qhttpserver/.gitignore

@@ -0,0 +1,30 @@
+# Folders
+build
+lib
+
+# Generated
+Makefile
+*.o
+moc_*
+
+# Docs
+docs/html
+
+# Build folders
+*/debug
+*/release
+*/*/debug
+*/*/release
+
+# Visual studio
+*.suo
+*.ncb
+*.user
+*.pdb
+*.idb
+*.vcproj
+*.vcxproj
+*.vcxproj.filters
+*.lib
+*.sln
+*.rc

+ 8 - 0
external/qhttpserver/CMakeLists.txt

@@ -0,0 +1,8 @@
+aux_source_directory(src HTTP_SRC)
+
+include_directories(http-parser)
+add_library(http-parser STATIC http-parser/http_parser.c)
+
+set(CMAKE_AUTOMOC ON)
+add_library(qhttpserver STATIC ${HTTP_SRC} ${PARSER_SRC})
+target_link_libraries(qhttpserver http-parser)

+ 19 - 0
external/qhttpserver/LICENSE

@@ -0,0 +1,19 @@
+Copyright (C) 2011-2014 Nikhil Marathe <nsm.nikhil@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE. 

+ 72 - 0
external/qhttpserver/README.md

@@ -0,0 +1,72 @@
+QHttpServer
+===========
+
+A Qt HTTP Server - because hard-core programmers write web-apps in C++ :)
+
+It uses Joyent's [HTTP Parser](http://github.com/joyent/http-parser) and is asynchronous and does not require any inheritance.
+
+QHttpServer is available under the MIT License.
+
+**NOTE: QHttpServer is NOT fully HTTP compliant right now! DO NOT use it for
+anything complex**
+
+Installation
+------------
+
+Requires Qt 4 or Qt 5.
+
+    qmake && make && su -c 'make install'
+
+To link to your projects put this in your project's qmake project file
+
+    LIBS += -lqhttpserver
+
+By default, the installation prefix is /usr/local. To change that to /usr,
+for example, run:
+
+    qmake -r PREFIX=/usr
+
+Usage
+-----
+
+Include the headers
+
+    #include <qhttpserver.h>
+    #include <qhttprequest.h>
+    #include <qhttpresponse.h>
+
+Create a server, and connect to the signal for new requests
+
+    QHttpServer *server = new QHttpServer;
+    connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
+            handler, SLOT(handle(QHttpRequest*, QHttpResponse*)));
+
+    // let's go
+    server->listen(8080);
+
+In the handler, you may dispatch on routes or do whatever other things
+you want. See the API documentation for what information
+is provided about the request via the QHttpRequest object.
+
+To send data back to the browser and end the request:
+
+    void Handler::handle(QHttpRequest *req, QHttpResponse *resp)
+    {
+    	resp->setHeader("Content-Length", 11);
+    	resp->writeHead(200); // everything is OK
+    	resp->write("Hello World");
+    	resp->end();
+    }
+
+The server and request/response objects emit various signals
+and have guarantees about memory management. See the API documentation for
+these.
+
+Contribute
+----------
+
+Feel free to file issues, branch and send pull requests. If you plan to work on a major feature (say WebSocket support), please run it by me first by filing an issue! qhttpserver has a narrow scope and API and I'd like to keep it that way, so a thousand line patch that implements the kitchen sink is unlikely to be accepted.
+
+- Nikhil Marathe (maintainer)
+
+Everybody who has ever contributed shows up in [Contributors](https://github.com/nikhilm/qhttpserver/graphs/contributors).

+ 7 - 0
external/qhttpserver/TODO

@@ -0,0 +1,7 @@
+* Expect & Continue stuff
+* Chunked encoding support
+* Only copy over public headers etc.
+* connection object should connect to QHttpResponse::destroyed()
+and stop pushing data into it or whatever if the object is destroyed.
+* response object should keep track of emitting done() and not accept writes after that
+* handle encoding in response write and end

+ 2314 - 0
external/qhttpserver/docs/Doxyfile

@@ -0,0 +1,2314 @@
+# Doxyfile 1.8.5
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+# 
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+# 
+# All text after a single hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME           = QHttpServer
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER         = 0.1
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          = "A Qt based asynchronous Http Server"
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
+# the documentation. The maximum height of the logo should not exceed 55 pixels
+# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
+# to the output directory.
+
+PROJECT_LOGO           = 
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = ./
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-
+# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi,
+# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en,
+# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish,
+# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish,
+# Turkish, Ukrainian and Vietnamese.
+# The default value is: English.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
+# description of a member or function before the detailed description
+# 
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+# The default value is: YES.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# doxygen will generate a detailed section even if there is only a brief
+# description.
+# The default value is: NO.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+# The default value is: NO.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
+
+FULL_PATH_NAMES        = YES
+
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+# 
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
+
+STRIP_FROM_PATH        = 
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH    = 
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
+
+JAVADOC_AUTOBRIEF      = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
+
+QT_AUTOBRIEF           = YES
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+# 
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
+
+MULTILINE_CPP_IS_BRIEF = YES
+
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
+# new page for each member. If set to NO, the documentation of a member will be
+# part of the file/class/namespace that contains it.
+# The default value is: NO.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE               = 4
+
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
+
+ALIASES                = 
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              = 
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make
+# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
+# (default is Fortran), use: inc=Fortran f=C.
+# 
+# Note For files without extension you can use no_extension as a placeholder.
+# 
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      = 
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by by putting a % sign in front of the word
+# or globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+# The default value is: NO.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+# The default value is: NO.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+# 
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL            = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PRIVATE        = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
+
+EXTRACT_STATIC         = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO only methods in the interface are
+# included.
+# The default value is: NO.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO these classes will be included in the various overviews. This option has
+# no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO these declarations will be
+# included in the documentation.
+# The default value is: NO.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
+
+CASE_SENSE_NAMES       = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES the
+# scope will be hidden.
+# The default value is: NO.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order.
+# The default value is: YES.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order.
+# The default value is: NO.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
+# todo list. This list is created by putting \todo commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TODOLIST      = NO
+
+# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
+# test list. This list is created by putting \test commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS       = 
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES the list
+# will mention the files that were used to generate the documentation.
+# The default value is: YES.
+
+SHOW_USED_FILES        = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
+
+SHOW_FILES             = NO
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
+
+FILE_VERSION_FILTER    = 
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+# 
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE            = 
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. Do not use file names with spaces, bibtex cannot handle them. See
+# also \cite for info how to create references.
+
+CITE_BIB_FILES         = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+# 
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
+
+WARNINGS               = YES
+
+# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO doxygen will only warn about wrong or incomplete parameter
+# documentation, but not about the absence of documentation.
+# The default value is: NO.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
+
+WARN_LOGFILE           = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces.
+# Note: If this tag is empty the current directory is searched.
+
+INPUT                  = pages \
+                         ../src
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank the
+# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
+# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
+# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
+# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
+# *.qsf, *.as and *.js.
+
+FILE_PATTERNS          = *.cpp \
+                         *.inl \
+                         *.h \
+                         *.dox
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
+
+RECURSIVE              = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+# 
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE                = 
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+# The default value is: NO.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories.
+# 
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       = ui_*.h \
+                         moc_*
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+# 
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS        = 
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
+
+EXAMPLE_PATH           = ../examples
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH             = 
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command:
+# 
+# <filter> <input-file>
+# 
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+# 
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+
+INPUT_FILTER           = 
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        = 
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER ) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS = 
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+# 
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
+
+SOURCE_BROWSER         = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+# 
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+# 
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+# 
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
+
+VERBATIM_HEADERS       = YES
+
+# If the CLANG_ASSISTED_PARSING tag is set to YES, then doxygen will use the
+# clang parser (see: http://clang.llvm.org/) for more acurate parsing at the
+# cost of reduced performance. This can be particularly helpful with template
+# rich C++ code for which doxygen's built-in parser lacks the necessary type
+# information.
+# Note: The availability of this option depends on whether or not doxygen was
+# compiled with the --with-libclang option.
+# The default value is: NO.
+
+CLANG_ASSISTED_PARSING = NO
+
+# If clang assisted parsing is enabled you can provide the compiler with command
+# line options that you would normally use when invoking the compiler. Note that
+# the include paths will already be set by doxygen for the files and directories
+# specified with INPUT and INCLUDE_PATH.
+# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
+
+CLANG_OPTIONS          = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
+
+ALPHABETICAL_INDEX     = YES
+
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX          = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
+# The default value is: YES.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+# 
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER            = 
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FOOTER            = 
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET        = 
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user-
+# defined cascading style sheet that is included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefor more robust against future updates.
+# Doxygen will copy the style sheet file to the output directory. For an example
+# see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  = 
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       = 
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the stylesheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_DOCSET        = NO
+
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+# 
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_HTMLHELP      = NO
+
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
+# written to the html output directory.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE               = 
+
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler ( hhc.exe). If non-empty
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION           = 
+
+# The GENERATE_CHI flag controls if a separate .chi index file is generated (
+# YES) or that it should be included in the master .chm file ( NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+GENERATE_CHI           = NO
+
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING     = 
+
+# The BINARY_TOC flag controls whether a binary table of contents is generated (
+# YES) or a normal table of contents ( NO) in the .chm file.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE               = 
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME   = 
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS  = 
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS  = 
+
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION           = 
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+DISABLE_INDEX          = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+# 
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+# 
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using prerendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH        = http://www.mathjax.org/mathjax
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     = 
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       = 
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavours of web server based searching depending on the
+# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for
+# searching and an index file used by the script. When EXTERNAL_SEARCH is
+# enabled the indexing and searching needs to be provided by external tools. See
+# the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH    = NO
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+# 
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+# 
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+# 
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       = 
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     = 
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
+# The default value is: YES.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+# 
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. To get the times font for
+# instance you can specify
+# EXTRA_PACKAGES=times
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+EXTRA_PACKAGES         = 
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+# 
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber. Doxygen will
+# replace them by respectively the title of the page, the current date and time,
+# only the current date, the version number of doxygen, the project name (see
+# PROJECT_NAME), or the project number (see PROJECT_NUMBER).
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER           = 
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer.
+# 
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           = 
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      = 
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PDF_HYPERLINKS         = YES
+
+# If the LATEX_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES to get a
+# higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BATCHMODE        = NO
+
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HIDE_INDICES     = NO
+
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+# 
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+# 
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+# 
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE    = 
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE    = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_OUTPUT             = xml
+
+# The XML_SCHEMA tag can be used to specify a XML schema, which can be used by a
+# validating XML parser to check the syntax of the XML files.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_SCHEMA             = 
+
+# The XML_DTD tag can be used to specify a XML DTD, which can be used by a
+# validating XML parser to check the syntax of the XML files.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_DTD                = 
+
+# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
+# Definitions (see http://autogen.sf.net) file that captures the structure of
+# the code including all documentation. Note that this feature is still
+# experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+# 
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
+# in the source code. If set to NO only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES the includes files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+INCLUDE_PATH           = 
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+INCLUDE_FILE_PATTERNS  = 
+
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED             = 
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED      = 
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all refrences to function-like macros that are alone on a line, have an
+# all uppercase name, and do not end with a semicolon. Such function macros are
+# typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have an unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
+
+TAGFILES               = 
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE       = 
+
+# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
+# class index. If set to NO only the inherited external classes will be listed.
+# The default value is: NO.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
+# the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+CLASS_DIAGRAMS         = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            = 
+
+# If set to YES, the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: NO.
+
+HAVE_DOT               = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font n the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH           = 
+
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDE_GRAPH          = YES
+
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+# 
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+# 
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot.
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, jpg, gif and svg.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+# 
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG        = NO
+
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_PATH               = 
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS           = 
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           = 
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+# 
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_CLEANUP            = YES

+ 10 - 0
external/qhttpserver/docs/pages/examples.dox

@@ -0,0 +1,10 @@
+/**
+
+@example helloworld/helloworld.cpp
+@example helloworld/helloworld.h
+@example greeting/greeting.cpp
+@example greeting/greeting.h
+@example bodydata/bodydata.cpp
+@example bodydata/bodydata.h
+
+*/

+ 105 - 0
external/qhttpserver/docs/pages/main-page.dox

@@ -0,0 +1,105 @@
+/**
+
+@mainpage %QHttpServer Documentation
+
+@section introduction Introduction
+
+%QHttpServer is a easy to use, fast and light-weight
+HTTP Server suitable for C++ web applications backed
+by Qt. Since C++ web applications are pretty uncommon
+the market for this project is pretty low.
+
+But integrating this with a module like QtScript and using it to write
+JavaScript web applications is a tempting possibility, and something that
+I demonstrated at <a href="http://conf.kde.in">conf.kde.in 2011</a>. The slides
+can be found on <a href="https://github.com/nikhilm/confkdein11">Github</a>.
+
+%QHttpServer uses a signal-slots based mechanism
+for all communication, so no inheritance is required.
+It tries to be as asynchronous as possible, to the
+extent that request body data is also delivered as and
+when it is received over the socket via signals. This
+kind of programming may take some getting used to.
+
+%QHttpServer is backed by <a href="http://github.com/ry/http-parser">Ryan
+Dahl's secure and fast http parser</a> which makes it streaming
+till the lowest level.
+
+@section usage Usage
+
+Using %QHttpServer is very simple. Simply create a QHttpServer,
+connect a slot to the newRequest() signal and use the request and
+response objects.
+See the QHttpServer class documentation for an example.
+
+@section memorymanagement Memory Management
+
+The QHttpRequest and QHttpResponse deletion policies
+are such.
+
+QHttpRequest is <b>never</b> deleted by %QHttpServer.
+Since it is not possible to determine till what point the application
+may want access to its data, it is up to the application to delete it.
+A recommended way to handle this is to create a new responder object for
+every request and to delete the request in that object's destructor. The
+object itself can be deleted by connecting to QHttpResponse's done()
+slot as explained below.
+
+You should <b>not</b> delete the QHttpRequest object until it
+has emitted an QHttpRequest::end() signal.
+
+QHttpResponse queues itself up for auto-deletion once the application
+calls its end() method. Once the data has been flushed to the underlying
+socket, the object will emit a QHttpResponse::done() signal before queueing itself up
+for deletion. You should <b>not</b> interact with the response
+object once it has emitted QHttpResponse::done() although actual deletion does not
+happen until QHttpResponse::destroyed() is emitted.
+QHttpResponse::done() serves as a useful way to handle memory management of the
+application itself. For example:
+
+@code
+
+MyApp::MyApp() : QObject()
+{
+    QHttpServer *server = new QHttpServer(this);
+    connect(server, SIGNAL(newRequest(...)), this, SLOT(handle(...)));
+    s.listen(8080);
+}
+
+void MyApp::handle(QHttpRequest *request, QHttpResponse *response)
+{
+    if (request->path() == x) // Match a route
+        new Responder(request, response);
+    else
+        new PageNotFound(request, response);
+}
+
+...
+
+Responder::Responder(QHttpRequest *request, QHttpResponse *response)
+{
+    m_request = request;
+
+    connect(request, SIGNAL(end()), response, SLOT(end()));
+  
+    // Once the request is complete, the response is sent.
+    // When the response ends, it deletes itself
+    // the Responder object connects to done()
+    // which will lead to it being deleted
+    // and this will delete the request.
+    // So all 3 are properly deleted.
+    connect(response, SIGNAL(done()), this, SLOT(deleteLater()));
+
+    response->writeHead(200);
+    response->write("Quitting soon");
+}
+
+Responder::~Responder()
+{
+    delete m_request;
+    m_request = 0;
+}
+
+@endcode
+
+*/

+ 76 - 0
external/qhttpserver/examples/bodydata/bodydata.cpp

@@ -0,0 +1,76 @@
+#include "bodydata.h"
+
+#include <QCoreApplication>
+#include <QRegExp>
+#include <QStringList>
+#include <QDebug>
+
+#include <qhttpserver.h>
+#include <qhttprequest.h>
+#include <qhttpresponse.h>
+
+/// BodyData
+
+BodyData::BodyData()
+{
+    QHttpServer *server = new QHttpServer(this);
+    connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
+        this, SLOT(handleRequest(QHttpRequest*, QHttpResponse*)));
+        
+    server->listen(QHostAddress::Any, 8080);
+}
+
+void BodyData::handleRequest(QHttpRequest *req, QHttpResponse *resp)
+{
+    new Responder(req, resp);
+}
+
+/// Responder
+
+Responder::Responder(QHttpRequest *req, QHttpResponse *resp)
+    : m_req(req)
+    , m_resp(resp)
+{
+    QRegExp exp("^/user/([a-z]+$)");
+    if (exp.indexIn(req->path()) == -1)
+    {
+        resp->writeHead(403);
+        resp->end(QByteArray("You aren't allowed here!"));
+        /// @todo There should be a way to tell request to stop streaming data
+        return;
+    }
+
+    resp->setHeader("Content-Type", "text/html");
+    resp->writeHead(200);
+    
+    QString name = exp.capturedTexts()[1];
+    QString bodyStart = tr("<html><head><title>BodyData App</title></head><body><h1>Hello %1!</h1><p>").arg(name);
+    resp->write(bodyStart.toUtf8());
+
+    connect(req, SIGNAL(data(const QByteArray&)), this, SLOT(accumulate(const QByteArray&)));
+    connect(req, SIGNAL(end()), this, SLOT(reply()));
+    connect(m_resp, SIGNAL(done()), this, SLOT(deleteLater()));
+}
+
+Responder::~Responder()
+{
+}
+
+void Responder::accumulate(const QByteArray &data)
+{
+    m_resp->write(data);
+}
+
+void Responder::reply()
+{
+    m_resp->end(QByteArray("</p></body></html>"));
+}
+
+/// main
+
+int main(int argc, char **argv)
+{
+    QCoreApplication app(argc, argv);
+    BodyData bodydata;
+    app.exec();
+}

+ 39 - 0
external/qhttpserver/examples/bodydata/bodydata.h

@@ -0,0 +1,39 @@
+#include "qhttpserverfwd.h"
+
+#include <QObject>
+#include <QScopedPointer>
+
+/// BodyData
+
+class BodyData : public QObject
+{
+    Q_OBJECT
+
+public:
+    BodyData();
+
+private slots:
+    void handleRequest(QHttpRequest *req, QHttpResponse *resp);
+};
+
+/// Responder
+
+class Responder : public QObject
+{
+    Q_OBJECT
+
+public:
+    Responder(QHttpRequest *req, QHttpResponse *resp);
+    ~Responder();
+
+signals:
+    void done();
+
+private slots:
+    void accumulate(const QByteArray &data);
+    void reply();
+
+private:
+    QScopedPointer<QHttpRequest> m_req;
+    QHttpResponse *m_resp;
+};

+ 19 - 0
external/qhttpserver/examples/bodydata/bodydata.pro

@@ -0,0 +1,19 @@
+TARGET = bodydata
+
+QT += network
+QT -= gui
+
+CONFIG += debug
+
+INCLUDEPATH += ../../src
+LIBS += -L../../lib
+
+win32 {
+    debug: LIBS += -lqhttpserverd
+    else: LIBS += -lqhttpserver
+} else {
+    LIBS += -lqhttpserver
+}
+
+SOURCES = bodydata.cpp
+HEADERS = bodydata.h

+ 5 - 0
external/qhttpserver/examples/examples.pro

@@ -0,0 +1,5 @@
+TEMPLATE = subdirs
+SUBDIRS += \
+helloworld\
+greeting\
+bodydata\

+ 48 - 0
external/qhttpserver/examples/greeting/greeting.cpp

@@ -0,0 +1,48 @@
+#include "greeting.h"
+
+#include <QCoreApplication>
+#include <QRegExp>
+#include <QStringList>
+
+#include <qhttpserver.h>
+#include <qhttprequest.h>
+#include <qhttpresponse.h>
+
+/// Greeting
+
+Greeting::Greeting()
+{
+    QHttpServer *server = new QHttpServer(this);
+    connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
+            this, SLOT(handleRequest(QHttpRequest*, QHttpResponse*)));
+            
+    server->listen(QHostAddress::Any, 8080);
+}
+
+void Greeting::handleRequest(QHttpRequest *req, QHttpResponse *resp)
+{
+    QRegExp exp("^/user/([a-z]+)$");
+    if( exp.indexIn(req->path()) != -1 )
+    {
+        resp->setHeader("Content-Type", "text/html");
+        resp->writeHead(200);
+        
+        QString name = exp.capturedTexts()[1];
+        QString body = tr("<html><head><title>Greeting App</title></head><body><h1>Hello %1!</h1></body></html>");
+        resp->end(body.arg(name).toUtf8());
+    }
+    else
+    {
+        resp->writeHead(403);
+        resp->end(QByteArray("You aren't allowed here!"));
+    }
+}
+
+/// main
+
+int main(int argc, char **argv)
+{
+    QCoreApplication app(argc, argv);
+    Greeting greeting;
+    app.exec();
+}

+ 16 - 0
external/qhttpserver/examples/greeting/greeting.h

@@ -0,0 +1,16 @@
+#include "qhttpserverfwd.h"
+
+#include <QObject>
+
+/// Greeting
+
+class Greeting : public QObject
+{
+    Q_OBJECT
+
+public:
+    Greeting();
+
+private slots:
+    void handleRequest(QHttpRequest *req, QHttpResponse *resp);
+};

+ 19 - 0
external/qhttpserver/examples/greeting/greeting.pro

@@ -0,0 +1,19 @@
+TARGET = greeting
+
+QT += network
+QT -= gui
+
+CONFIG += debug
+
+INCLUDEPATH += ../../src
+LIBS += -L../../lib
+
+win32 {
+    debug: LIBS += -lqhttpserverd
+    else: LIBS += -lqhttpserver
+} else {
+    LIBS += -lqhttpserver
+}
+
+SOURCES = greeting.cpp
+HEADERS = greeting.h

+ 37 - 0
external/qhttpserver/examples/helloworld/helloworld.cpp

@@ -0,0 +1,37 @@
+#include "helloworld.h"
+
+#include <QCoreApplication>
+
+#include <qhttpserver.h>
+#include <qhttprequest.h>
+#include <qhttpresponse.h>
+
+/// HelloWorld
+
+HelloWorld::HelloWorld()
+{
+    QHttpServer *server = new QHttpServer(this);
+    connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
+            this, SLOT(handleRequest(QHttpRequest*, QHttpResponse*)));
+
+    server->listen(QHostAddress::Any, 8080);
+}
+
+void HelloWorld::handleRequest(QHttpRequest *req, QHttpResponse *resp)
+{
+    Q_UNUSED(req);
+
+    QByteArray body = "Hello World";
+    resp->setHeader("Content-Length", QString::number(body.size()));
+    resp->writeHead(200);
+    resp->end(body);
+}
+
+/// main
+
+int main(int argc, char **argv)
+{
+    QCoreApplication app(argc, argv);
+    HelloWorld hello;
+    app.exec();
+}

+ 16 - 0
external/qhttpserver/examples/helloworld/helloworld.h

@@ -0,0 +1,16 @@
+#include "qhttpserverfwd.h"
+
+#include <QObject>
+
+/// HelloWorld
+
+class HelloWorld : public QObject
+{
+    Q_OBJECT
+
+public:
+    HelloWorld();
+
+private slots:
+    void handleRequest(QHttpRequest *req, QHttpResponse *resp);
+};

+ 19 - 0
external/qhttpserver/examples/helloworld/helloworld.pro

@@ -0,0 +1,19 @@
+TARGET = helloworld
+
+QT += network
+QT -= gui
+
+CONFIG += debug
+
+INCLUDEPATH += ../../src
+LIBS += -L../../lib
+
+win32 {
+    debug: LIBS += -lqhttpserverd
+    else: LIBS += -lqhttpserver
+} else {
+    LIBS += -lqhttpserver
+}
+
+SOURCES = helloworld.cpp
+HEADERS = helloworld.h

+ 28 - 0
external/qhttpserver/http-parser/.gitignore

@@ -0,0 +1,28 @@
+/out/
+core
+tags
+*.o
+test
+test_g
+test_fast
+bench
+url_parser
+parsertrace
+parsertrace_g
+*.mk
+*.Makefile
+*.so.*
+*.a
+
+
+# Visual Studio uglies
+*.suo
+*.sln
+*.vcxproj
+*.vcxproj.filters
+*.vcxproj.user
+*.opensdf
+*.ncrunchsolution*
+*.sdf
+*.vsp
+*.psess

+ 8 - 0
external/qhttpserver/http-parser/.mailmap

@@ -0,0 +1,8 @@
+# update AUTHORS with:
+#   git log --all --reverse --format='%aN <%aE>' | perl -ne 'BEGIN{print "# Authors ordered by first contribution.\n"} print unless $h{$_}; $h{$_} = 1' > AUTHORS
+Ryan Dahl <ry@tinyclouds.org>
+Salman Haq <salman.haq@asti-usa.com>
+Simon Zimmermann <simonz05@gmail.com>
+Thomas LE ROUX <thomas@november-eleven.fr> LE ROUX Thomas <thomas@procheo.fr>
+Thomas LE ROUX <thomas@november-eleven.fr> Thomas LE ROUX <thomas@procheo.fr>
+Fedor Indutny <fedor@indutny.com>

+ 13 - 0
external/qhttpserver/http-parser/.travis.yml

@@ -0,0 +1,13 @@
+language: c
+
+compiler:
+  - clang
+  - gcc
+
+script:
+  - "make"
+
+notifications:
+  email: false
+  irc:
+    - "irc.freenode.net#node-ci"

+ 67 - 0
external/qhttpserver/http-parser/AUTHORS

@@ -0,0 +1,67 @@
+# Authors ordered by first contribution.
+Ryan Dahl <ry@tinyclouds.org>
+Jeremy Hinegardner <jeremy@hinegardner.org>
+Sergey Shepelev <temotor@gmail.com>
+Joe Damato <ice799@gmail.com>
+tomika <tomika_nospam@freemail.hu>
+Phoenix Sol <phoenix@burninglabs.com>
+Cliff Frey <cliff@meraki.com>
+Ewen Cheslack-Postava <ewencp@cs.stanford.edu>
+Santiago Gala <sgala@apache.org>
+Tim Becker <tim.becker@syngenio.de>
+Jeff Terrace <jterrace@gmail.com>
+Ben Noordhuis <info@bnoordhuis.nl>
+Nathan Rajlich <nathan@tootallnate.net>
+Mark Nottingham <mnot@mnot.net>
+Aman Gupta <aman@tmm1.net>
+Tim Becker <tim.becker@kuriositaet.de>
+Sean Cunningham <sean.cunningham@mandiant.com>
+Peter Griess <pg@std.in>
+Salman Haq <salman.haq@asti-usa.com>
+Cliff Frey <clifffrey@gmail.com>
+Jon Kolb <jon@b0g.us>
+Fouad Mardini <f.mardini@gmail.com>
+Paul Querna <pquerna@apache.org>
+Felix Geisendörfer <felix@debuggable.com>
+koichik <koichik@improvement.jp>
+Andre Caron <andre.l.caron@gmail.com>
+Ivo Raisr <ivosh@ivosh.net>
+James McLaughlin <jamie@lacewing-project.org>
+David Gwynne <loki@animata.net>
+Thomas LE ROUX <thomas@november-eleven.fr>
+Randy Rizun <rrizun@ortivawireless.com>
+Andre Louis Caron <andre.louis.caron@usherbrooke.ca>
+Simon Zimmermann <simonz05@gmail.com>
+Erik Dubbelboer <erik@dubbelboer.com>
+Martell Malone <martellmalone@gmail.com>
+Bertrand Paquet <bpaquet@octo.com>
+BogDan Vatra <bogdan@kde.org>
+Peter Faiman <peter@thepicard.org>
+Corey Richardson <corey@octayn.net>
+Tóth Tamás <tomika_nospam@freemail.hu>
+Cam Swords <cam.swords@gmail.com>
+Chris Dickinson <christopher.s.dickinson@gmail.com>
+Uli Köhler <ukoehler@btronik.de>
+Charlie Somerville <charlie@charliesomerville.com>
+Patrik Stutz <patrik.stutz@gmail.com>
+Fedor Indutny <fedor.indutny@gmail.com>
+runner <runner.mei@gmail.com>
+Alexis Campailla <alexis@janeasystems.com>
+David Wragg <david@wragg.org>
+Vinnie Falco <vinnie.falco@gmail.com>
+Alex Butum <alexbutum@linux.com>
+Rex Feng <rexfeng@gmail.com>
+Alex Kocharin <alex@kocharin.ru>
+Mark Koopman <markmontymark@yahoo.com>
+Helge Heß <me@helgehess.eu>
+Alexis La Goutte <alexis.lagoutte@gmail.com>
+George Miroshnykov <george.miroshnykov@gmail.com>
+Maciej Małecki <me@mmalecki.com>
+Marc O'Morain <github.com@marcomorain.com>
+Jeff Pinner <jpinner@twitter.com>
+Timothy J Fontaine <tjfontaine@gmail.com>
+Akagi201 <akagi201@gmail.com>
+Romain Giraud <giraud.romain@gmail.com>
+Jay Satiro <raysatiro@yahoo.com>
+Arne Steen <Arne.Steen@gmx.de>
+Kjell Schubert <kjell.schubert@gmail.com>

+ 4 - 0
external/qhttpserver/http-parser/CONTRIBUTIONS

@@ -0,0 +1,4 @@
+Contributors must agree to the Contributor License Agreement before patches
+can be accepted.
+
+http://spreadsheets2.google.com/viewform?hl=en&formkey=dDJXOGUwbzlYaWM4cHN1MERwQS1CSnc6MQ

+ 23 - 0
external/qhttpserver/http-parser/LICENSE-MIT

@@ -0,0 +1,23 @@
+http_parser.c is based on src/http/ngx_http_parse.c from NGINX copyright
+Igor Sysoev.
+
+Additional changes are licensed under the same terms as NGINX and
+copyright Joyent, Inc. and other Node contributors. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE. 

+ 183 - 0
external/qhttpserver/http-parser/README.md

@@ -0,0 +1,183 @@
+HTTP Parser
+===========
+
+[![Build Status](https://travis-ci.org/joyent/http-parser.png?branch=master)](https://travis-ci.org/joyent/http-parser)
+
+This is a parser for HTTP messages written in C. It parses both requests and
+responses. The parser is designed to be used in performance HTTP
+applications. It does not make any syscalls nor allocations, it does not
+buffer data, it can be interrupted at anytime. Depending on your
+architecture, it only requires about 40 bytes of data per message
+stream (in a web server that is per connection).
+
+Features:
+
+  * No dependencies
+  * Handles persistent streams (keep-alive).
+  * Decodes chunked encoding.
+  * Upgrade support
+  * Defends against buffer overflow attacks.
+
+The parser extracts the following information from HTTP messages:
+
+  * Header fields and values
+  * Content-Length
+  * Request method
+  * Response status code
+  * Transfer-Encoding
+  * HTTP version
+  * Request URL
+  * Message body
+
+
+Usage
+-----
+
+One `http_parser` object is used per TCP connection. Initialize the struct
+using `http_parser_init()` and set the callbacks. That might look something
+like this for a request parser:
+```c
+http_parser_settings settings;
+settings.on_url = my_url_callback;
+settings.on_header_field = my_header_field_callback;
+/* ... */
+
+http_parser *parser = malloc(sizeof(http_parser));
+http_parser_init(parser, HTTP_REQUEST);
+parser->data = my_socket;
+```
+
+When data is received on the socket execute the parser and check for errors.
+
+```c
+size_t len = 80*1024, nparsed;
+char buf[len];
+ssize_t recved;
+
+recved = recv(fd, buf, len, 0);
+
+if (recved < 0) {
+  /* Handle error. */
+}
+
+/* Start up / continue the parser.
+ * Note we pass recved==0 to signal that EOF has been received.
+ */
+nparsed = http_parser_execute(parser, &settings, buf, recved);
+
+if (parser->upgrade) {
+  /* handle new protocol */
+} else if (nparsed != recved) {
+  /* Handle error. Usually just close the connection. */
+}
+```
+
+HTTP needs to know where the end of the stream is. For example, sometimes
+servers send responses without Content-Length and expect the client to
+consume input (for the body) until EOF. To tell http_parser about EOF, give
+`0` as the fourth parameter to `http_parser_execute()`. Callbacks and errors
+can still be encountered during an EOF, so one must still be prepared
+to receive them.
+
+Scalar valued message information such as `status_code`, `method`, and the
+HTTP version are stored in the parser structure. This data is only
+temporally stored in `http_parser` and gets reset on each new message. If
+this information is needed later, copy it out of the structure during the
+`headers_complete` callback.
+
+The parser decodes the transfer-encoding for both requests and responses
+transparently. That is, a chunked encoding is decoded before being sent to
+the on_body callback.
+
+
+The Special Problem of Upgrade
+------------------------------
+
+HTTP supports upgrading the connection to a different protocol. An
+increasingly common example of this is the Web Socket protocol which sends
+a request like
+
+        GET /demo HTTP/1.1
+        Upgrade: WebSocket
+        Connection: Upgrade
+        Host: example.com
+        Origin: http://example.com
+        WebSocket-Protocol: sample
+
+followed by non-HTTP data.
+
+(See http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 for more
+information the Web Socket protocol.)
+
+To support this, the parser will treat this as a normal HTTP message without a
+body, issuing both on_headers_complete and on_message_complete callbacks. However
+http_parser_execute() will stop parsing at the end of the headers and return.
+
+The user is expected to check if `parser->upgrade` has been set to 1 after
+`http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied
+offset by the return value of `http_parser_execute()`.
+
+
+Callbacks
+---------
+
+During the `http_parser_execute()` call, the callbacks set in
+`http_parser_settings` will be executed. The parser maintains state and
+never looks behind, so buffering the data is not necessary. If you need to
+save certain data for later usage, you can do that from the callbacks.
+
+There are two types of callbacks:
+
+* notification `typedef int (*http_cb) (http_parser*);`
+    Callbacks: on_message_begin, on_headers_complete, on_message_complete.
+* data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);`
+    Callbacks: (requests only) on_url,
+               (common) on_header_field, on_header_value, on_body;
+
+Callbacks must return 0 on success. Returning a non-zero value indicates
+error to the parser, making it exit immediately.
+
+In case you parse HTTP message in chunks (i.e. `read()` request line
+from socket, parse, read half headers, parse, etc) your data callbacks
+may be called more than once. Http-parser guarantees that data pointer is only
+valid for the lifetime of callback. You can also `read()` into a heap allocated
+buffer to avoid copying memory around if this fits your application.
+
+Reading headers may be a tricky task if you read/parse headers partially.
+Basically, you need to remember whether last header callback was field or value
+and apply the following logic:
+
+    (on_header_field and on_header_value shortened to on_h_*)
+     ------------------------ ------------ --------------------------------------------
+    | State (prev. callback) | Callback   | Description/action                         |
+     ------------------------ ------------ --------------------------------------------
+    | nothing (first call)   | on_h_field | Allocate new buffer and copy callback data |
+    |                        |            | into it                                    |
+     ------------------------ ------------ --------------------------------------------
+    | value                  | on_h_field | New header started.                        |
+    |                        |            | Copy current name,value buffers to headers |
+    |                        |            | list and allocate new buffer for new name  |
+     ------------------------ ------------ --------------------------------------------
+    | field                  | on_h_field | Previous name continues. Reallocate name   |
+    |                        |            | buffer and append callback data to it      |
+     ------------------------ ------------ --------------------------------------------
+    | field                  | on_h_value | Value for current header started. Allocate |
+    |                        |            | new buffer and copy callback data to it    |
+     ------------------------ ------------ --------------------------------------------
+    | value                  | on_h_value | Value continues. Reallocate value buffer   |
+    |                        |            | and append callback data to it             |
+     ------------------------ ------------ --------------------------------------------
+
+
+Parsing URLs
+------------
+
+A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`.
+Users of this library may wish to use it to parse URLs constructed from
+consecutive `on_url` callbacks.
+
+See examples of reading in headers:
+
+* [partial example](http://gist.github.com/155877) in C
+* [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C
+* [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript

+ 111 - 0
external/qhttpserver/http-parser/bench.c

@@ -0,0 +1,111 @@
+/* Copyright Fedor Indutny. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#include "http_parser.h"
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/time.h>
+
+static const char data[] =
+    "POST /joyent/http-parser HTTP/1.1\r\n"
+    "Host: github.com\r\n"
+    "DNT: 1\r\n"
+    "Accept-Encoding: gzip, deflate, sdch\r\n"
+    "Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4\r\n"
+    "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) "
+        "AppleWebKit/537.36 (KHTML, like Gecko) "
+        "Chrome/39.0.2171.65 Safari/537.36\r\n"
+    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,"
+        "image/webp,*/*;q=0.8\r\n"
+    "Referer: https://github.com/joyent/http-parser\r\n"
+    "Connection: keep-alive\r\n"
+    "Transfer-Encoding: chunked\r\n"
+    "Cache-Control: max-age=0\r\n\r\nb\r\nhello world\r\n0\r\n\r\n";
+static const size_t data_len = sizeof(data) - 1;
+
+static int on_info(http_parser* p) {
+  return 0;
+}
+
+
+static int on_data(http_parser* p, const char *at, size_t length) {
+  return 0;
+}
+
+static http_parser_settings settings = {
+  .on_message_begin = on_info,
+  .on_headers_complete = on_info,
+  .on_message_complete = on_info,
+  .on_header_field = on_data,
+  .on_header_value = on_data,
+  .on_url = on_data,
+  .on_status = on_data,
+  .on_body = on_data
+};
+
+int bench(int iter_count, int silent) {
+  struct http_parser parser;
+  int i;
+  int err;
+  struct timeval start;
+  struct timeval end;
+  float rps;
+
+  if (!silent) {
+    err = gettimeofday(&start, NULL);
+    assert(err == 0);
+  }
+
+  for (i = 0; i < iter_count; i++) {
+    size_t parsed;
+    http_parser_init(&parser, HTTP_REQUEST);
+
+    parsed = http_parser_execute(&parser, &settings, data, data_len);
+    assert(parsed == data_len);
+  }
+
+  if (!silent) {
+    err = gettimeofday(&end, NULL);
+    assert(err == 0);
+
+    fprintf(stdout, "Benchmark result:\n");
+
+    rps = (float) (end.tv_sec - start.tv_sec) +
+          (end.tv_usec - start.tv_usec) * 1e-6f;
+    fprintf(stdout, "Took %f seconds to run\n", rps);
+
+    rps = (float) iter_count / rps;
+    fprintf(stdout, "%f req/sec\n", rps);
+    fflush(stdout);
+  }
+
+  return 0;
+}
+
+int main(int argc, char** argv) {
+  if (argc == 2 && strcmp(argv[1], "infinite") == 0) {
+    for (;;)
+      bench(5000000, 1);
+    return 0;
+  } else {
+    return bench(5000000, 0);
+  }
+}

+ 160 - 0
external/qhttpserver/http-parser/contrib/parsertrace.c

@@ -0,0 +1,160 @@
+/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
+ *
+ * Additional changes are licensed under the same terms as NGINX and
+ * copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+/* Dump what the parser finds to stdout as it happen */
+
+#include "http_parser.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int on_message_begin(http_parser* _) {
+  (void)_;
+  printf("\n***MESSAGE BEGIN***\n\n");
+  return 0;
+}
+
+int on_headers_complete(http_parser* _) {
+  (void)_;
+  printf("\n***HEADERS COMPLETE***\n\n");
+  return 0;
+}
+
+int on_message_complete(http_parser* _) {
+  (void)_;
+  printf("\n***MESSAGE COMPLETE***\n\n");
+  return 0;
+}
+
+int on_url(http_parser* _, const char* at, size_t length) {
+  (void)_;
+  printf("Url: %.*s\n", (int)length, at);
+  return 0;
+}
+
+int on_header_field(http_parser* _, const char* at, size_t length) {
+  (void)_;
+  printf("Header field: %.*s\n", (int)length, at);
+  return 0;
+}
+
+int on_header_value(http_parser* _, const char* at, size_t length) {
+  (void)_;
+  printf("Header value: %.*s\n", (int)length, at);
+  return 0;
+}
+
+int on_body(http_parser* _, const char* at, size_t length) {
+  (void)_;
+  printf("Body: %.*s\n", (int)length, at);
+  return 0;
+}
+
+void usage(const char* name) {
+  fprintf(stderr,
+          "Usage: %s $type $filename\n"
+          "  type: -x, where x is one of {r,b,q}\n"
+          "  parses file as a Response, reQuest, or Both\n",
+          name);
+  exit(EXIT_FAILURE);
+}
+
+int main(int argc, char* argv[]) {
+  enum http_parser_type file_type;
+
+  if (argc != 3) {
+    usage(argv[0]);
+  }
+
+  char* type = argv[1];
+  if (type[0] != '-') {
+    usage(argv[0]);
+  }
+
+  switch (type[1]) {
+    /* in the case of "-", type[1] will be NUL */
+    case 'r':
+      file_type = HTTP_RESPONSE;
+      break;
+    case 'q':
+      file_type = HTTP_REQUEST;
+      break;
+    case 'b':
+      file_type = HTTP_BOTH;
+      break;
+    default:
+      usage(argv[0]);
+  }
+
+  char* filename = argv[2];
+  FILE* file = fopen(filename, "r");
+  if (file == NULL) {
+    perror("fopen");
+    goto fail;
+  }
+
+  fseek(file, 0, SEEK_END);
+  long file_length = ftell(file);
+  if (file_length == -1) {
+    perror("ftell");
+    goto fail;
+  }
+  fseek(file, 0, SEEK_SET);
+
+  char* data = malloc(file_length);
+  if (fread(data, 1, file_length, file) != (size_t)file_length) {
+    fprintf(stderr, "couldn't read entire file\n");
+    free(data);
+    goto fail;
+  }
+
+  http_parser_settings settings;
+  memset(&settings, 0, sizeof(settings));
+  settings.on_message_begin = on_message_begin;
+  settings.on_url = on_url;
+  settings.on_header_field = on_header_field;
+  settings.on_header_value = on_header_value;
+  settings.on_headers_complete = on_headers_complete;
+  settings.on_body = on_body;
+  settings.on_message_complete = on_message_complete;
+
+  http_parser parser;
+  http_parser_init(&parser, file_type);
+  size_t nparsed = http_parser_execute(&parser, &settings, data, file_length);
+  free(data);
+
+  if (nparsed != (size_t)file_length) {
+    fprintf(stderr,
+            "Error: %s (%s)\n",
+            http_errno_description(HTTP_PARSER_ERRNO(&parser)),
+            http_errno_name(HTTP_PARSER_ERRNO(&parser)));
+    goto fail;
+  }
+
+  return EXIT_SUCCESS;
+
+fail:
+  fclose(file);
+  return EXIT_FAILURE;
+}

+ 46 - 0
external/qhttpserver/http-parser/contrib/url_parser.c

@@ -0,0 +1,46 @@
+#include "http_parser.h"
+#include <stdio.h>
+#include <string.h>
+
+void
+dump_url (const char *url, const struct http_parser_url *u)
+{
+  unsigned int i;
+
+  printf("\tfield_set: 0x%x, port: %u\n", u->field_set, u->port);
+  for (i = 0; i < UF_MAX; i++) {
+    if ((u->field_set & (1 << i)) == 0) {
+      printf("\tfield_data[%u]: unset\n", i);
+      continue;
+    }
+
+    printf("\tfield_data[%u]: off: %u, len: %u, part: %.*s\n",
+           i,
+           u->field_data[i].off,
+           u->field_data[i].len,
+           u->field_data[i].len,
+           url + u->field_data[i].off);
+  }
+}
+
+int main(int argc, char ** argv) {
+  struct http_parser_url u;
+  int len, connect, result;
+
+  if (argc != 3) {
+    printf("Syntax : %s connect|get url\n", argv[0]);
+    return 1;
+  }
+  len = strlen(argv[2]);
+  connect = strcmp("connect", argv[1]) == 0 ? 1 : 0;
+  printf("Parsing %s, connect %d\n", argv[2], connect);
+
+  result = http_parser_parse_url(argv[2], len, connect, &u);
+  if (result != 0) {
+    printf("Parse error : %d\n", result);
+    return result;
+  }
+  printf("Parse ok, result : \n");
+  dump_url(argv[2], &u);
+  return 0;
+}

+ 2429 - 0
external/qhttpserver/http-parser/http_parser.c

@@ -0,0 +1,2429 @@
+/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
+ *
+ * Additional changes are licensed under the same terms as NGINX and
+ * copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#include "http_parser.h"
+#include <assert.h>
+#include <stddef.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#ifndef ULLONG_MAX
+# define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */
+#endif
+
+#ifndef MIN
+# define MIN(a,b) ((a) < (b) ? (a) : (b))
+#endif
+
+#ifndef ARRAY_SIZE
+# define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+#endif
+
+#ifndef BIT_AT
+# define BIT_AT(a, i)                                                \
+  (!!((unsigned int) (a)[(unsigned int) (i) >> 3] &                  \
+   (1 << ((unsigned int) (i) & 7))))
+#endif
+
+#ifndef ELEM_AT
+# define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v))
+#endif
+
+#define SET_ERRNO(e)                                                 \
+do {                                                                 \
+  parser->http_errno = (e);                                          \
+} while(0)
+
+#define CURRENT_STATE() p_state
+#define UPDATE_STATE(V) p_state = (enum state) (V);
+#define RETURN(V)                                                    \
+do {                                                                 \
+  parser->state = CURRENT_STATE();                                   \
+  return (V);                                                        \
+} while (0);
+#define REEXECUTE()                                                  \
+  goto reexecute;                                                    \
+
+
+#ifdef __GNUC__
+# define LIKELY(X) __builtin_expect(!!(X), 1)
+# define UNLIKELY(X) __builtin_expect(!!(X), 0)
+#else
+# define LIKELY(X) (X)
+# define UNLIKELY(X) (X)
+#endif
+
+
+/* Run the notify callback FOR, returning ER if it fails */
+#define CALLBACK_NOTIFY_(FOR, ER)                                    \
+do {                                                                 \
+  assert(HTTP_PARSER_ERRNO(parser) == HPE_OK);                       \
+                                                                     \
+  if (LIKELY(settings->on_##FOR)) {                                  \
+    parser->state = CURRENT_STATE();                                 \
+    if (UNLIKELY(0 != settings->on_##FOR(parser))) {                 \
+      SET_ERRNO(HPE_CB_##FOR);                                       \
+    }                                                                \
+    UPDATE_STATE(parser->state);                                     \
+                                                                     \
+    /* We either errored above or got paused; get out */             \
+    if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) {             \
+      return (ER);                                                   \
+    }                                                                \
+  }                                                                  \
+} while (0)
+
+/* Run the notify callback FOR and consume the current byte */
+#define CALLBACK_NOTIFY(FOR)            CALLBACK_NOTIFY_(FOR, p - data + 1)
+
+/* Run the notify callback FOR and don't consume the current byte */
+#define CALLBACK_NOTIFY_NOADVANCE(FOR)  CALLBACK_NOTIFY_(FOR, p - data)
+
+/* Run data callback FOR with LEN bytes, returning ER if it fails */
+#define CALLBACK_DATA_(FOR, LEN, ER)                                 \
+do {                                                                 \
+  assert(HTTP_PARSER_ERRNO(parser) == HPE_OK);                       \
+                                                                     \
+  if (FOR##_mark) {                                                  \
+    if (LIKELY(settings->on_##FOR)) {                                \
+      parser->state = CURRENT_STATE();                               \
+      if (UNLIKELY(0 !=                                              \
+                   settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \
+        SET_ERRNO(HPE_CB_##FOR);                                     \
+      }                                                              \
+      UPDATE_STATE(parser->state);                                   \
+                                                                     \
+      /* We either errored above or got paused; get out */           \
+      if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) {           \
+        return (ER);                                                 \
+      }                                                              \
+    }                                                                \
+    FOR##_mark = NULL;                                               \
+  }                                                                  \
+} while (0)
+  
+/* Run the data callback FOR and consume the current byte */
+#define CALLBACK_DATA(FOR)                                           \
+    CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1)
+
+/* Run the data callback FOR and don't consume the current byte */
+#define CALLBACK_DATA_NOADVANCE(FOR)                                 \
+    CALLBACK_DATA_(FOR, p - FOR##_mark, p - data)
+
+/* Set the mark FOR; non-destructive if mark is already set */
+#define MARK(FOR)                                                    \
+do {                                                                 \
+  if (!FOR##_mark) {                                                 \
+    FOR##_mark = p;                                                  \
+  }                                                                  \
+} while (0)
+
+/* Don't allow the total size of the HTTP headers (including the status
+ * line) to exceed HTTP_MAX_HEADER_SIZE.  This check is here to protect
+ * embedders against denial-of-service attacks where the attacker feeds
+ * us a never-ending header that the embedder keeps buffering.
+ *
+ * This check is arguably the responsibility of embedders but we're doing
+ * it on the embedder's behalf because most won't bother and this way we
+ * make the web a little safer.  HTTP_MAX_HEADER_SIZE is still far bigger
+ * than any reasonable request or response so this should never affect
+ * day-to-day operation.
+ */
+#define COUNT_HEADER_SIZE(V)                                         \
+do {                                                                 \
+  parser->nread += (V);                                              \
+  if (UNLIKELY(parser->nread > (HTTP_MAX_HEADER_SIZE))) {            \
+    SET_ERRNO(HPE_HEADER_OVERFLOW);                                  \
+    goto error;                                                      \
+  }                                                                  \
+} while (0)
+
+
+#define PROXY_CONNECTION "proxy-connection"
+#define CONNECTION "connection"
+#define CONTENT_LENGTH "content-length"
+#define TRANSFER_ENCODING "transfer-encoding"
+#define UPGRADE "upgrade"
+#define CHUNKED "chunked"
+#define KEEP_ALIVE "keep-alive"
+#define CLOSE "close"
+
+
+static const char *method_strings[] =
+  {
+#define XX(num, name, string) #string,
+  HTTP_METHOD_MAP(XX)
+#undef XX
+  };
+
+
+/* Tokens as defined by rfc 2616. Also lowercases them.
+ *        token       = 1*<any CHAR except CTLs or separators>
+ *     separators     = "(" | ")" | "<" | ">" | "@"
+ *                    | "," | ";" | ":" | "\" | <">
+ *                    | "/" | "[" | "]" | "?" | "="
+ *                    | "{" | "}" | SP | HT
+ */
+static const char tokens[256] = {
+/*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
+        0,       0,       0,       0,       0,       0,       0,       0,
+/*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
+        0,      '!',      0,      '#',     '$',     '%',     '&',    '\'',
+/*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
+        0,       0,      '*',     '+',      0,      '-',     '.',      0,
+/*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
+       '0',     '1',     '2',     '3',     '4',     '5',     '6',     '7',
+/*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
+       '8',     '9',      0,       0,       0,       0,       0,       0,
+/*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
+        0,      'a',     'b',     'c',     'd',     'e',     'f',     'g',
+/*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
+       'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
+/*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
+       'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
+/*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
+       'x',     'y',     'z',      0,       0,       0,      '^',     '_',
+/*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
+       '`',     'a',     'b',     'c',     'd',     'e',     'f',     'g',
+/* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
+       'h',     'i',     'j',     'k',     'l',     'm',     'n',     'o',
+/* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
+       'p',     'q',     'r',     's',     't',     'u',     'v',     'w',
+/* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
+       'x',     'y',     'z',      0,      '|',      0,      '~',       0 };
+
+
+static const int8_t unhex[256] =
+  {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
+  ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+  };
+
+
+#if HTTP_PARSER_STRICT
+# define T(v) 0
+#else
+# define T(v) v
+#endif
+
+
+static const uint8_t normal_url_char[32] = {
+/*   0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel  */
+        0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
+/*   8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si   */
+        0    | T(2)   |   0    |   0    | T(16)  |   0    |   0    |   0,
+/*  16 dle   17 dc1   18 dc2   19 dc3   20 dc4   21 nak   22 syn   23 etb */
+        0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
+/*  24 can   25 em    26 sub   27 esc   28 fs    29 gs    30 rs    31 us  */
+        0    |   0    |   0    |   0    |   0    |   0    |   0    |   0,
+/*  32 sp    33  !    34  "    35  #    36  $    37  %    38  &    39  '  */
+        0    |   2    |   4    |   0    |   16   |   32   |   64   |  128,
+/*  40  (    41  )    42  *    43  +    44  ,    45  -    46  .    47  /  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  48  0    49  1    50  2    51  3    52  4    53  5    54  6    55  7  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  56  8    57  9    58  :    59  ;    60  <    61  =    62  >    63  ?  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |   0,
+/*  64  @    65  A    66  B    67  C    68  D    69  E    70  F    71  G  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  72  H    73  I    74  J    75  K    76  L    77  M    78  N    79  O  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  80  P    81  Q    82  R    83  S    84  T    85  U    86  V    87  W  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  88  X    89  Y    90  Z    91  [    92  \    93  ]    94  ^    95  _  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/*  96  `    97  a    98  b    99  c   100  d   101  e   102  f   103  g  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/* 104  h   105  i   106  j   107  k   108  l   109  m   110  n   111  o  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/* 112  p   113  q   114  r   115  s   116  t   117  u   118  v   119  w  */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |  128,
+/* 120  x   121  y   122  z   123  {   124  |   125  }   126  ~   127 del */
+        1    |   2    |   4    |   8    |   16   |   32   |   64   |   0, };
+
+#undef T
+
+enum state
+  { s_dead = 1 /* important that this is > 0 */
+
+  , s_start_req_or_res
+  , s_res_or_resp_H
+  , s_start_res
+  , s_res_H
+  , s_res_HT
+  , s_res_HTT
+  , s_res_HTTP
+  , s_res_first_http_major
+  , s_res_http_major
+  , s_res_first_http_minor
+  , s_res_http_minor
+  , s_res_first_status_code
+  , s_res_status_code
+  , s_res_status_start
+  , s_res_status
+  , s_res_line_almost_done
+
+  , s_start_req
+
+  , s_req_method
+  , s_req_spaces_before_url
+  , s_req_schema
+  , s_req_schema_slash
+  , s_req_schema_slash_slash
+  , s_req_server_start
+  , s_req_server
+  , s_req_server_with_at
+  , s_req_path
+  , s_req_query_string_start
+  , s_req_query_string
+  , s_req_fragment_start
+  , s_req_fragment
+  , s_req_http_start
+  , s_req_http_H
+  , s_req_http_HT
+  , s_req_http_HTT
+  , s_req_http_HTTP
+  , s_req_first_http_major
+  , s_req_http_major
+  , s_req_first_http_minor
+  , s_req_http_minor
+  , s_req_line_almost_done
+
+  , s_header_field_start
+  , s_header_field
+  , s_header_value_discard_ws
+  , s_header_value_discard_ws_almost_done
+  , s_header_value_discard_lws
+  , s_header_value_start
+  , s_header_value
+  , s_header_value_lws
+
+  , s_header_almost_done
+
+  , s_chunk_size_start
+  , s_chunk_size
+  , s_chunk_parameters
+  , s_chunk_size_almost_done
+
+  , s_headers_almost_done
+  , s_headers_done
+
+  /* Important: 's_headers_done' must be the last 'header' state. All
+   * states beyond this must be 'body' states. It is used for overflow
+   * checking. See the PARSING_HEADER() macro.
+   */
+
+  , s_chunk_data
+  , s_chunk_data_almost_done
+  , s_chunk_data_done
+
+  , s_body_identity
+  , s_body_identity_eof
+
+  , s_message_done
+  };
+
+
+#define PARSING_HEADER(state) (state <= s_headers_done)
+
+
+enum header_states
+  { h_general = 0
+  , h_C
+  , h_CO
+  , h_CON
+
+  , h_matching_connection
+  , h_matching_proxy_connection
+  , h_matching_content_length
+  , h_matching_transfer_encoding
+  , h_matching_upgrade
+
+  , h_connection
+  , h_content_length
+  , h_transfer_encoding
+  , h_upgrade
+
+  , h_matching_transfer_encoding_chunked
+  , h_matching_connection_token_start
+  , h_matching_connection_keep_alive
+  , h_matching_connection_close
+  , h_matching_connection_upgrade
+  , h_matching_connection_token
+
+  , h_transfer_encoding_chunked
+  , h_connection_keep_alive
+  , h_connection_close
+  , h_connection_upgrade
+  };
+
+enum http_host_state
+  {
+    s_http_host_dead = 1
+  , s_http_userinfo_start
+  , s_http_userinfo
+  , s_http_host_start
+  , s_http_host_v6_start
+  , s_http_host
+  , s_http_host_v6
+  , s_http_host_v6_end
+  , s_http_host_port_start
+  , s_http_host_port
+};
+
+/* Macros for character classes; depends on strict-mode  */
+#define CR                  '\r'
+#define LF                  '\n'
+#define LOWER(c)            (unsigned char)(c | 0x20)
+#define IS_ALPHA(c)         (LOWER(c) >= 'a' && LOWER(c) <= 'z')
+#define IS_NUM(c)           ((c) >= '0' && (c) <= '9')
+#define IS_ALPHANUM(c)      (IS_ALPHA(c) || IS_NUM(c))
+#define IS_HEX(c)           (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'))
+#define IS_MARK(c)          ((c) == '-' || (c) == '_' || (c) == '.' || \
+  (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
+  (c) == ')')
+#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \
+  (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
+  (c) == '$' || (c) == ',')
+
+#define STRICT_TOKEN(c)     (tokens[(unsigned char)c])
+
+#if HTTP_PARSER_STRICT
+#define TOKEN(c)            (tokens[(unsigned char)c])
+#define IS_URL_CHAR(c)      (BIT_AT(normal_url_char, (unsigned char)c))
+#define IS_HOST_CHAR(c)     (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
+#else
+#define TOKEN(c)            ((c == ' ') ? ' ' : tokens[(unsigned char)c])
+#define IS_URL_CHAR(c)                                                         \
+  (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80))
+#define IS_HOST_CHAR(c)                                                        \
+  (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
+#endif
+
+
+#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res)
+
+
+#if HTTP_PARSER_STRICT
+# define STRICT_CHECK(cond)                                          \
+do {                                                                 \
+  if (cond) {                                                        \
+    SET_ERRNO(HPE_STRICT);                                           \
+    goto error;                                                      \
+  }                                                                  \
+} while (0)
+# define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead)
+#else
+# define STRICT_CHECK(cond)
+# define NEW_MESSAGE() start_state
+#endif
+
+
+/* Map errno values to strings for human-readable output */
+#define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s },
+static struct {
+  const char *name;
+  const char *description;
+} http_strerror_tab[] = {
+  HTTP_ERRNO_MAP(HTTP_STRERROR_GEN)
+};
+#undef HTTP_STRERROR_GEN
+
+int http_message_needs_eof(const http_parser *parser);
+
+/* Our URL parser.
+ *
+ * This is designed to be shared by http_parser_execute() for URL validation,
+ * hence it has a state transition + byte-for-byte interface. In addition, it
+ * is meant to be embedded in http_parser_parse_url(), which does the dirty
+ * work of turning state transitions URL components for its API.
+ *
+ * This function should only be invoked with non-space characters. It is
+ * assumed that the caller cares about (and can detect) the transition between
+ * URL and non-URL states by looking for these.
+ */
+static enum state
+parse_url_char(enum state s, const char ch)
+{
+  if (ch == ' ' || ch == '\r' || ch == '\n') {
+    return s_dead;
+  }
+
+#if HTTP_PARSER_STRICT
+  if (ch == '\t' || ch == '\f') {
+    return s_dead;
+  }
+#endif
+
+  switch (s) {
+    case s_req_spaces_before_url:
+      /* Proxied requests are followed by scheme of an absolute URI (alpha).
+       * All methods except CONNECT are followed by '/' or '*'.
+       */
+
+      if (ch == '/' || ch == '*') {
+        return s_req_path;
+      }
+
+      if (IS_ALPHA(ch)) {
+        return s_req_schema;
+      }
+
+      break;
+
+    case s_req_schema:
+      if (IS_ALPHA(ch)) {
+        return s;
+      }
+
+      if (ch == ':') {
+        return s_req_schema_slash;
+      }
+
+      break;
+
+    case s_req_schema_slash:
+      if (ch == '/') {
+        return s_req_schema_slash_slash;
+      }
+
+      break;
+
+    case s_req_schema_slash_slash:
+      if (ch == '/') {
+        return s_req_server_start;
+      }
+
+      break;
+
+    case s_req_server_with_at:
+      if (ch == '@') {
+        return s_dead;
+      }
+
+    /* FALLTHROUGH */
+    case s_req_server_start:
+    case s_req_server:
+      if (ch == '/') {
+        return s_req_path;
+      }
+
+      if (ch == '?') {
+        return s_req_query_string_start;
+      }
+
+      if (ch == '@') {
+        return s_req_server_with_at;
+      }
+
+      if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
+        return s_req_server;
+      }
+
+      break;
+
+    case s_req_path:
+      if (IS_URL_CHAR(ch)) {
+        return s;
+      }
+
+      switch (ch) {
+        case '?':
+          return s_req_query_string_start;
+
+        case '#':
+          return s_req_fragment_start;
+      }
+
+      break;
+
+    case s_req_query_string_start:
+    case s_req_query_string:
+      if (IS_URL_CHAR(ch)) {
+        return s_req_query_string;
+      }
+
+      switch (ch) {
+        case '?':
+          /* allow extra '?' in query string */
+          return s_req_query_string;
+
+        case '#':
+          return s_req_fragment_start;
+      }
+
+      break;
+
+    case s_req_fragment_start:
+      if (IS_URL_CHAR(ch)) {
+        return s_req_fragment;
+      }
+
+      switch (ch) {
+        case '?':
+          return s_req_fragment;
+
+        case '#':
+          return s;
+      }
+
+      break;
+
+    case s_req_fragment:
+      if (IS_URL_CHAR(ch)) {
+        return s;
+      }
+
+      switch (ch) {
+        case '?':
+        case '#':
+          return s;
+      }
+
+      break;
+
+    default:
+      break;
+  }
+
+  /* We should never fall out of the switch above unless there's an error */
+  return s_dead;
+}
+
+size_t http_parser_execute (http_parser *parser,
+                            const http_parser_settings *settings,
+                            const char *data,
+                            size_t len)
+{
+  char c, ch;
+  int8_t unhex_val;
+  const char *p = data;
+  const char *header_field_mark = 0;
+  const char *header_value_mark = 0;
+  const char *url_mark = 0;
+  const char *body_mark = 0;
+  const char *status_mark = 0;
+  enum state p_state = (enum state) parser->state;
+
+  /* We're in an error state. Don't bother doing anything. */
+  if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
+    return 0;
+  }
+
+  if (len == 0) {
+    switch (CURRENT_STATE()) {
+      case s_body_identity_eof:
+        /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if
+         * we got paused.
+         */
+        CALLBACK_NOTIFY_NOADVANCE(message_complete);
+        return 0;
+
+      case s_dead:
+      case s_start_req_or_res:
+      case s_start_res:
+      case s_start_req:
+        return 0;
+
+      default:
+        SET_ERRNO(HPE_INVALID_EOF_STATE);
+        return 1;
+    }
+  }
+
+
+  if (CURRENT_STATE() == s_header_field)
+    header_field_mark = data;
+  if (CURRENT_STATE() == s_header_value)
+    header_value_mark = data;
+  switch (CURRENT_STATE()) {
+  case s_req_path:
+  case s_req_schema:
+  case s_req_schema_slash:
+  case s_req_schema_slash_slash:
+  case s_req_server_start:
+  case s_req_server:
+  case s_req_server_with_at:
+  case s_req_query_string_start:
+  case s_req_query_string:
+  case s_req_fragment_start:
+  case s_req_fragment:
+    url_mark = data;
+    break;
+  case s_res_status:
+    status_mark = data;
+    break;
+  default:
+    break;
+  }
+
+  for (p=data; p != data + len; p++) {
+    ch = *p;
+
+    if (PARSING_HEADER(CURRENT_STATE()))
+      COUNT_HEADER_SIZE(1);
+
+reexecute:
+    switch (CURRENT_STATE()) {
+
+      case s_dead:
+        /* this state is used after a 'Connection: close' message
+         * the parser will error out if it reads another message
+         */
+        if (LIKELY(ch == CR || ch == LF))
+          break;
+
+        SET_ERRNO(HPE_CLOSED_CONNECTION);
+        goto error;
+
+      case s_start_req_or_res:
+      {
+        if (ch == CR || ch == LF)
+          break;
+        parser->flags = 0;
+        parser->content_length = ULLONG_MAX;
+
+        if (ch == 'H') {
+          UPDATE_STATE(s_res_or_resp_H);
+
+          CALLBACK_NOTIFY(message_begin);
+        } else {
+          parser->type = HTTP_REQUEST;
+          UPDATE_STATE(s_start_req);
+          REEXECUTE();
+        }
+
+        break;
+      }
+
+      case s_res_or_resp_H:
+        if (ch == 'T') {
+          parser->type = HTTP_RESPONSE;
+          UPDATE_STATE(s_res_HT);
+        } else {
+          if (UNLIKELY(ch != 'E')) {
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+          }
+
+          parser->type = HTTP_REQUEST;
+          parser->method = HTTP_HEAD;
+          parser->index = 2;
+          UPDATE_STATE(s_req_method);
+        }
+        break;
+
+      case s_start_res:
+      {
+        parser->flags = 0;
+        parser->content_length = ULLONG_MAX;
+
+        switch (ch) {
+          case 'H':
+            UPDATE_STATE(s_res_H);
+            break;
+
+          case CR:
+          case LF:
+            break;
+
+          default:
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+        }
+
+        CALLBACK_NOTIFY(message_begin);
+        break;
+      }
+
+      case s_res_H:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_res_HT);
+        break;
+
+      case s_res_HT:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_res_HTT);
+        break;
+
+      case s_res_HTT:
+        STRICT_CHECK(ch != 'P');
+        UPDATE_STATE(s_res_HTTP);
+        break;
+
+      case s_res_HTTP:
+        STRICT_CHECK(ch != '/');
+        UPDATE_STATE(s_res_first_http_major);
+        break;
+
+      case s_res_first_http_major:
+        if (UNLIKELY(ch < '0' || ch > '9')) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major = ch - '0';
+        UPDATE_STATE(s_res_http_major);
+        break;
+
+      /* major HTTP version or dot */
+      case s_res_http_major:
+      {
+        if (ch == '.') {
+          UPDATE_STATE(s_res_first_http_minor);
+          break;
+        }
+
+        if (!IS_NUM(ch)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major *= 10;
+        parser->http_major += ch - '0';
+
+        if (UNLIKELY(parser->http_major > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* first digit of minor HTTP version */
+      case s_res_first_http_minor:
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor = ch - '0';
+        UPDATE_STATE(s_res_http_minor);
+        break;
+
+      /* minor HTTP version or end of request line */
+      case s_res_http_minor:
+      {
+        if (ch == ' ') {
+          UPDATE_STATE(s_res_first_status_code);
+          break;
+        }
+
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor *= 10;
+        parser->http_minor += ch - '0';
+
+        if (UNLIKELY(parser->http_minor > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_res_first_status_code:
+      {
+        if (!IS_NUM(ch)) {
+          if (ch == ' ') {
+            break;
+          }
+
+          SET_ERRNO(HPE_INVALID_STATUS);
+          goto error;
+        }
+        parser->status_code = ch - '0';
+        UPDATE_STATE(s_res_status_code);
+        break;
+      }
+
+      case s_res_status_code:
+      {
+        if (!IS_NUM(ch)) {
+          switch (ch) {
+            case ' ':
+              UPDATE_STATE(s_res_status_start);
+              break;
+            case CR:
+              UPDATE_STATE(s_res_line_almost_done);
+              break;
+            case LF:
+              UPDATE_STATE(s_header_field_start);
+              break;
+            default:
+              SET_ERRNO(HPE_INVALID_STATUS);
+              goto error;
+          }
+          break;
+        }
+
+        parser->status_code *= 10;
+        parser->status_code += ch - '0';
+
+        if (UNLIKELY(parser->status_code > 999)) {
+          SET_ERRNO(HPE_INVALID_STATUS);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_res_status_start:
+      {
+        if (ch == CR) {
+          UPDATE_STATE(s_res_line_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_field_start);
+          break;
+        }
+
+        MARK(status);
+        UPDATE_STATE(s_res_status);
+        parser->index = 0;
+        break;
+      }
+
+      case s_res_status:
+        if (ch == CR) {
+          UPDATE_STATE(s_res_line_almost_done);
+          CALLBACK_DATA(status);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_field_start);
+          CALLBACK_DATA(status);
+          break;
+        }
+
+        break;
+
+      case s_res_line_almost_done:
+        STRICT_CHECK(ch != LF);
+        UPDATE_STATE(s_header_field_start);
+        break;
+
+      case s_start_req:
+      {
+        if (ch == CR || ch == LF)
+          break;
+        parser->flags = 0;
+        parser->content_length = ULLONG_MAX;
+
+        if (UNLIKELY(!IS_ALPHA(ch))) {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        parser->method = (enum http_method) 0;
+        parser->index = 1;
+        switch (ch) {
+          case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
+          case 'D': parser->method = HTTP_DELETE; break;
+          case 'G': parser->method = HTTP_GET; break;
+          case 'H': parser->method = HTTP_HEAD; break;
+          case 'L': parser->method = HTTP_LOCK; break;
+          case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;
+          case 'N': parser->method = HTTP_NOTIFY; break;
+          case 'O': parser->method = HTTP_OPTIONS; break;
+          case 'P': parser->method = HTTP_POST;
+            /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */
+            break;
+          case 'R': parser->method = HTTP_REPORT; break;
+          case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break;
+          case 'T': parser->method = HTTP_TRACE; break;
+          case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break;
+          default:
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+        }
+        UPDATE_STATE(s_req_method);
+
+        CALLBACK_NOTIFY(message_begin);
+
+        break;
+      }
+
+      case s_req_method:
+      {
+        const char *matcher;
+        if (UNLIKELY(ch == '\0')) {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        matcher = method_strings[parser->method];
+        if (ch == ' ' && matcher[parser->index] == '\0') {
+          UPDATE_STATE(s_req_spaces_before_url);
+        } else if (ch == matcher[parser->index]) {
+          ; /* nada */
+        } else if (parser->method == HTTP_CONNECT) {
+          if (parser->index == 1 && ch == 'H') {
+            parser->method = HTTP_CHECKOUT;
+          } else if (parser->index == 2  && ch == 'P') {
+            parser->method = HTTP_COPY;
+          } else {
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+          }
+        } else if (parser->method == HTTP_MKCOL) {
+          if (parser->index == 1 && ch == 'O') {
+            parser->method = HTTP_MOVE;
+          } else if (parser->index == 1 && ch == 'E') {
+            parser->method = HTTP_MERGE;
+          } else if (parser->index == 1 && ch == '-') {
+            parser->method = HTTP_MSEARCH;
+          } else if (parser->index == 2 && ch == 'A') {
+            parser->method = HTTP_MKACTIVITY;
+          } else if (parser->index == 3 && ch == 'A') {
+            parser->method = HTTP_MKCALENDAR;
+          } else {
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+          }
+        } else if (parser->method == HTTP_SUBSCRIBE) {
+          if (parser->index == 1 && ch == 'E') {
+            parser->method = HTTP_SEARCH;
+          } else {
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+          }
+        } else if (parser->index == 1 && parser->method == HTTP_POST) {
+          if (ch == 'R') {
+            parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */
+          } else if (ch == 'U') {
+            parser->method = HTTP_PUT; /* or HTTP_PURGE */
+          } else if (ch == 'A') {
+            parser->method = HTTP_PATCH;
+          } else {
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+          }
+        } else if (parser->index == 2) {
+          if (parser->method == HTTP_PUT) {
+            if (ch == 'R') {
+              parser->method = HTTP_PURGE;
+            } else {
+              SET_ERRNO(HPE_INVALID_METHOD);
+              goto error;
+            }
+          } else if (parser->method == HTTP_UNLOCK) {
+            if (ch == 'S') {
+              parser->method = HTTP_UNSUBSCRIBE;
+            } else {
+              SET_ERRNO(HPE_INVALID_METHOD);
+              goto error;
+            }
+          } else {
+            SET_ERRNO(HPE_INVALID_METHOD);
+            goto error;
+          }
+        } else if (parser->index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') {
+          parser->method = HTTP_PROPPATCH;
+        } else {
+          SET_ERRNO(HPE_INVALID_METHOD);
+          goto error;
+        }
+
+        ++parser->index;
+        break;
+      }
+
+      case s_req_spaces_before_url:
+      {
+        if (ch == ' ') break;
+
+        MARK(url);
+        if (parser->method == HTTP_CONNECT) {
+          UPDATE_STATE(s_req_server_start);
+        }
+
+        UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
+        if (UNLIKELY(CURRENT_STATE() == s_dead)) {
+          SET_ERRNO(HPE_INVALID_URL);
+          goto error;
+        }
+
+        break;
+      }
+
+      case s_req_schema:
+      case s_req_schema_slash:
+      case s_req_schema_slash_slash:
+      case s_req_server_start:
+      {
+        switch (ch) {
+          /* No whitespace allowed here */
+          case ' ':
+          case CR:
+          case LF:
+            SET_ERRNO(HPE_INVALID_URL);
+            goto error;
+          default:
+            UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
+            if (UNLIKELY(CURRENT_STATE() == s_dead)) {
+              SET_ERRNO(HPE_INVALID_URL);
+              goto error;
+            }
+        }
+
+        break;
+      }
+
+      case s_req_server:
+      case s_req_server_with_at:
+      case s_req_path:
+      case s_req_query_string_start:
+      case s_req_query_string:
+      case s_req_fragment_start:
+      case s_req_fragment:
+      {
+        switch (ch) {
+          case ' ':
+            UPDATE_STATE(s_req_http_start);
+            CALLBACK_DATA(url);
+            break;
+          case CR:
+          case LF:
+            parser->http_major = 0;
+            parser->http_minor = 9;
+            UPDATE_STATE((ch == CR) ?
+              s_req_line_almost_done :
+              s_header_field_start);
+            CALLBACK_DATA(url);
+            break;
+          default:
+            UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
+            if (UNLIKELY(CURRENT_STATE() == s_dead)) {
+              SET_ERRNO(HPE_INVALID_URL);
+              goto error;
+            }
+        }
+        break;
+      }
+
+      case s_req_http_start:
+        switch (ch) {
+          case 'H':
+            UPDATE_STATE(s_req_http_H);
+            break;
+          case ' ':
+            break;
+          default:
+            SET_ERRNO(HPE_INVALID_CONSTANT);
+            goto error;
+        }
+        break;
+
+      case s_req_http_H:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_req_http_HT);
+        break;
+
+      case s_req_http_HT:
+        STRICT_CHECK(ch != 'T');
+        UPDATE_STATE(s_req_http_HTT);
+        break;
+
+      case s_req_http_HTT:
+        STRICT_CHECK(ch != 'P');
+        UPDATE_STATE(s_req_http_HTTP);
+        break;
+
+      case s_req_http_HTTP:
+        STRICT_CHECK(ch != '/');
+        UPDATE_STATE(s_req_first_http_major);
+        break;
+
+      /* first digit of major HTTP version */
+      case s_req_first_http_major:
+        if (UNLIKELY(ch < '1' || ch > '9')) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major = ch - '0';
+        UPDATE_STATE(s_req_http_major);
+        break;
+
+      /* major HTTP version or dot */
+      case s_req_http_major:
+      {
+        if (ch == '.') {
+          UPDATE_STATE(s_req_first_http_minor);
+          break;
+        }
+
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_major *= 10;
+        parser->http_major += ch - '0';
+
+        if (UNLIKELY(parser->http_major > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* first digit of minor HTTP version */
+      case s_req_first_http_minor:
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor = ch - '0';
+        UPDATE_STATE(s_req_http_minor);
+        break;
+
+      /* minor HTTP version or end of request line */
+      case s_req_http_minor:
+      {
+        if (ch == CR) {
+          UPDATE_STATE(s_req_line_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_field_start);
+          break;
+        }
+
+        /* XXX allow spaces after digit? */
+
+        if (UNLIKELY(!IS_NUM(ch))) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        parser->http_minor *= 10;
+        parser->http_minor += ch - '0';
+
+        if (UNLIKELY(parser->http_minor > 999)) {
+          SET_ERRNO(HPE_INVALID_VERSION);
+          goto error;
+        }
+
+        break;
+      }
+
+      /* end of request line */
+      case s_req_line_almost_done:
+      {
+        if (UNLIKELY(ch != LF)) {
+          SET_ERRNO(HPE_LF_EXPECTED);
+          goto error;
+        }
+
+        UPDATE_STATE(s_header_field_start);
+        break;
+      }
+
+      case s_header_field_start:
+      {
+        if (ch == CR) {
+          UPDATE_STATE(s_headers_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          /* they might be just sending \n instead of \r\n so this would be
+           * the second \n to denote the end of headers*/
+          UPDATE_STATE(s_headers_almost_done);
+          REEXECUTE();
+        }
+
+        c = TOKEN(ch);
+
+        if (UNLIKELY(!c)) {
+          SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+          goto error;
+        }
+
+        MARK(header_field);
+
+        parser->index = 0;
+        UPDATE_STATE(s_header_field);
+
+        switch (c) {
+          case 'c':
+            parser->header_state = h_C;
+            break;
+
+          case 'p':
+            parser->header_state = h_matching_proxy_connection;
+            break;
+
+          case 't':
+            parser->header_state = h_matching_transfer_encoding;
+            break;
+
+          case 'u':
+            parser->header_state = h_matching_upgrade;
+            break;
+
+          default:
+            parser->header_state = h_general;
+            break;
+        }
+        break;
+      }
+
+      case s_header_field:
+      {
+        const char* start = p;
+        for (; p != data + len; p++) {
+          ch = *p;
+          c = TOKEN(ch);
+
+          if (!c)
+            break;
+
+          switch (parser->header_state) {
+            case h_general:
+              break;
+
+            case h_C:
+              parser->index++;
+              parser->header_state = (c == 'o' ? h_CO : h_general);
+              break;
+
+            case h_CO:
+              parser->index++;
+              parser->header_state = (c == 'n' ? h_CON : h_general);
+              break;
+
+            case h_CON:
+              parser->index++;
+              switch (c) {
+                case 'n':
+                  parser->header_state = h_matching_connection;
+                  break;
+                case 't':
+                  parser->header_state = h_matching_content_length;
+                  break;
+                default:
+                  parser->header_state = h_general;
+                  break;
+              }
+              break;
+
+            /* connection */
+
+            case h_matching_connection:
+              parser->index++;
+              if (parser->index > sizeof(CONNECTION)-1
+                  || c != CONNECTION[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(CONNECTION)-2) {
+                parser->header_state = h_connection;
+              }
+              break;
+
+            /* proxy-connection */
+
+            case h_matching_proxy_connection:
+              parser->index++;
+              if (parser->index > sizeof(PROXY_CONNECTION)-1
+                  || c != PROXY_CONNECTION[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(PROXY_CONNECTION)-2) {
+                parser->header_state = h_connection;
+              }
+              break;
+
+            /* content-length */
+
+            case h_matching_content_length:
+              parser->index++;
+              if (parser->index > sizeof(CONTENT_LENGTH)-1
+                  || c != CONTENT_LENGTH[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(CONTENT_LENGTH)-2) {
+                parser->header_state = h_content_length;
+              }
+              break;
+
+            /* transfer-encoding */
+
+            case h_matching_transfer_encoding:
+              parser->index++;
+              if (parser->index > sizeof(TRANSFER_ENCODING)-1
+                  || c != TRANSFER_ENCODING[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) {
+                parser->header_state = h_transfer_encoding;
+              }
+              break;
+
+            /* upgrade */
+
+            case h_matching_upgrade:
+              parser->index++;
+              if (parser->index > sizeof(UPGRADE)-1
+                  || c != UPGRADE[parser->index]) {
+                parser->header_state = h_general;
+              } else if (parser->index == sizeof(UPGRADE)-2) {
+                parser->header_state = h_upgrade;
+              }
+              break;
+
+            case h_connection:
+            case h_content_length:
+            case h_transfer_encoding:
+            case h_upgrade:
+              if (ch != ' ') parser->header_state = h_general;
+              break;
+
+            default:
+              assert(0 && "Unknown header_state");
+              break;
+          }
+        }
+
+        COUNT_HEADER_SIZE(p - start);
+
+        if (p == data + len) {
+          --p;
+          break;
+        }
+
+        if (ch == ':') {
+          UPDATE_STATE(s_header_value_discard_ws);
+          CALLBACK_DATA(header_field);
+          break;
+        }
+
+        SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+        goto error;
+      }
+
+      case s_header_value_discard_ws:
+        if (ch == ' ' || ch == '\t') break;
+
+        if (ch == CR) {
+          UPDATE_STATE(s_header_value_discard_ws_almost_done);
+          break;
+        }
+
+        if (ch == LF) {
+          UPDATE_STATE(s_header_value_discard_lws);
+          break;
+        }
+
+        /* FALLTHROUGH */
+
+      case s_header_value_start:
+      {
+        MARK(header_value);
+
+        UPDATE_STATE(s_header_value);
+        parser->index = 0;
+
+        c = LOWER(ch);
+
+        switch (parser->header_state) {
+          case h_upgrade:
+            parser->flags |= F_UPGRADE;
+            parser->header_state = h_general;
+            break;
+
+          case h_transfer_encoding:
+            /* looking for 'Transfer-Encoding: chunked' */
+            if ('c' == c) {
+              parser->header_state = h_matching_transfer_encoding_chunked;
+            } else {
+              parser->header_state = h_general;
+            }
+            break;
+
+          case h_content_length:
+            if (UNLIKELY(!IS_NUM(ch))) {
+              SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+              goto error;
+            }
+
+            parser->content_length = ch - '0';
+            break;
+
+          case h_connection:
+            /* looking for 'Connection: keep-alive' */
+            if (c == 'k') {
+              parser->header_state = h_matching_connection_keep_alive;
+            /* looking for 'Connection: close' */
+            } else if (c == 'c') {
+              parser->header_state = h_matching_connection_close;
+            } else if (c == 'u') {
+              parser->header_state = h_matching_connection_upgrade;
+            } else {
+              parser->header_state = h_matching_connection_token;
+            }
+            break;
+
+          /* Multi-value `Connection` header */
+          case h_matching_connection_token_start:
+            break;
+
+          default:
+            parser->header_state = h_general;
+            break;
+        }
+        break;
+      }
+
+      case s_header_value:
+      {
+        const char* start = p;
+        enum header_states h_state = (enum header_states) parser->header_state;
+        for (; p != data + len; p++) {
+          ch = *p;
+          if (ch == CR) {
+            UPDATE_STATE(s_header_almost_done);
+            parser->header_state = h_state;
+            CALLBACK_DATA(header_value);
+            break;
+          }
+
+          if (ch == LF) {
+            UPDATE_STATE(s_header_almost_done);
+            COUNT_HEADER_SIZE(p - start);
+            parser->header_state = h_state;
+            CALLBACK_DATA_NOADVANCE(header_value);
+            REEXECUTE();
+          }
+
+          c = LOWER(ch);
+
+          switch (h_state) {
+            case h_general:
+            {
+              const char* p_cr;
+              const char* p_lf;
+              size_t limit = data + len - p;
+
+              limit = MIN(limit, HTTP_MAX_HEADER_SIZE);
+
+              p_cr = (const char*) memchr(p, CR, limit);
+              p_lf = (const char*) memchr(p, LF, limit);
+              if (p_cr != NULL) {
+                if (p_lf != NULL && p_cr >= p_lf)
+                  p = p_lf;
+                else
+                  p = p_cr;
+              } else if (UNLIKELY(p_lf != NULL)) {
+                p = p_lf;
+              } else {
+                p = data + len;
+              }
+              --p;
+
+              break;
+            }
+
+            case h_connection:
+            case h_transfer_encoding:
+              assert(0 && "Shouldn't get here.");
+              break;
+
+            case h_content_length:
+            {
+              uint64_t t;
+
+              if (ch == ' ') break;
+
+              if (UNLIKELY(!IS_NUM(ch))) {
+                SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+                parser->header_state = h_state;
+                goto error;
+              }
+
+              t = parser->content_length;
+              t *= 10;
+              t += ch - '0';
+
+              /* Overflow? Test against a conservative limit for simplicity. */
+              if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) {
+                SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+                parser->header_state = h_state;
+                goto error;
+              }
+
+              parser->content_length = t;
+              break;
+            }
+
+            /* Transfer-Encoding: chunked */
+            case h_matching_transfer_encoding_chunked:
+              parser->index++;
+              if (parser->index > sizeof(CHUNKED)-1
+                  || c != CHUNKED[parser->index]) {
+                h_state = h_general;
+              } else if (parser->index == sizeof(CHUNKED)-2) {
+                h_state = h_transfer_encoding_chunked;
+              }
+              break;
+
+            case h_matching_connection_token_start:
+              /* looking for 'Connection: keep-alive' */
+              if (c == 'k') {
+                h_state = h_matching_connection_keep_alive;
+              /* looking for 'Connection: close' */
+              } else if (c == 'c') {
+                h_state = h_matching_connection_close;
+              } else if (c == 'u') {
+                h_state = h_matching_connection_upgrade;
+              } else if (STRICT_TOKEN(c)) {
+                h_state = h_matching_connection_token;
+              } else if (c == ' ' || c == '\t') {
+                /* Skip lws */
+              } else {
+                h_state = h_general;
+              }
+              break;
+
+            /* looking for 'Connection: keep-alive' */
+            case h_matching_connection_keep_alive:
+              parser->index++;
+              if (parser->index > sizeof(KEEP_ALIVE)-1
+                  || c != KEEP_ALIVE[parser->index]) {
+                h_state = h_matching_connection_token;
+              } else if (parser->index == sizeof(KEEP_ALIVE)-2) {
+                h_state = h_connection_keep_alive;
+              }
+              break;
+
+            /* looking for 'Connection: close' */
+            case h_matching_connection_close:
+              parser->index++;
+              if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) {
+                h_state = h_matching_connection_token;
+              } else if (parser->index == sizeof(CLOSE)-2) {
+                h_state = h_connection_close;
+              }
+              break;
+
+            /* looking for 'Connection: upgrade' */
+            case h_matching_connection_upgrade:
+              parser->index++;
+              if (parser->index > sizeof(UPGRADE) - 1 ||
+                  c != UPGRADE[parser->index]) {
+                h_state = h_matching_connection_token;
+              } else if (parser->index == sizeof(UPGRADE)-2) {
+                h_state = h_connection_upgrade;
+              }
+              break;
+
+            case h_matching_connection_token:
+              if (ch == ',') {
+                h_state = h_matching_connection_token_start;
+                parser->index = 0;
+              }
+              break;
+
+            case h_transfer_encoding_chunked:
+              if (ch != ' ') h_state = h_general;
+              break;
+
+            case h_connection_keep_alive:
+            case h_connection_close:
+            case h_connection_upgrade:
+              if (ch == ',') {
+                if (h_state == h_connection_keep_alive) {
+                  parser->flags |= F_CONNECTION_KEEP_ALIVE;
+                } else if (h_state == h_connection_close) {
+                  parser->flags |= F_CONNECTION_CLOSE;
+                } else if (h_state == h_connection_upgrade) {
+                  parser->flags |= F_CONNECTION_UPGRADE;
+                }
+                h_state = h_matching_connection_token_start;
+                parser->index = 0;
+              } else if (ch != ' ') {
+                h_state = h_matching_connection_token;
+              }
+              break;
+
+            default:
+              UPDATE_STATE(s_header_value);
+              h_state = h_general;
+              break;
+          }
+        }
+        parser->header_state = h_state;
+
+        COUNT_HEADER_SIZE(p - start);
+
+        if (p == data + len)
+          --p;
+        break;
+      }
+
+      case s_header_almost_done:
+      {
+        STRICT_CHECK(ch != LF);
+
+        UPDATE_STATE(s_header_value_lws);
+        break;
+      }
+
+      case s_header_value_lws:
+      {
+        if (ch == ' ' || ch == '\t') {
+          UPDATE_STATE(s_header_value_start);
+          REEXECUTE();
+        }
+
+        /* finished the header */
+        switch (parser->header_state) {
+          case h_connection_keep_alive:
+            parser->flags |= F_CONNECTION_KEEP_ALIVE;
+            break;
+          case h_connection_close:
+            parser->flags |= F_CONNECTION_CLOSE;
+            break;
+          case h_transfer_encoding_chunked:
+            parser->flags |= F_CHUNKED;
+            break;
+          case h_connection_upgrade:
+            parser->flags |= F_CONNECTION_UPGRADE;
+            break;
+          default:
+            break;
+        }
+
+        UPDATE_STATE(s_header_field_start);
+        REEXECUTE();
+      }
+
+      case s_header_value_discard_ws_almost_done:
+      {
+        STRICT_CHECK(ch != LF);
+        UPDATE_STATE(s_header_value_discard_lws);
+        break;
+      }
+
+      case s_header_value_discard_lws:
+      {
+        if (ch == ' ' || ch == '\t') {
+          UPDATE_STATE(s_header_value_discard_ws);
+          break;
+        } else {
+          switch (parser->header_state) {
+            case h_connection_keep_alive:
+              parser->flags |= F_CONNECTION_KEEP_ALIVE;
+              break;
+            case h_connection_close:
+              parser->flags |= F_CONNECTION_CLOSE;
+              break;
+            case h_connection_upgrade:
+              parser->flags |= F_CONNECTION_UPGRADE;
+              break;
+            case h_transfer_encoding_chunked:
+              parser->flags |= F_CHUNKED;
+              break;
+            default:
+              break;
+          }
+
+          /* header value was empty */
+          MARK(header_value);
+          UPDATE_STATE(s_header_field_start);
+          CALLBACK_DATA_NOADVANCE(header_value);
+          REEXECUTE();
+        }
+      }
+
+      case s_headers_almost_done:
+      {
+        STRICT_CHECK(ch != LF);
+
+        if (parser->flags & F_TRAILING) {
+          /* End of a chunked request */
+          UPDATE_STATE(s_message_done);
+          CALLBACK_NOTIFY_NOADVANCE(chunk_complete);
+          REEXECUTE();
+        }
+
+        UPDATE_STATE(s_headers_done);
+
+        /* Set this here so that on_headers_complete() callbacks can see it */
+        parser->upgrade =
+          ((parser->flags & (F_UPGRADE | F_CONNECTION_UPGRADE)) ==
+           (F_UPGRADE | F_CONNECTION_UPGRADE) ||
+           parser->method == HTTP_CONNECT);
+
+        /* Here we call the headers_complete callback. This is somewhat
+         * different than other callbacks because if the user returns 1, we
+         * will interpret that as saying that this message has no body. This
+         * is needed for the annoying case of recieving a response to a HEAD
+         * request.
+         *
+         * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so
+         * we have to simulate it by handling a change in errno below.
+         */
+        if (settings->on_headers_complete) {
+          switch (settings->on_headers_complete(parser)) {
+            case 0:
+              break;
+
+            case 1:
+              parser->flags |= F_SKIPBODY;
+              break;
+
+            default:
+              SET_ERRNO(HPE_CB_headers_complete);
+              RETURN(p - data); /* Error */
+          }
+        }
+
+        if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
+          RETURN(p - data);
+        }
+
+        REEXECUTE();
+      }
+
+      case s_headers_done:
+      {
+        STRICT_CHECK(ch != LF);
+
+        parser->nread = 0;
+
+        int hasBody = parser->flags & F_CHUNKED ||
+          (parser->content_length > 0 && parser->content_length != ULLONG_MAX);
+        if (parser->upgrade && (parser->method == HTTP_CONNECT ||
+                                (parser->flags & F_SKIPBODY) || !hasBody)) {
+          /* Exit, the rest of the message is in a different protocol. */
+          UPDATE_STATE(NEW_MESSAGE());
+          CALLBACK_NOTIFY(message_complete);
+          RETURN((p - data) + 1);
+        }
+
+        if (parser->flags & F_SKIPBODY) {
+          UPDATE_STATE(NEW_MESSAGE());
+          CALLBACK_NOTIFY(message_complete);
+        } else if (parser->flags & F_CHUNKED) {
+          /* chunked encoding - ignore Content-Length header */
+          UPDATE_STATE(s_chunk_size_start);
+        } else {
+          if (parser->content_length == 0) {
+            /* Content-Length header given but zero: Content-Length: 0\r\n */
+            UPDATE_STATE(NEW_MESSAGE());
+            CALLBACK_NOTIFY(message_complete);
+          } else if (parser->content_length != ULLONG_MAX) {
+            /* Content-Length header given and non-zero */
+            UPDATE_STATE(s_body_identity);
+          } else {
+            if (parser->type == HTTP_REQUEST ||
+                !http_message_needs_eof(parser)) {
+              /* Assume content-length 0 - read the next */
+              UPDATE_STATE(NEW_MESSAGE());
+              CALLBACK_NOTIFY(message_complete);
+            } else {
+              /* Read body until EOF */
+              UPDATE_STATE(s_body_identity_eof);
+            }
+          }
+        }
+
+        break;
+      }
+
+      case s_body_identity:
+      {
+        uint64_t to_read = MIN(parser->content_length,
+                               (uint64_t) ((data + len) - p));
+
+        assert(parser->content_length != 0
+            && parser->content_length != ULLONG_MAX);
+
+        /* The difference between advancing content_length and p is because
+         * the latter will automaticaly advance on the next loop iteration.
+         * Further, if content_length ends up at 0, we want to see the last
+         * byte again for our message complete callback.
+         */
+        MARK(body);
+        parser->content_length -= to_read;
+        p += to_read - 1;
+
+        if (parser->content_length == 0) {
+          UPDATE_STATE(s_message_done);
+
+          /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte.
+           *
+           * The alternative to doing this is to wait for the next byte to
+           * trigger the data callback, just as in every other case. The
+           * problem with this is that this makes it difficult for the test
+           * harness to distinguish between complete-on-EOF and
+           * complete-on-length. It's not clear that this distinction is
+           * important for applications, but let's keep it for now.
+           */
+          CALLBACK_DATA_(body, p - body_mark + 1, p - data);
+          REEXECUTE();
+        }
+
+        break;
+      }
+
+      /* read until EOF */
+      case s_body_identity_eof:
+        MARK(body);
+        p = data + len - 1;
+
+        break;
+
+      case s_message_done:
+        UPDATE_STATE(NEW_MESSAGE());
+        CALLBACK_NOTIFY(message_complete);
+        if (parser->upgrade) {
+          /* Exit, the rest of the message is in a different protocol. */
+          RETURN((p - data) + 1);
+        }
+        break;
+
+      case s_chunk_size_start:
+      {
+        assert(parser->nread == 1);
+        assert(parser->flags & F_CHUNKED);
+
+        unhex_val = unhex[(unsigned char)ch];
+        if (UNLIKELY(unhex_val == -1)) {
+          SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
+          goto error;
+        }
+
+        parser->content_length = unhex_val;
+        UPDATE_STATE(s_chunk_size);
+        break;
+      }
+
+      case s_chunk_size:
+      {
+        uint64_t t;
+
+        assert(parser->flags & F_CHUNKED);
+
+        if (ch == CR) {
+          UPDATE_STATE(s_chunk_size_almost_done);
+          break;
+        }
+
+        unhex_val = unhex[(unsigned char)ch];
+
+        if (unhex_val == -1) {
+          if (ch == ';' || ch == ' ') {
+            UPDATE_STATE(s_chunk_parameters);
+            break;
+          }
+
+          SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
+          goto error;
+        }
+
+        t = parser->content_length;
+        t *= 16;
+        t += unhex_val;
+
+        /* Overflow? Test against a conservative limit for simplicity. */
+        if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) {
+          SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
+          goto error;
+        }
+
+        parser->content_length = t;
+        break;
+      }
+
+      case s_chunk_parameters:
+      {
+        assert(parser->flags & F_CHUNKED);
+        /* just ignore this shit. TODO check for overflow */
+        if (ch == CR) {
+          UPDATE_STATE(s_chunk_size_almost_done);
+          break;
+        }
+        break;
+      }
+
+      case s_chunk_size_almost_done:
+      {
+        assert(parser->flags & F_CHUNKED);
+        STRICT_CHECK(ch != LF);
+
+        parser->nread = 0;
+
+        if (parser->content_length == 0) {
+          parser->flags |= F_TRAILING;
+          UPDATE_STATE(s_header_field_start);
+        } else {
+          UPDATE_STATE(s_chunk_data);
+        }
+        CALLBACK_NOTIFY(chunk_header);
+        break;
+      }
+
+      case s_chunk_data:
+      {
+        uint64_t to_read = MIN(parser->content_length,
+                               (uint64_t) ((data + len) - p));
+
+        assert(parser->flags & F_CHUNKED);
+        assert(parser->content_length != 0
+            && parser->content_length != ULLONG_MAX);
+
+        /* See the explanation in s_body_identity for why the content
+         * length and data pointers are managed this way.
+         */
+        MARK(body);
+        parser->content_length -= to_read;
+        p += to_read - 1;
+
+        if (parser->content_length == 0) {
+          UPDATE_STATE(s_chunk_data_almost_done);
+        }
+
+        break;
+      }
+
+      case s_chunk_data_almost_done:
+        assert(parser->flags & F_CHUNKED);
+        assert(parser->content_length == 0);
+        STRICT_CHECK(ch != CR);
+        UPDATE_STATE(s_chunk_data_done);
+        CALLBACK_DATA(body);
+        break;
+
+      case s_chunk_data_done:
+        assert(parser->flags & F_CHUNKED);
+        STRICT_CHECK(ch != LF);
+        parser->nread = 0;
+        UPDATE_STATE(s_chunk_size_start);
+        CALLBACK_NOTIFY(chunk_complete);
+        break;
+
+      default:
+        assert(0 && "unhandled state");
+        SET_ERRNO(HPE_INVALID_INTERNAL_STATE);
+        goto error;
+    }
+  }
+
+  /* Run callbacks for any marks that we have leftover after we ran our of
+   * bytes. There should be at most one of these set, so it's OK to invoke
+   * them in series (unset marks will not result in callbacks).
+   *
+   * We use the NOADVANCE() variety of callbacks here because 'p' has already
+   * overflowed 'data' and this allows us to correct for the off-by-one that
+   * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p'
+   * value that's in-bounds).
+   */
+
+  assert(((header_field_mark ? 1 : 0) +
+          (header_value_mark ? 1 : 0) +
+          (url_mark ? 1 : 0)  +
+          (body_mark ? 1 : 0) +
+          (status_mark ? 1 : 0)) <= 1);
+
+  CALLBACK_DATA_NOADVANCE(header_field);
+  CALLBACK_DATA_NOADVANCE(header_value);
+  CALLBACK_DATA_NOADVANCE(url);
+  CALLBACK_DATA_NOADVANCE(body);
+  CALLBACK_DATA_NOADVANCE(status);
+
+  RETURN(len);
+
+error:
+  if (HTTP_PARSER_ERRNO(parser) == HPE_OK) {
+    SET_ERRNO(HPE_UNKNOWN);
+  }
+
+  RETURN(p - data);
+}
+
+
+/* Does the parser need to see an EOF to find the end of the message? */
+int
+http_message_needs_eof (const http_parser *parser)
+{
+  if (parser->type == HTTP_REQUEST) {
+    return 0;
+  }
+
+  /* See RFC 2616 section 4.4 */
+  if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */
+      parser->status_code == 204 ||     /* No Content */
+      parser->status_code == 304 ||     /* Not Modified */
+      parser->flags & F_SKIPBODY) {     /* response to a HEAD request */
+    return 0;
+  }
+
+  if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) {
+    return 0;
+  }
+
+  return 1;
+}
+
+
+int
+http_should_keep_alive (const http_parser *parser)
+{
+  if (parser->http_major > 0 && parser->http_minor > 0) {
+    /* HTTP/1.1 */
+    if (parser->flags & F_CONNECTION_CLOSE) {
+      return 0;
+    }
+  } else {
+    /* HTTP/1.0 or earlier */
+    if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) {
+      return 0;
+    }
+  }
+
+  return !http_message_needs_eof(parser);
+}
+
+
+const char *
+http_method_str (enum http_method m)
+{
+  return ELEM_AT(method_strings, m, "<unknown>");
+}
+
+
+void
+http_parser_init (http_parser *parser, enum http_parser_type t)
+{
+  void *data = parser->data; /* preserve application data */
+  memset(parser, 0, sizeof(*parser));
+  parser->data = data;
+  parser->type = t;
+  parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res));
+  parser->http_errno = HPE_OK;
+}
+
+void
+http_parser_settings_init(http_parser_settings *settings)
+{
+  memset(settings, 0, sizeof(*settings));
+}
+
+const char *
+http_errno_name(enum http_errno err) {
+  assert(((size_t) err) <
+      (sizeof(http_strerror_tab) / sizeof(http_strerror_tab[0])));
+  return http_strerror_tab[err].name;
+}
+
+const char *
+http_errno_description(enum http_errno err) {
+  assert(((size_t) err) <
+      (sizeof(http_strerror_tab) / sizeof(http_strerror_tab[0])));
+  return http_strerror_tab[err].description;
+}
+
+static enum http_host_state
+http_parse_host_char(enum http_host_state s, const char ch) {
+  switch(s) {
+    case s_http_userinfo:
+    case s_http_userinfo_start:
+      if (ch == '@') {
+        return s_http_host_start;
+      }
+
+      if (IS_USERINFO_CHAR(ch)) {
+        return s_http_userinfo;
+      }
+      break;
+
+    case s_http_host_start:
+      if (ch == '[') {
+        return s_http_host_v6_start;
+      }
+
+      if (IS_HOST_CHAR(ch)) {
+        return s_http_host;
+      }
+
+      break;
+
+    case s_http_host:
+      if (IS_HOST_CHAR(ch)) {
+        return s_http_host;
+      }
+
+    /* FALLTHROUGH */
+    case s_http_host_v6_end:
+      if (ch == ':') {
+        return s_http_host_port_start;
+      }
+
+      break;
+
+    case s_http_host_v6:
+      if (ch == ']') {
+        return s_http_host_v6_end;
+      }
+
+    /* FALLTHROUGH */
+    case s_http_host_v6_start:
+      if (IS_HEX(ch) || ch == ':' || ch == '.') {
+        return s_http_host_v6;
+      }
+
+      break;
+
+    case s_http_host_port:
+    case s_http_host_port_start:
+      if (IS_NUM(ch)) {
+        return s_http_host_port;
+      }
+
+      break;
+
+    default:
+      break;
+  }
+  return s_http_host_dead;
+}
+
+static int
+http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
+  enum http_host_state s;
+
+  const char *p;
+  size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;
+
+  u->field_data[UF_HOST].len = 0;
+
+  s = found_at ? s_http_userinfo_start : s_http_host_start;
+
+  for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) {
+    enum http_host_state new_s = http_parse_host_char(s, *p);
+
+    if (new_s == s_http_host_dead) {
+      return 1;
+    }
+
+    switch(new_s) {
+      case s_http_host:
+        if (s != s_http_host) {
+          u->field_data[UF_HOST].off = p - buf;
+        }
+        u->field_data[UF_HOST].len++;
+        break;
+
+      case s_http_host_v6:
+        if (s != s_http_host_v6) {
+          u->field_data[UF_HOST].off = p - buf;
+        }
+        u->field_data[UF_HOST].len++;
+        break;
+
+      case s_http_host_port:
+        if (s != s_http_host_port) {
+          u->field_data[UF_PORT].off = p - buf;
+          u->field_data[UF_PORT].len = 0;
+          u->field_set |= (1 << UF_PORT);
+        }
+        u->field_data[UF_PORT].len++;
+        break;
+
+      case s_http_userinfo:
+        if (s != s_http_userinfo) {
+          u->field_data[UF_USERINFO].off = p - buf ;
+          u->field_data[UF_USERINFO].len = 0;
+          u->field_set |= (1 << UF_USERINFO);
+        }
+        u->field_data[UF_USERINFO].len++;
+        break;
+
+      default:
+        break;
+    }
+    s = new_s;
+  }
+
+  /* Make sure we don't end somewhere unexpected */
+  switch (s) {
+    case s_http_host_start:
+    case s_http_host_v6_start:
+    case s_http_host_v6:
+    case s_http_host_port_start:
+    case s_http_userinfo:
+    case s_http_userinfo_start:
+      return 1;
+    default:
+      break;
+  }
+
+  return 0;
+}
+
+int
+http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
+                      struct http_parser_url *u)
+{
+  enum state s;
+  const char *p;
+  enum http_parser_url_fields uf, old_uf;
+  int found_at = 0;
+
+  u->port = u->field_set = 0;
+  s = is_connect ? s_req_server_start : s_req_spaces_before_url;
+  old_uf = UF_MAX;
+
+  for (p = buf; p < buf + buflen; p++) {
+    s = parse_url_char(s, *p);
+
+    /* Figure out the next field that we're operating on */
+    switch (s) {
+      case s_dead:
+        return 1;
+
+      /* Skip delimeters */
+      case s_req_schema_slash:
+      case s_req_schema_slash_slash:
+      case s_req_server_start:
+      case s_req_query_string_start:
+      case s_req_fragment_start:
+        continue;
+
+      case s_req_schema:
+        uf = UF_SCHEMA;
+        break;
+
+      case s_req_server_with_at:
+        found_at = 1;
+
+      /* FALLTROUGH */
+      case s_req_server:
+        uf = UF_HOST;
+        break;
+
+      case s_req_path:
+        uf = UF_PATH;
+        break;
+
+      case s_req_query_string:
+        uf = UF_QUERY;
+        break;
+
+      case s_req_fragment:
+        uf = UF_FRAGMENT;
+        break;
+
+      default:
+        assert(!"Unexpected state");
+        return 1;
+    }
+
+    /* Nothing's changed; soldier on */
+    if (uf == old_uf) {
+      u->field_data[uf].len++;
+      continue;
+    }
+
+    u->field_data[uf].off = p - buf;
+    u->field_data[uf].len = 1;
+
+    u->field_set |= (1 << uf);
+    old_uf = uf;
+  }
+
+  /* host must be present if there is a schema */
+  /* parsing http:///toto will fail */
+  if ((u->field_set & ((1 << UF_SCHEMA) | (1 << UF_HOST))) != 0) {
+    if (http_parse_host(buf, u, found_at) != 0) {
+      return 1;
+    }
+  }
+
+  /* CONNECT requests can only contain "hostname:port" */
+  if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) {
+    return 1;
+  }
+
+  if (u->field_set & (1 << UF_PORT)) {
+    /* Don't bother with endp; we've already validated the string */
+    unsigned long v = strtoul(buf + u->field_data[UF_PORT].off, NULL, 10);
+
+    /* Ports have a max value of 2^16 */
+    if (v > 0xffff) {
+      return 1;
+    }
+
+    u->port = (uint16_t) v;
+  }
+
+  return 0;
+}
+
+void
+http_parser_pause(http_parser *parser, int paused) {
+  /* Users should only be pausing/unpausing a parser that is not in an error
+   * state. In non-debug builds, there's not much that we can do about this
+   * other than ignore it.
+   */
+  if (HTTP_PARSER_ERRNO(parser) == HPE_OK ||
+      HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) {
+    SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK);
+  } else {
+    assert(0 && "Attempting to pause parser in error state");
+  }
+}
+
+int
+http_body_is_final(const struct http_parser *parser) {
+    return parser->state == s_message_done;
+}
+
+unsigned long
+http_parser_version(void) {
+  return HTTP_PARSER_VERSION_MAJOR * 0x10000 |
+         HTTP_PARSER_VERSION_MINOR * 0x00100 |
+         HTTP_PARSER_VERSION_PATCH * 0x00001;
+}

+ 111 - 0
external/qhttpserver/http-parser/http_parser.gyp

@@ -0,0 +1,111 @@
+# This file is used with the GYP meta build system.
+# http://code.google.com/p/gyp/
+# To build try this:
+#   svn co http://gyp.googlecode.com/svn/trunk gyp
+#   ./gyp/gyp -f make --depth=`pwd` http_parser.gyp 
+#   ./out/Debug/test 
+{
+  'target_defaults': {
+    'default_configuration': 'Debug',
+    'configurations': {
+      # TODO: hoist these out and put them somewhere common, because
+      #       RuntimeLibrary MUST MATCH across the entire project
+      'Debug': {
+        'defines': [ 'DEBUG', '_DEBUG' ],
+        'cflags': [ '-Wall', '-Wextra', '-O0', '-g', '-ftrapv' ],
+        'msvs_settings': {
+          'VCCLCompilerTool': {
+            'RuntimeLibrary': 1, # static debug
+          },
+        },
+      },
+      'Release': {
+        'defines': [ 'NDEBUG' ],
+        'cflags': [ '-Wall', '-Wextra', '-O3' ],
+        'msvs_settings': {
+          'VCCLCompilerTool': {
+            'RuntimeLibrary': 0, # static release
+          },
+        },
+      }
+    },
+    'msvs_settings': {
+      'VCCLCompilerTool': {
+      },
+      'VCLibrarianTool': {
+      },
+      'VCLinkerTool': {
+        'GenerateDebugInformation': 'true',
+      },
+    },
+    'conditions': [
+      ['OS == "win"', {
+        'defines': [
+          'WIN32'
+        ],
+      }]
+    ],
+  },
+
+  'targets': [
+    {
+      'target_name': 'http_parser',
+      'type': 'static_library',
+      'include_dirs': [ '.' ],
+      'direct_dependent_settings': {
+        'defines': [ 'HTTP_PARSER_STRICT=0' ],
+        'include_dirs': [ '.' ],
+      },
+      'defines': [ 'HTTP_PARSER_STRICT=0' ],
+      'sources': [ './http_parser.c', ],
+      'conditions': [
+        ['OS=="win"', {
+          'msvs_settings': {
+            'VCCLCompilerTool': {
+              # Compile as C++. http_parser.c is actually C99, but C++ is
+              # close enough in this case.
+              'CompileAs': 2,
+            },
+          },
+        }]
+      ],
+    },
+
+    {
+      'target_name': 'http_parser_strict',
+      'type': 'static_library',
+      'include_dirs': [ '.' ],
+      'direct_dependent_settings': {
+        'defines': [ 'HTTP_PARSER_STRICT=1' ],
+        'include_dirs': [ '.' ],
+      },
+      'defines': [ 'HTTP_PARSER_STRICT=1' ],
+      'sources': [ './http_parser.c', ],
+      'conditions': [
+        ['OS=="win"', {
+          'msvs_settings': {
+            'VCCLCompilerTool': {
+              # Compile as C++. http_parser.c is actually C99, but C++ is
+              # close enough in this case.
+              'CompileAs': 2,
+            },
+          },
+        }]
+      ],
+    },
+
+    {
+      'target_name': 'test-nonstrict',
+      'type': 'executable',
+      'dependencies': [ 'http_parser' ],
+      'sources': [ 'test.c' ]
+    },
+
+    {
+      'target_name': 'test-strict',
+      'type': 'executable',
+      'dependencies': [ 'http_parser_strict' ],
+      'sources': [ 'test.c' ]
+    }
+  ]
+}

+ 342 - 0
external/qhttpserver/http-parser/http_parser.h

@@ -0,0 +1,342 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#ifndef http_parser_h
+#define http_parser_h
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Also update SONAME in the Makefile whenever you change these. */
+#define HTTP_PARSER_VERSION_MAJOR 2
+#define HTTP_PARSER_VERSION_MINOR 5
+#define HTTP_PARSER_VERSION_PATCH 0
+
+#include <sys/types.h>
+#if defined(_WIN32) && !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER<1600)
+#include <BaseTsd.h>
+#include <stddef.h>
+typedef __int8 int8_t;
+typedef unsigned __int8 uint8_t;
+typedef __int16 int16_t;
+typedef unsigned __int16 uint16_t;
+typedef __int32 int32_t;
+typedef unsigned __int32 uint32_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+#else
+#include <stdint.h>
+#endif
+
+/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
+ * faster
+ */
+#ifndef HTTP_PARSER_STRICT
+# define HTTP_PARSER_STRICT 1
+#endif
+
+/* Maximium header size allowed. If the macro is not defined
+ * before including this header then the default is used. To
+ * change the maximum header size, define the macro in the build
+ * environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
+ * the effective limit on the size of the header, define the macro
+ * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
+ */
+#ifndef HTTP_MAX_HEADER_SIZE
+# define HTTP_MAX_HEADER_SIZE (80*1024)
+#endif
+
+typedef struct http_parser http_parser;
+typedef struct http_parser_settings http_parser_settings;
+
+
+/* Callbacks should return non-zero to indicate an error. The parser will
+ * then halt execution.
+ *
+ * The one exception is on_headers_complete. In a HTTP_RESPONSE parser
+ * returning '1' from on_headers_complete will tell the parser that it
+ * should not expect a body. This is used when receiving a response to a
+ * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
+ * chunked' headers that indicate the presence of a body.
+ *
+ * http_data_cb does not return data chunks. It will be called arbitrarily
+ * many times for each string. E.G. you might get 10 callbacks for "on_url"
+ * each providing just a few characters more data.
+ */
+typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
+typedef int (*http_cb) (http_parser*);
+
+
+/* Request Methods */
+#define HTTP_METHOD_MAP(XX)         \
+  XX(0,  DELETE,      DELETE)       \
+  XX(1,  GET,         GET)          \
+  XX(2,  HEAD,        HEAD)         \
+  XX(3,  POST,        POST)         \
+  XX(4,  PUT,         PUT)          \
+  /* pathological */                \
+  XX(5,  CONNECT,     CONNECT)      \
+  XX(6,  OPTIONS,     OPTIONS)      \
+  XX(7,  TRACE,       TRACE)        \
+  /* webdav */                      \
+  XX(8,  COPY,        COPY)         \
+  XX(9,  LOCK,        LOCK)         \
+  XX(10, MKCOL,       MKCOL)        \
+  XX(11, MOVE,        MOVE)         \
+  XX(12, PROPFIND,    PROPFIND)     \
+  XX(13, PROPPATCH,   PROPPATCH)    \
+  XX(14, SEARCH,      SEARCH)       \
+  XX(15, UNLOCK,      UNLOCK)       \
+  /* subversion */                  \
+  XX(16, REPORT,      REPORT)       \
+  XX(17, MKACTIVITY,  MKACTIVITY)   \
+  XX(18, CHECKOUT,    CHECKOUT)     \
+  XX(19, MERGE,       MERGE)        \
+  /* upnp */                        \
+  XX(20, MSEARCH,     M-SEARCH)     \
+  XX(21, NOTIFY,      NOTIFY)       \
+  XX(22, SUBSCRIBE,   SUBSCRIBE)    \
+  XX(23, UNSUBSCRIBE, UNSUBSCRIBE)  \
+  /* RFC-5789 */                    \
+  XX(24, PATCH,       PATCH)        \
+  XX(25, PURGE,       PURGE)        \
+  /* CalDAV */                      \
+  XX(26, MKCALENDAR,  MKCALENDAR)   \
+
+enum http_method
+  {
+#define XX(num, name, string) HTTP_##name = num,
+  HTTP_METHOD_MAP(XX)
+#undef XX
+  };
+
+
+enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
+
+
+/* Flag values for http_parser.flags field */
+enum flags
+  { F_CHUNKED               = 1 << 0
+  , F_CONNECTION_KEEP_ALIVE = 1 << 1
+  , F_CONNECTION_CLOSE      = 1 << 2
+  , F_CONNECTION_UPGRADE    = 1 << 3
+  , F_TRAILING              = 1 << 4
+  , F_UPGRADE               = 1 << 5
+  , F_SKIPBODY              = 1 << 6
+  };
+
+
+/* Map for errno-related constants
+ * 
+ * The provided argument should be a macro that takes 2 arguments.
+ */
+#define HTTP_ERRNO_MAP(XX)                                           \
+  /* No error */                                                     \
+  XX(OK, "success")                                                  \
+                                                                     \
+  /* Callback-related errors */                                      \
+  XX(CB_message_begin, "the on_message_begin callback failed")       \
+  XX(CB_url, "the on_url callback failed")                           \
+  XX(CB_header_field, "the on_header_field callback failed")         \
+  XX(CB_header_value, "the on_header_value callback failed")         \
+  XX(CB_headers_complete, "the on_headers_complete callback failed") \
+  XX(CB_body, "the on_body callback failed")                         \
+  XX(CB_message_complete, "the on_message_complete callback failed") \
+  XX(CB_status, "the on_status callback failed")                     \
+  XX(CB_chunk_header, "the on_chunk_header callback failed")         \
+  XX(CB_chunk_complete, "the on_chunk_complete callback failed")     \
+                                                                     \
+  /* Parsing-related errors */                                       \
+  XX(INVALID_EOF_STATE, "stream ended at an unexpected time")        \
+  XX(HEADER_OVERFLOW,                                                \
+     "too many header bytes seen; overflow detected")                \
+  XX(CLOSED_CONNECTION,                                              \
+     "data received after completed connection: close message")      \
+  XX(INVALID_VERSION, "invalid HTTP version")                        \
+  XX(INVALID_STATUS, "invalid HTTP status code")                     \
+  XX(INVALID_METHOD, "invalid HTTP method")                          \
+  XX(INVALID_URL, "invalid URL")                                     \
+  XX(INVALID_HOST, "invalid host")                                   \
+  XX(INVALID_PORT, "invalid port")                                   \
+  XX(INVALID_PATH, "invalid path")                                   \
+  XX(INVALID_QUERY_STRING, "invalid query string")                   \
+  XX(INVALID_FRAGMENT, "invalid fragment")                           \
+  XX(LF_EXPECTED, "LF character expected")                           \
+  XX(INVALID_HEADER_TOKEN, "invalid character in header")            \
+  XX(INVALID_CONTENT_LENGTH,                                         \
+     "invalid character in content-length header")                   \
+  XX(INVALID_CHUNK_SIZE,                                             \
+     "invalid character in chunk size header")                       \
+  XX(INVALID_CONSTANT, "invalid constant string")                    \
+  XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
+  XX(STRICT, "strict mode assertion failed")                         \
+  XX(PAUSED, "parser is paused")                                     \
+  XX(UNKNOWN, "an unknown error occurred")
+
+
+/* Define HPE_* values for each errno value above */
+#define HTTP_ERRNO_GEN(n, s) HPE_##n,
+enum http_errno {
+  HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
+};
+#undef HTTP_ERRNO_GEN
+
+
+/* Get an http_errno value from an http_parser */
+#define HTTP_PARSER_ERRNO(p)            ((enum http_errno) (p)->http_errno)
+
+
+struct http_parser {
+  /** PRIVATE **/
+  unsigned int type : 2;         /* enum http_parser_type */
+  unsigned int flags : 7;        /* F_* values from 'flags' enum; semi-public */
+  unsigned int state : 7;        /* enum state from http_parser.c */
+  unsigned int header_state : 8; /* enum header_state from http_parser.c */
+  unsigned int index : 8;        /* index into current matcher */
+
+  uint32_t nread;          /* # bytes read in various scenarios */
+  uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
+
+  /** READ-ONLY **/
+  unsigned short http_major;
+  unsigned short http_minor;
+  unsigned int status_code : 16; /* responses only */
+  unsigned int method : 8;       /* requests only */
+  unsigned int http_errno : 7;
+
+  /* 1 = Upgrade header was present and the parser has exited because of that.
+   * 0 = No upgrade header present.
+   * Should be checked when http_parser_execute() returns in addition to
+   * error checking.
+   */
+  unsigned int upgrade : 1;
+
+  /** PUBLIC **/
+  void *data; /* A pointer to get hook to the "connection" or "socket" object */
+};
+
+
+struct http_parser_settings {
+  http_cb      on_message_begin;
+  http_data_cb on_url;
+  http_data_cb on_status;
+  http_data_cb on_header_field;
+  http_data_cb on_header_value;
+  http_cb      on_headers_complete;
+  http_data_cb on_body;
+  http_cb      on_message_complete;
+  /* When on_chunk_header is called, the current chunk length is stored
+   * in parser->content_length.
+   */
+  http_cb      on_chunk_header;
+  http_cb      on_chunk_complete;
+};
+
+
+enum http_parser_url_fields
+  { UF_SCHEMA           = 0
+  , UF_HOST             = 1
+  , UF_PORT             = 2
+  , UF_PATH             = 3
+  , UF_QUERY            = 4
+  , UF_FRAGMENT         = 5
+  , UF_USERINFO         = 6
+  , UF_MAX              = 7
+  };
+
+
+/* Result structure for http_parser_parse_url().
+ *
+ * Callers should index into field_data[] with UF_* values iff field_set
+ * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
+ * because we probably have padding left over), we convert any port to
+ * a uint16_t.
+ */
+struct http_parser_url {
+  uint16_t field_set;           /* Bitmask of (1 << UF_*) values */
+  uint16_t port;                /* Converted UF_PORT string */
+
+  struct {
+    uint16_t off;               /* Offset into buffer in which field starts */
+    uint16_t len;               /* Length of run in buffer */
+  } field_data[UF_MAX];
+};
+
+
+/* Returns the library version. Bits 16-23 contain the major version number,
+ * bits 8-15 the minor version number and bits 0-7 the patch level.
+ * Usage example:
+ *
+ *   unsigned long version = http_parser_version();
+ *   unsigned major = (version >> 16) & 255;
+ *   unsigned minor = (version >> 8) & 255;
+ *   unsigned patch = version & 255;
+ *   printf("http_parser v%u.%u.%u\n", major, minor, patch);
+ */
+unsigned long http_parser_version(void);
+
+void http_parser_init(http_parser *parser, enum http_parser_type type);
+
+
+/* Initialize http_parser_settings members to 0
+ */
+void http_parser_settings_init(http_parser_settings *settings);
+
+
+/* Executes the parser. Returns number of parsed bytes. Sets
+ * `parser->http_errno` on error. */
+size_t http_parser_execute(http_parser *parser,
+                           const http_parser_settings *settings,
+                           const char *data,
+                           size_t len);
+
+
+/* If http_should_keep_alive() in the on_headers_complete or
+ * on_message_complete callback returns 0, then this should be
+ * the last message on the connection.
+ * If you are the server, respond with the "Connection: close" header.
+ * If you are the client, close the connection.
+ */
+int http_should_keep_alive(const http_parser *parser);
+
+/* Returns a string version of the HTTP method. */
+const char *http_method_str(enum http_method m);
+
+/* Return a string name of the given error */
+const char *http_errno_name(enum http_errno err);
+
+/* Return a string description of the given error */
+const char *http_errno_description(enum http_errno err);
+
+/* Parse a URL; return nonzero on failure */
+int http_parser_parse_url(const char *buf, size_t buflen,
+                          int is_connect,
+                          struct http_parser_url *u);
+
+/* Pause or un-pause the parser; a nonzero value pauses */
+void http_parser_pause(http_parser *parser, int paused);
+
+/* Checks if this is the final chunk of the body. */
+int http_body_is_final(const http_parser *parser);
+
+#ifdef __cplusplus
+}
+#endif
+#endif

+ 3852 - 0
external/qhttpserver/http-parser/test.c

@@ -0,0 +1,3852 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+#include "http_parser.h"
+#include <stdlib.h>
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h> /* rand */
+#include <string.h>
+#include <stdarg.h>
+
+#if defined(__APPLE__)
+# undef strlcat
+# undef strlncpy
+# undef strlcpy
+#endif  /* defined(__APPLE__) */
+
+#undef TRUE
+#define TRUE 1
+#undef FALSE
+#define FALSE 0
+
+#define MAX_HEADERS 13
+#define MAX_ELEMENT_SIZE 2048
+#define MAX_CHUNKS 16
+
+#define MIN(a,b) ((a) < (b) ? (a) : (b))
+
+static http_parser *parser;
+
+struct message {
+  const char *name; // for debugging purposes
+  const char *raw;
+  enum http_parser_type type;
+  enum http_method method;
+  int status_code;
+  char response_status[MAX_ELEMENT_SIZE];
+  char request_path[MAX_ELEMENT_SIZE];
+  char request_url[MAX_ELEMENT_SIZE];
+  char fragment[MAX_ELEMENT_SIZE];
+  char query_string[MAX_ELEMENT_SIZE];
+  char body[MAX_ELEMENT_SIZE];
+  size_t body_size;
+  const char *host;
+  const char *userinfo;
+  uint16_t port;
+  int num_headers;
+  enum { NONE=0, FIELD, VALUE } last_header_element;
+  char headers [MAX_HEADERS][2][MAX_ELEMENT_SIZE];
+  int should_keep_alive;
+
+  int num_chunks;
+  int num_chunks_complete;
+  int chunk_lengths[MAX_CHUNKS];
+
+  const char *upgrade; // upgraded body
+
+  unsigned short http_major;
+  unsigned short http_minor;
+
+  int message_begin_cb_called;
+  int headers_complete_cb_called;
+  int message_complete_cb_called;
+  int message_complete_on_eof;
+  int body_is_final;
+};
+
+static int currently_parsing_eof;
+
+static struct message messages[5];
+static int num_messages;
+static http_parser_settings *current_pause_parser;
+
+/* * R E Q U E S T S * */
+const struct message requests[] =
+#define CURL_GET 0
+{ {.name= "curl get"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /test HTTP/1.1\r\n"
+         "User-Agent: curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n"
+         "Host: 0.0.0.0=5000\r\n"
+         "Accept: */*\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/test"
+  ,.request_url= "/test"
+  ,.num_headers= 3
+  ,.headers=
+    { { "User-Agent", "curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1" }
+    , { "Host", "0.0.0.0=5000" }
+    , { "Accept", "*/*" }
+    }
+  ,.body= ""
+  }
+
+#define FIREFOX_GET 1
+, {.name= "firefox get"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /favicon.ico HTTP/1.1\r\n"
+         "Host: 0.0.0.0=5000\r\n"
+         "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0\r\n"
+         "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
+         "Accept-Language: en-us,en;q=0.5\r\n"
+         "Accept-Encoding: gzip,deflate\r\n"
+         "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
+         "Keep-Alive: 300\r\n"
+         "Connection: keep-alive\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/favicon.ico"
+  ,.request_url= "/favicon.ico"
+  ,.num_headers= 8
+  ,.headers=
+    { { "Host", "0.0.0.0=5000" }
+    , { "User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008061015 Firefox/3.0" }
+    , { "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }
+    , { "Accept-Language", "en-us,en;q=0.5" }
+    , { "Accept-Encoding", "gzip,deflate" }
+    , { "Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7" }
+    , { "Keep-Alive", "300" }
+    , { "Connection", "keep-alive" }
+    }
+  ,.body= ""
+  }
+
+#define DUMBFUCK 2
+, {.name= "dumbfuck"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /dumbfuck HTTP/1.1\r\n"
+         "aaaaaaaaaaaaa:++++++++++\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/dumbfuck"
+  ,.request_url= "/dumbfuck"
+  ,.num_headers= 1
+  ,.headers=
+    { { "aaaaaaaaaaaaa",  "++++++++++" }
+    }
+  ,.body= ""
+  }
+
+#define FRAGMENT_IN_URI 3
+, {.name= "fragment in url"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= "page=1"
+  ,.fragment= "posts-17408"
+  ,.request_path= "/forums/1/topics/2375"
+  /* XXX request url does include fragment? */
+  ,.request_url= "/forums/1/topics/2375?page=1#posts-17408"
+  ,.num_headers= 0
+  ,.body= ""
+  }
+
+#define GET_NO_HEADERS_NO_BODY 4
+, {.name= "get no headers no body"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /get_no_headers_no_body/world HTTP/1.1\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE /* would need Connection: close */
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/get_no_headers_no_body/world"
+  ,.request_url= "/get_no_headers_no_body/world"
+  ,.num_headers= 0
+  ,.body= ""
+  }
+
+#define GET_ONE_HEADER_NO_BODY 5
+, {.name= "get one header no body"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /get_one_header_no_body HTTP/1.1\r\n"
+         "Accept: */*\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE /* would need Connection: close */
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/get_one_header_no_body"
+  ,.request_url= "/get_one_header_no_body"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Accept" , "*/*" }
+    }
+  ,.body= ""
+  }
+
+#define GET_FUNKY_CONTENT_LENGTH 6
+, {.name= "get funky content length body hello"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /get_funky_content_length_body_hello HTTP/1.0\r\n"
+         "conTENT-Length: 5\r\n"
+         "\r\n"
+         "HELLO"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/get_funky_content_length_body_hello"
+  ,.request_url= "/get_funky_content_length_body_hello"
+  ,.num_headers= 1
+  ,.headers=
+    { { "conTENT-Length" , "5" }
+    }
+  ,.body= "HELLO"
+  }
+
+#define POST_IDENTITY_BODY_WORLD 7
+, {.name= "post identity body world"
+  ,.type= HTTP_REQUEST
+  ,.raw= "POST /post_identity_body_world?q=search#hey HTTP/1.1\r\n"
+         "Accept: */*\r\n"
+         "Transfer-Encoding: identity\r\n"
+         "Content-Length: 5\r\n"
+         "\r\n"
+         "World"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.query_string= "q=search"
+  ,.fragment= "hey"
+  ,.request_path= "/post_identity_body_world"
+  ,.request_url= "/post_identity_body_world?q=search#hey"
+  ,.num_headers= 3
+  ,.headers=
+    { { "Accept", "*/*" }
+    , { "Transfer-Encoding", "identity" }
+    , { "Content-Length", "5" }
+    }
+  ,.body= "World"
+  }
+
+#define POST_CHUNKED_ALL_YOUR_BASE 8
+, {.name= "post - chunked body: all your base are belong to us"
+  ,.type= HTTP_REQUEST
+  ,.raw= "POST /post_chunked_all_your_base HTTP/1.1\r\n"
+         "Transfer-Encoding: chunked\r\n"
+         "\r\n"
+         "1e\r\nall your base are belong to us\r\n"
+         "0\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/post_chunked_all_your_base"
+  ,.request_url= "/post_chunked_all_your_base"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Transfer-Encoding" , "chunked" }
+    }
+  ,.body= "all your base are belong to us"
+  ,.num_chunks_complete= 2
+  ,.chunk_lengths= { 0x1e }
+  }
+
+#define TWO_CHUNKS_MULT_ZERO_END 9
+, {.name= "two chunks ; triple zero ending"
+  ,.type= HTTP_REQUEST
+  ,.raw= "POST /two_chunks_mult_zero_end HTTP/1.1\r\n"
+         "Transfer-Encoding: chunked\r\n"
+         "\r\n"
+         "5\r\nhello\r\n"
+         "6\r\n world\r\n"
+         "000\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/two_chunks_mult_zero_end"
+  ,.request_url= "/two_chunks_mult_zero_end"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Transfer-Encoding", "chunked" }
+    }
+  ,.body= "hello world"
+  ,.num_chunks_complete= 3
+  ,.chunk_lengths= { 5, 6 }
+  }
+
+#define CHUNKED_W_TRAILING_HEADERS 10
+, {.name= "chunked with trailing headers. blech."
+  ,.type= HTTP_REQUEST
+  ,.raw= "POST /chunked_w_trailing_headers HTTP/1.1\r\n"
+         "Transfer-Encoding: chunked\r\n"
+         "\r\n"
+         "5\r\nhello\r\n"
+         "6\r\n world\r\n"
+         "0\r\n"
+         "Vary: *\r\n"
+         "Content-Type: text/plain\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/chunked_w_trailing_headers"
+  ,.request_url= "/chunked_w_trailing_headers"
+  ,.num_headers= 3
+  ,.headers=
+    { { "Transfer-Encoding",  "chunked" }
+    , { "Vary", "*" }
+    , { "Content-Type", "text/plain" }
+    }
+  ,.body= "hello world"
+  ,.num_chunks_complete= 3
+  ,.chunk_lengths= { 5, 6 }
+  }
+
+#define CHUNKED_W_BULLSHIT_AFTER_LENGTH 11
+, {.name= "with bullshit after the length"
+  ,.type= HTTP_REQUEST
+  ,.raw= "POST /chunked_w_bullshit_after_length HTTP/1.1\r\n"
+         "Transfer-Encoding: chunked\r\n"
+         "\r\n"
+         "5; ihatew3;whatthefuck=aretheseparametersfor\r\nhello\r\n"
+         "6; blahblah; blah\r\n world\r\n"
+         "0\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/chunked_w_bullshit_after_length"
+  ,.request_url= "/chunked_w_bullshit_after_length"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Transfer-Encoding", "chunked" }
+    }
+  ,.body= "hello world"
+  ,.num_chunks_complete= 3
+  ,.chunk_lengths= { 5, 6 }
+  }
+
+#define WITH_QUOTES 12
+, {.name= "with quotes"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /with_\"stupid\"_quotes?foo=\"bar\" HTTP/1.1\r\n\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= "foo=\"bar\""
+  ,.fragment= ""
+  ,.request_path= "/with_\"stupid\"_quotes"
+  ,.request_url= "/with_\"stupid\"_quotes?foo=\"bar\""
+  ,.num_headers= 0
+  ,.headers= { }
+  ,.body= ""
+  }
+
+#define APACHEBENCH_GET 13
+/* The server receiving this request SHOULD NOT wait for EOF
+ * to know that content-length == 0.
+ * How to represent this in a unit test? message_complete_on_eof
+ * Compare with NO_CONTENT_LENGTH_RESPONSE.
+ */
+, {.name = "apachebench get"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /test HTTP/1.0\r\n"
+         "Host: 0.0.0.0:5000\r\n"
+         "User-Agent: ApacheBench/2.3\r\n"
+         "Accept: */*\r\n\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/test"
+  ,.request_url= "/test"
+  ,.num_headers= 3
+  ,.headers= { { "Host", "0.0.0.0:5000" }
+             , { "User-Agent", "ApacheBench/2.3" }
+             , { "Accept", "*/*" }
+             }
+  ,.body= ""
+  }
+
+#define QUERY_URL_WITH_QUESTION_MARK_GET 14
+/* Some clients include '?' characters in query strings.
+ */
+, {.name = "query url with question mark"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /test.cgi?foo=bar?baz HTTP/1.1\r\n\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= "foo=bar?baz"
+  ,.fragment= ""
+  ,.request_path= "/test.cgi"
+  ,.request_url= "/test.cgi?foo=bar?baz"
+  ,.num_headers= 0
+  ,.headers= {}
+  ,.body= ""
+  }
+
+#define PREFIX_NEWLINE_GET 15
+/* Some clients, especially after a POST in a keep-alive connection,
+ * will send an extra CRLF before the next request
+ */
+, {.name = "newline prefix get"
+  ,.type= HTTP_REQUEST
+  ,.raw= "\r\nGET /test HTTP/1.1\r\n\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/test"
+  ,.request_url= "/test"
+  ,.num_headers= 0
+  ,.headers= { }
+  ,.body= ""
+  }
+
+#define UPGRADE_REQUEST 16
+, {.name = "upgrade request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /demo HTTP/1.1\r\n"
+         "Host: example.com\r\n"
+         "Connection: Upgrade\r\n"
+         "Sec-WebSocket-Key2: 12998 5 Y3 1  .P00\r\n"
+         "Sec-WebSocket-Protocol: sample\r\n"
+         "Upgrade: WebSocket\r\n"
+         "Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5\r\n"
+         "Origin: http://example.com\r\n"
+         "\r\n"
+         "Hot diggity dogg"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/demo"
+  ,.request_url= "/demo"
+  ,.num_headers= 7
+  ,.upgrade="Hot diggity dogg"
+  ,.headers= { { "Host", "example.com" }
+             , { "Connection", "Upgrade" }
+             , { "Sec-WebSocket-Key2", "12998 5 Y3 1  .P00" }
+             , { "Sec-WebSocket-Protocol", "sample" }
+             , { "Upgrade", "WebSocket" }
+             , { "Sec-WebSocket-Key1", "4 @1  46546xW%0l 1 5" }
+             , { "Origin", "http://example.com" }
+             }
+  ,.body= ""
+  }
+
+#define CONNECT_REQUEST 17
+, {.name = "connect request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "CONNECT 0-home0.netscape.com:443 HTTP/1.0\r\n"
+         "User-agent: Mozilla/1.1N\r\n"
+         "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
+         "\r\n"
+         "some data\r\n"
+         "and yet even more data"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.method= HTTP_CONNECT
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= ""
+  ,.request_url= "0-home0.netscape.com:443"
+  ,.num_headers= 2
+  ,.upgrade="some data\r\nand yet even more data"
+  ,.headers= { { "User-agent", "Mozilla/1.1N" }
+             , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" }
+             }
+  ,.body= ""
+  }
+
+#define REPORT_REQ 18
+, {.name= "report request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "REPORT /test HTTP/1.1\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_REPORT
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/test"
+  ,.request_url= "/test"
+  ,.num_headers= 0
+  ,.headers= {}
+  ,.body= ""
+  }
+
+#define NO_HTTP_VERSION 19
+, {.name= "request with no http version"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 0
+  ,.http_minor= 9
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/"
+  ,.request_url= "/"
+  ,.num_headers= 0
+  ,.headers= {}
+  ,.body= ""
+  }
+
+#define MSEARCH_REQ 20
+, {.name= "m-search request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "M-SEARCH * HTTP/1.1\r\n"
+         "HOST: 239.255.255.250:1900\r\n"
+         "MAN: \"ssdp:discover\"\r\n"
+         "ST: \"ssdp:all\"\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_MSEARCH
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "*"
+  ,.request_url= "*"
+  ,.num_headers= 3
+  ,.headers= { { "HOST", "239.255.255.250:1900" }
+             , { "MAN", "\"ssdp:discover\"" }
+             , { "ST", "\"ssdp:all\"" }
+             }
+  ,.body= ""
+  }
+
+#define LINE_FOLDING_IN_HEADER 21
+, {.name= "line folding in header value"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET / HTTP/1.1\r\n"
+         "Line1:   abc\r\n"
+         "\tdef\r\n"
+         " ghi\r\n"
+         "\t\tjkl\r\n"
+         "  mno \r\n"
+         "\t \tqrs\r\n"
+         "Line2: \t line2\t\r\n"
+         "Line3:\r\n"
+         " line3\r\n"
+         "Line4: \r\n"
+         " \r\n"
+         "Connection:\r\n"
+         " close\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/"
+  ,.request_url= "/"
+  ,.num_headers= 5
+  ,.headers= { { "Line1", "abc\tdef ghi\t\tjkl  mno \t \tqrs" }
+             , { "Line2", "line2\t" }
+             , { "Line3", "line3" }
+             , { "Line4", "" }
+             , { "Connection", "close" },
+             }
+  ,.body= ""
+  }
+
+
+#define QUERY_TERMINATED_HOST 22
+, {.name= "host terminated by a query string"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET http://hypnotoad.org?hail=all HTTP/1.1\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= "hail=all"
+  ,.fragment= ""
+  ,.request_path= ""
+  ,.request_url= "http://hypnotoad.org?hail=all"
+  ,.host= "hypnotoad.org"
+  ,.num_headers= 0
+  ,.headers= { }
+  ,.body= ""
+  }
+
+#define QUERY_TERMINATED_HOSTPORT 23
+, {.name= "host:port terminated by a query string"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET http://hypnotoad.org:1234?hail=all HTTP/1.1\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= "hail=all"
+  ,.fragment= ""
+  ,.request_path= ""
+  ,.request_url= "http://hypnotoad.org:1234?hail=all"
+  ,.host= "hypnotoad.org"
+  ,.port= 1234
+  ,.num_headers= 0
+  ,.headers= { }
+  ,.body= ""
+  }
+
+#define SPACE_TERMINATED_HOSTPORT 24
+, {.name= "host:port terminated by a space"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET http://hypnotoad.org:1234 HTTP/1.1\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= ""
+  ,.request_url= "http://hypnotoad.org:1234"
+  ,.host= "hypnotoad.org"
+  ,.port= 1234
+  ,.num_headers= 0
+  ,.headers= { }
+  ,.body= ""
+  }
+
+#define PATCH_REQ 25
+, {.name = "PATCH request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "PATCH /file.txt HTTP/1.1\r\n"
+         "Host: www.example.com\r\n"
+         "Content-Type: application/example\r\n"
+         "If-Match: \"e0023aa4e\"\r\n"
+         "Content-Length: 10\r\n"
+         "\r\n"
+         "cccccccccc"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_PATCH
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/file.txt"
+  ,.request_url= "/file.txt"
+  ,.num_headers= 4
+  ,.headers= { { "Host", "www.example.com" }
+             , { "Content-Type", "application/example" }
+             , { "If-Match", "\"e0023aa4e\"" }
+             , { "Content-Length", "10" }
+             }
+  ,.body= "cccccccccc"
+  }
+
+#define CONNECT_CAPS_REQUEST 26
+, {.name = "connect caps request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "CONNECT HOME0.NETSCAPE.COM:443 HTTP/1.0\r\n"
+         "User-agent: Mozilla/1.1N\r\n"
+         "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.method= HTTP_CONNECT
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= ""
+  ,.request_url= "HOME0.NETSCAPE.COM:443"
+  ,.num_headers= 2
+  ,.upgrade=""
+  ,.headers= { { "User-agent", "Mozilla/1.1N" }
+             , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" }
+             }
+  ,.body= ""
+  }
+
+#if !HTTP_PARSER_STRICT
+#define UTF8_PATH_REQ 27
+, {.name= "utf-8 path request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /δ¶/δt/pope?q=1#narf HTTP/1.1\r\n"
+         "Host: github.com\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= "q=1"
+  ,.fragment= "narf"
+  ,.request_path= "/δ¶/δt/pope"
+  ,.request_url= "/δ¶/δt/pope?q=1#narf"
+  ,.num_headers= 1
+  ,.headers= { {"Host", "github.com" }
+             }
+  ,.body= ""
+  }
+
+#define HOSTNAME_UNDERSCORE 28
+, {.name = "hostname underscore"
+  ,.type= HTTP_REQUEST
+  ,.raw= "CONNECT home_0.netscape.com:443 HTTP/1.0\r\n"
+         "User-agent: Mozilla/1.1N\r\n"
+         "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.method= HTTP_CONNECT
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= ""
+  ,.request_url= "home_0.netscape.com:443"
+  ,.num_headers= 2
+  ,.upgrade=""
+  ,.headers= { { "User-agent", "Mozilla/1.1N" }
+             , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" }
+             }
+  ,.body= ""
+  }
+#endif  /* !HTTP_PARSER_STRICT */
+
+/* see https://github.com/ry/http-parser/issues/47 */
+#define EAT_TRAILING_CRLF_NO_CONNECTION_CLOSE 29
+, {.name = "eat CRLF between requests, no \"Connection: close\" header"
+  ,.raw= "POST / HTTP/1.1\r\n"
+         "Host: www.example.com\r\n"
+         "Content-Type: application/x-www-form-urlencoded\r\n"
+         "Content-Length: 4\r\n"
+         "\r\n"
+         "q=42\r\n" /* note the trailing CRLF */
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/"
+  ,.request_url= "/"
+  ,.num_headers= 3
+  ,.upgrade= 0
+  ,.headers= { { "Host", "www.example.com" }
+             , { "Content-Type", "application/x-www-form-urlencoded" }
+             , { "Content-Length", "4" }
+             }
+  ,.body= "q=42"
+  }
+
+/* see https://github.com/ry/http-parser/issues/47 */
+#define EAT_TRAILING_CRLF_WITH_CONNECTION_CLOSE 30
+, {.name = "eat CRLF between requests even if \"Connection: close\" is set"
+  ,.raw= "POST / HTTP/1.1\r\n"
+         "Host: www.example.com\r\n"
+         "Content-Type: application/x-www-form-urlencoded\r\n"
+         "Content-Length: 4\r\n"
+         "Connection: close\r\n"
+         "\r\n"
+         "q=42\r\n" /* note the trailing CRLF */
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE /* input buffer isn't empty when on_message_complete is called */
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/"
+  ,.request_url= "/"
+  ,.num_headers= 4
+  ,.upgrade= 0
+  ,.headers= { { "Host", "www.example.com" }
+             , { "Content-Type", "application/x-www-form-urlencoded" }
+             , { "Content-Length", "4" }
+             , { "Connection", "close" }
+             }
+  ,.body= "q=42"
+  }
+
+#define PURGE_REQ 31
+, {.name = "PURGE request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "PURGE /file.txt HTTP/1.1\r\n"
+         "Host: www.example.com\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_PURGE
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/file.txt"
+  ,.request_url= "/file.txt"
+  ,.num_headers= 1
+  ,.headers= { { "Host", "www.example.com" } }
+  ,.body= ""
+  }
+
+#define SEARCH_REQ 32
+, {.name = "SEARCH request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "SEARCH / HTTP/1.1\r\n"
+         "Host: www.example.com\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_SEARCH
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/"
+  ,.request_url= "/"
+  ,.num_headers= 1
+  ,.headers= { { "Host", "www.example.com" } }
+  ,.body= ""
+  }
+
+#define PROXY_WITH_BASIC_AUTH 33
+, {.name= "host:port and basic_auth"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET http://a%12:b!&*$@hypnotoad.org:1234/toto HTTP/1.1\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.fragment= ""
+  ,.request_path= "/toto"
+  ,.request_url= "http://a%12:b!&*$@hypnotoad.org:1234/toto"
+  ,.host= "hypnotoad.org"
+  ,.userinfo= "a%12:b!&*$"
+  ,.port= 1234
+  ,.num_headers= 0
+  ,.headers= { }
+  ,.body= ""
+  }
+
+#define LINE_FOLDING_IN_HEADER_WITH_LF 34
+, {.name= "line folding in header value"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET / HTTP/1.1\n"
+         "Line1:   abc\n"
+         "\tdef\n"
+         " ghi\n"
+         "\t\tjkl\n"
+         "  mno \n"
+         "\t \tqrs\n"
+         "Line2: \t line2\t\n"
+         "Line3:\n"
+         " line3\n"
+         "Line4: \n"
+         " \n"
+         "Connection:\n"
+         " close\n"
+         "\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/"
+  ,.request_url= "/"
+  ,.num_headers= 5
+  ,.headers= { { "Line1", "abc\tdef ghi\t\tjkl  mno \t \tqrs" }
+             , { "Line2", "line2\t" }
+             , { "Line3", "line3" }
+             , { "Line4", "" }
+             , { "Connection", "close" },
+             }
+  ,.body= ""
+  }
+
+#define CONNECTION_MULTI 35
+, {.name = "multiple connection header values with folding"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /demo HTTP/1.1\r\n"
+         "Host: example.com\r\n"
+         "Connection: Something,\r\n"
+         " Upgrade, ,Keep-Alive\r\n"
+         "Sec-WebSocket-Key2: 12998 5 Y3 1  .P00\r\n"
+         "Sec-WebSocket-Protocol: sample\r\n"
+         "Upgrade: WebSocket\r\n"
+         "Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5\r\n"
+         "Origin: http://example.com\r\n"
+         "\r\n"
+         "Hot diggity dogg"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/demo"
+  ,.request_url= "/demo"
+  ,.num_headers= 7
+  ,.upgrade="Hot diggity dogg"
+  ,.headers= { { "Host", "example.com" }
+             , { "Connection", "Something, Upgrade, ,Keep-Alive" }
+             , { "Sec-WebSocket-Key2", "12998 5 Y3 1  .P00" }
+             , { "Sec-WebSocket-Protocol", "sample" }
+             , { "Upgrade", "WebSocket" }
+             , { "Sec-WebSocket-Key1", "4 @1  46546xW%0l 1 5" }
+             , { "Origin", "http://example.com" }
+             }
+  ,.body= ""
+  }
+
+#define CONNECTION_MULTI_LWS 36
+, {.name = "multiple connection header values with folding and lws"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /demo HTTP/1.1\r\n"
+         "Connection: keep-alive, upgrade\r\n"
+         "Upgrade: WebSocket\r\n"
+         "\r\n"
+         "Hot diggity dogg"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/demo"
+  ,.request_url= "/demo"
+  ,.num_headers= 2
+  ,.upgrade="Hot diggity dogg"
+  ,.headers= { { "Connection", "keep-alive, upgrade" }
+             , { "Upgrade", "WebSocket" }
+             }
+  ,.body= ""
+  }
+
+#define CONNECTION_MULTI_LWS_CRLF 37
+, {.name = "multiple connection header values with folding and lws"
+  ,.type= HTTP_REQUEST
+  ,.raw= "GET /demo HTTP/1.1\r\n"
+         "Connection: keep-alive, \r\n upgrade\r\n"
+         "Upgrade: WebSocket\r\n"
+         "\r\n"
+         "Hot diggity dogg"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_GET
+  ,.query_string= ""
+  ,.fragment= ""
+  ,.request_path= "/demo"
+  ,.request_url= "/demo"
+  ,.num_headers= 2
+  ,.upgrade="Hot diggity dogg"
+  ,.headers= { { "Connection", "keep-alive,  upgrade" }
+             , { "Upgrade", "WebSocket" }
+             }
+  ,.body= ""
+  }
+
+#define UPGRADE_POST_REQUEST 38
+, {.name = "upgrade post request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "POST /demo HTTP/1.1\r\n"
+         "Host: example.com\r\n"
+         "Connection: Upgrade\r\n"
+         "Upgrade: HTTP/2.0\r\n"
+         "Content-Length: 15\r\n"
+         "\r\n"
+         "sweet post body"
+         "Hot diggity dogg"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.method= HTTP_POST
+  ,.request_path= "/demo"
+  ,.request_url= "/demo"
+  ,.num_headers= 4
+  ,.upgrade="Hot diggity dogg"
+  ,.headers= { { "Host", "example.com" }
+             , { "Connection", "Upgrade" }
+             , { "Upgrade", "HTTP/2.0" }
+             , { "Content-Length", "15" }
+             }
+  ,.body= "sweet post body"
+  }
+
+#define CONNECT_WITH_BODY_REQUEST 39
+, {.name = "connect with body request"
+  ,.type= HTTP_REQUEST
+  ,.raw= "CONNECT foo.bar.com:443 HTTP/1.0\r\n"
+         "User-agent: Mozilla/1.1N\r\n"
+         "Proxy-authorization: basic aGVsbG86d29ybGQ=\r\n"
+         "Content-Length: 10\r\n"
+         "\r\n"
+         "blarfcicle"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.method= HTTP_CONNECT
+  ,.request_url= "foo.bar.com:443"
+  ,.num_headers= 3
+  ,.upgrade="blarfcicle"
+  ,.headers= { { "User-agent", "Mozilla/1.1N" }
+             , { "Proxy-authorization", "basic aGVsbG86d29ybGQ=" }
+             , { "Content-Length", "10" }
+             }
+  ,.body= ""
+  }
+
+, {.name= NULL } /* sentinel */
+};
+
+/* * R E S P O N S E S * */
+const struct message responses[] =
+#define GOOGLE_301 0
+{ {.name= "google 301"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 301 Moved Permanently\r\n"
+         "Location: http://www.google.com/\r\n"
+         "Content-Type: text/html; charset=UTF-8\r\n"
+         "Date: Sun, 26 Apr 2009 11:11:49 GMT\r\n"
+         "Expires: Tue, 26 May 2009 11:11:49 GMT\r\n"
+         "X-$PrototypeBI-Version: 1.6.0.3\r\n" /* $ char in header field */
+         "Cache-Control: public, max-age=2592000\r\n"
+         "Server: gws\r\n"
+         "Content-Length:  219  \r\n"
+         "\r\n"
+         "<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"
+         "<TITLE>301 Moved</TITLE></HEAD><BODY>\n"
+         "<H1>301 Moved</H1>\n"
+         "The document has moved\n"
+         "<A HREF=\"http://www.google.com/\">here</A>.\r\n"
+         "</BODY></HTML>\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 301
+  ,.response_status= "Moved Permanently"
+  ,.num_headers= 8
+  ,.headers=
+    { { "Location", "http://www.google.com/" }
+    , { "Content-Type", "text/html; charset=UTF-8" }
+    , { "Date", "Sun, 26 Apr 2009 11:11:49 GMT" }
+    , { "Expires", "Tue, 26 May 2009 11:11:49 GMT" }
+    , { "X-$PrototypeBI-Version", "1.6.0.3" }
+    , { "Cache-Control", "public, max-age=2592000" }
+    , { "Server", "gws" }
+    , { "Content-Length", "219  " }
+    }
+  ,.body= "<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"
+          "<TITLE>301 Moved</TITLE></HEAD><BODY>\n"
+          "<H1>301 Moved</H1>\n"
+          "The document has moved\n"
+          "<A HREF=\"http://www.google.com/\">here</A>.\r\n"
+          "</BODY></HTML>\r\n"
+  }
+
+#define NO_CONTENT_LENGTH_RESPONSE 1
+/* The client should wait for the server's EOF. That is, when content-length
+ * is not specified, and "Connection: close", the end of body is specified
+ * by the EOF.
+ * Compare with APACHEBENCH_GET
+ */
+, {.name= "no content-length response"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Date: Tue, 04 Aug 2009 07:59:32 GMT\r\n"
+         "Server: Apache\r\n"
+         "X-Powered-By: Servlet/2.5 JSP/2.1\r\n"
+         "Content-Type: text/xml; charset=utf-8\r\n"
+         "Connection: close\r\n"
+         "\r\n"
+         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+         "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
+         "  <SOAP-ENV:Body>\n"
+         "    <SOAP-ENV:Fault>\n"
+         "       <faultcode>SOAP-ENV:Client</faultcode>\n"
+         "       <faultstring>Client Error</faultstring>\n"
+         "    </SOAP-ENV:Fault>\n"
+         "  </SOAP-ENV:Body>\n"
+         "</SOAP-ENV:Envelope>"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 5
+  ,.headers=
+    { { "Date", "Tue, 04 Aug 2009 07:59:32 GMT" }
+    , { "Server", "Apache" }
+    , { "X-Powered-By", "Servlet/2.5 JSP/2.1" }
+    , { "Content-Type", "text/xml; charset=utf-8" }
+    , { "Connection", "close" }
+    }
+  ,.body= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+          "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
+          "  <SOAP-ENV:Body>\n"
+          "    <SOAP-ENV:Fault>\n"
+          "       <faultcode>SOAP-ENV:Client</faultcode>\n"
+          "       <faultstring>Client Error</faultstring>\n"
+          "    </SOAP-ENV:Fault>\n"
+          "  </SOAP-ENV:Body>\n"
+          "</SOAP-ENV:Envelope>"
+  }
+
+#define NO_HEADERS_NO_BODY_404 2
+, {.name= "404 no headers no body"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 404 Not Found\r\n\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 404
+  ,.response_status= "Not Found"
+  ,.num_headers= 0
+  ,.headers= {}
+  ,.body_size= 0
+  ,.body= ""
+  }
+
+#define NO_REASON_PHRASE 3
+, {.name= "301 no response phrase"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 301\r\n\r\n"
+  ,.should_keep_alive = FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 301
+  ,.response_status= ""
+  ,.num_headers= 0
+  ,.headers= {}
+  ,.body= ""
+  }
+
+#define TRAILING_SPACE_ON_CHUNKED_BODY 4
+, {.name="200 trailing space on chunked body"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Content-Type: text/plain\r\n"
+         "Transfer-Encoding: chunked\r\n"
+         "\r\n"
+         "25  \r\n"
+         "This is the data in the first chunk\r\n"
+         "\r\n"
+         "1C\r\n"
+         "and this is the second one\r\n"
+         "\r\n"
+         "0  \r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 2
+  ,.headers=
+    { {"Content-Type", "text/plain" }
+    , {"Transfer-Encoding", "chunked" }
+    }
+  ,.body_size = 37+28
+  ,.body =
+         "This is the data in the first chunk\r\n"
+         "and this is the second one\r\n"
+  ,.num_chunks_complete= 3
+  ,.chunk_lengths= { 0x25, 0x1c }
+  }
+
+#define NO_CARRIAGE_RET 5
+, {.name="no carriage ret"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\n"
+         "Content-Type: text/html; charset=utf-8\n"
+         "Connection: close\n"
+         "\n"
+         "these headers are from http://news.ycombinator.com/"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 2
+  ,.headers=
+    { {"Content-Type", "text/html; charset=utf-8" }
+    , {"Connection", "close" }
+    }
+  ,.body= "these headers are from http://news.ycombinator.com/"
+  }
+
+#define PROXY_CONNECTION 6
+, {.name="proxy connection"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Content-Type: text/html; charset=UTF-8\r\n"
+         "Content-Length: 11\r\n"
+         "Proxy-Connection: close\r\n"
+         "Date: Thu, 31 Dec 2009 20:55:48 +0000\r\n"
+         "\r\n"
+         "hello world"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 4
+  ,.headers=
+    { {"Content-Type", "text/html; charset=UTF-8" }
+    , {"Content-Length", "11" }
+    , {"Proxy-Connection", "close" }
+    , {"Date", "Thu, 31 Dec 2009 20:55:48 +0000"}
+    }
+  ,.body= "hello world"
+  }
+
+#define UNDERSTORE_HEADER_KEY 7
+  // shown by
+  // curl -o /dev/null -v "http://ad.doubleclick.net/pfadx/DARTSHELLCONFIGXML;dcmt=text/xml;"
+, {.name="underscore header key"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Server: DCLK-AdSvr\r\n"
+         "Content-Type: text/xml\r\n"
+         "Content-Length: 0\r\n"
+         "DCLK_imp: v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o\r\n\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 4
+  ,.headers=
+    { {"Server", "DCLK-AdSvr" }
+    , {"Content-Type", "text/xml" }
+    , {"Content-Length", "0" }
+    , {"DCLK_imp", "v7;x;114750856;0-0;0;17820020;0/0;21603567/21621457/1;;~okv=;dcmt=text/xml;;~cs=o" }
+    }
+  ,.body= ""
+  }
+
+#define BONJOUR_MADAME_FR 8
+/* The client should not merge two headers fields when the first one doesn't
+ * have a value.
+ */
+, {.name= "bonjourmadame.fr"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.0 301 Moved Permanently\r\n"
+         "Date: Thu, 03 Jun 2010 09:56:32 GMT\r\n"
+         "Server: Apache/2.2.3 (Red Hat)\r\n"
+         "Cache-Control: public\r\n"
+         "Pragma: \r\n"
+         "Location: http://www.bonjourmadame.fr/\r\n"
+         "Vary: Accept-Encoding\r\n"
+         "Content-Length: 0\r\n"
+         "Content-Type: text/html; charset=UTF-8\r\n"
+         "Connection: keep-alive\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.status_code= 301
+  ,.response_status= "Moved Permanently"
+  ,.num_headers= 9
+  ,.headers=
+    { { "Date", "Thu, 03 Jun 2010 09:56:32 GMT" }
+    , { "Server", "Apache/2.2.3 (Red Hat)" }
+    , { "Cache-Control", "public" }
+    , { "Pragma", "" }
+    , { "Location", "http://www.bonjourmadame.fr/" }
+    , { "Vary",  "Accept-Encoding" }
+    , { "Content-Length", "0" }
+    , { "Content-Type", "text/html; charset=UTF-8" }
+    , { "Connection", "keep-alive" }
+    }
+  ,.body= ""
+  }
+
+#define RES_FIELD_UNDERSCORE 9
+/* Should handle spaces in header fields */
+, {.name= "field underscore"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Date: Tue, 28 Sep 2010 01:14:13 GMT\r\n"
+         "Server: Apache\r\n"
+         "Cache-Control: no-cache, must-revalidate\r\n"
+         "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n"
+         ".et-Cookie: PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com\r\n"
+         "Vary: Accept-Encoding\r\n"
+         "_eep-Alive: timeout=45\r\n" /* semantic value ignored */
+         "_onnection: Keep-Alive\r\n" /* semantic value ignored */
+         "Transfer-Encoding: chunked\r\n"
+         "Content-Type: text/html\r\n"
+         "Connection: close\r\n"
+         "\r\n"
+         "0\r\n\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 11
+  ,.headers=
+    { { "Date", "Tue, 28 Sep 2010 01:14:13 GMT" }
+    , { "Server", "Apache" }
+    , { "Cache-Control", "no-cache, must-revalidate" }
+    , { "Expires", "Mon, 26 Jul 1997 05:00:00 GMT" }
+    , { ".et-Cookie", "PlaxoCS=1274804622353690521; path=/; domain=.plaxo.com" }
+    , { "Vary", "Accept-Encoding" }
+    , { "_eep-Alive", "timeout=45" }
+    , { "_onnection", "Keep-Alive" }
+    , { "Transfer-Encoding", "chunked" }
+    , { "Content-Type", "text/html" }
+    , { "Connection", "close" }
+    }
+  ,.body= ""
+  ,.num_chunks_complete= 1
+  ,.chunk_lengths= {}
+  }
+
+#define NON_ASCII_IN_STATUS_LINE 10
+/* Should handle non-ASCII in status line */
+, {.name= "non-ASCII in status line"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 500 Oriëntatieprobleem\r\n"
+         "Date: Fri, 5 Nov 2010 23:07:12 GMT+2\r\n"
+         "Content-Length: 0\r\n"
+         "Connection: close\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 500
+  ,.response_status= "Oriëntatieprobleem"
+  ,.num_headers= 3
+  ,.headers=
+    { { "Date", "Fri, 5 Nov 2010 23:07:12 GMT+2" }
+    , { "Content-Length", "0" }
+    , { "Connection", "close" }
+    }
+  ,.body= ""
+  }
+
+#define HTTP_VERSION_0_9 11
+/* Should handle HTTP/0.9 */
+, {.name= "http version 0.9"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/0.9 200 OK\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 0
+  ,.http_minor= 9
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 0
+  ,.headers=
+    {}
+  ,.body= ""
+  }
+
+#define NO_CONTENT_LENGTH_NO_TRANSFER_ENCODING_RESPONSE 12
+/* The client should wait for the server's EOF. That is, when neither
+ * content-length nor transfer-encoding is specified, the end of body
+ * is specified by the EOF.
+ */
+, {.name= "neither content-length nor transfer-encoding response"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Content-Type: text/plain\r\n"
+         "\r\n"
+         "hello world"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Content-Type", "text/plain" }
+    }
+  ,.body= "hello world"
+  }
+
+#define NO_BODY_HTTP10_KA_200 13
+, {.name= "HTTP/1.0 with keep-alive and EOF-terminated 200 status"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.0 200 OK\r\n"
+         "Connection: keep-alive\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Connection", "keep-alive" }
+    }
+  ,.body_size= 0
+  ,.body= ""
+  }
+
+#define NO_BODY_HTTP10_KA_204 14
+, {.name= "HTTP/1.0 with keep-alive and a 204 status"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.0 204 No content\r\n"
+         "Connection: keep-alive\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 0
+  ,.status_code= 204
+  ,.response_status= "No content"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Connection", "keep-alive" }
+    }
+  ,.body_size= 0
+  ,.body= ""
+  }
+
+#define NO_BODY_HTTP11_KA_200 15
+, {.name= "HTTP/1.1 with an EOF-terminated 200 status"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 0
+  ,.headers={}
+  ,.body_size= 0
+  ,.body= ""
+  }
+
+#define NO_BODY_HTTP11_KA_204 16
+, {.name= "HTTP/1.1 with a 204 status"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 204 No content\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 204
+  ,.response_status= "No content"
+  ,.num_headers= 0
+  ,.headers={}
+  ,.body_size= 0
+  ,.body= ""
+  }
+
+#define NO_BODY_HTTP11_NOKA_204 17
+, {.name= "HTTP/1.1 with a 204 status and keep-alive disabled"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 204 No content\r\n"
+         "Connection: close\r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 204
+  ,.response_status= "No content"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Connection", "close" }
+    }
+  ,.body_size= 0
+  ,.body= ""
+  }
+
+#define NO_BODY_HTTP11_KA_CHUNKED_200 18
+, {.name= "HTTP/1.1 with chunked endocing and a 200 response"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Transfer-Encoding: chunked\r\n"
+         "\r\n"
+         "0\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 1
+  ,.headers=
+    { { "Transfer-Encoding", "chunked" }
+    }
+  ,.body_size= 0
+  ,.body= ""
+  ,.num_chunks_complete= 1
+  }
+
+#if !HTTP_PARSER_STRICT
+#define SPACE_IN_FIELD_RES 19
+/* Should handle spaces in header fields */
+, {.name= "field space"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 OK\r\n"
+         "Server: Microsoft-IIS/6.0\r\n"
+         "X-Powered-By: ASP.NET\r\n"
+         "en-US Content-Type: text/xml\r\n" /* this is the problem */
+         "Content-Type: text/xml\r\n"
+         "Content-Length: 16\r\n"
+         "Date: Fri, 23 Jul 2010 18:45:38 GMT\r\n"
+         "Connection: keep-alive\r\n"
+         "\r\n"
+         "<xml>hello</xml>" /* fake body */
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= "OK"
+  ,.num_headers= 7
+  ,.headers=
+    { { "Server",  "Microsoft-IIS/6.0" }
+    , { "X-Powered-By", "ASP.NET" }
+    , { "en-US Content-Type", "text/xml" }
+    , { "Content-Type", "text/xml" }
+    , { "Content-Length", "16" }
+    , { "Date", "Fri, 23 Jul 2010 18:45:38 GMT" }
+    , { "Connection", "keep-alive" }
+    }
+  ,.body= "<xml>hello</xml>"
+  }
+#endif /* !HTTP_PARSER_STRICT */
+
+#define AMAZON_COM 20
+, {.name= "amazon.com"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 301 MovedPermanently\r\n"
+         "Date: Wed, 15 May 2013 17:06:33 GMT\r\n"
+         "Server: Server\r\n"
+         "x-amz-id-1: 0GPHKXSJQ826RK7GZEB2\r\n"
+         "p3p: policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \"\r\n"
+         "x-amz-id-2: STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD\r\n"
+         "Location: http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846\r\n"
+         "Vary: Accept-Encoding,User-Agent\r\n"
+         "Content-Type: text/html; charset=ISO-8859-1\r\n"
+         "Transfer-Encoding: chunked\r\n"
+         "\r\n"
+         "1\r\n"
+         "\n\r\n"
+         "0\r\n"
+         "\r\n"
+  ,.should_keep_alive= TRUE
+  ,.message_complete_on_eof= FALSE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 301
+  ,.response_status= "MovedPermanently"
+  ,.num_headers= 9
+  ,.headers= { { "Date", "Wed, 15 May 2013 17:06:33 GMT" }
+             , { "Server", "Server" }
+             , { "x-amz-id-1", "0GPHKXSJQ826RK7GZEB2" }
+             , { "p3p", "policyref=\"http://www.amazon.com/w3c/p3p.xml\",CP=\"CAO DSP LAW CUR ADM IVAo IVDo CONo OTPo OUR DELi PUBi OTRi BUS PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA HEA PRE LOC GOV OTC \"" }
+             , { "x-amz-id-2", "STN69VZxIFSz9YJLbz1GDbxpbjG6Qjmmq5E3DxRhOUw+Et0p4hr7c/Q8qNcx4oAD" }
+             , { "Location", "http://www.amazon.com/Dan-Brown/e/B000AP9DSU/ref=s9_pop_gw_al1?_encoding=UTF8&refinementId=618073011&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0SHYY5BZXN3KR20BNFAY&pf_rd_t=101&pf_rd_p=1263340922&pf_rd_i=507846" }
+             , { "Vary", "Accept-Encoding,User-Agent" }
+             , { "Content-Type", "text/html; charset=ISO-8859-1" }
+             , { "Transfer-Encoding", "chunked" }
+             }
+  ,.body= "\n"
+  ,.num_chunks_complete= 2
+  ,.chunk_lengths= { 1 }
+  }
+
+#define EMPTY_REASON_PHRASE_AFTER_SPACE 20
+, {.name= "empty reason phrase after space"
+  ,.type= HTTP_RESPONSE
+  ,.raw= "HTTP/1.1 200 \r\n"
+         "\r\n"
+  ,.should_keep_alive= FALSE
+  ,.message_complete_on_eof= TRUE
+  ,.http_major= 1
+  ,.http_minor= 1
+  ,.status_code= 200
+  ,.response_status= ""
+  ,.num_headers= 0
+  ,.headers= {}
+  ,.body= ""
+  }
+
+, {.name= NULL } /* sentinel */
+};
+
+/* strnlen() is a POSIX.2008 addition. Can't rely on it being available so
+ * define it ourselves.
+ */
+size_t
+strnlen(const char *s, size_t maxlen)
+{
+  const char *p;
+
+  p = memchr(s, '\0', maxlen);
+  if (p == NULL)
+    return maxlen;
+
+  return p - s;
+}
+
+size_t
+strlncat(char *dst, size_t len, const char *src, size_t n)
+{
+  size_t slen;
+  size_t dlen;
+  size_t rlen;
+  size_t ncpy;
+
+  slen = strnlen(src, n);
+  dlen = strnlen(dst, len);
+
+  if (dlen < len) {
+    rlen = len - dlen;
+    ncpy = slen < rlen ? slen : (rlen - 1);
+    memcpy(dst + dlen, src, ncpy);
+    dst[dlen + ncpy] = '\0';
+  }
+
+  assert(len > slen + dlen);
+  return slen + dlen;
+}
+
+size_t
+strlcat(char *dst, const char *src, size_t len)
+{
+  return strlncat(dst, len, src, (size_t) -1);
+}
+
+size_t
+strlncpy(char *dst, size_t len, const char *src, size_t n)
+{
+  size_t slen;
+  size_t ncpy;
+
+  slen = strnlen(src, n);
+
+  if (len > 0) {
+    ncpy = slen < len ? slen : (len - 1);
+    memcpy(dst, src, ncpy);
+    dst[ncpy] = '\0';
+  }
+
+  assert(len > slen);
+  return slen;
+}
+
+size_t
+strlcpy(char *dst, const char *src, size_t len)
+{
+  return strlncpy(dst, len, src, (size_t) -1);
+}
+
+int
+request_url_cb (http_parser *p, const char *buf, size_t len)
+{
+  assert(p == parser);
+  strlncat(messages[num_messages].request_url,
+           sizeof(messages[num_messages].request_url),
+           buf,
+           len);
+  return 0;
+}
+
+int
+header_field_cb (http_parser *p, const char *buf, size_t len)
+{
+  assert(p == parser);
+  struct message *m = &messages[num_messages];
+
+  if (m->last_header_element != FIELD)
+    m->num_headers++;
+
+  strlncat(m->headers[m->num_headers-1][0],
+           sizeof(m->headers[m->num_headers-1][0]),
+           buf,
+           len);
+
+  m->last_header_element = FIELD;
+
+  return 0;
+}
+
+int
+header_value_cb (http_parser *p, const char *buf, size_t len)
+{
+  assert(p == parser);
+  struct message *m = &messages[num_messages];
+
+  strlncat(m->headers[m->num_headers-1][1],
+           sizeof(m->headers[m->num_headers-1][1]),
+           buf,
+           len);
+
+  m->last_header_element = VALUE;
+
+  return 0;
+}
+
+void
+check_body_is_final (const http_parser *p)
+{
+  if (messages[num_messages].body_is_final) {
+    fprintf(stderr, "\n\n *** Error http_body_is_final() should return 1 "
+                    "on last on_body callback call "
+                    "but it doesn't! ***\n\n");
+    assert(0);
+    abort();
+  }
+  messages[num_messages].body_is_final = http_body_is_final(p);
+}
+
+int
+body_cb (http_parser *p, const char *buf, size_t len)
+{
+  assert(p == parser);
+  strlncat(messages[num_messages].body,
+           sizeof(messages[num_messages].body),
+           buf,
+           len);
+  messages[num_messages].body_size += len;
+  check_body_is_final(p);
+ // printf("body_cb: '%s'\n", requests[num_messages].body);
+  return 0;
+}
+
+int
+count_body_cb (http_parser *p, const char *buf, size_t len)
+{
+  assert(p == parser);
+  assert(buf);
+  messages[num_messages].body_size += len;
+  check_body_is_final(p);
+  return 0;
+}
+
+int
+message_begin_cb (http_parser *p)
+{
+  assert(p == parser);
+  messages[num_messages].message_begin_cb_called = TRUE;
+  return 0;
+}
+
+int
+headers_complete_cb (http_parser *p)
+{
+  assert(p == parser);
+  messages[num_messages].method = parser->method;
+  messages[num_messages].status_code = parser->status_code;
+  messages[num_messages].http_major = parser->http_major;
+  messages[num_messages].http_minor = parser->http_minor;
+  messages[num_messages].headers_complete_cb_called = TRUE;
+  messages[num_messages].should_keep_alive = http_should_keep_alive(parser);
+  return 0;
+}
+
+int
+message_complete_cb (http_parser *p)
+{
+  assert(p == parser);
+  if (messages[num_messages].should_keep_alive != http_should_keep_alive(parser))
+  {
+    fprintf(stderr, "\n\n *** Error http_should_keep_alive() should have same "
+                    "value in both on_message_complete and on_headers_complete "
+                    "but it doesn't! ***\n\n");
+    assert(0);
+    abort();
+  }
+
+  if (messages[num_messages].body_size &&
+      http_body_is_final(p) &&
+      !messages[num_messages].body_is_final)
+  {
+    fprintf(stderr, "\n\n *** Error http_body_is_final() should return 1 "
+                    "on last on_body callback call "
+                    "but it doesn't! ***\n\n");
+    assert(0);
+    abort();
+  }
+
+  messages[num_messages].message_complete_cb_called = TRUE;
+
+  messages[num_messages].message_complete_on_eof = currently_parsing_eof;
+
+  num_messages++;
+  return 0;
+}
+
+int
+response_status_cb (http_parser *p, const char *buf, size_t len)
+{
+  assert(p == parser);
+  strlncat(messages[num_messages].response_status,
+           sizeof(messages[num_messages].response_status),
+           buf,
+           len);
+  return 0;
+}
+
+int
+chunk_header_cb (http_parser *p)
+{
+  assert(p == parser);
+  int chunk_idx = messages[num_messages].num_chunks;
+  messages[num_messages].num_chunks++;
+  if (chunk_idx < MAX_CHUNKS) {
+    messages[num_messages].chunk_lengths[chunk_idx] = p->content_length;
+  }
+
+  return 0;
+}
+
+int
+chunk_complete_cb (http_parser *p)
+{
+  assert(p == parser);
+
+  /* Here we want to verify that each chunk_header_cb is matched by a
+   * chunk_complete_cb, so not only should the total number of calls to
+   * both callbacks be the same, but they also should be interleaved
+   * properly */
+  assert(messages[num_messages].num_chunks ==
+         messages[num_messages].num_chunks_complete + 1);
+
+  messages[num_messages].num_chunks_complete++;
+  return 0;
+}
+
+/* These dontcall_* callbacks exist so that we can verify that when we're
+ * paused, no additional callbacks are invoked */
+int
+dontcall_message_begin_cb (http_parser *p)
+{
+  if (p) { } // gcc
+  fprintf(stderr, "\n\n*** on_message_begin() called on paused parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_header_field_cb (http_parser *p, const char *buf, size_t len)
+{
+  if (p || buf || len) { } // gcc
+  fprintf(stderr, "\n\n*** on_header_field() called on paused parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_header_value_cb (http_parser *p, const char *buf, size_t len)
+{
+  if (p || buf || len) { } // gcc
+  fprintf(stderr, "\n\n*** on_header_value() called on paused parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_request_url_cb (http_parser *p, const char *buf, size_t len)
+{
+  if (p || buf || len) { } // gcc
+  fprintf(stderr, "\n\n*** on_request_url() called on paused parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_body_cb (http_parser *p, const char *buf, size_t len)
+{
+  if (p || buf || len) { } // gcc
+  fprintf(stderr, "\n\n*** on_body_cb() called on paused parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_headers_complete_cb (http_parser *p)
+{
+  if (p) { } // gcc
+  fprintf(stderr, "\n\n*** on_headers_complete() called on paused "
+                  "parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_message_complete_cb (http_parser *p)
+{
+  if (p) { } // gcc
+  fprintf(stderr, "\n\n*** on_message_complete() called on paused "
+                  "parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_response_status_cb (http_parser *p, const char *buf, size_t len)
+{
+  if (p || buf || len) { } // gcc
+  fprintf(stderr, "\n\n*** on_status() called on paused parser ***\n\n");
+  abort();
+}
+
+int
+dontcall_chunk_header_cb (http_parser *p)
+{
+  if (p) { } // gcc
+  fprintf(stderr, "\n\n*** on_chunk_header() called on paused parser ***\n\n");
+  exit(1);
+}
+
+int
+dontcall_chunk_complete_cb (http_parser *p)
+{
+  if (p) { } // gcc
+  fprintf(stderr, "\n\n*** on_chunk_complete() "
+          "called on paused parser ***\n\n");
+  exit(1);
+}
+
+static http_parser_settings settings_dontcall =
+  {.on_message_begin = dontcall_message_begin_cb
+  ,.on_header_field = dontcall_header_field_cb
+  ,.on_header_value = dontcall_header_value_cb
+  ,.on_url = dontcall_request_url_cb
+  ,.on_status = dontcall_response_status_cb
+  ,.on_body = dontcall_body_cb
+  ,.on_headers_complete = dontcall_headers_complete_cb
+  ,.on_message_complete = dontcall_message_complete_cb
+  ,.on_chunk_header = dontcall_chunk_header_cb
+  ,.on_chunk_complete = dontcall_chunk_complete_cb
+  };
+
+/* These pause_* callbacks always pause the parser and just invoke the regular
+ * callback that tracks content. Before returning, we overwrite the parser
+ * settings to point to the _dontcall variety so that we can verify that
+ * the pause actually did, you know, pause. */
+int
+pause_message_begin_cb (http_parser *p)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return message_begin_cb(p);
+}
+
+int
+pause_header_field_cb (http_parser *p, const char *buf, size_t len)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return header_field_cb(p, buf, len);
+}
+
+int
+pause_header_value_cb (http_parser *p, const char *buf, size_t len)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return header_value_cb(p, buf, len);
+}
+
+int
+pause_request_url_cb (http_parser *p, const char *buf, size_t len)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return request_url_cb(p, buf, len);
+}
+
+int
+pause_body_cb (http_parser *p, const char *buf, size_t len)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return body_cb(p, buf, len);
+}
+
+int
+pause_headers_complete_cb (http_parser *p)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return headers_complete_cb(p);
+}
+
+int
+pause_message_complete_cb (http_parser *p)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return message_complete_cb(p);
+}
+
+int
+pause_response_status_cb (http_parser *p, const char *buf, size_t len)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return response_status_cb(p, buf, len);
+}
+
+int
+pause_chunk_header_cb (http_parser *p)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return chunk_header_cb(p);
+}
+
+int
+pause_chunk_complete_cb (http_parser *p)
+{
+  http_parser_pause(p, 1);
+  *current_pause_parser = settings_dontcall;
+  return chunk_complete_cb(p);
+}
+
+static http_parser_settings settings_pause =
+  {.on_message_begin = pause_message_begin_cb
+  ,.on_header_field = pause_header_field_cb
+  ,.on_header_value = pause_header_value_cb
+  ,.on_url = pause_request_url_cb
+  ,.on_status = pause_response_status_cb
+  ,.on_body = pause_body_cb
+  ,.on_headers_complete = pause_headers_complete_cb
+  ,.on_message_complete = pause_message_complete_cb
+  ,.on_chunk_header = pause_chunk_header_cb
+  ,.on_chunk_complete = pause_chunk_complete_cb
+  };
+
+static http_parser_settings settings =
+  {.on_message_begin = message_begin_cb
+  ,.on_header_field = header_field_cb
+  ,.on_header_value = header_value_cb
+  ,.on_url = request_url_cb
+  ,.on_status = response_status_cb
+  ,.on_body = body_cb
+  ,.on_headers_complete = headers_complete_cb
+  ,.on_message_complete = message_complete_cb
+  ,.on_chunk_header = chunk_header_cb
+  ,.on_chunk_complete = chunk_complete_cb
+  };
+
+static http_parser_settings settings_count_body =
+  {.on_message_begin = message_begin_cb
+  ,.on_header_field = header_field_cb
+  ,.on_header_value = header_value_cb
+  ,.on_url = request_url_cb
+  ,.on_status = response_status_cb
+  ,.on_body = count_body_cb
+  ,.on_headers_complete = headers_complete_cb
+  ,.on_message_complete = message_complete_cb
+  ,.on_chunk_header = chunk_header_cb
+  ,.on_chunk_complete = chunk_complete_cb
+  };
+
+static http_parser_settings settings_null =
+  {.on_message_begin = 0
+  ,.on_header_field = 0
+  ,.on_header_value = 0
+  ,.on_url = 0
+  ,.on_status = 0
+  ,.on_body = 0
+  ,.on_headers_complete = 0
+  ,.on_message_complete = 0
+  ,.on_chunk_header = 0
+  ,.on_chunk_complete = 0
+  };
+
+void
+parser_init (enum http_parser_type type)
+{
+  num_messages = 0;
+
+  assert(parser == NULL);
+
+  parser = malloc(sizeof(http_parser));
+
+  http_parser_init(parser, type);
+
+  memset(&messages, 0, sizeof messages);
+
+}
+
+void
+parser_free ()
+{
+  assert(parser);
+  free(parser);
+  parser = NULL;
+}
+
+size_t parse (const char *buf, size_t len)
+{
+  size_t nparsed;
+  currently_parsing_eof = (len == 0);
+  nparsed = http_parser_execute(parser, &settings, buf, len);
+  return nparsed;
+}
+
+size_t parse_count_body (const char *buf, size_t len)
+{
+  size_t nparsed;
+  currently_parsing_eof = (len == 0);
+  nparsed = http_parser_execute(parser, &settings_count_body, buf, len);
+  return nparsed;
+}
+
+size_t parse_pause (const char *buf, size_t len)
+{
+  size_t nparsed;
+  http_parser_settings s = settings_pause;
+
+  currently_parsing_eof = (len == 0);
+  current_pause_parser = &s;
+  nparsed = http_parser_execute(parser, current_pause_parser, buf, len);
+  return nparsed;
+}
+
+static inline int
+check_str_eq (const struct message *m,
+              const char *prop,
+              const char *expected,
+              const char *found) {
+  if ((expected == NULL) != (found == NULL)) {
+    printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name);
+    printf("expected %s\n", (expected == NULL) ? "NULL" : expected);
+    printf("   found %s\n", (found == NULL) ? "NULL" : found);
+    return 0;
+  }
+  if (expected != NULL && 0 != strcmp(expected, found)) {
+    printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name);
+    printf("expected '%s'\n", expected);
+    printf("   found '%s'\n", found);
+    return 0;
+  }
+  return 1;
+}
+
+static inline int
+check_num_eq (const struct message *m,
+              const char *prop,
+              int expected,
+              int found) {
+  if (expected != found) {
+    printf("\n*** Error: %s in '%s' ***\n\n", prop, m->name);
+    printf("expected %d\n", expected);
+    printf("   found %d\n", found);
+    return 0;
+  }
+  return 1;
+}
+
+#define MESSAGE_CHECK_STR_EQ(expected, found, prop) \
+  if (!check_str_eq(expected, #prop, expected->prop, found->prop)) return 0
+
+#define MESSAGE_CHECK_NUM_EQ(expected, found, prop) \
+  if (!check_num_eq(expected, #prop, expected->prop, found->prop)) return 0
+
+#define MESSAGE_CHECK_URL_EQ(u, expected, found, prop, fn)           \
+do {                                                                 \
+  char ubuf[256];                                                    \
+                                                                     \
+  if ((u)->field_set & (1 << (fn))) {                                \
+    memcpy(ubuf, (found)->request_url + (u)->field_data[(fn)].off,   \
+      (u)->field_data[(fn)].len);                                    \
+    ubuf[(u)->field_data[(fn)].len] = '\0';                          \
+  } else {                                                           \
+    ubuf[0] = '\0';                                                  \
+  }                                                                  \
+                                                                     \
+  check_str_eq(expected, #prop, expected->prop, ubuf);               \
+} while(0)
+
+int
+message_eq (int index, const struct message *expected)
+{
+  int i;
+  struct message *m = &messages[index];
+
+  MESSAGE_CHECK_NUM_EQ(expected, m, http_major);
+  MESSAGE_CHECK_NUM_EQ(expected, m, http_minor);
+
+  if (expected->type == HTTP_REQUEST) {
+    MESSAGE_CHECK_NUM_EQ(expected, m, method);
+  } else {
+    MESSAGE_CHECK_NUM_EQ(expected, m, status_code);
+    MESSAGE_CHECK_STR_EQ(expected, m, response_status);
+  }
+
+  MESSAGE_CHECK_NUM_EQ(expected, m, should_keep_alive);
+  MESSAGE_CHECK_NUM_EQ(expected, m, message_complete_on_eof);
+
+  assert(m->message_begin_cb_called);
+  assert(m->headers_complete_cb_called);
+  assert(m->message_complete_cb_called);
+
+
+  MESSAGE_CHECK_STR_EQ(expected, m, request_url);
+
+  /* Check URL components; we can't do this w/ CONNECT since it doesn't
+   * send us a well-formed URL.
+   */
+  if (*m->request_url && m->method != HTTP_CONNECT) {
+    struct http_parser_url u;
+
+    if (http_parser_parse_url(m->request_url, strlen(m->request_url), 0, &u)) {
+      fprintf(stderr, "\n\n*** failed to parse URL %s ***\n\n",
+        m->request_url);
+      abort();
+    }
+
+    if (expected->host) {
+      MESSAGE_CHECK_URL_EQ(&u, expected, m, host, UF_HOST);
+    }
+
+    if (expected->userinfo) {
+      MESSAGE_CHECK_URL_EQ(&u, expected, m, userinfo, UF_USERINFO);
+    }
+
+    m->port = (u.field_set & (1 << UF_PORT)) ?
+      u.port : 0;
+
+    MESSAGE_CHECK_URL_EQ(&u, expected, m, query_string, UF_QUERY);
+    MESSAGE_CHECK_URL_EQ(&u, expected, m, fragment, UF_FRAGMENT);
+    MESSAGE_CHECK_URL_EQ(&u, expected, m, request_path, UF_PATH);
+    MESSAGE_CHECK_NUM_EQ(expected, m, port);
+  }
+
+  if (expected->body_size) {
+    MESSAGE_CHECK_NUM_EQ(expected, m, body_size);
+  } else {
+    MESSAGE_CHECK_STR_EQ(expected, m, body);
+  }
+
+  assert(m->num_chunks == m->num_chunks_complete);
+  MESSAGE_CHECK_NUM_EQ(expected, m, num_chunks_complete);
+  for (i = 0; i < m->num_chunks && i < MAX_CHUNKS; i++) {
+    MESSAGE_CHECK_NUM_EQ(expected, m, chunk_lengths[i]);
+  }
+
+  MESSAGE_CHECK_NUM_EQ(expected, m, num_headers);
+
+  int r;
+  for (i = 0; i < m->num_headers; i++) {
+    r = check_str_eq(expected, "header field", expected->headers[i][0], m->headers[i][0]);
+    if (!r) return 0;
+    r = check_str_eq(expected, "header value", expected->headers[i][1], m->headers[i][1]);
+    if (!r) return 0;
+  }
+
+  MESSAGE_CHECK_STR_EQ(expected, m, upgrade);
+
+  return 1;
+}
+
+/* Given a sequence of varargs messages, return the number of them that the
+ * parser should successfully parse, taking into account that upgraded
+ * messages prevent all subsequent messages from being parsed.
+ */
+size_t
+count_parsed_messages(const size_t nmsgs, ...) {
+  size_t i;
+  va_list ap;
+
+  va_start(ap, nmsgs);
+
+  for (i = 0; i < nmsgs; i++) {
+    struct message *m = va_arg(ap, struct message *);
+
+    if (m->upgrade) {
+      va_end(ap);
+      return i + 1;
+    }
+  }
+
+  va_end(ap);
+  return nmsgs;
+}
+
+/* Given a sequence of bytes and the number of these that we were able to
+ * parse, verify that upgrade bodies are correct.
+ */
+void
+upgrade_message_fix(char *body, const size_t nread, const size_t nmsgs, ...) {
+  va_list ap;
+  size_t i;
+  size_t off = 0;
+ 
+  va_start(ap, nmsgs);
+
+  for (i = 0; i < nmsgs; i++) {
+    struct message *m = va_arg(ap, struct message *);
+
+    off += strlen(m->raw);
+
+    if (m->upgrade) {
+      off -= strlen(m->upgrade);
+
+      /* Check the portion of the response after its specified upgrade */
+      if (!check_str_eq(m, "upgrade", body + off, body + nread)) {
+        abort();
+      }
+
+      /* Fix up the response so that message_eq() will verify the beginning
+       * of the upgrade */
+      *(body + nread + strlen(m->upgrade)) = '\0';
+      messages[num_messages -1 ].upgrade = body + nread;
+
+      va_end(ap);
+      return;
+    }
+  }
+
+  va_end(ap);
+  printf("\n\n*** Error: expected a message with upgrade ***\n");
+
+  abort();
+}
+
+static void
+print_error (const char *raw, size_t error_location)
+{
+  fprintf(stderr, "\n*** %s ***\n\n",
+          http_errno_description(HTTP_PARSER_ERRNO(parser)));
+
+  int this_line = 0, char_len = 0;
+  size_t i, j, len = strlen(raw), error_location_line = 0;
+  for (i = 0; i < len; i++) {
+    if (i == error_location) this_line = 1;
+    switch (raw[i]) {
+      case '\r':
+        char_len = 2;
+        fprintf(stderr, "\\r");
+        break;
+
+      case '\n':
+        fprintf(stderr, "\\n\n");
+
+        if (this_line) goto print;
+
+        error_location_line = 0;
+        continue;
+
+      default:
+        char_len = 1;
+        fputc(raw[i], stderr);
+        break;
+    }
+    if (!this_line) error_location_line += char_len;
+  }
+
+  fprintf(stderr, "[eof]\n");
+
+ print:
+  for (j = 0; j < error_location_line; j++) {
+    fputc(' ', stderr);
+  }
+  fprintf(stderr, "^\n\nerror location: %u\n", (unsigned int)error_location);
+}
+
+void
+test_preserve_data (void)
+{
+  char my_data[] = "application-specific data";
+  http_parser parser;
+  parser.data = my_data;
+  http_parser_init(&parser, HTTP_REQUEST);
+  if (parser.data != my_data) {
+    printf("\n*** parser.data not preserved accross http_parser_init ***\n\n");
+    abort();
+  }
+}
+
+struct url_test {
+  const char *name;
+  const char *url;
+  int is_connect;
+  struct http_parser_url u;
+  int rv;
+};
+
+const struct url_test url_tests[] =
+{ {.name="proxy request"
+  ,.url="http://hostname/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  7,  8 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 15,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="proxy request with port"
+  ,.url="http://hostname:444/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PORT) | (1 << UF_PATH)
+    ,.port=444
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  7,  8 } /* UF_HOST */
+      ,{ 16,  3 } /* UF_PORT */
+      ,{ 19,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="CONNECT request"
+  ,.url="hostname:443"
+  ,.is_connect=1
+  ,.u=
+    {.field_set=(1 << UF_HOST) | (1 << UF_PORT)
+    ,.port=443
+    ,.field_data=
+      {{  0,  0 } /* UF_SCHEMA */
+      ,{  0,  8 } /* UF_HOST */
+      ,{  9,  3 } /* UF_PORT */
+      ,{  0,  0 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="CONNECT request but not connect"
+  ,.url="hostname:443"
+  ,.is_connect=0
+  ,.rv=1
+  }
+
+, {.name="proxy ipv6 request"
+  ,.url="http://[1:2::3:4]/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  8,  8 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 17,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="proxy ipv6 request with port"
+  ,.url="http://[1:2::3:4]:67/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PORT) | (1 << UF_PATH)
+    ,.port=67
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  8,  8 } /* UF_HOST */
+      ,{ 18,  2 } /* UF_PORT */
+      ,{ 20,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="CONNECT ipv6 address"
+  ,.url="[1:2::3:4]:443"
+  ,.is_connect=1
+  ,.u=
+    {.field_set=(1 << UF_HOST) | (1 << UF_PORT)
+    ,.port=443
+    ,.field_data=
+      {{  0,  0 } /* UF_SCHEMA */
+      ,{  1,  8 } /* UF_HOST */
+      ,{ 11,  3 } /* UF_PORT */
+      ,{  0,  0 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="ipv4 in ipv6 address"
+  ,.url="http://[2001:0000:0000:0000:0000:0000:1.9.1.1]/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set=(1 << UF_SCHEMA) | (1 << UF_HOST) | (1 << UF_PATH)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  8, 37 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 46,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="extra ? in query string"
+  ,.url="http://a.tbcdn.cn/p/fp/2010c/??fp-header-min.css,fp-base-min.css,"
+  "fp-channel-min.css,fp-product-min.css,fp-mall-min.css,fp-category-min.css,"
+  "fp-sub-min.css,fp-gdp4p-min.css,fp-css3-min.css,fp-misc-min.css?t=20101022.css"
+  ,.is_connect=0
+  ,.u=
+    {.field_set=(1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PATH) | (1<<UF_QUERY)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  7, 10 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 17, 12 } /* UF_PATH */
+      ,{ 30,187 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="space URL encoded"
+  ,.url="/toto.html?toto=a%20b"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_PATH) | (1<<UF_QUERY)
+    ,.port=0
+    ,.field_data=
+      {{  0,  0 } /* UF_SCHEMA */
+      ,{  0,  0 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{  0, 10 } /* UF_PATH */
+      ,{ 11, 10 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+
+, {.name="URL fragment"
+  ,.url="/toto.html#titi"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_PATH) | (1<<UF_FRAGMENT)
+    ,.port=0
+    ,.field_data=
+      {{  0,  0 } /* UF_SCHEMA */
+      ,{  0,  0 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{  0, 10 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{ 11,  4 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="complex URL fragment"
+  ,.url="http://www.webmasterworld.com/r.cgi?f=21&d=8405&url="
+    "http://www.example.com/index.html?foo=bar&hello=world#midpage"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PATH) | (1<<UF_QUERY) |\
+      (1<<UF_FRAGMENT)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  7, 22 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 29,  6 } /* UF_PATH */
+      ,{ 36, 69 } /* UF_QUERY */
+      ,{106,  7 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="complex URL from node js url parser doc"
+  ,.url="http://host.com:8080/p/a/t/h?query=string#hash"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PORT) | (1<<UF_PATH) |\
+      (1<<UF_QUERY) | (1<<UF_FRAGMENT)
+    ,.port=8080
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  7,  8 } /* UF_HOST */
+      ,{ 16,  4 } /* UF_PORT */
+      ,{ 20,  8 } /* UF_PATH */
+      ,{ 29, 12 } /* UF_QUERY */
+      ,{ 42,  4 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="complex URL with basic auth from node js url parser doc"
+  ,.url="http://a:b@host.com:8080/p/a/t/h?query=string#hash"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PORT) | (1<<UF_PATH) |\
+      (1<<UF_QUERY) | (1<<UF_FRAGMENT) | (1<<UF_USERINFO)
+    ,.port=8080
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{ 11,  8 } /* UF_HOST */
+      ,{ 20,  4 } /* UF_PORT */
+      ,{ 24,  8 } /* UF_PATH */
+      ,{ 33, 12 } /* UF_QUERY */
+      ,{ 46,  4 } /* UF_FRAGMENT */
+      ,{  7,  3 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="double @"
+  ,.url="http://a:b@@hostname:443/"
+  ,.is_connect=0
+  ,.rv=1
+  }
+
+, {.name="proxy empty host"
+  ,.url="http://:443/"
+  ,.is_connect=0
+  ,.rv=1
+  }
+
+, {.name="proxy empty port"
+  ,.url="http://hostname:/"
+  ,.is_connect=0
+  ,.rv=1
+  }
+
+, {.name="CONNECT with basic auth"
+  ,.url="a:b@hostname:443"
+  ,.is_connect=1
+  ,.rv=1
+  }
+
+, {.name="CONNECT empty host"
+  ,.url=":443"
+  ,.is_connect=1
+  ,.rv=1
+  }
+
+, {.name="CONNECT empty port"
+  ,.url="hostname:"
+  ,.is_connect=1
+  ,.rv=1
+  }
+
+, {.name="CONNECT with extra bits"
+  ,.url="hostname:443/"
+  ,.is_connect=1
+  ,.rv=1
+  }
+
+, {.name="space in URL"
+  ,.url="/foo bar/"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy basic auth with space url encoded"
+  ,.url="http://a%20:b@host.com/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PATH) | (1<<UF_USERINFO)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{ 14,  8 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 22,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  7,  6 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="carriage return in URL"
+  ,.url="/foo\rbar/"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy double : in URL"
+  ,.url="http://hostname::443/"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy basic auth with double :"
+  ,.url="http://a::b@host.com/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PATH) | (1<<UF_USERINFO)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{ 12,  8 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 20,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  7,  4 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="line feed in URL"
+  ,.url="/foo\nbar/"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy empty basic auth"
+  ,.url="http://@hostname/fo"
+  ,.u=
+    {.field_set= (1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PATH)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{  8,  8 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 16,  3 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+, {.name="proxy line feed in hostname"
+  ,.url="http://host\name/fo"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy % in hostname"
+  ,.url="http://host%name/fo"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy ; in hostname"
+  ,.url="http://host;ame/fo"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy basic auth with unreservedchars"
+  ,.url="http://a!;-_!=+$@host.com/"
+  ,.is_connect=0
+  ,.u=
+    {.field_set= (1<<UF_SCHEMA) | (1<<UF_HOST) | (1<<UF_PATH) | (1<<UF_USERINFO)
+    ,.port=0
+    ,.field_data=
+      {{  0,  4 } /* UF_SCHEMA */
+      ,{ 17,  8 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{ 25,  1 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  7,  9 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="proxy only empty basic auth"
+  ,.url="http://@/fo"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy only basic auth"
+  ,.url="http://toto@/fo"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy emtpy hostname"
+  ,.url="http:///fo"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="proxy = in URL"
+  ,.url="http://host=ame/fo"
+  ,.rv=1 /* s_dead */
+  }
+
+#if HTTP_PARSER_STRICT
+
+, {.name="tab in URL"
+  ,.url="/foo\tbar/"
+  ,.rv=1 /* s_dead */
+  }
+
+, {.name="form feed in URL"
+  ,.url="/foo\fbar/"
+  ,.rv=1 /* s_dead */
+  }
+
+#else /* !HTTP_PARSER_STRICT */
+
+, {.name="tab in URL"
+  ,.url="/foo\tbar/"
+  ,.u=
+    {.field_set=(1 << UF_PATH)
+    ,.field_data=
+      {{  0,  0 } /* UF_SCHEMA */
+      ,{  0,  0 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{  0,  9 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+
+, {.name="form feed in URL"
+  ,.url="/foo\fbar/"
+  ,.u=
+    {.field_set=(1 << UF_PATH)
+    ,.field_data=
+      {{  0,  0 } /* UF_SCHEMA */
+      ,{  0,  0 } /* UF_HOST */
+      ,{  0,  0 } /* UF_PORT */
+      ,{  0,  9 } /* UF_PATH */
+      ,{  0,  0 } /* UF_QUERY */
+      ,{  0,  0 } /* UF_FRAGMENT */
+      ,{  0,  0 } /* UF_USERINFO */
+      }
+    }
+  ,.rv=0
+  }
+#endif
+};
+
+void
+dump_url (const char *url, const struct http_parser_url *u)
+{
+  unsigned int i;
+
+  printf("\tfield_set: 0x%x, port: %u\n", u->field_set, u->port);
+  for (i = 0; i < UF_MAX; i++) {
+    if ((u->field_set & (1 << i)) == 0) {
+      printf("\tfield_data[%u]: unset\n", i);
+      continue;
+    }
+
+    printf("\tfield_data[%u]: off: %u len: %u part: \"%.*s\n\"",
+           i,
+           u->field_data[i].off,
+           u->field_data[i].len,
+           u->field_data[i].len,
+           url + u->field_data[i].off);
+  }
+}
+
+void
+test_parse_url (void)
+{
+  struct http_parser_url u;
+  const struct url_test *test;
+  unsigned int i;
+  int rv;
+
+  for (i = 0; i < (sizeof(url_tests) / sizeof(url_tests[0])); i++) {
+    test = &url_tests[i];
+    memset(&u, 0, sizeof(u));
+
+    rv = http_parser_parse_url(test->url,
+                               strlen(test->url),
+                               test->is_connect,
+                               &u);
+
+    if (test->rv == 0) {
+      if (rv != 0) {
+        printf("\n*** http_parser_parse_url(\"%s\") \"%s\" test failed, "
+               "unexpected rv %d ***\n\n", test->url, test->name, rv);
+        abort();
+      }
+
+      if (memcmp(&u, &test->u, sizeof(u)) != 0) {
+        printf("\n*** http_parser_parse_url(\"%s\") \"%s\" failed ***\n",
+               test->url, test->name);
+
+        printf("target http_parser_url:\n");
+        dump_url(test->url, &test->u);
+        printf("result http_parser_url:\n");
+        dump_url(test->url, &u);
+
+        abort();
+      }
+    } else {
+      /* test->rv != 0 */
+      if (rv == 0) {
+        printf("\n*** http_parser_parse_url(\"%s\") \"%s\" test failed, "
+               "unexpected rv %d ***\n\n", test->url, test->name, rv);
+        abort();
+      }
+    }
+  }
+}
+
+void
+test_method_str (void)
+{
+  assert(0 == strcmp("GET", http_method_str(HTTP_GET)));
+  assert(0 == strcmp("<unknown>", http_method_str(1337)));
+}
+
+void
+test_message (const struct message *message)
+{
+  size_t raw_len = strlen(message->raw);
+  size_t msg1len;
+  for (msg1len = 0; msg1len < raw_len; msg1len++) {
+    parser_init(message->type);
+
+    size_t read;
+    const char *msg1 = message->raw;
+    const char *msg2 = msg1 + msg1len;
+    size_t msg2len = raw_len - msg1len;
+
+    if (msg1len) {
+      read = parse(msg1, msg1len);
+
+      if (message->upgrade && parser->upgrade && num_messages > 0) {
+        messages[num_messages - 1].upgrade = msg1 + read;
+        goto test;
+      }
+
+      if (read != msg1len) {
+        print_error(msg1, read);
+        abort();
+      }
+    }
+
+
+    read = parse(msg2, msg2len);
+
+    if (message->upgrade && parser->upgrade) {
+      messages[num_messages - 1].upgrade = msg2 + read;
+      goto test;
+    }
+
+    if (read != msg2len) {
+      print_error(msg2, read);
+      abort();
+    }
+
+    read = parse(NULL, 0);
+
+    if (read != 0) {
+      print_error(message->raw, read);
+      abort();
+    }
+
+  test:
+
+    if (num_messages != 1) {
+      printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name);
+      abort();
+    }
+
+    if(!message_eq(0, message)) abort();
+
+    parser_free();
+  }
+}
+
+void
+test_message_count_body (const struct message *message)
+{
+  parser_init(message->type);
+
+  size_t read;
+  size_t l = strlen(message->raw);
+  size_t i, toread;
+  size_t chunk = 4024;
+
+  for (i = 0; i < l; i+= chunk) {
+    toread = MIN(l-i, chunk);
+    read = parse_count_body(message->raw + i, toread);
+    if (read != toread) {
+      print_error(message->raw, read);
+      abort();
+    }
+  }
+
+
+  read = parse_count_body(NULL, 0);
+  if (read != 0) {
+    print_error(message->raw, read);
+    abort();
+  }
+
+  if (num_messages != 1) {
+    printf("\n*** num_messages != 1 after testing '%s' ***\n\n", message->name);
+    abort();
+  }
+
+  if(!message_eq(0, message)) abort();
+
+  parser_free();
+}
+
+void
+test_simple (const char *buf, enum http_errno err_expected)
+{
+  parser_init(HTTP_REQUEST);
+
+  enum http_errno err;
+
+  parse(buf, strlen(buf));
+  err = HTTP_PARSER_ERRNO(parser);
+  parse(NULL, 0);
+
+  parser_free();
+
+  /* In strict mode, allow us to pass with an unexpected HPE_STRICT as
+   * long as the caller isn't expecting success.
+   */
+#if HTTP_PARSER_STRICT
+  if (err_expected != err && err_expected != HPE_OK && err != HPE_STRICT) {
+#else
+  if (err_expected != err) {
+#endif
+    fprintf(stderr, "\n*** test_simple expected %s, but saw %s ***\n\n%s\n",
+        http_errno_name(err_expected), http_errno_name(err), buf);
+    abort();
+  }
+}
+
+void
+test_header_overflow_error (int req)
+{
+  http_parser parser;
+  http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE);
+  size_t parsed;
+  const char *buf;
+  buf = req ? "GET / HTTP/1.1\r\n" : "HTTP/1.0 200 OK\r\n";
+  parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf));
+  assert(parsed == strlen(buf));
+
+  buf = "header-key: header-value\r\n";
+  size_t buflen = strlen(buf);
+
+  int i;
+  for (i = 0; i < 10000; i++) {
+    parsed = http_parser_execute(&parser, &settings_null, buf, buflen);
+    if (parsed != buflen) {
+      //fprintf(stderr, "error found on iter %d\n", i);
+      assert(HTTP_PARSER_ERRNO(&parser) == HPE_HEADER_OVERFLOW);
+      return;
+    }
+  }
+
+  fprintf(stderr, "\n*** Error expected but none in header overflow test ***\n");
+  abort();
+}
+
+
+void
+test_header_nread_value ()
+{
+  http_parser parser;
+  http_parser_init(&parser, HTTP_REQUEST);
+  size_t parsed;
+  const char *buf;
+  buf = "GET / HTTP/1.1\r\nheader: value\nhdr: value\r\n";
+  parsed = http_parser_execute(&parser, &settings_null, buf, strlen(buf));
+  assert(parsed == strlen(buf));
+
+  assert(parser.nread == strlen(buf));
+}
+
+
+static void
+test_content_length_overflow (const char *buf, size_t buflen, int expect_ok)
+{
+  http_parser parser;
+  http_parser_init(&parser, HTTP_RESPONSE);
+  http_parser_execute(&parser, &settings_null, buf, buflen);
+
+  if (expect_ok)
+    assert(HTTP_PARSER_ERRNO(&parser) == HPE_OK);
+  else
+    assert(HTTP_PARSER_ERRNO(&parser) == HPE_INVALID_CONTENT_LENGTH);
+}
+
+void
+test_header_content_length_overflow_error (void)
+{
+#define X(size)                                                               \
+  "HTTP/1.1 200 OK\r\n"                                                       \
+  "Content-Length: " #size "\r\n"                                             \
+  "\r\n"
+  const char a[] = X(1844674407370955160);  /* 2^64 / 10 - 1 */
+  const char b[] = X(18446744073709551615); /* 2^64-1 */
+  const char c[] = X(18446744073709551616); /* 2^64   */
+#undef X
+  test_content_length_overflow(a, sizeof(a) - 1, 1); /* expect ok      */
+  test_content_length_overflow(b, sizeof(b) - 1, 0); /* expect failure */
+  test_content_length_overflow(c, sizeof(c) - 1, 0); /* expect failure */
+}
+
+void
+test_chunk_content_length_overflow_error (void)
+{
+#define X(size)                                                               \
+    "HTTP/1.1 200 OK\r\n"                                                     \
+    "Transfer-Encoding: chunked\r\n"                                          \
+    "\r\n"                                                                    \
+    #size "\r\n"                                                              \
+    "..."
+  const char a[] = X(FFFFFFFFFFFFFFE);   /* 2^64 / 16 - 1 */
+  const char b[] = X(FFFFFFFFFFFFFFFF);  /* 2^64-1 */
+  const char c[] = X(10000000000000000); /* 2^64   */
+#undef X
+  test_content_length_overflow(a, sizeof(a) - 1, 1); /* expect ok      */
+  test_content_length_overflow(b, sizeof(b) - 1, 0); /* expect failure */
+  test_content_length_overflow(c, sizeof(c) - 1, 0); /* expect failure */
+}
+
+void
+test_no_overflow_long_body (int req, size_t length)
+{
+  http_parser parser;
+  http_parser_init(&parser, req ? HTTP_REQUEST : HTTP_RESPONSE);
+  size_t parsed;
+  size_t i;
+  char buf1[3000];
+  size_t buf1len = sprintf(buf1, "%s\r\nConnection: Keep-Alive\r\nContent-Length: %lu\r\n\r\n",
+      req ? "POST / HTTP/1.0" : "HTTP/1.0 200 OK", (unsigned long)length);
+  parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len);
+  if (parsed != buf1len)
+    goto err;
+
+  for (i = 0; i < length; i++) {
+    char foo = 'a';
+    parsed = http_parser_execute(&parser, &settings_null, &foo, 1);
+    if (parsed != 1)
+      goto err;
+  }
+
+  parsed = http_parser_execute(&parser, &settings_null, buf1, buf1len);
+  if (parsed != buf1len) goto err;
+  return;
+
+ err:
+  fprintf(stderr,
+          "\n*** error in test_no_overflow_long_body %s of length %lu ***\n",
+          req ? "REQUEST" : "RESPONSE",
+          (unsigned long)length);
+  abort();
+}
+
+void
+test_multiple3 (const struct message *r1, const struct message *r2, const struct message *r3)
+{
+  int message_count = count_parsed_messages(3, r1, r2, r3);
+
+  char total[ strlen(r1->raw)
+            + strlen(r2->raw)
+            + strlen(r3->raw)
+            + 1
+            ];
+  total[0] = '\0';
+
+  strcat(total, r1->raw);
+  strcat(total, r2->raw);
+  strcat(total, r3->raw);
+
+  parser_init(r1->type);
+
+  size_t read;
+
+  read = parse(total, strlen(total));
+
+  if (parser->upgrade) {
+    upgrade_message_fix(total, read, 3, r1, r2, r3);
+    goto test;
+  }
+
+  if (read != strlen(total)) {
+    print_error(total, read);
+    abort();
+  }
+
+  read = parse(NULL, 0);
+
+  if (read != 0) {
+    print_error(total, read);
+    abort();
+  }
+
+test:
+
+  if (message_count != num_messages) {
+    fprintf(stderr, "\n\n*** Parser didn't see 3 messages only %d *** \n", num_messages);
+    abort();
+  }
+
+  if (!message_eq(0, r1)) abort();
+  if (message_count > 1 && !message_eq(1, r2)) abort();
+  if (message_count > 2 && !message_eq(2, r3)) abort();
+
+  parser_free();
+}
+
+/* SCAN through every possible breaking to make sure the
+ * parser can handle getting the content in any chunks that
+ * might come from the socket
+ */
+void
+test_scan (const struct message *r1, const struct message *r2, const struct message *r3)
+{
+  char total[80*1024] = "\0";
+  char buf1[80*1024] = "\0";
+  char buf2[80*1024] = "\0";
+  char buf3[80*1024] = "\0";
+
+  strcat(total, r1->raw);
+  strcat(total, r2->raw);
+  strcat(total, r3->raw);
+
+  size_t read;
+
+  int total_len = strlen(total);
+
+  int total_ops = 2 * (total_len - 1) * (total_len - 2) / 2;
+  int ops = 0 ;
+
+  size_t buf1_len, buf2_len, buf3_len;
+  int message_count = count_parsed_messages(3, r1, r2, r3);
+
+  int i,j,type_both;
+  for (type_both = 0; type_both < 2; type_both ++ ) {
+    for (j = 2; j < total_len; j ++ ) {
+      for (i = 1; i < j; i ++ ) {
+
+        if (ops % 1000 == 0)  {
+          printf("\b\b\b\b%3.0f%%", 100 * (float)ops /(float)total_ops);
+          fflush(stdout);
+        }
+        ops += 1;
+
+        parser_init(type_both ? HTTP_BOTH : r1->type);
+
+        buf1_len = i;
+        strlncpy(buf1, sizeof(buf1), total, buf1_len);
+        buf1[buf1_len] = 0;
+
+        buf2_len = j - i;
+        strlncpy(buf2, sizeof(buf1), total+i, buf2_len);
+        buf2[buf2_len] = 0;
+
+        buf3_len = total_len - j;
+        strlncpy(buf3, sizeof(buf1), total+j, buf3_len);
+        buf3[buf3_len] = 0;
+
+        read = parse(buf1, buf1_len);
+
+        if (parser->upgrade) goto test;
+
+        if (read != buf1_len) {
+          print_error(buf1, read);
+          goto error;
+        }
+
+        read += parse(buf2, buf2_len);
+
+        if (parser->upgrade) goto test;
+
+        if (read != buf1_len + buf2_len) {
+          print_error(buf2, read);
+          goto error;
+        }
+
+        read += parse(buf3, buf3_len);
+
+        if (parser->upgrade) goto test;
+
+        if (read != buf1_len + buf2_len + buf3_len) {
+          print_error(buf3, read);
+          goto error;
+        }
+
+        parse(NULL, 0);
+
+test:
+        if (parser->upgrade) {
+          upgrade_message_fix(total, read, 3, r1, r2, r3);
+        }
+
+        if (message_count != num_messages) {
+          fprintf(stderr, "\n\nParser didn't see %d messages only %d\n",
+            message_count, num_messages);
+          goto error;
+        }
+
+        if (!message_eq(0, r1)) {
+          fprintf(stderr, "\n\nError matching messages[0] in test_scan.\n");
+          goto error;
+        }
+
+        if (message_count > 1 && !message_eq(1, r2)) {
+          fprintf(stderr, "\n\nError matching messages[1] in test_scan.\n");
+          goto error;
+        }
+
+        if (message_count > 2 && !message_eq(2, r3)) {
+          fprintf(stderr, "\n\nError matching messages[2] in test_scan.\n");
+          goto error;
+        }
+
+        parser_free();
+      }
+    }
+  }
+  puts("\b\b\b\b100%");
+  return;
+
+ error:
+  fprintf(stderr, "i=%d  j=%d\n", i, j);
+  fprintf(stderr, "buf1 (%u) %s\n\n", (unsigned int)buf1_len, buf1);
+  fprintf(stderr, "buf2 (%u) %s\n\n", (unsigned int)buf2_len , buf2);
+  fprintf(stderr, "buf3 (%u) %s\n", (unsigned int)buf3_len, buf3);
+  abort();
+}
+
+// user required to free the result
+// string terminated by \0
+char *
+create_large_chunked_message (int body_size_in_kb, const char* headers)
+{
+  int i;
+  size_t wrote = 0;
+  size_t headers_len = strlen(headers);
+  size_t bufsize = headers_len + (5+1024+2)*body_size_in_kb + 6;
+  char * buf = malloc(bufsize);
+
+  memcpy(buf, headers, headers_len);
+  wrote += headers_len;
+
+  for (i = 0; i < body_size_in_kb; i++) {
+    // write 1kb chunk into the body.
+    memcpy(buf + wrote, "400\r\n", 5);
+    wrote += 5;
+    memset(buf + wrote, 'C', 1024);
+    wrote += 1024;
+    strcpy(buf + wrote, "\r\n");
+    wrote += 2;
+  }
+
+  memcpy(buf + wrote, "0\r\n\r\n", 6);
+  wrote += 6;
+  assert(wrote == bufsize);
+
+  return buf;
+}
+
+/* Verify that we can pause parsing at any of the bytes in the
+ * message and still get the result that we're expecting. */
+void
+test_message_pause (const struct message *msg)
+{
+  char *buf = (char*) msg->raw;
+  size_t buflen = strlen(msg->raw);
+  size_t nread;
+
+  parser_init(msg->type);
+
+  do {
+    nread = parse_pause(buf, buflen);
+
+    // We can only set the upgrade buffer once we've gotten our message
+    // completion callback.
+    if (messages[0].message_complete_cb_called &&
+        msg->upgrade &&
+        parser->upgrade) {
+      messages[0].upgrade = buf + nread;
+      goto test;
+    }
+
+    if (nread < buflen) {
+
+      // Not much do to if we failed a strict-mode check
+      if (HTTP_PARSER_ERRNO(parser) == HPE_STRICT) {
+        parser_free();
+        return;
+      }
+
+      assert (HTTP_PARSER_ERRNO(parser) == HPE_PAUSED);
+    }
+
+    buf += nread;
+    buflen -= nread;
+    http_parser_pause(parser, 0);
+  } while (buflen > 0);
+
+  nread = parse_pause(NULL, 0);
+  assert (nread == 0);
+
+test:
+  if (num_messages != 1) {
+    printf("\n*** num_messages != 1 after testing '%s' ***\n\n", msg->name);
+    abort();
+  }
+
+  if(!message_eq(0, msg)) abort();
+
+  parser_free();
+}
+
+int
+main (void)
+{
+  parser = NULL;
+  int i, j, k;
+  int request_count;
+  int response_count;
+  unsigned long version;
+  unsigned major;
+  unsigned minor;
+  unsigned patch;
+
+  version = http_parser_version();
+  major = (version >> 16) & 255;
+  minor = (version >> 8) & 255;
+  patch = version & 255;
+  printf("http_parser v%u.%u.%u (0x%06lx)\n", major, minor, patch, version);
+
+  printf("sizeof(http_parser) = %u\n", (unsigned int)sizeof(http_parser));
+
+  for (request_count = 0; requests[request_count].name; request_count++);
+  for (response_count = 0; responses[response_count].name; response_count++);
+
+  //// API
+  test_preserve_data();
+  test_parse_url();
+  test_method_str();
+
+  //// NREAD
+  test_header_nread_value();
+
+  //// OVERFLOW CONDITIONS
+
+  test_header_overflow_error(HTTP_REQUEST);
+  test_no_overflow_long_body(HTTP_REQUEST, 1000);
+  test_no_overflow_long_body(HTTP_REQUEST, 100000);
+
+  test_header_overflow_error(HTTP_RESPONSE);
+  test_no_overflow_long_body(HTTP_RESPONSE, 1000);
+  test_no_overflow_long_body(HTTP_RESPONSE, 100000);
+
+  test_header_content_length_overflow_error();
+  test_chunk_content_length_overflow_error();
+
+  //// RESPONSES
+
+  for (i = 0; i < response_count; i++) {
+    test_message(&responses[i]);
+  }
+
+  for (i = 0; i < response_count; i++) {
+    test_message_pause(&responses[i]);
+  }
+
+  for (i = 0; i < response_count; i++) {
+    if (!responses[i].should_keep_alive) continue;
+    for (j = 0; j < response_count; j++) {
+      if (!responses[j].should_keep_alive) continue;
+      for (k = 0; k < response_count; k++) {
+        test_multiple3(&responses[i], &responses[j], &responses[k]);
+      }
+    }
+  }
+
+  test_message_count_body(&responses[NO_HEADERS_NO_BODY_404]);
+  test_message_count_body(&responses[TRAILING_SPACE_ON_CHUNKED_BODY]);
+
+  // test very large chunked response
+  {
+    char * msg = create_large_chunked_message(31337,
+      "HTTP/1.0 200 OK\r\n"
+      "Transfer-Encoding: chunked\r\n"
+      "Content-Type: text/plain\r\n"
+      "\r\n");
+    struct message large_chunked =
+      {.name= "large chunked"
+      ,.type= HTTP_RESPONSE
+      ,.raw= msg
+      ,.should_keep_alive= FALSE
+      ,.message_complete_on_eof= FALSE
+      ,.http_major= 1
+      ,.http_minor= 0
+      ,.status_code= 200
+      ,.response_status= "OK"
+      ,.num_headers= 2
+      ,.headers=
+        { { "Transfer-Encoding", "chunked" }
+        , { "Content-Type", "text/plain" }
+        }
+      ,.body_size= 31337*1024
+      ,.num_chunks_complete= 31338
+      };
+    for (i = 0; i < MAX_CHUNKS; i++) {
+      large_chunked.chunk_lengths[i] = 1024;
+    }
+    test_message_count_body(&large_chunked);
+    free(msg);
+  }
+
+
+
+  printf("response scan 1/2      ");
+  test_scan( &responses[TRAILING_SPACE_ON_CHUNKED_BODY]
+           , &responses[NO_BODY_HTTP10_KA_204]
+           , &responses[NO_REASON_PHRASE]
+           );
+
+  printf("response scan 2/2      ");
+  test_scan( &responses[BONJOUR_MADAME_FR]
+           , &responses[UNDERSTORE_HEADER_KEY]
+           , &responses[NO_CARRIAGE_RET]
+           );
+
+  puts("responses okay");
+
+
+  /// REQUESTS
+
+  test_simple("GET / HTP/1.1\r\n\r\n", HPE_INVALID_VERSION);
+
+  // Well-formed but incomplete
+  test_simple("GET / HTTP/1.1\r\n"
+              "Content-Type: text/plain\r\n"
+              "Content-Length: 6\r\n"
+              "\r\n"
+              "fooba",
+              HPE_OK);
+
+  static const char *all_methods[] = {
+    "DELETE",
+    "GET",
+    "HEAD",
+    "POST",
+    "PUT",
+    //"CONNECT", //CONNECT can't be tested like other methods, it's a tunnel
+    "OPTIONS",
+    "TRACE",
+    "COPY",
+    "LOCK",
+    "MKCOL",
+    "MOVE",
+    "PROPFIND",
+    "PROPPATCH",
+    "UNLOCK",
+    "REPORT",
+    "MKACTIVITY",
+    "CHECKOUT",
+    "MERGE",
+    "M-SEARCH",
+    "NOTIFY",
+    "SUBSCRIBE",
+    "UNSUBSCRIBE",
+    "PATCH",
+    0 };
+  const char **this_method;
+  for (this_method = all_methods; *this_method; this_method++) {
+    char buf[200];
+    sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method);
+    test_simple(buf, HPE_OK);
+  }
+
+  static const char *bad_methods[] = {
+      "ASDF",
+      "C******",
+      "COLA",
+      "GEM",
+      "GETA",
+      "M****",
+      "MKCOLA",
+      "PROPPATCHA",
+      "PUN",
+      "PX",
+      "SA",
+      "hello world",
+      0 };
+  for (this_method = bad_methods; *this_method; this_method++) {
+    char buf[200];
+    sprintf(buf, "%s / HTTP/1.1\r\n\r\n", *this_method);
+    test_simple(buf, HPE_INVALID_METHOD);
+  }
+
+  // illegal header field name line folding
+  test_simple("GET / HTTP/1.1\r\n"
+              "name\r\n"
+              " : value\r\n"
+              "\r\n",
+              HPE_INVALID_HEADER_TOKEN);
+
+  const char *dumbfuck2 =
+    "GET / HTTP/1.1\r\n"
+    "X-SSL-Bullshit:   -----BEGIN CERTIFICATE-----\r\n"
+    "\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\r\n"
+    "\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\r\n"
+    "\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\r\n"
+    "\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\r\n"
+    "\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\r\n"
+    "\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\r\n"
+    "\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC/1R64fAcEF\r\n"
+    "\tW51rEyFYiIeZGx/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\r\n"
+    "\tgW7cMA/s/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi/F1SiFlPDxuDfmdiNzL31+sL\r\n"
+    "\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW/iaLB0/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\r\n"
+    "\tu2MSpFyf+9BbC/aXgaZuiCvSR+8Snv3xApQY+fULK/xY8h8Ua51iXoQ5jrgu2SqR\r\n"
+    "\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\r\n"
+    "\tA1UdEwEB/wQCMAAwEQYJYIZIAYb4QgHTTPAQDAgWgMA4GA1UdDwEB/wQEAwID6DAs\r\n"
+    "\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\r\n"
+    "\tVR0OBBYEFDTt/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\r\n"
+    "\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\r\n"
+    "\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\r\n"
+    "\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\r\n"
+    "\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\r\n"
+    "\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\r\n"
+    "\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\r\n"
+    "\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\r\n"
+    "\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\r\n"
+    "\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS/U4iiooBENGW/Hwmmd3\r\n"
+    "\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv/hmi0qlnlHs+k/3Iobc3LjS5AMYr5L8\r\n"
+    "\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\r\n"
+    "\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\r\n"
+    "\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7/ZhW6DqT8UFvsAdjvQbXyhV8Eu\r\n"
+    "\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0/ES5gDGsABo4fqovUKlgop3\r\n"
+    "\tRA==\r\n"
+    "\t-----END CERTIFICATE-----\r\n"
+    "\r\n";
+  test_simple(dumbfuck2, HPE_OK);
+
+  const char *corrupted_connection =
+    "GET / HTTP/1.1\r\n"
+    "Host: www.example.com\r\n"
+    "Connection\r\033\065\325eep-Alive\r\n"
+    "Accept-Encoding: gzip\r\n"
+    "\r\n";
+  test_simple(corrupted_connection, HPE_INVALID_HEADER_TOKEN);
+
+  const char *corrupted_header_name =
+    "GET / HTTP/1.1\r\n"
+    "Host: www.example.com\r\n"
+    "X-Some-Header\r\033\065\325eep-Alive\r\n"
+    "Accept-Encoding: gzip\r\n"
+    "\r\n";
+  test_simple(corrupted_header_name, HPE_INVALID_HEADER_TOKEN);
+
+#if 0
+  // NOTE(Wed Nov 18 11:57:27 CET 2009) this seems okay. we just read body
+  // until EOF.
+  //
+  // no content-length
+  // error if there is a body without content length
+  const char *bad_get_no_headers_no_body = "GET /bad_get_no_headers_no_body/world HTTP/1.1\r\n"
+                                           "Accept: */*\r\n"
+                                           "\r\n"
+                                           "HELLO";
+  test_simple(bad_get_no_headers_no_body, 0);
+#endif
+  /* TODO sending junk and large headers gets rejected */
+
+
+  /* check to make sure our predefined requests are okay */
+  for (i = 0; requests[i].name; i++) {
+    test_message(&requests[i]);
+  }
+
+  for (i = 0; i < request_count; i++) {
+    test_message_pause(&requests[i]);
+  }
+
+  for (i = 0; i < request_count; i++) {
+    if (!requests[i].should_keep_alive) continue;
+    for (j = 0; j < request_count; j++) {
+      if (!requests[j].should_keep_alive) continue;
+      for (k = 0; k < request_count; k++) {
+        test_multiple3(&requests[i], &requests[j], &requests[k]);
+      }
+    }
+  }
+
+  printf("request scan 1/4      ");
+  test_scan( &requests[GET_NO_HEADERS_NO_BODY]
+           , &requests[GET_ONE_HEADER_NO_BODY]
+           , &requests[GET_NO_HEADERS_NO_BODY]
+           );
+
+  printf("request scan 2/4      ");
+  test_scan( &requests[POST_CHUNKED_ALL_YOUR_BASE]
+           , &requests[POST_IDENTITY_BODY_WORLD]
+           , &requests[GET_FUNKY_CONTENT_LENGTH]
+           );
+
+  printf("request scan 3/4      ");
+  test_scan( &requests[TWO_CHUNKS_MULT_ZERO_END]
+           , &requests[CHUNKED_W_TRAILING_HEADERS]
+           , &requests[CHUNKED_W_BULLSHIT_AFTER_LENGTH]
+           );
+
+  printf("request scan 4/4      ");
+  test_scan( &requests[QUERY_URL_WITH_QUESTION_MARK_GET]
+           , &requests[PREFIX_NEWLINE_GET ]
+           , &requests[CONNECT_REQUEST]
+           );
+
+  puts("requests okay");
+
+  return 0;
+}

+ 44 - 0
external/qhttpserver/http-parser/url_parser.c

@@ -0,0 +1,44 @@
+#include "http_parser.h"
+#include <stdio.h>
+#include <string.h>
+
+void
+dump_url (const char *url, const struct http_parser_url *u)
+{
+  unsigned int i;
+
+  printf("\tfield_set: 0x%x, port: %u\n", u->field_set, u->port);
+  for (i = 0; i < UF_MAX; i++) {
+    if ((u->field_set & (1 << i)) == 0) {
+      printf("\tfield_data[%u]: unset\n", i);
+      continue;
+    }
+
+    printf("\tfield_data[%u]: off: %u len: %u part: \"%.*s\n",
+           i,
+           u->field_data[i].off,
+           u->field_data[i].len,
+           u->field_data[i].len,
+           url + u->field_data[i].off);
+  }
+}
+
+int main(int argc, char ** argv) {
+  if (argc != 3) {
+    printf("Syntax : %s connect|get url\n", argv[0]);
+    return 1;
+  }
+  struct http_parser_url u;
+  int len = strlen(argv[2]);
+  int connect = strcmp("connect", argv[1]) == 0 ? 1 : 0;
+  printf("Parsing %s, connect %d\n", argv[2], connect);
+
+  int result = http_parser_parse_url(argv[2], len, connect, &u);
+  if (result != 0) {
+    printf("Parse error : %d\n", result);
+    return result;
+  }
+  printf("Parse ok, result : \n");
+  dump_url(argv[2], &u);
+  return 0;
+}

+ 46 - 0
external/qhttpserver/konvergo-error.patch

@@ -0,0 +1,46 @@
+diff --git a/external/qhttpserver/src/qhttpserver.cpp b/external/qhttpserver/src/qhttpserver.cpp
+index 07e4a85..507645d 100755
+--- a/external/qhttpserver/src/qhttpserver.cpp
++++ b/external/qhttpserver/src/qhttpserver.cpp
+@@ -115,6 +115,7 @@ bool QHttpServer::listen(const QHostAddress &address, quint16 port)
+     if (couldBindToPort) {
+         connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(newConnection()));
+     } else {
++        m_errorString = m_tcpServer->errorString();
+         delete m_tcpServer;
+         m_tcpServer = NULL;
+     }
+@@ -126,6 +127,11 @@ bool QHttpServer::listen(quint16 port)
+     return listen(QHostAddress::Any, port);
+ }
+ 
++QString QHttpServer::errorString() const
++{
++    return m_errorString;
++}
++
+ void QHttpServer::close()
+ {
+     if (m_tcpServer)
+diff --git a/external/qhttpserver/src/qhttpserver.h b/external/qhttpserver/src/qhttpserver.h
+index a3cb74b..4adb391 100755
+--- a/external/qhttpserver/src/qhttpserver.h
++++ b/external/qhttpserver/src/qhttpserver.h
+@@ -79,6 +79,9 @@ public:
+         @sa listen(const QHostAddress&, quint16) */
+     bool listen(quint16 port);
+ 
++    /// Return the last error encountered.
++    QString errorString() const;
++
+     /// Stop the server and listening for new connections.
+     void close();
+ signals:
+@@ -94,6 +97,7 @@ private slots:
+ 
+ private:
+     QTcpServer *m_tcpServer;
++    QString m_errorString;
+ };
+ 
+ #endif

+ 3 - 0
external/qhttpserver/qhttpserver.pri

@@ -0,0 +1,3 @@
+isEmpty(PREFIX):PREFIX = /usr/local
+isEmpty(LIBDIR):LIBDIR = $${PREFIX}/lib
+isEmpty(INCLUDEDIR):INCLUDEDIR = $${PREFIX}/include

+ 8 - 0
external/qhttpserver/qhttpserver.pro

@@ -0,0 +1,8 @@
+CONFIG += ordered
+
+TEMPLATE = subdirs
+
+SUBDIRS += src \
+           examples
+
+examples.depends = src

+ 293 - 0
external/qhttpserver/src/qhttpconnection.cpp

@@ -0,0 +1,293 @@
+/*
+ * Copyright 2011-2014 Nikhil Marathe <nsm.nikhil@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#include "qhttpconnection.h"
+
+#include <QTcpSocket>
+#include <QHostAddress>
+
+#include "http_parser.h"
+#include "qhttprequest.h"
+#include "qhttpresponse.h"
+
+/// @cond nodoc
+
+QHttpConnection::QHttpConnection(QTcpSocket *socket, QObject *parent)
+    : QObject(parent),
+      m_socket(socket),
+      m_parser(0),
+      m_parserSettings(0),
+      m_request(0),
+      m_transmitLen(0),
+      m_transmitPos(0)
+{
+    m_parser = (http_parser *)malloc(sizeof(http_parser));
+    http_parser_init(m_parser, HTTP_REQUEST);
+
+    m_parserSettings = new http_parser_settings();
+    m_parserSettings->on_message_begin = MessageBegin;
+    m_parserSettings->on_url = Url;
+    m_parserSettings->on_header_field = HeaderField;
+    m_parserSettings->on_header_value = HeaderValue;
+    m_parserSettings->on_headers_complete = HeadersComplete;
+    m_parserSettings->on_body = Body;
+    m_parserSettings->on_message_complete = MessageComplete;
+
+    m_parser->data = this;
+
+    connect(socket, SIGNAL(readyRead()), this, SLOT(parseRequest()));
+    connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
+    connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(updateWriteCount(qint64)));
+}
+
+QHttpConnection::~QHttpConnection()
+{
+    m_socket = 0;
+
+    free(m_parser);
+    m_parser = 0;
+
+    delete m_parserSettings;
+    m_parserSettings = 0;
+}
+
+void QHttpConnection::socketDisconnected()
+{
+    deleteLater();
+
+    if (m_request) {
+        if (m_request->successful())
+            return;
+
+        m_request->setSuccessful(false);
+        Q_EMIT m_request->end();
+    }
+}
+
+void QHttpConnection::updateWriteCount(qint64 count)
+{
+    Q_ASSERT(m_transmitPos + count <= m_transmitLen);
+
+    m_transmitPos += count;
+
+    if (m_transmitPos == m_transmitLen)
+    {
+        m_transmitLen = 0;
+        m_transmitPos = 0;
+        Q_EMIT allBytesWritten();
+    }
+}
+
+void QHttpConnection::parseRequest()
+{
+    Q_ASSERT(m_parser);
+
+    while (m_socket->bytesAvailable()) {
+        QByteArray arr = m_socket->readAll();
+        http_parser_execute(m_parser, m_parserSettings, arr.constData(), arr.size());
+    }
+}
+
+void QHttpConnection::write(const QByteArray &data)
+{
+    m_socket->write(data);
+    m_transmitLen += data.size();
+}
+
+void QHttpConnection::flush()
+{
+    m_socket->flush();
+}
+
+void QHttpConnection::waitForBytesWritten()
+{
+    m_socket->waitForBytesWritten();
+}
+
+void QHttpConnection::responseDone()
+{
+    QHttpResponse *response = qobject_cast<QHttpResponse *>(QObject::sender());
+    if (response->m_last)
+        m_socket->disconnectFromHost();
+}
+
+/* URL Utilities */
+#define HAS_URL_FIELD(info, field) (info.field_set &(1 << (field)))
+
+#define GET_FIELD(data, info, field)                                                               \
+    QString::fromLatin1(data + info.field_data[field].off, info.field_data[field].len)
+
+#define CHECK_AND_GET_FIELD(data, info, field)                                                     \
+    (HAS_URL_FIELD(info, field) ? GET_FIELD(data, info, field) : QString())
+
+QUrl createUrl(const char *urlData, const http_parser_url &urlInfo)
+{
+    QUrl url;
+    url.setScheme(CHECK_AND_GET_FIELD(urlData, urlInfo, UF_SCHEMA));
+    url.setHost(CHECK_AND_GET_FIELD(urlData, urlInfo, UF_HOST));
+    // Port is dealt with separately since it is available as an integer.
+    url.setPath(CHECK_AND_GET_FIELD(urlData, urlInfo, UF_PATH));
+#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
+    url.setQuery(CHECK_AND_GET_FIELD(urlData, urlInfo, UF_QUERY));
+#else
+    if (HAS_URL_FIELD(urlInfo, UF_QUERY)) {
+        url.setEncodedQuery(QByteArray(urlData + urlInfo.field_data[UF_QUERY].off,
+                                       urlInfo.field_data[UF_QUERY].len));
+    }
+#endif
+    url.setFragment(CHECK_AND_GET_FIELD(urlData, urlInfo, UF_FRAGMENT));
+    url.setUserInfo(CHECK_AND_GET_FIELD(urlData, urlInfo, UF_USERINFO));
+
+    if (HAS_URL_FIELD(urlInfo, UF_PORT))
+        url.setPort(urlInfo.port);
+
+    return url;
+}
+
+#undef CHECK_AND_SET_FIELD
+#undef GET_FIELD
+#undef HAS_URL_FIELD
+
+/********************
+ * Static Callbacks *
+ *******************/
+
+int QHttpConnection::MessageBegin(http_parser *parser)
+{
+    QHttpConnection *theConnection = static_cast<QHttpConnection *>(parser->data);
+    theConnection->m_currentHeaders.clear();
+    theConnection->m_currentUrl.clear();
+    theConnection->m_currentUrl.reserve(128);
+
+    // The QHttpRequest should not be parented to this, since it's memory
+    // management is the responsibility of the user of the library.
+    theConnection->m_request = new QHttpRequest(theConnection);
+    return 0;
+}
+
+int QHttpConnection::HeadersComplete(http_parser *parser)
+{
+    QHttpConnection *theConnection = static_cast<QHttpConnection *>(parser->data);
+    Q_ASSERT(theConnection->m_request);
+
+    /** set method **/
+    theConnection->m_request->setMethod(static_cast<QHttpRequest::HttpMethod>(parser->method));
+
+    /** set version **/
+    theConnection->m_request->setVersion(
+        QString("%1.%2").arg(parser->http_major).arg(parser->http_minor));
+
+    /** get parsed url **/
+    struct http_parser_url urlInfo;
+    int r = http_parser_parse_url(theConnection->m_currentUrl.constData(),
+                                  theConnection->m_currentUrl.size(),
+                                  parser->method == HTTP_CONNECT, &urlInfo);
+    Q_ASSERT(r == 0);
+    Q_UNUSED(r);
+
+    theConnection->m_request->setUrl(createUrl(theConnection->m_currentUrl.constData(), urlInfo));
+
+    // Insert last remaining header
+    theConnection->m_currentHeaders[theConnection->m_currentHeaderField.toLower()] =
+        theConnection->m_currentHeaderValue;
+    theConnection->m_request->setHeaders(theConnection->m_currentHeaders);
+
+    /** set client information **/
+    theConnection->m_request->m_remoteAddress = theConnection->m_socket->peerAddress().toString();
+    theConnection->m_request->m_remotePort = theConnection->m_socket->peerPort();
+
+    QHttpResponse *response = new QHttpResponse(theConnection);
+    if (parser->http_major < 1 || parser->http_minor < 1)
+        response->m_keepAlive = false;
+
+    connect(theConnection, SIGNAL(destroyed()), response, SLOT(connectionClosed()));
+    connect(response, SIGNAL(done()), theConnection, SLOT(responseDone()));
+
+    // we are good to go!
+    Q_EMIT theConnection->newRequest(theConnection->m_request, response);
+    return 0;
+}
+
+int QHttpConnection::MessageComplete(http_parser *parser)
+{
+    // TODO: do cleanup and prepare for next request
+    QHttpConnection *theConnection = static_cast<QHttpConnection *>(parser->data);
+    Q_ASSERT(theConnection->m_request);
+
+    theConnection->m_request->setSuccessful(true);
+    Q_EMIT theConnection->m_request->end();
+    return 0;
+}
+
+int QHttpConnection::Url(http_parser *parser, const char *at, size_t length)
+{
+    QHttpConnection *theConnection = static_cast<QHttpConnection *>(parser->data);
+    Q_ASSERT(theConnection->m_request);
+
+    theConnection->m_currentUrl.append(at, length);
+    return 0;
+}
+
+int QHttpConnection::HeaderField(http_parser *parser, const char *at, size_t length)
+{
+    QHttpConnection *theConnection = static_cast<QHttpConnection *>(parser->data);
+    Q_ASSERT(theConnection->m_request);
+
+    // insert the header we parsed previously
+    // into the header map
+    if (!theConnection->m_currentHeaderField.isEmpty() &&
+        !theConnection->m_currentHeaderValue.isEmpty()) {
+        // header names are always lower-cased
+        theConnection->m_currentHeaders[theConnection->m_currentHeaderField.toLower()] =
+            theConnection->m_currentHeaderValue;
+        // clear header value. this sets up a nice
+        // feedback loop where the next time
+        // HeaderValue is called, it can simply append
+        theConnection->m_currentHeaderField = QString();
+        theConnection->m_currentHeaderValue = QString();
+    }
+
+    QString fieldSuffix = QString::fromLatin1(at, length);
+    theConnection->m_currentHeaderField += fieldSuffix;
+    return 0;
+}
+
+int QHttpConnection::HeaderValue(http_parser *parser, const char *at, size_t length)
+{
+    QHttpConnection *theConnection = static_cast<QHttpConnection *>(parser->data);
+    Q_ASSERT(theConnection->m_request);
+
+    QString valueSuffix = QString::fromLatin1(at, length);
+    theConnection->m_currentHeaderValue += valueSuffix;
+    return 0;
+}
+
+int QHttpConnection::Body(http_parser *parser, const char *at, size_t length)
+{
+    QHttpConnection *theConnection = static_cast<QHttpConnection *>(parser->data);
+    Q_ASSERT(theConnection->m_request);
+
+    Q_EMIT theConnection->m_request->data(QByteArray(at, length));
+    return 0;
+}
+
+/// @endcond

+ 85 - 0
external/qhttpserver/src/qhttpconnection.h

@@ -0,0 +1,85 @@
+/*
+ * Copyright 2011-2014 Nikhil Marathe <nsm.nikhil@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef Q_HTTP_CONNECTION
+#define Q_HTTP_CONNECTION
+
+#include "qhttpserverapi.h"
+#include "qhttpserverfwd.h"
+
+#include <QObject>
+
+/// @cond nodoc
+
+class QHTTPSERVER_API QHttpConnection : public QObject
+{
+    Q_OBJECT
+
+public:
+    QHttpConnection(QTcpSocket *socket, QObject *parent = 0);
+    virtual ~QHttpConnection();
+
+    void write(const QByteArray &data);
+    void flush();
+    void waitForBytesWritten();
+
+Q_SIGNALS:
+    void newRequest(QHttpRequest *, QHttpResponse *);
+    void allBytesWritten();
+
+private Q_SLOTS:
+    void parseRequest();
+    void responseDone();
+    void socketDisconnected();
+    void updateWriteCount(qint64);
+
+private:
+    static int MessageBegin(http_parser *parser);
+    static int Url(http_parser *parser, const char *at, size_t length);
+    static int HeaderField(http_parser *parser, const char *at, size_t length);
+    static int HeaderValue(http_parser *parser, const char *at, size_t length);
+    static int HeadersComplete(http_parser *parser);
+    static int Body(http_parser *parser, const char *at, size_t length);
+    static int MessageComplete(http_parser *parser);
+
+private:
+    QTcpSocket *m_socket;
+    http_parser *m_parser;
+    http_parser_settings *m_parserSettings;
+
+    // Since there can only be one request at any time even with pipelining.
+    QHttpRequest *m_request;
+
+    QByteArray m_currentUrl;
+    // The ones we are reading in from the parser
+    HeaderHash m_currentHeaders;
+    QString m_currentHeaderField;
+    QString m_currentHeaderValue;
+
+    // Keep track of transmit buffer status
+    qint64 m_transmitLen;
+    qint64 m_transmitPos;
+};
+
+/// @endcond
+
+#endif

+ 96 - 0
external/qhttpserver/src/qhttprequest.cpp

@@ -0,0 +1,96 @@
+/*
+ * Copyright 2011-2014 Nikhil Marathe <nsm.nikhil@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#include "qhttprequest.h"
+
+#include "qhttpconnection.h"
+
+QHttpRequest::QHttpRequest(QHttpConnection *connection, QObject *parent)
+    : QObject(parent), m_connection(connection), m_url("http://localhost/"), m_success(false)
+{
+}
+
+QHttpRequest::~QHttpRequest()
+{
+}
+
+QString QHttpRequest::header(const QString &field)
+{
+    return m_headers.value(field.toLower(), "");
+}
+
+const HeaderHash &QHttpRequest::headers() const
+{
+    return m_headers;
+}
+
+const QString &QHttpRequest::httpVersion() const
+{
+    return m_version;
+}
+
+const QUrl &QHttpRequest::url() const
+{
+    return m_url;
+}
+
+const QString QHttpRequest::path() const
+{
+    return m_url.path();
+}
+
+const QString QHttpRequest::methodString() const
+{
+    return MethodToString(method());
+}
+
+QHttpRequest::HttpMethod QHttpRequest::method() const
+{
+    return m_method;
+}
+
+const QString &QHttpRequest::remoteAddress() const
+{
+    return m_remoteAddress;
+}
+
+quint16 QHttpRequest::remotePort() const
+{
+    return m_remotePort;
+}
+
+void QHttpRequest::storeBody()
+{
+    connect(this, SIGNAL(data(const QByteArray &)), this, SLOT(appendBody(const QByteArray &)),
+            Qt::UniqueConnection);
+}
+
+QString QHttpRequest::MethodToString(HttpMethod method)
+{
+    int index = staticMetaObject.indexOfEnumerator("HttpMethod");
+    return staticMetaObject.enumerator(index).valueToKey(method);
+}
+
+void QHttpRequest::appendBody(const QByteArray &body)
+{
+    m_body.append(body);
+}

+ 202 - 0
external/qhttpserver/src/qhttprequest.h

@@ -0,0 +1,202 @@
+/*
+ * Copyright 2011-2014 Nikhil Marathe <nsm.nikhil@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef Q_HTTP_REQUEST
+#define Q_HTTP_REQUEST
+
+#include "qhttpserverapi.h"
+#include "qhttpserverfwd.h"
+
+#include <QObject>
+#include <QMetaEnum>
+#include <QMetaType>
+#include <QUrl>
+
+/// The QHttpRequest class represents the header and body data sent by the client.
+/** The requests header data is available immediately. Body data is streamed as
+    it comes in via the data() signal. As a consequence the application's request
+    callback should ensure that it connects to the data() signal before control
+    returns back to the event loop. Otherwise there is a risk of some data never
+    being received by the application.
+
+    The class is <b>read-only</b>. */
+class QHTTPSERVER_API QHttpRequest : public QObject
+{
+    Q_OBJECT
+
+    Q_PROPERTY(HeaderHash headers READ headers)
+    Q_PROPERTY(QString remoteAddress READ remoteAddress)
+    Q_PROPERTY(quint16 remotePort READ remotePort)
+    Q_PROPERTY(QString method READ method)
+    Q_PROPERTY(QUrl url READ url)
+    Q_PROPERTY(QString path READ path)
+    Q_PROPERTY(QString httpVersion READ httpVersion)
+
+    Q_ENUMS(HttpMethod)
+
+    /// @cond nodoc
+    friend class QHttpConnection;
+    /// @endcond
+
+public:
+    virtual ~QHttpRequest();
+
+    /// Request method enumeration.
+    /** @note Taken from http_parser.h -- make sure to keep synced */
+    enum HttpMethod {
+        HTTP_DELETE = 0,
+        HTTP_GET,
+        HTTP_HEAD,
+        HTTP_POST,
+        HTTP_PUT,
+        // pathological
+        HTTP_CONNECT,
+        HTTP_OPTIONS,
+        HTTP_TRACE,
+        // webdav
+        HTTP_COPY,
+        HTTP_LOCK,
+        HTTP_MKCOL,
+        HTTP_MOVE,
+        HTTP_PROPFIND,
+        HTTP_PROPPATCH,
+        HTTP_SEARCH,
+        HTTP_UNLOCK,
+        // subversion
+        HTTP_REPORT,
+        HTTP_MKACTIVITY,
+        HTTP_CHECKOUT,
+        HTTP_MERGE,
+        // upnp
+        HTTP_MSEARCH,
+        HTTP_NOTIFY,
+        HTTP_SUBSCRIBE,
+        HTTP_UNSUBSCRIBE,
+        // RFC-5789
+        HTTP_PATCH,
+        HTTP_PURGE
+    };
+
+    /// The method used for the request.
+    HttpMethod method() const;
+
+    /// Returns the method string for the request.
+    /** @note This will plainly transform the enum into a string HTTP_GET -> "HTTP_GET". */
+    const QString methodString() const;
+
+    /// The complete URL for the request.
+    /** This includes the path and query string.
+        @sa path() */
+    const QUrl &url() const;
+
+    /// The path portion of the query URL.
+    /** @sa url() */
+    const QString path() const;
+
+    /// The HTTP version of the request.
+    /** @return A string in the form of "x.x" */
+    const QString &httpVersion() const;
+
+    /// Return all the headers sent by the client.
+    /** This returns a reference. If you want to store headers
+        somewhere else, where the request may be deleted,
+        make sure you store them as a copy.
+        @note All header names are <b>lowercase</b>
+        so that Content-Length becomes content-length etc. */
+    const HeaderHash &headers() const;
+
+    /// Get the value of a header.
+    /** Headers are stored as lowercase so the input @c field will be lowercased.
+        @param field Name of the header field
+        @return Value of the header or empty string if not found. */
+    QString header(const QString &field);
+
+    /// IP Address of the client in dotted decimal format.
+    const QString &remoteAddress() const;
+
+    /// Outbound connection port for the client.
+    quint16 remotePort() const;
+
+    /// Request body data, empty for non POST/PUT requests.
+    /** @sa storeBody() */
+    const QByteArray &body() const
+    {
+        return m_body;
+    }
+
+    /// If this request was successfully received.
+    /** Set before end() has been emitted, stating whether
+        the message was properly received. This is false
+        until the receiving the full request has completed. */
+    bool successful() const
+    {
+        return m_success;
+    }
+
+    /// Utility function to make this request store all body data internally.
+    /** If you call this when the request is received via QHttpServer::newRequest()
+        the request will take care of storing the body data for you.
+        Once the end() signal is emitted you can access the body data with
+        the body() function.
+
+        If you wish to handle incoming data yourself don't call this function
+        and see the data() signal.
+        @sa data() body() */
+    void storeBody();
+
+Q_SIGNALS:
+    /// Emitted when new body data has been received.
+    /** @note This may be emitted zero or more times
+        depending on the request type.
+        @param data Received data. */
+    void data(const QByteArray &data);
+
+    /// Emitted when the request has been fully received.
+    /** @note The no more data() signals will be emitted after this. */
+    void end();
+
+private Q_SLOTS:
+    void appendBody(const QByteArray &body);
+
+private:
+    QHttpRequest(QHttpConnection *connection, QObject *parent = 0);
+
+    static QString MethodToString(HttpMethod method);
+
+    void setMethod(HttpMethod method) { m_method = method; }
+    void setVersion(const QString &version) { m_version = version; }
+    void setUrl(const QUrl &url) { m_url = url; }
+    void setHeaders(const HeaderHash headers) { m_headers = headers; }
+    void setSuccessful(bool success) { m_success = success; }
+
+    QHttpConnection *m_connection;
+    HeaderHash m_headers;
+    HttpMethod m_method;
+    QUrl m_url;
+    QString m_version;
+    QString m_remoteAddress;
+    quint16 m_remotePort;
+    QByteArray m_body;
+    bool m_success;
+};
+
+#endif

Some files were not shown because too many files changed in this diff