commit 4485f045ca1acf6b357a13a36d701791a9333edd Author: ecpvint Date: Thu Aug 15 18:40:30 2024 +0800 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..670a114 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# Prerequisites +*.d + +/build* + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Fortran module files +*.mod +*.smod + +# Executables +*.exe +*.out +*.app diff --git a/Android.mk b/Android.mk new file mode 100644 index 0000000..8914d91 --- /dev/null +++ b/Android.mk @@ -0,0 +1,26 @@ +LOCAL_PATH:= $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_CPP_EXTENSION := .cpp .cc + +#traverse all the directory and subdirectory +define walk + $(wildcard $(1)) $(foreach e, $(wildcard $(1)/*), $(call walk, $(e))) +endef + +#find all the file recursively under jni/ +ALLFILES = $(call walk, $(LOCAL_PATH)) +FILE_LIST := $(filter %.cpp %.cc %.c, $(ALLFILES)) + +LOCAL_SRC_FILES := $(FILE_LIST:$(LOCAL_PATH)/%=%) + +LOCAL_MODULE := libnative-utilities-dll + +LOCAL_CPPFLAGS += -fexceptions -std=c++14 + +ifeq ($(TARGET_ARCH_ABI),x86) + LOCAL_CFLAGS += -ffast-math -mtune=atom -mssse3 -mfpmath=sse +endif + +include $(BUILD_SHARED_LIBRARY) \ No newline at end of file diff --git a/Application.mk b/Application.mk new file mode 100644 index 0000000..5a4c22b --- /dev/null +++ b/Application.mk @@ -0,0 +1,4 @@ +NDK_TOOLCHAIN_VERSION := 4.9 +APP_STL := gnustl_static +APP_PIE := $(APP_PIE_REQUIRED) +APP_ABI := armeabi-v7a arm64-v8a x86 x86_64 diff --git a/OpenSSL_LICENSE b/OpenSSL_LICENSE new file mode 100644 index 0000000..e953f59 --- /dev/null +++ b/OpenSSL_LICENSE @@ -0,0 +1,125 @@ + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a double license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved. + * + * 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. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED 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 OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + diff --git a/OpenSSL_README b/OpenSSL_README new file mode 100644 index 0000000..e70acb3 --- /dev/null +++ b/OpenSSL_README @@ -0,0 +1,93 @@ + + OpenSSL 1.1.1 11 Sep 2018 + + Copyright (c) 1998-2018 The OpenSSL Project + Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson + All rights reserved. + + DESCRIPTION + ----------- + + The OpenSSL Project is a collaborative effort to develop a robust, + commercial-grade, fully featured, and Open Source toolkit implementing the + Transport Layer Security (TLS) protocols (including SSLv3) as well as a + full-strength general purpose cryptographic library. + + OpenSSL is descended from the SSLeay library developed by Eric A. Young + and Tim J. Hudson. The OpenSSL toolkit is licensed under a dual-license (the + OpenSSL license plus the SSLeay license), which means that you are free to + get and use it for commercial and non-commercial purposes as long as you + fulfill the conditions of both licenses. + + OVERVIEW + -------- + + The OpenSSL toolkit includes: + + libssl (with platform specific naming): + Provides the client and server-side implementations for SSLv3 and TLS. + + libcrypto (with platform specific naming): + Provides general cryptographic and X.509 support needed by SSL/TLS but + not logically part of it. + + openssl: + A command line tool that can be used for: + Creation of key parameters + Creation of X.509 certificates, CSRs and CRLs + Calculation of message digests + Encryption and decryption + SSL/TLS client and server tests + Handling of S/MIME signed or encrypted mail + And more... + + INSTALLATION + ------------ + + See the appropriate file: + INSTALL Linux, Unix, Windows, OpenVMS, ... + NOTES.* INSTALL addendums for different platforms + + SUPPORT + ------- + + See the OpenSSL website www.openssl.org for details on how to obtain + commercial technical support. Free community support is available through the + openssl-users email list (see + https://www.openssl.org/community/mailinglists.html for further details). + + If you have any problems with OpenSSL then please take the following steps + first: + + - Download the latest version from the repository + to see if the problem has already been addressed + - Configure with no-asm + - Remove compiler optimization flags + + If you wish to report a bug then please include the following information + and create an issue on GitHub: + + - OpenSSL version: output of 'openssl version -a' + - Configuration data: output of 'perl configdata.pm --dump' + - OS Name, Version, Hardware platform + - Compiler Details (name, version) + - Application Details (name, version) + - Problem Description (steps that will reproduce the problem, if known) + - Stack Traceback (if the application dumps core) + + Just because something doesn't work the way you expect does not mean it + is necessarily a bug in OpenSSL. Use the openssl-users email list for this type + of query. + + HOW TO CONTRIBUTE TO OpenSSL + ---------------------------- + + See CONTRIBUTING + + LEGALITIES + ---------- + + A number of nations restrict the use or export of cryptography. If you + are potentially subject to such restrictions you should seek competent + professional legal advice before attempting to develop or distribute + cryptographic code. diff --git a/RakNet_LICENSE b/RakNet_LICENSE new file mode 100644 index 0000000..29dfb0e --- /dev/null +++ b/RakNet_LICENSE @@ -0,0 +1,25 @@ +BSD License +For RakNet software + +Copyright (c) 2014, Oculus VR, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* 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 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. \ No newline at end of file diff --git a/RakNet_README b/RakNet_README new file mode 100644 index 0000000..e66acf3 --- /dev/null +++ b/RakNet_README @@ -0,0 +1,271 @@ +RakNet 4.081 +============ + +Copyright (c) 2014, Oculus VR, Inc. + +Package notes +------------------------------------------ +The Help directory contains index.html, which is full help documentation in HTML format +The Source directory contain all files required for the core of Raknet and is used if you want to use the source in your program or create your own dll +The Samples directory contains code samples and one game using an older version of Raknet. The code samples each demonstrate one feature of Raknet. The game samples cover several features. +The lib directory contains libs for debug and release versions of RakNet and RakVoice +There is a make file for linux users in the root directory. Windows users can use projects under Samples\Project Samples + +C# support +------------------------------------------ + +See Help\swigtutorial.html + +Upgrading from version 3 +------------------------------------------ + +See 3.x_to_4.x_upgrade.txt + +Windows users (Visual Studio 2008 and 2010) +----------------------------------------- +Load RakNet_VS2008.sln and convert if necessary. + +After the project conversion, if you encounter error MSB4006, +follow the steps below to fix it: + +1. Open project properties +2. Click on "Common Properties" +3. Click on "Framework and References" +4. Look under "Build Properties" +5. Change the "Copy Local" flag from "True" to "False" + +For other compiler issues, please see Help/compilersetup.html + +Windows users (VC6) +----------------------------------------- +Not supported, but you can get by if you directly include the source. + +CYGWIN users +----------------------------------------- +Copy Include, Source, and whatever you want to run in the home directory. Then type +`g++ ../../lib/w32api/libws2_32.a *.cpp` +You can run `a.exe`. +You might have to copy `*.dll` from `cygwin\bin` as well. + +Linux users +----------------------------------------- +Use `cmake`, or `g++ -lpthread -g *.cpp` in the /Source directory. +With libcat, use `g++ -pthread -g -I./../DependentExtensions *.cpp` in the /Source directory. + +64 bit use -m64 command line +Sometimes you need -pthread instead of -lpthread + +Command to build 64 bit chat example server from the /Source directory: + + g++ -m64 -g -lpthread -I./ "../Samples/Chat Example/Chat Example Server.cpp" *.cpp + +Command to build NATCompleteServer from the Samples/NATCompleteServer directory: + + g++ -g -lpthread -I./ -I./../../Source main.cpp -I./../CloudServer ./../../Source/*.cpp ./../CloudServer/CloudServerHelper.cpp + +Command to build autopatcher server from /Source directory: + + g++ -lpthread -lpq -lssl -lbz2 -lssl -lcrypto -L/opt/PostgreSQL/9.0/lib -L../DependentExtensions/bzip2-1.0.6 -I/opt/PostgreSQL/9.0/include -I../DependentExtensions/bzip2-1.0.6 -I./ -I../DependentExtensions/Autopatcher -I../DependentExtensions/Autopatcher/AutopatcherPostgreRepository -I../DependentExtensions/PostgreSQLInterface -g *.cpp ../DependentExtensions/Autopatcher/AutopatcherServer.cpp ../DependentExtensions/Autopatcher/CreatePatch.cpp ../DependentExtensions/Autopatcher/MemoryCompressor.cpp ../DependentExtensions/Autopatcher/AutopatcherPostgreRepository/AutopatcherPostgreRepository.cpp ../DependentExtensions/PostgreSQLInterface/PostgreSQLInterface.cpp ../Samples/AutopatcherServer/AutopatcherServerTest.cpp + +Command to build NATCompleteServer from /Source directory: + + g++ -lpthread -I./ -I../Samples/CloudServer ../Samples/CloudServer/CloudServerHelper.cpp ../Samples/NATCompleteServer/main.cpp *.cpp + +Command to build BigPacketTest from /Source directory: + + g++ -lpthread -I./ ../Samples/BigPacketTest/BigPacketTest.cpp *.cpp + +Or with debugging info on: + + g++ -g -lpthread -I./ ../Samples/BigPacketTest/BigPacketTest.cpp *.cpp + +If you get /usr/local/lib/libraknet.so: undefined reference to \`__sync_fetch_and_add_4 then build with `-march=i686` + +To debug: +http://www.unknownroad.com/rtfm/gdbtut/gdbstack.html +http://cs.baylor.edu/~donahoo/tools/gdb/tutorial.html +http://linux.bytesex.org/gdb.html +http://www.delorie.com/gnu/docs/gdb/gdb_29.html + + gdb ./a.out + +Set breakpoint: + + b file:line + +Disable a breakpoint: + + disable + +Delete a breakpoint: + + delete + +Get a list of breakpoints: + + info breakpoints + +St breakpoint to be ignored that number of times + + ignore + run + +Other useful commands: + + info stack + info locals + delete (Clears all breakpoints) + step (step into) + next (step over) + finish (step out) + continue to keep going after step or next + p + For example: p users.orderedList.listArray[0].guid + +Command to install g++ + + sudo apt-get install gcc-c++ + sudo apt-get install build-essential +Or: + + yum install gcc-c++ +Or: + + sudo apt-get update + sudo apt-get install g++ + +Command to install gdb + + sudo apt-get install gdb + +Command to install wget, used to download files from webpages +sudo apt-get install wget + +Series of commands for a new server: + sudo apt-get install wget + sudo apt-get update + sudo apt-get install --fix-missing g++ + sudo apt-get install gdb + cd RakNet_Install_Directory\Source + g++ -m64 -g -pthread -I./ "../Samples/Chat Example/Chat Example Server.cpp" *.cpp + ./a.out + +Mac Users +----------------------------------------- +Open a Terminal window and type: + + cd ~/Desktop/RakNet/Source + g++ -c -DNDEBUG -I -isysroot /Developer/SDKs/MacOSX10.5u.sdk/ -arch i386 *.cpp + +Use whichever SDK you have. However, the 10.4 SDK is bugged and will not compile unless you use GCC 4.0 from inside XCODE + +The sources should build cleanly. This gives you a bunch of PowerPC binaries, compiled against the 10.3.9 SDK which is a good thing. + +Give the following command: + + libtool -static -o raknetppc.a *.o + +This will stitch together a static library for the PowerPC architecture. There may be warnings that some .o files do not have any symbols. If you want to be prudent, remove the named files (the .o files, not the .cpp files!) and re-run the libtool command. + +Now, we build the source files for Intel: + + gcc -c -I ../Include -isysroot /Developer/SDKs/MacOSX10.4u.sdk/ -arch i386 *.cpp + +..and stitch it into a i386 library: + + libtool -static -o rakneti386.a *.o + +Now, type: + + ls *.a + +which should list the two .a files. Now, we make them into a universal binary: + + lipo -create *.a -o libraknet.a + +You now have a file named libraknet.a. This is the RakNet library, built to run on both PowerPC and Intel Macs. Enjoy! ;-) + +IPod +----------------------------------------- +Depending on what version you target, you may have to change two defines to not use 64 bit integers and floats or doubles. + +Android +----------------------------------------- + +You will need the latest CYWGIN and the android SDK to build native code on the android. Under CYWGIN, you will need to run ndk-build on a directory for RakNet. + +1. Under cygwin, create the RakNet directory somewhere, such as under samples. +For example, if you create the path `\cygwin\home\Kevin\android-ndk-r4b\samples\RakNet` + +2. I copied the Android.Manifest.xml and other files from another sample + +3. Under jni, you will need the following Android.mk + + LOCAL_PATH := $(call my-dir) + include $(CLEAR_VARS) + LOCAL_MODULE := RakNet + MY_PREFIX := $(LOCAL_PATH)/RakNetSources/ + MY_SOURCES := $(wildcard $(MY_PREFIX)*.cpp) + LOCAL_SRC_FILES += $(MY_SOURCES:$(MY_PREFIX)%=RakNetSources/%) + include $(BUILD_SHARED_LIBRARY) + +This version of Android.mk assumes there is a directory called RakNetSources, for example +`cygwin/home/Kevin/android-ndk-r4b/samples/RakNet/jni/RakNetSources` + +Under RakNetSources should be the /Source directory to RakNet. Rather than copy the files I used junction.exe +http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx + +The command I used to create the junction was: + + D:/cygwin/home/Kevin/android-ndk-r4b/samples/RakNet/jni/junction.exe -s D:/cygwin/home/Kevin/android-ndk-r4b/samples/RakNet/jni/RakNetSources D:/RakNet4/Source + +To unjunction I used: + + D:/cygwin/home/Kevin/android-ndk-r4b/samples/RakNet/jni/junction.exe -d D:/cygwin/home/Kevin/android-ndk-r4b/samples/RakNet/jni/RakNetSources + +From within the CYWGIN enviroment, navigate to home/Kevin/android-ndk-r4b/samples/RakNet. Then type + + ../../ndk-build + +Everything should build and you should end up with a .so file. + +You should then be able to create a project in eclipse, and import cygwin/home/Kevin/android-ndk-r4b/samples/RakNet + +Native client +----------------------------------------- +Solution: RakNet_NativeClient_VS2010. See Samples\nacl_sdk\RakNet_NativeClient_VS2010\HowToSetup.txt for detailed instructions on setup. + +Windows Phone 8 +----------------------------------------- +Example solution: RakNet_WinPhone8_VS2012. +Add to your project DependentExtensions\WinPhone8\ThreadEmulation.cpp +Add DependentExtensions\WinPhone8\ to your include paths +Define _CRT_SECURE_NO_WARNINGS and WINDOWS_PHONE_8 + +Windows Store 8 +----------------------------------------- +Example solution: RakNet_WindowsStore8_VS2012.sln +Add to your project DependentExtensions\WinPhone8\ThreadEmulation.cpp +Add DependentExtensions\WinPhone8\ and DependentExtensions\WinRT to your include paths +TCP is not supported, only UDP (RakPeer). +IPV4 only (not hard to also add IPV6 upon request). +Define: +_CRT_SECURE_NO_WARNINGS +WINDOWS_STORE_RT +_RAKNET_SUPPORT_TCPInterface=0 +_RAKNET_SUPPORT_PacketizedTCP=0 +_RAKNET_SUPPORT_EmailSender=0 +_RAKNET_SUPPORT_HTTPConnection=0 +_RAKNET_SUPPORT_HTTPConnection2=0 +_RAKNET_SUPPORT_TelnetTransport=0 +_RAKNET_SUPPORT_NatTypeDetectionServer=0 +_RAKNET_SUPPORT_UDPProxyServer=0 +_RAKNET_SUPPORT_UDPProxyCoordinator=0 +_RAKNET_SUPPORT_UDPForwarder=0 + + +Unreal engine +----------------------------------------- +See https://udn.epicgames.com/lists/showpost.php?list=unprog3&id=37697&lessthan=&show=20 + + diff --git a/include/array/GrowableArray.hpp b/include/array/GrowableArray.hpp new file mode 100644 index 0000000..47f22ba --- /dev/null +++ b/include/array/GrowableArray.hpp @@ -0,0 +1,74 @@ +#ifndef GROWABLEARRAY_HPP +#define GROWABLEARRAY_HPP + +class GrowableArray{ + + public: + + static const unsigned int TYPE_BOOLEAN; + + static const unsigned int TYPE_BYTE; + + static const unsigned int TYPE_SHORT; + + static const unsigned int TYPE_INT; + + static const unsigned int TYPE_FLOAT; + + static const unsigned int TYPE_DOUBLE; + + static const unsigned int TYPE_LONG; + + static const unsigned int TYPE_VOIDPTR; + + GrowableArray(unsigned int type, unsigned int initSize); + + ~GrowableArray(); + + void* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const void* e); + + void set(unsigned index, const void* e); + + void copyFrom(const void* data, unsigned int count); + + void copyFrom(const void* data, unsigned int index, unsigned int count); + + void copyFrom(const void* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + void* get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + private: + + unsigned int arrlen; + + unsigned int arrayCapacity; + + unsigned int elementSize; + + unsigned int init_cap; + + void* array; + + void grow(unsigned int count); + + void decrease(unsigned int count); + + void checkIndex(unsigned int index); + +}; + +#endif // GROWABLEARRAY_HPP diff --git a/include/array/GrowableBooleanArray.hpp b/include/array/GrowableBooleanArray.hpp new file mode 100644 index 0000000..d99e55a --- /dev/null +++ b/include/array/GrowableBooleanArray.hpp @@ -0,0 +1,51 @@ +#ifndef GROWABLEBOOLEANARRAY_HPP +#define GROWABLEBOOLEANARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableBooleanArray{ + + public: + + GrowableBooleanArray(unsigned int initSize=minmum_capacity); + + int* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const int e); + + void set(unsigned index, const int e); + + void copyFrom(const int* data, unsigned int count); + + void copyFrom(const int* data, unsigned int index, unsigned int count); + + void copyFrom(const int* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + int get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + ~GrowableBooleanArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + static const unsigned int minmum_capacity; + +}; + +#endif // GROWABLEBOOLEANARRAY_HPP diff --git a/include/array/GrowableByteArray.hpp b/include/array/GrowableByteArray.hpp new file mode 100644 index 0000000..a06ed27 --- /dev/null +++ b/include/array/GrowableByteArray.hpp @@ -0,0 +1,51 @@ +#ifndef GROWABLEBYTEARRAY_HPP +#define GROWABLEBYTEARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableByteArray{ + + public: + + GrowableByteArray(unsigned int initSize=minmum_capacity); + + unsigned char* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const unsigned char e); + + void set(unsigned index, const unsigned char e); + + void copyFrom(const unsigned char* data, unsigned int count); + + void copyFrom(const unsigned char* data, unsigned int index, unsigned int count); + + void copyFrom(const unsigned char* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + unsigned char get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + ~GrowableByteArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + static const unsigned int minmum_capacity; + +}; + +#endif // GROWABLEBYTEARRAY_HPP diff --git a/include/array/GrowableDoubleArray.hpp b/include/array/GrowableDoubleArray.hpp new file mode 100644 index 0000000..870af17 --- /dev/null +++ b/include/array/GrowableDoubleArray.hpp @@ -0,0 +1,51 @@ +#ifndef GROWABLEDOUBLEARRAY_HPP +#define GROWABLEDOUBLEARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableDoubleArray{ + + public: + + GrowableDoubleArray(unsigned int initSize=minmum_capacity); + + double* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const double e); + + void set(unsigned index, const double e); + + void copyFrom(const double* data, unsigned int count); + + void copyFrom(const double* data, unsigned int index, unsigned int count); + + void copyFrom(const double* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + double get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + ~GrowableDoubleArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + static const unsigned int minmum_capacity; + +}; + +#endif // GROWABLEDOUBLEARRAY_HPP diff --git a/include/array/GrowableFloatArray.hpp b/include/array/GrowableFloatArray.hpp new file mode 100644 index 0000000..b3475c5 --- /dev/null +++ b/include/array/GrowableFloatArray.hpp @@ -0,0 +1,51 @@ +#ifndef GROWABLEFLOATARRAY_HPP +#define GROWABLEFLOATARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableFloatArray{ + + public: + + GrowableFloatArray(unsigned int initSize=minmum_capacity); + + float* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const float e); + + void set(unsigned index, const float e); + + void copyFrom(const float* data, unsigned int count); + + void copyFrom(const float* data, unsigned int index, unsigned int count); + + void copyFrom(const float* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + float get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + ~GrowableFloatArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + static const unsigned int minmum_capacity; + +}; + +#endif // GROWABLEFLOATARRAY_HPP diff --git a/include/array/GrowableIntegerArray.hpp b/include/array/GrowableIntegerArray.hpp new file mode 100644 index 0000000..e9da70c --- /dev/null +++ b/include/array/GrowableIntegerArray.hpp @@ -0,0 +1,51 @@ +#ifndef GROWABLEINTEGERARRAY_HPP +#define GROWABLEINTEGERARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableIntegerArray{ + + public: + + GrowableIntegerArray(unsigned int initSize=minmum_capacity); + + int* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const int e); + + void set(unsigned index, const int e); + + void copyFrom(const int* data, unsigned int count); + + void copyFrom(const int* data, unsigned int index, unsigned int count); + + void copyFrom(const int* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + int get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + ~GrowableIntegerArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + static const unsigned int minmum_capacity; + +}; + +#endif // GROWABLEINTEGERARRAY_HPP diff --git a/include/array/GrowableLongArray.hpp b/include/array/GrowableLongArray.hpp new file mode 100644 index 0000000..7e3e593 --- /dev/null +++ b/include/array/GrowableLongArray.hpp @@ -0,0 +1,52 @@ +#ifndef GROWABLELONGARRAY_HPP +#define GROWABLELONGARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableLongArray{ + + public: + + GrowableLongArray(unsigned int initSize=minmum_capacity); + + long long* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const long long e); + + void set(unsigned index, const long long e); + + void copyFrom(const long long* data, unsigned int count); + + void copyFrom(const long long* data, unsigned int index, unsigned int count); + + void copyFrom(const long long* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + long long get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + ~GrowableLongArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + static const unsigned int minmum_capacity; + +}; + + +#endif // GROWABLELONGARRAY_HPP diff --git a/include/array/GrowableObjectArray.hpp b/include/array/GrowableObjectArray.hpp new file mode 100644 index 0000000..ea81a6a --- /dev/null +++ b/include/array/GrowableObjectArray.hpp @@ -0,0 +1,55 @@ +#ifndef GROWABLEOBJECTARRAY_HPP +#define GROWABLEOBJECTARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableObjectArray{ + + public: + + GrowableObjectArray(unsigned int initSize=minmum_capacity); + + void* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const void* e); + + void set(unsigned index, const void* e); + + void copyFrom(const void* data, unsigned int count); + + void copyFrom(const void* data, unsigned int index, unsigned int count); + + void copyFrom(const void* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + void* get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + void destroyAllObjectOnDelete(unsigned int flag); + + ~GrowableObjectArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + unsigned int destroyFlag=false; + + static const unsigned int minmum_capacity; + +}; + +#endif // GROWABLEOBJECTARRAY_HPP diff --git a/include/array/GrowableShortArray.hpp b/include/array/GrowableShortArray.hpp new file mode 100644 index 0000000..e3f5dff --- /dev/null +++ b/include/array/GrowableShortArray.hpp @@ -0,0 +1,51 @@ +#ifndef GROWABLESHORTARRAY_HPP +#define GROWABLESHORTARRAY_HPP + +#include "include/array/GrowableArray.hpp" + +class GrowableShortArray{ + + public: + + GrowableShortArray(unsigned int initSize=minmum_capacity); + + short* getArrayData(); + + unsigned int capacity(); + + const unsigned int& length=arrlen; + + const unsigned int& element_size=elementSize; + + void put(const short e); + + void set(unsigned index, const short e); + + void copyFrom(const short* data, unsigned int count); + + void copyFrom(const short* data, unsigned int index, unsigned int count); + + void copyFrom(const short* data, unsigned int index, unsigned int bufferOffset, unsigned int count); + + short get(unsigned int index); + + void remove(unsigned int index); + + void gc(); + + void clear(); + + ~GrowableShortArray(); + + private: + + GrowableArray* array; + + unsigned int arrlen; + unsigned int elementSize; + + static const unsigned int minmum_capacity; + +}; + +#endif // GROWABLESHORTARRAY_HPP diff --git a/include/colorspace/SampleUtils.hpp b/include/colorspace/SampleUtils.hpp new file mode 100644 index 0000000..89db4cc --- /dev/null +++ b/include/colorspace/SampleUtils.hpp @@ -0,0 +1,24 @@ +#ifndef SAMPLEUTILS_H +#define SAMPLEUTILS_H + +class SampleUtils{ + + private: + + SampleUtils(); + + public: + + static unsigned char convert1BitTo8Bit(unsigned char color); + + static unsigned char convert2BitTo8Bit(unsigned char color); + + static unsigned char convert4BitTo8Bit(unsigned char color); + + static unsigned char convert16BitTo8Bit(unsigned short color); + + static unsigned int convertRGBtoBrightness(unsigned int color); + +}; + +#endif // SAMPLEUTILS_H diff --git a/include/drfstream/drfstream.hpp b/include/drfstream/drfstream.hpp new file mode 100644 index 0000000..b4c2a73 --- /dev/null +++ b/include/drfstream/drfstream.hpp @@ -0,0 +1,12 @@ +#ifndef EXPORT_HPP +#define EXPORT_HPP + +extern "C"{ + + char* encode(const char* srcData, const unsigned int dataLength, unsigned int* resultLength); + + char* decode(const char* srcData, const unsigned int dataLength, unsigned int* resultLength); + +} + +#endif // EXPORT_HPP diff --git a/include/encoding/CharTableGBK.hpp b/include/encoding/CharTableGBK.hpp new file mode 100644 index 0000000..950b86f --- /dev/null +++ b/include/encoding/CharTableGBK.hpp @@ -0,0 +1,14 @@ +#ifndef CHARTABLEGBK_HPP +#define CHARTABLEGBK_HPP + +class CharTableGBK{ + + public: + + static const unsigned int GBKTable_size=22645; + + static const unsigned short GBKTable[GBKTable_size]; + +}; + +#endif // CHARTABLEGBK_HPP diff --git a/include/encoding/CharTableUTF8.hpp b/include/encoding/CharTableUTF8.hpp new file mode 100644 index 0000000..283dcf6 --- /dev/null +++ b/include/encoding/CharTableUTF8.hpp @@ -0,0 +1,14 @@ +#ifndef CHARTABLEUTF8_HPP +#define CHARTABLEUTF8_HPP + +class CharTableUTF8{ + + public: + + static const unsigned int UTF8Table_size=22645; + + static const unsigned int UTF8Table[UTF8Table_size]; + +}; + +#endif // CHARTABLEUTF8_HPP diff --git a/include/encoding/EncodingUtils.hpp b/include/encoding/EncodingUtils.hpp new file mode 100644 index 0000000..0d516ec --- /dev/null +++ b/include/encoding/EncodingUtils.hpp @@ -0,0 +1,26 @@ +#ifndef ENCODINGUTILS_HPP +#define ENCODINGUTILS_HPP + +class EncodingUtils{ + + public: + + static char* convertUTF8toGBK(const char* str); + + static char* convertGBKtoUTF8(const char* str); + + static unsigned int getUTF8TableSize(); + + static char* getUTF8TableElement(unsigned int index); + + static unsigned int getGBKTableSize(); + + static char* getGBKTableElement(unsigned int index); + + static unsigned int getUTF8CharLength(char header); + + static unsigned int getGBKCharLength(char header); + +}; + +#endif diff --git a/include/memory/Memory.hpp b/include/memory/Memory.hpp new file mode 100644 index 0000000..0312bf3 --- /dev/null +++ b/include/memory/Memory.hpp @@ -0,0 +1,20 @@ +#ifndef MEMORY_HPP +#define MEMORY_HPP + +class Memory{ + + public: + + static void* allocateMemory(unsigned long size); + + static void* allocateExecutableMemory(unsigned long size); + + static void* allocateHugePage(unsigned long size); + + static int setPremission(void* page,unsigned long size, unsigned int permission); + + static int releaseMemory(void* mem, unsigned long size); + +}; + +#endif diff --git a/include/openssl/__DECC_INCLUDE_EPILOGUE.H b/include/openssl/__DECC_INCLUDE_EPILOGUE.H new file mode 100644 index 0000000..c350018 --- /dev/null +++ b/include/openssl/__DECC_INCLUDE_EPILOGUE.H @@ -0,0 +1,16 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* restore state. Must correspond to the save in __decc_include_prologue.h */ +#pragma names restore diff --git a/include/openssl/__DECC_INCLUDE_PROLOGUE.H b/include/openssl/__DECC_INCLUDE_PROLOGUE.H new file mode 100644 index 0000000..9a9c777 --- /dev/null +++ b/include/openssl/__DECC_INCLUDE_PROLOGUE.H @@ -0,0 +1,20 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* save state */ +#pragma names save +/* have the compiler shorten symbols larger than 31 chars to 23 chars + * followed by a 8 hex char CRC + */ +#pragma names as_is,shortened diff --git a/include/openssl/aes.h b/include/openssl/aes.h new file mode 100644 index 0000000..b1a27cb --- /dev/null +++ b/include/openssl/aes.h @@ -0,0 +1,92 @@ +/* + * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_AES_H +# define HEADER_AES_H + +# include + +# include +# ifdef __cplusplus +extern "C" { +# endif + +# define AES_ENCRYPT 1 +# define AES_DECRYPT 0 + +/* + * Because array size can't be a const in C, the following two are macros. + * Both sizes are in bytes. + */ +# define AES_MAXNR 14 +# define AES_BLOCK_SIZE 16 + +/* This should be a hidden type, but EVP requires that the size be known */ +struct aes_key_st { +# ifdef AES_LONG + unsigned long rd_key[4 * (AES_MAXNR + 1)]; +# else + unsigned int rd_key[4 * (AES_MAXNR + 1)]; +# endif + int rounds; +}; +typedef struct aes_key_st AES_KEY; + +const char *AES_options(void); + +int AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); +int AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); + +void AES_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key); +void AES_decrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key); + +void AES_ecb_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key, const int enc); +void AES_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, const int enc); +void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num); +/* NB: the IV is _two_ blocks long */ +void AES_ige_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, const int enc); +/* NB: the IV is _four_ blocks long */ +void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + const AES_KEY *key2, const unsigned char *ivec, + const int enc); + +int AES_wrap_key(AES_KEY *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, unsigned int inlen); +int AES_unwrap_key(AES_KEY *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, unsigned int inlen); + + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/include/openssl/asn1.h b/include/openssl/asn1.h new file mode 100644 index 0000000..9681a27 --- /dev/null +++ b/include/openssl/asn1.h @@ -0,0 +1,886 @@ +/* + * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ASN1_H +# define HEADER_ASN1_H + +# include +# include +# include +# include +# include +# include +# include + +# include +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# endif + +# ifdef OPENSSL_BUILD_SHLIBCRYPTO +# undef OPENSSL_EXTERN +# define OPENSSL_EXTERN OPENSSL_EXPORT +# endif + +#ifdef __cplusplus +extern "C" { +#endif + +# define V_ASN1_UNIVERSAL 0x00 +# define V_ASN1_APPLICATION 0x40 +# define V_ASN1_CONTEXT_SPECIFIC 0x80 +# define V_ASN1_PRIVATE 0xc0 + +# define V_ASN1_CONSTRUCTED 0x20 +# define V_ASN1_PRIMITIVE_TAG 0x1f +# define V_ASN1_PRIMATIVE_TAG /*compat*/ V_ASN1_PRIMITIVE_TAG + +# define V_ASN1_APP_CHOOSE -2/* let the recipient choose */ +# define V_ASN1_OTHER -3/* used in ASN1_TYPE */ +# define V_ASN1_ANY -4/* used in ASN1 template code */ + +# define V_ASN1_UNDEF -1 +/* ASN.1 tag values */ +# define V_ASN1_EOC 0 +# define V_ASN1_BOOLEAN 1 /**/ +# define V_ASN1_INTEGER 2 +# define V_ASN1_BIT_STRING 3 +# define V_ASN1_OCTET_STRING 4 +# define V_ASN1_NULL 5 +# define V_ASN1_OBJECT 6 +# define V_ASN1_OBJECT_DESCRIPTOR 7 +# define V_ASN1_EXTERNAL 8 +# define V_ASN1_REAL 9 +# define V_ASN1_ENUMERATED 10 +# define V_ASN1_UTF8STRING 12 +# define V_ASN1_SEQUENCE 16 +# define V_ASN1_SET 17 +# define V_ASN1_NUMERICSTRING 18 /**/ +# define V_ASN1_PRINTABLESTRING 19 +# define V_ASN1_T61STRING 20 +# define V_ASN1_TELETEXSTRING 20/* alias */ +# define V_ASN1_VIDEOTEXSTRING 21 /**/ +# define V_ASN1_IA5STRING 22 +# define V_ASN1_UTCTIME 23 +# define V_ASN1_GENERALIZEDTIME 24 /**/ +# define V_ASN1_GRAPHICSTRING 25 /**/ +# define V_ASN1_ISO64STRING 26 /**/ +# define V_ASN1_VISIBLESTRING 26/* alias */ +# define V_ASN1_GENERALSTRING 27 /**/ +# define V_ASN1_UNIVERSALSTRING 28 /**/ +# define V_ASN1_BMPSTRING 30 + +/* + * NB the constants below are used internally by ASN1_INTEGER + * and ASN1_ENUMERATED to indicate the sign. They are *not* on + * the wire tag values. + */ + +# define V_ASN1_NEG 0x100 +# define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG) +# define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG) + +/* For use with d2i_ASN1_type_bytes() */ +# define B_ASN1_NUMERICSTRING 0x0001 +# define B_ASN1_PRINTABLESTRING 0x0002 +# define B_ASN1_T61STRING 0x0004 +# define B_ASN1_TELETEXSTRING 0x0004 +# define B_ASN1_VIDEOTEXSTRING 0x0008 +# define B_ASN1_IA5STRING 0x0010 +# define B_ASN1_GRAPHICSTRING 0x0020 +# define B_ASN1_ISO64STRING 0x0040 +# define B_ASN1_VISIBLESTRING 0x0040 +# define B_ASN1_GENERALSTRING 0x0080 +# define B_ASN1_UNIVERSALSTRING 0x0100 +# define B_ASN1_OCTET_STRING 0x0200 +# define B_ASN1_BIT_STRING 0x0400 +# define B_ASN1_BMPSTRING 0x0800 +# define B_ASN1_UNKNOWN 0x1000 +# define B_ASN1_UTF8STRING 0x2000 +# define B_ASN1_UTCTIME 0x4000 +# define B_ASN1_GENERALIZEDTIME 0x8000 +# define B_ASN1_SEQUENCE 0x10000 +/* For use with ASN1_mbstring_copy() */ +# define MBSTRING_FLAG 0x1000 +# define MBSTRING_UTF8 (MBSTRING_FLAG) +# define MBSTRING_ASC (MBSTRING_FLAG|1) +# define MBSTRING_BMP (MBSTRING_FLAG|2) +# define MBSTRING_UNIV (MBSTRING_FLAG|4) +# define SMIME_OLDMIME 0x400 +# define SMIME_CRLFEOL 0x800 +# define SMIME_STREAM 0x1000 + struct X509_algor_st; +DEFINE_STACK_OF(X509_ALGOR) + +# define ASN1_STRING_FLAG_BITS_LEFT 0x08/* Set if 0x07 has bits left value */ +/* + * This indicates that the ASN1_STRING is not a real value but just a place + * holder for the location where indefinite length constructed data should be + * inserted in the memory buffer + */ +# define ASN1_STRING_FLAG_NDEF 0x010 + +/* + * This flag is used by the CMS code to indicate that a string is not + * complete and is a place holder for content when it had all been accessed. + * The flag will be reset when content has been written to it. + */ + +# define ASN1_STRING_FLAG_CONT 0x020 +/* + * This flag is used by ASN1 code to indicate an ASN1_STRING is an MSTRING + * type. + */ +# define ASN1_STRING_FLAG_MSTRING 0x040 +/* String is embedded and only content should be freed */ +# define ASN1_STRING_FLAG_EMBED 0x080 +/* String should be parsed in RFC 5280's time format */ +# define ASN1_STRING_FLAG_X509_TIME 0x100 +/* This is the base type that holds just about everything :-) */ +struct asn1_string_st { + int length; + int type; + unsigned char *data; + /* + * The value of the following field depends on the type being held. It + * is mostly being used for BIT_STRING so if the input data has a + * non-zero 'unused bits' value, it will be handled correctly + */ + long flags; +}; + +/* + * ASN1_ENCODING structure: this is used to save the received encoding of an + * ASN1 type. This is useful to get round problems with invalid encodings + * which can break signatures. + */ + +typedef struct ASN1_ENCODING_st { + unsigned char *enc; /* DER encoding */ + long len; /* Length of encoding */ + int modified; /* set to 1 if 'enc' is invalid */ +} ASN1_ENCODING; + +/* Used with ASN1 LONG type: if a long is set to this it is omitted */ +# define ASN1_LONG_UNDEF 0x7fffffffL + +# define STABLE_FLAGS_MALLOC 0x01 +/* + * A zero passed to ASN1_STRING_TABLE_new_add for the flags is interpreted + * as "don't change" and STABLE_FLAGS_MALLOC is always set. By setting + * STABLE_FLAGS_MALLOC only we can clear the existing value. Use the alias + * STABLE_FLAGS_CLEAR to reflect this. + */ +# define STABLE_FLAGS_CLEAR STABLE_FLAGS_MALLOC +# define STABLE_NO_MASK 0x02 +# define DIRSTRING_TYPE \ + (B_ASN1_PRINTABLESTRING|B_ASN1_T61STRING|B_ASN1_BMPSTRING|B_ASN1_UTF8STRING) +# define PKCS9STRING_TYPE (DIRSTRING_TYPE|B_ASN1_IA5STRING) + +typedef struct asn1_string_table_st { + int nid; + long minsize; + long maxsize; + unsigned long mask; + unsigned long flags; +} ASN1_STRING_TABLE; + +DEFINE_STACK_OF(ASN1_STRING_TABLE) + +/* size limits: this stuff is taken straight from RFC2459 */ + +# define ub_name 32768 +# define ub_common_name 64 +# define ub_locality_name 128 +# define ub_state_name 128 +# define ub_organization_name 64 +# define ub_organization_unit_name 64 +# define ub_title 64 +# define ub_email_address 128 + +/* + * Declarations for template structures: for full definitions see asn1t.h + */ +typedef struct ASN1_TEMPLATE_st ASN1_TEMPLATE; +typedef struct ASN1_TLC_st ASN1_TLC; +/* This is just an opaque pointer */ +typedef struct ASN1_VALUE_st ASN1_VALUE; + +/* Declare ASN1 functions: the implement macro in in asn1t.h */ + +# define DECLARE_ASN1_FUNCTIONS(type) DECLARE_ASN1_FUNCTIONS_name(type, type) + +# define DECLARE_ASN1_ALLOC_FUNCTIONS(type) \ + DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, type) + +# define DECLARE_ASN1_FUNCTIONS_name(type, name) \ + DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \ + DECLARE_ASN1_ENCODE_FUNCTIONS(type, name, name) + +# define DECLARE_ASN1_FUNCTIONS_fname(type, itname, name) \ + DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \ + DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) + +# define DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) \ + type *d2i_##name(type **a, const unsigned char **in, long len); \ + int i2d_##name(type *a, unsigned char **out); \ + DECLARE_ASN1_ITEM(itname) + +# define DECLARE_ASN1_ENCODE_FUNCTIONS_const(type, name) \ + type *d2i_##name(type **a, const unsigned char **in, long len); \ + int i2d_##name(const type *a, unsigned char **out); \ + DECLARE_ASN1_ITEM(name) + +# define DECLARE_ASN1_NDEF_FUNCTION(name) \ + int i2d_##name##_NDEF(name *a, unsigned char **out); + +# define DECLARE_ASN1_FUNCTIONS_const(name) \ + DECLARE_ASN1_ALLOC_FUNCTIONS(name) \ + DECLARE_ASN1_ENCODE_FUNCTIONS_const(name, name) + +# define DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \ + type *name##_new(void); \ + void name##_free(type *a); + +# define DECLARE_ASN1_PRINT_FUNCTION(stname) \ + DECLARE_ASN1_PRINT_FUNCTION_fname(stname, stname) + +# define DECLARE_ASN1_PRINT_FUNCTION_fname(stname, fname) \ + int fname##_print_ctx(BIO *out, stname *x, int indent, \ + const ASN1_PCTX *pctx); + +# define D2I_OF(type) type *(*)(type **,const unsigned char **,long) +# define I2D_OF(type) int (*)(type *,unsigned char **) +# define I2D_OF_const(type) int (*)(const type *,unsigned char **) + +# define CHECKED_D2I_OF(type, d2i) \ + ((d2i_of_void*) (1 ? d2i : ((D2I_OF(type))0))) +# define CHECKED_I2D_OF(type, i2d) \ + ((i2d_of_void*) (1 ? i2d : ((I2D_OF(type))0))) +# define CHECKED_NEW_OF(type, xnew) \ + ((void *(*)(void)) (1 ? xnew : ((type *(*)(void))0))) +# define CHECKED_PTR_OF(type, p) \ + ((void*) (1 ? p : (type*)0)) +# define CHECKED_PPTR_OF(type, p) \ + ((void**) (1 ? p : (type**)0)) + +# define TYPEDEF_D2I_OF(type) typedef type *d2i_of_##type(type **,const unsigned char **,long) +# define TYPEDEF_I2D_OF(type) typedef int i2d_of_##type(type *,unsigned char **) +# define TYPEDEF_D2I2D_OF(type) TYPEDEF_D2I_OF(type); TYPEDEF_I2D_OF(type) + +TYPEDEF_D2I2D_OF(void); + +/*- + * The following macros and typedefs allow an ASN1_ITEM + * to be embedded in a structure and referenced. Since + * the ASN1_ITEM pointers need to be globally accessible + * (possibly from shared libraries) they may exist in + * different forms. On platforms that support it the + * ASN1_ITEM structure itself will be globally exported. + * Other platforms will export a function that returns + * an ASN1_ITEM pointer. + * + * To handle both cases transparently the macros below + * should be used instead of hard coding an ASN1_ITEM + * pointer in a structure. + * + * The structure will look like this: + * + * typedef struct SOMETHING_st { + * ... + * ASN1_ITEM_EXP *iptr; + * ... + * } SOMETHING; + * + * It would be initialised as e.g.: + * + * SOMETHING somevar = {...,ASN1_ITEM_ref(X509),...}; + * + * and the actual pointer extracted with: + * + * const ASN1_ITEM *it = ASN1_ITEM_ptr(somevar.iptr); + * + * Finally an ASN1_ITEM pointer can be extracted from an + * appropriate reference with: ASN1_ITEM_rptr(X509). This + * would be used when a function takes an ASN1_ITEM * argument. + * + */ + +# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION + +/* ASN1_ITEM pointer exported type */ +typedef const ASN1_ITEM ASN1_ITEM_EXP; + +/* Macro to obtain ASN1_ITEM pointer from exported type */ +# define ASN1_ITEM_ptr(iptr) (iptr) + +/* Macro to include ASN1_ITEM pointer from base type */ +# define ASN1_ITEM_ref(iptr) (&(iptr##_it)) + +# define ASN1_ITEM_rptr(ref) (&(ref##_it)) + +# define DECLARE_ASN1_ITEM(name) \ + OPENSSL_EXTERN const ASN1_ITEM name##_it; + +# else + +/* + * Platforms that can't easily handle shared global variables are declared as + * functions returning ASN1_ITEM pointers. + */ + +/* ASN1_ITEM pointer exported type */ +typedef const ASN1_ITEM *ASN1_ITEM_EXP (void); + +/* Macro to obtain ASN1_ITEM pointer from exported type */ +# define ASN1_ITEM_ptr(iptr) (iptr()) + +/* Macro to include ASN1_ITEM pointer from base type */ +# define ASN1_ITEM_ref(iptr) (iptr##_it) + +# define ASN1_ITEM_rptr(ref) (ref##_it()) + +# define DECLARE_ASN1_ITEM(name) \ + const ASN1_ITEM * name##_it(void); + +# endif + +/* Parameters used by ASN1_STRING_print_ex() */ + +/* + * These determine which characters to escape: RFC2253 special characters, + * control characters and MSB set characters + */ + +# define ASN1_STRFLGS_ESC_2253 1 +# define ASN1_STRFLGS_ESC_CTRL 2 +# define ASN1_STRFLGS_ESC_MSB 4 + +/* + * This flag determines how we do escaping: normally RC2253 backslash only, + * set this to use backslash and quote. + */ + +# define ASN1_STRFLGS_ESC_QUOTE 8 + +/* These three flags are internal use only. */ + +/* Character is a valid PrintableString character */ +# define CHARTYPE_PRINTABLESTRING 0x10 +/* Character needs escaping if it is the first character */ +# define CHARTYPE_FIRST_ESC_2253 0x20 +/* Character needs escaping if it is the last character */ +# define CHARTYPE_LAST_ESC_2253 0x40 + +/* + * NB the internal flags are safely reused below by flags handled at the top + * level. + */ + +/* + * If this is set we convert all character strings to UTF8 first + */ + +# define ASN1_STRFLGS_UTF8_CONVERT 0x10 + +/* + * If this is set we don't attempt to interpret content: just assume all + * strings are 1 byte per character. This will produce some pretty odd + * looking output! + */ + +# define ASN1_STRFLGS_IGNORE_TYPE 0x20 + +/* If this is set we include the string type in the output */ +# define ASN1_STRFLGS_SHOW_TYPE 0x40 + +/* + * This determines which strings to display and which to 'dump' (hex dump of + * content octets or DER encoding). We can only dump non character strings or + * everything. If we don't dump 'unknown' they are interpreted as character + * strings with 1 octet per character and are subject to the usual escaping + * options. + */ + +# define ASN1_STRFLGS_DUMP_ALL 0x80 +# define ASN1_STRFLGS_DUMP_UNKNOWN 0x100 + +/* + * These determine what 'dumping' does, we can dump the content octets or the + * DER encoding: both use the RFC2253 #XXXXX notation. + */ + +# define ASN1_STRFLGS_DUMP_DER 0x200 + +/* + * This flag specifies that RC2254 escaping shall be performed. + */ +#define ASN1_STRFLGS_ESC_2254 0x400 + +/* + * All the string flags consistent with RFC2253, escaping control characters + * isn't essential in RFC2253 but it is advisable anyway. + */ + +# define ASN1_STRFLGS_RFC2253 (ASN1_STRFLGS_ESC_2253 | \ + ASN1_STRFLGS_ESC_CTRL | \ + ASN1_STRFLGS_ESC_MSB | \ + ASN1_STRFLGS_UTF8_CONVERT | \ + ASN1_STRFLGS_DUMP_UNKNOWN | \ + ASN1_STRFLGS_DUMP_DER) + +DEFINE_STACK_OF(ASN1_INTEGER) + +DEFINE_STACK_OF(ASN1_GENERALSTRING) + +DEFINE_STACK_OF(ASN1_UTF8STRING) + +typedef struct asn1_type_st { + int type; + union { + char *ptr; + ASN1_BOOLEAN boolean; + ASN1_STRING *asn1_string; + ASN1_OBJECT *object; + ASN1_INTEGER *integer; + ASN1_ENUMERATED *enumerated; + ASN1_BIT_STRING *bit_string; + ASN1_OCTET_STRING *octet_string; + ASN1_PRINTABLESTRING *printablestring; + ASN1_T61STRING *t61string; + ASN1_IA5STRING *ia5string; + ASN1_GENERALSTRING *generalstring; + ASN1_BMPSTRING *bmpstring; + ASN1_UNIVERSALSTRING *universalstring; + ASN1_UTCTIME *utctime; + ASN1_GENERALIZEDTIME *generalizedtime; + ASN1_VISIBLESTRING *visiblestring; + ASN1_UTF8STRING *utf8string; + /* + * set and sequence are left complete and still contain the set or + * sequence bytes + */ + ASN1_STRING *set; + ASN1_STRING *sequence; + ASN1_VALUE *asn1_value; + } value; +} ASN1_TYPE; + +DEFINE_STACK_OF(ASN1_TYPE) + +typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY; + +DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY) +DECLARE_ASN1_ENCODE_FUNCTIONS_const(ASN1_SEQUENCE_ANY, ASN1_SET_ANY) + +/* This is used to contain a list of bit names */ +typedef struct BIT_STRING_BITNAME_st { + int bitnum; + const char *lname; + const char *sname; +} BIT_STRING_BITNAME; + +# define B_ASN1_TIME \ + B_ASN1_UTCTIME | \ + B_ASN1_GENERALIZEDTIME + +# define B_ASN1_PRINTABLE \ + B_ASN1_NUMERICSTRING| \ + B_ASN1_PRINTABLESTRING| \ + B_ASN1_T61STRING| \ + B_ASN1_IA5STRING| \ + B_ASN1_BIT_STRING| \ + B_ASN1_UNIVERSALSTRING|\ + B_ASN1_BMPSTRING|\ + B_ASN1_UTF8STRING|\ + B_ASN1_SEQUENCE|\ + B_ASN1_UNKNOWN + +# define B_ASN1_DIRECTORYSTRING \ + B_ASN1_PRINTABLESTRING| \ + B_ASN1_TELETEXSTRING|\ + B_ASN1_BMPSTRING|\ + B_ASN1_UNIVERSALSTRING|\ + B_ASN1_UTF8STRING + +# define B_ASN1_DISPLAYTEXT \ + B_ASN1_IA5STRING| \ + B_ASN1_VISIBLESTRING| \ + B_ASN1_BMPSTRING|\ + B_ASN1_UTF8STRING + +DECLARE_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE) + +int ASN1_TYPE_get(const ASN1_TYPE *a); +void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value); +int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value); +int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b); + +ASN1_TYPE *ASN1_TYPE_pack_sequence(const ASN1_ITEM *it, void *s, ASN1_TYPE **t); +void *ASN1_TYPE_unpack_sequence(const ASN1_ITEM *it, const ASN1_TYPE *t); + +ASN1_OBJECT *ASN1_OBJECT_new(void); +void ASN1_OBJECT_free(ASN1_OBJECT *a); +int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp); +ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, + long length); + +DECLARE_ASN1_ITEM(ASN1_OBJECT) + +DEFINE_STACK_OF(ASN1_OBJECT) + +ASN1_STRING *ASN1_STRING_new(void); +void ASN1_STRING_free(ASN1_STRING *a); +void ASN1_STRING_clear_free(ASN1_STRING *a); +int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str); +ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *a); +ASN1_STRING *ASN1_STRING_type_new(int type); +int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b); + /* + * Since this is used to store all sorts of things, via macros, for now, + * make its data void * + */ +int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len); +void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len); +int ASN1_STRING_length(const ASN1_STRING *x); +void ASN1_STRING_length_set(ASN1_STRING *x, int n); +int ASN1_STRING_type(const ASN1_STRING *x); +DEPRECATEDIN_1_1_0(unsigned char *ASN1_STRING_data(ASN1_STRING *x)) +const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x); + +DECLARE_ASN1_FUNCTIONS(ASN1_BIT_STRING) +int ASN1_BIT_STRING_set(ASN1_BIT_STRING *a, unsigned char *d, int length); +int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value); +int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n); +int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a, + const unsigned char *flags, int flags_len); + +int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs, + BIT_STRING_BITNAME *tbl, int indent); +int ASN1_BIT_STRING_num_asc(const char *name, BIT_STRING_BITNAME *tbl); +int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, const char *name, int value, + BIT_STRING_BITNAME *tbl); + +DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER) +ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp, + long length); +ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x); +int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y); + +DECLARE_ASN1_FUNCTIONS(ASN1_ENUMERATED) + +int ASN1_UTCTIME_check(const ASN1_UTCTIME *a); +ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t); +ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t, + int offset_day, long offset_sec); +int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str); +int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t); + +int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *a); +ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s, + time_t t); +ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s, + time_t t, int offset_day, + long offset_sec); +int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str); + +int ASN1_TIME_diff(int *pday, int *psec, + const ASN1_TIME *from, const ASN1_TIME *to); + +DECLARE_ASN1_FUNCTIONS(ASN1_OCTET_STRING) +ASN1_OCTET_STRING *ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *a); +int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a, + const ASN1_OCTET_STRING *b); +int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, const unsigned char *data, + int len); + +DECLARE_ASN1_FUNCTIONS(ASN1_VISIBLESTRING) +DECLARE_ASN1_FUNCTIONS(ASN1_UNIVERSALSTRING) +DECLARE_ASN1_FUNCTIONS(ASN1_UTF8STRING) +DECLARE_ASN1_FUNCTIONS(ASN1_NULL) +DECLARE_ASN1_FUNCTIONS(ASN1_BMPSTRING) + +int UTF8_getc(const unsigned char *str, int len, unsigned long *val); +int UTF8_putc(unsigned char *str, int len, unsigned long value); + +DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE) + +DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING) +DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT) +DECLARE_ASN1_FUNCTIONS(ASN1_PRINTABLESTRING) +DECLARE_ASN1_FUNCTIONS(ASN1_T61STRING) +DECLARE_ASN1_FUNCTIONS(ASN1_IA5STRING) +DECLARE_ASN1_FUNCTIONS(ASN1_GENERALSTRING) +DECLARE_ASN1_FUNCTIONS(ASN1_UTCTIME) +DECLARE_ASN1_FUNCTIONS(ASN1_GENERALIZEDTIME) +DECLARE_ASN1_FUNCTIONS(ASN1_TIME) + +DECLARE_ASN1_ITEM(ASN1_OCTET_STRING_NDEF) + +ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t); +ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t, + int offset_day, long offset_sec); +int ASN1_TIME_check(const ASN1_TIME *t); +ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t, + ASN1_GENERALIZEDTIME **out); +int ASN1_TIME_set_string(ASN1_TIME *s, const char *str); +int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str); +int ASN1_TIME_to_tm(const ASN1_TIME *s, struct tm *tm); +int ASN1_TIME_normalize(ASN1_TIME *s); +int ASN1_TIME_cmp_time_t(const ASN1_TIME *s, time_t t); +int ASN1_TIME_compare(const ASN1_TIME *a, const ASN1_TIME *b); + +int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a); +int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size); +int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a); +int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size); +int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a); +int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size); +int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type); +int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a); + +int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num); +ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len, + const char *sn, const char *ln); + +int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a); +int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r); +int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a); +int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r); + +int ASN1_INTEGER_set(ASN1_INTEGER *a, long v); +long ASN1_INTEGER_get(const ASN1_INTEGER *a); +ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai); +BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn); + +int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a); +int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r); + + +int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v); +long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a); +ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai); +BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn); + +/* General */ +/* given a string, return the correct type, max is the maximum length */ +int ASN1_PRINTABLE_type(const unsigned char *s, int max); + +unsigned long ASN1_tag2bit(int tag); + +/* SPECIALS */ +int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag, + int *pclass, long omax); +int ASN1_check_infinite_end(unsigned char **p, long len); +int ASN1_const_check_infinite_end(const unsigned char **p, long len); +void ASN1_put_object(unsigned char **pp, int constructed, int length, + int tag, int xclass); +int ASN1_put_eoc(unsigned char **pp); +int ASN1_object_size(int constructed, int length, int tag); + +/* Used to implement other functions */ +void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, void *x); + +# define ASN1_dup_of(type,i2d,d2i,x) \ + ((type*)ASN1_dup(CHECKED_I2D_OF(type, i2d), \ + CHECKED_D2I_OF(type, d2i), \ + CHECKED_PTR_OF(type, x))) + +# define ASN1_dup_of_const(type,i2d,d2i,x) \ + ((type*)ASN1_dup(CHECKED_I2D_OF(const type, i2d), \ + CHECKED_D2I_OF(type, d2i), \ + CHECKED_PTR_OF(const type, x))) + +void *ASN1_item_dup(const ASN1_ITEM *it, void *x); + +/* ASN1 alloc/free macros for when a type is only used internally */ + +# define M_ASN1_new_of(type) (type *)ASN1_item_new(ASN1_ITEM_rptr(type)) +# define M_ASN1_free_of(x, type) \ + ASN1_item_free(CHECKED_PTR_OF(type, x), ASN1_ITEM_rptr(type)) + +# ifndef OPENSSL_NO_STDIO +void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x); + +# define ASN1_d2i_fp_of(type,xnew,d2i,in,x) \ + ((type*)ASN1_d2i_fp(CHECKED_NEW_OF(type, xnew), \ + CHECKED_D2I_OF(type, d2i), \ + in, \ + CHECKED_PPTR_OF(type, x))) + +void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x); +int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, void *x); + +# define ASN1_i2d_fp_of(type,i2d,out,x) \ + (ASN1_i2d_fp(CHECKED_I2D_OF(type, i2d), \ + out, \ + CHECKED_PTR_OF(type, x))) + +# define ASN1_i2d_fp_of_const(type,i2d,out,x) \ + (ASN1_i2d_fp(CHECKED_I2D_OF(const type, i2d), \ + out, \ + CHECKED_PTR_OF(const type, x))) + +int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x); +int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags); +# endif + +int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in); + +void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x); + +# define ASN1_d2i_bio_of(type,xnew,d2i,in,x) \ + ((type*)ASN1_d2i_bio( CHECKED_NEW_OF(type, xnew), \ + CHECKED_D2I_OF(type, d2i), \ + in, \ + CHECKED_PPTR_OF(type, x))) + +void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x); +int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, unsigned char *x); + +# define ASN1_i2d_bio_of(type,i2d,out,x) \ + (ASN1_i2d_bio(CHECKED_I2D_OF(type, i2d), \ + out, \ + CHECKED_PTR_OF(type, x))) + +# define ASN1_i2d_bio_of_const(type,i2d,out,x) \ + (ASN1_i2d_bio(CHECKED_I2D_OF(const type, i2d), \ + out, \ + CHECKED_PTR_OF(const type, x))) + +int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x); +int ASN1_UTCTIME_print(BIO *fp, const ASN1_UTCTIME *a); +int ASN1_GENERALIZEDTIME_print(BIO *fp, const ASN1_GENERALIZEDTIME *a); +int ASN1_TIME_print(BIO *fp, const ASN1_TIME *a); +int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v); +int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags); +int ASN1_buf_print(BIO *bp, const unsigned char *buf, size_t buflen, int off); +int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num, + unsigned char *buf, int off); +int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent); +int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent, + int dump); +const char *ASN1_tag2str(int tag); + +/* Used to load and write Netscape format cert */ + +int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s); + +int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len); +int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_len); +int ASN1_TYPE_set_int_octetstring(ASN1_TYPE *a, long num, + unsigned char *data, int len); +int ASN1_TYPE_get_int_octetstring(const ASN1_TYPE *a, long *num, + unsigned char *data, int max_len); + +void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it); + +ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, + ASN1_OCTET_STRING **oct); + +void ASN1_STRING_set_default_mask(unsigned long mask); +int ASN1_STRING_set_default_mask_asc(const char *p); +unsigned long ASN1_STRING_get_default_mask(void); +int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len, + int inform, unsigned long mask); +int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len, + int inform, unsigned long mask, + long minsize, long maxsize); + +ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, + const unsigned char *in, int inlen, + int inform, int nid); +ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid); +int ASN1_STRING_TABLE_add(int, long, long, unsigned long, unsigned long); +void ASN1_STRING_TABLE_cleanup(void); + +/* ASN1 template functions */ + +/* Old API compatible functions */ +ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it); +void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it); +ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **val, const unsigned char **in, + long len, const ASN1_ITEM *it); +int ASN1_item_i2d(ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it); +int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out, + const ASN1_ITEM *it); + +void ASN1_add_oid_module(void); +void ASN1_add_stable_module(void); + +ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf); +ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf); +int ASN1_str2mask(const char *str, unsigned long *pmask); + +/* ASN1 Print flags */ + +/* Indicate missing OPTIONAL fields */ +# define ASN1_PCTX_FLAGS_SHOW_ABSENT 0x001 +/* Mark start and end of SEQUENCE */ +# define ASN1_PCTX_FLAGS_SHOW_SEQUENCE 0x002 +/* Mark start and end of SEQUENCE/SET OF */ +# define ASN1_PCTX_FLAGS_SHOW_SSOF 0x004 +/* Show the ASN1 type of primitives */ +# define ASN1_PCTX_FLAGS_SHOW_TYPE 0x008 +/* Don't show ASN1 type of ANY */ +# define ASN1_PCTX_FLAGS_NO_ANY_TYPE 0x010 +/* Don't show ASN1 type of MSTRINGs */ +# define ASN1_PCTX_FLAGS_NO_MSTRING_TYPE 0x020 +/* Don't show field names in SEQUENCE */ +# define ASN1_PCTX_FLAGS_NO_FIELD_NAME 0x040 +/* Show structure names of each SEQUENCE field */ +# define ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME 0x080 +/* Don't show structure name even at top level */ +# define ASN1_PCTX_FLAGS_NO_STRUCT_NAME 0x100 + +int ASN1_item_print(BIO *out, ASN1_VALUE *ifld, int indent, + const ASN1_ITEM *it, const ASN1_PCTX *pctx); +ASN1_PCTX *ASN1_PCTX_new(void); +void ASN1_PCTX_free(ASN1_PCTX *p); +unsigned long ASN1_PCTX_get_flags(const ASN1_PCTX *p); +void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags); +unsigned long ASN1_PCTX_get_nm_flags(const ASN1_PCTX *p); +void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags); +unsigned long ASN1_PCTX_get_cert_flags(const ASN1_PCTX *p); +void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags); +unsigned long ASN1_PCTX_get_oid_flags(const ASN1_PCTX *p); +void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags); +unsigned long ASN1_PCTX_get_str_flags(const ASN1_PCTX *p); +void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags); + +ASN1_SCTX *ASN1_SCTX_new(int (*scan_cb) (ASN1_SCTX *ctx)); +void ASN1_SCTX_free(ASN1_SCTX *p); +const ASN1_ITEM *ASN1_SCTX_get_item(ASN1_SCTX *p); +const ASN1_TEMPLATE *ASN1_SCTX_get_template(ASN1_SCTX *p); +unsigned long ASN1_SCTX_get_flags(ASN1_SCTX *p); +void ASN1_SCTX_set_app_data(ASN1_SCTX *p, void *data); +void *ASN1_SCTX_get_app_data(ASN1_SCTX *p); + +const BIO_METHOD *BIO_f_asn1(void); + +BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it); + +int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags, + const ASN1_ITEM *it); +int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags, + const char *hdr, const ASN1_ITEM *it); +int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags, + int ctype_nid, int econt_nid, + STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it); +ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it); +int SMIME_crlf_copy(BIO *in, BIO *out, int flags); +int SMIME_text(BIO *in, BIO *out); + +const ASN1_ITEM *ASN1_ITEM_lookup(const char *name); +const ASN1_ITEM *ASN1_ITEM_get(size_t i); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/asn1_mac.h b/include/openssl/asn1_mac.h new file mode 100644 index 0000000..7ac1782 --- /dev/null +++ b/include/openssl/asn1_mac.h @@ -0,0 +1,10 @@ +/* + * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#error "This file is obsolete; please update your software." diff --git a/include/openssl/asn1err.h b/include/openssl/asn1err.h new file mode 100644 index 0000000..5a91126 --- /dev/null +++ b/include/openssl/asn1err.h @@ -0,0 +1,252 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ASN1ERR_H +# define HEADER_ASN1ERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_ASN1_strings(void); + +/* + * ASN1 function codes. + */ +# define ASN1_F_A2D_ASN1_OBJECT 100 +# define ASN1_F_A2I_ASN1_INTEGER 102 +# define ASN1_F_A2I_ASN1_STRING 103 +# define ASN1_F_APPEND_EXP 176 +# define ASN1_F_ASN1_BIO_INIT 113 +# define ASN1_F_ASN1_BIT_STRING_SET_BIT 183 +# define ASN1_F_ASN1_CB 177 +# define ASN1_F_ASN1_CHECK_TLEN 104 +# define ASN1_F_ASN1_COLLECT 106 +# define ASN1_F_ASN1_D2I_EX_PRIMITIVE 108 +# define ASN1_F_ASN1_D2I_FP 109 +# define ASN1_F_ASN1_D2I_READ_BIO 107 +# define ASN1_F_ASN1_DIGEST 184 +# define ASN1_F_ASN1_DO_ADB 110 +# define ASN1_F_ASN1_DO_LOCK 233 +# define ASN1_F_ASN1_DUP 111 +# define ASN1_F_ASN1_ENC_SAVE 115 +# define ASN1_F_ASN1_EX_C2I 204 +# define ASN1_F_ASN1_FIND_END 190 +# define ASN1_F_ASN1_GENERALIZEDTIME_ADJ 216 +# define ASN1_F_ASN1_GENERATE_V3 178 +# define ASN1_F_ASN1_GET_INT64 224 +# define ASN1_F_ASN1_GET_OBJECT 114 +# define ASN1_F_ASN1_GET_UINT64 225 +# define ASN1_F_ASN1_I2D_BIO 116 +# define ASN1_F_ASN1_I2D_FP 117 +# define ASN1_F_ASN1_ITEM_D2I_FP 206 +# define ASN1_F_ASN1_ITEM_DUP 191 +# define ASN1_F_ASN1_ITEM_EMBED_D2I 120 +# define ASN1_F_ASN1_ITEM_EMBED_NEW 121 +# define ASN1_F_ASN1_ITEM_FLAGS_I2D 118 +# define ASN1_F_ASN1_ITEM_I2D_BIO 192 +# define ASN1_F_ASN1_ITEM_I2D_FP 193 +# define ASN1_F_ASN1_ITEM_PACK 198 +# define ASN1_F_ASN1_ITEM_SIGN 195 +# define ASN1_F_ASN1_ITEM_SIGN_CTX 220 +# define ASN1_F_ASN1_ITEM_UNPACK 199 +# define ASN1_F_ASN1_ITEM_VERIFY 197 +# define ASN1_F_ASN1_MBSTRING_NCOPY 122 +# define ASN1_F_ASN1_OBJECT_NEW 123 +# define ASN1_F_ASN1_OUTPUT_DATA 214 +# define ASN1_F_ASN1_PCTX_NEW 205 +# define ASN1_F_ASN1_PRIMITIVE_NEW 119 +# define ASN1_F_ASN1_SCTX_NEW 221 +# define ASN1_F_ASN1_SIGN 128 +# define ASN1_F_ASN1_STR2TYPE 179 +# define ASN1_F_ASN1_STRING_GET_INT64 227 +# define ASN1_F_ASN1_STRING_GET_UINT64 230 +# define ASN1_F_ASN1_STRING_SET 186 +# define ASN1_F_ASN1_STRING_TABLE_ADD 129 +# define ASN1_F_ASN1_STRING_TO_BN 228 +# define ASN1_F_ASN1_STRING_TYPE_NEW 130 +# define ASN1_F_ASN1_TEMPLATE_EX_D2I 132 +# define ASN1_F_ASN1_TEMPLATE_NEW 133 +# define ASN1_F_ASN1_TEMPLATE_NOEXP_D2I 131 +# define ASN1_F_ASN1_TIME_ADJ 217 +# define ASN1_F_ASN1_TYPE_GET_INT_OCTETSTRING 134 +# define ASN1_F_ASN1_TYPE_GET_OCTETSTRING 135 +# define ASN1_F_ASN1_UTCTIME_ADJ 218 +# define ASN1_F_ASN1_VERIFY 137 +# define ASN1_F_B64_READ_ASN1 209 +# define ASN1_F_B64_WRITE_ASN1 210 +# define ASN1_F_BIO_NEW_NDEF 208 +# define ASN1_F_BITSTR_CB 180 +# define ASN1_F_BN_TO_ASN1_STRING 229 +# define ASN1_F_C2I_ASN1_BIT_STRING 189 +# define ASN1_F_C2I_ASN1_INTEGER 194 +# define ASN1_F_C2I_ASN1_OBJECT 196 +# define ASN1_F_C2I_IBUF 226 +# define ASN1_F_C2I_UINT64_INT 101 +# define ASN1_F_COLLECT_DATA 140 +# define ASN1_F_D2I_ASN1_OBJECT 147 +# define ASN1_F_D2I_ASN1_UINTEGER 150 +# define ASN1_F_D2I_AUTOPRIVATEKEY 207 +# define ASN1_F_D2I_PRIVATEKEY 154 +# define ASN1_F_D2I_PUBLICKEY 155 +# define ASN1_F_DO_BUF 142 +# define ASN1_F_DO_CREATE 124 +# define ASN1_F_DO_DUMP 125 +# define ASN1_F_DO_TCREATE 222 +# define ASN1_F_I2A_ASN1_OBJECT 126 +# define ASN1_F_I2D_ASN1_BIO_STREAM 211 +# define ASN1_F_I2D_ASN1_OBJECT 143 +# define ASN1_F_I2D_DSA_PUBKEY 161 +# define ASN1_F_I2D_EC_PUBKEY 181 +# define ASN1_F_I2D_PRIVATEKEY 163 +# define ASN1_F_I2D_PUBLICKEY 164 +# define ASN1_F_I2D_RSA_PUBKEY 165 +# define ASN1_F_LONG_C2I 166 +# define ASN1_F_NDEF_PREFIX 127 +# define ASN1_F_NDEF_SUFFIX 136 +# define ASN1_F_OID_MODULE_INIT 174 +# define ASN1_F_PARSE_TAGGING 182 +# define ASN1_F_PKCS5_PBE2_SET_IV 167 +# define ASN1_F_PKCS5_PBE2_SET_SCRYPT 231 +# define ASN1_F_PKCS5_PBE_SET 202 +# define ASN1_F_PKCS5_PBE_SET0_ALGOR 215 +# define ASN1_F_PKCS5_PBKDF2_SET 219 +# define ASN1_F_PKCS5_SCRYPT_SET 232 +# define ASN1_F_SMIME_READ_ASN1 212 +# define ASN1_F_SMIME_TEXT 213 +# define ASN1_F_STABLE_GET 138 +# define ASN1_F_STBL_MODULE_INIT 223 +# define ASN1_F_UINT32_C2I 105 +# define ASN1_F_UINT32_NEW 139 +# define ASN1_F_UINT64_C2I 112 +# define ASN1_F_UINT64_NEW 141 +# define ASN1_F_X509_CRL_ADD0_REVOKED 169 +# define ASN1_F_X509_INFO_NEW 170 +# define ASN1_F_X509_NAME_ENCODE 203 +# define ASN1_F_X509_NAME_EX_D2I 158 +# define ASN1_F_X509_NAME_EX_NEW 171 +# define ASN1_F_X509_PKEY_NEW 173 + +/* + * ASN1 reason codes. + */ +# define ASN1_R_ADDING_OBJECT 171 +# define ASN1_R_ASN1_PARSE_ERROR 203 +# define ASN1_R_ASN1_SIG_PARSE_ERROR 204 +# define ASN1_R_AUX_ERROR 100 +# define ASN1_R_BAD_OBJECT_HEADER 102 +# define ASN1_R_BMPSTRING_IS_WRONG_LENGTH 214 +# define ASN1_R_BN_LIB 105 +# define ASN1_R_BOOLEAN_IS_WRONG_LENGTH 106 +# define ASN1_R_BUFFER_TOO_SMALL 107 +# define ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER 108 +# define ASN1_R_CONTEXT_NOT_INITIALISED 217 +# define ASN1_R_DATA_IS_WRONG 109 +# define ASN1_R_DECODE_ERROR 110 +# define ASN1_R_DEPTH_EXCEEDED 174 +# define ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED 198 +# define ASN1_R_ENCODE_ERROR 112 +# define ASN1_R_ERROR_GETTING_TIME 173 +# define ASN1_R_ERROR_LOADING_SECTION 172 +# define ASN1_R_ERROR_SETTING_CIPHER_PARAMS 114 +# define ASN1_R_EXPECTING_AN_INTEGER 115 +# define ASN1_R_EXPECTING_AN_OBJECT 116 +# define ASN1_R_EXPLICIT_LENGTH_MISMATCH 119 +# define ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED 120 +# define ASN1_R_FIELD_MISSING 121 +# define ASN1_R_FIRST_NUM_TOO_LARGE 122 +# define ASN1_R_HEADER_TOO_LONG 123 +# define ASN1_R_ILLEGAL_BITSTRING_FORMAT 175 +# define ASN1_R_ILLEGAL_BOOLEAN 176 +# define ASN1_R_ILLEGAL_CHARACTERS 124 +# define ASN1_R_ILLEGAL_FORMAT 177 +# define ASN1_R_ILLEGAL_HEX 178 +# define ASN1_R_ILLEGAL_IMPLICIT_TAG 179 +# define ASN1_R_ILLEGAL_INTEGER 180 +# define ASN1_R_ILLEGAL_NEGATIVE_VALUE 226 +# define ASN1_R_ILLEGAL_NESTED_TAGGING 181 +# define ASN1_R_ILLEGAL_NULL 125 +# define ASN1_R_ILLEGAL_NULL_VALUE 182 +# define ASN1_R_ILLEGAL_OBJECT 183 +# define ASN1_R_ILLEGAL_OPTIONAL_ANY 126 +# define ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE 170 +# define ASN1_R_ILLEGAL_PADDING 221 +# define ASN1_R_ILLEGAL_TAGGED_ANY 127 +# define ASN1_R_ILLEGAL_TIME_VALUE 184 +# define ASN1_R_ILLEGAL_ZERO_CONTENT 222 +# define ASN1_R_INTEGER_NOT_ASCII_FORMAT 185 +# define ASN1_R_INTEGER_TOO_LARGE_FOR_LONG 128 +# define ASN1_R_INVALID_BIT_STRING_BITS_LEFT 220 +# define ASN1_R_INVALID_BMPSTRING_LENGTH 129 +# define ASN1_R_INVALID_DIGIT 130 +# define ASN1_R_INVALID_MIME_TYPE 205 +# define ASN1_R_INVALID_MODIFIER 186 +# define ASN1_R_INVALID_NUMBER 187 +# define ASN1_R_INVALID_OBJECT_ENCODING 216 +# define ASN1_R_INVALID_SCRYPT_PARAMETERS 227 +# define ASN1_R_INVALID_SEPARATOR 131 +# define ASN1_R_INVALID_STRING_TABLE_VALUE 218 +# define ASN1_R_INVALID_UNIVERSALSTRING_LENGTH 133 +# define ASN1_R_INVALID_UTF8STRING 134 +# define ASN1_R_INVALID_VALUE 219 +# define ASN1_R_LIST_ERROR 188 +# define ASN1_R_MIME_NO_CONTENT_TYPE 206 +# define ASN1_R_MIME_PARSE_ERROR 207 +# define ASN1_R_MIME_SIG_PARSE_ERROR 208 +# define ASN1_R_MISSING_EOC 137 +# define ASN1_R_MISSING_SECOND_NUMBER 138 +# define ASN1_R_MISSING_VALUE 189 +# define ASN1_R_MSTRING_NOT_UNIVERSAL 139 +# define ASN1_R_MSTRING_WRONG_TAG 140 +# define ASN1_R_NESTED_ASN1_STRING 197 +# define ASN1_R_NESTED_TOO_DEEP 201 +# define ASN1_R_NON_HEX_CHARACTERS 141 +# define ASN1_R_NOT_ASCII_FORMAT 190 +# define ASN1_R_NOT_ENOUGH_DATA 142 +# define ASN1_R_NO_CONTENT_TYPE 209 +# define ASN1_R_NO_MATCHING_CHOICE_TYPE 143 +# define ASN1_R_NO_MULTIPART_BODY_FAILURE 210 +# define ASN1_R_NO_MULTIPART_BOUNDARY 211 +# define ASN1_R_NO_SIG_CONTENT_TYPE 212 +# define ASN1_R_NULL_IS_WRONG_LENGTH 144 +# define ASN1_R_OBJECT_NOT_ASCII_FORMAT 191 +# define ASN1_R_ODD_NUMBER_OF_CHARS 145 +# define ASN1_R_SECOND_NUMBER_TOO_LARGE 147 +# define ASN1_R_SEQUENCE_LENGTH_MISMATCH 148 +# define ASN1_R_SEQUENCE_NOT_CONSTRUCTED 149 +# define ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG 192 +# define ASN1_R_SHORT_LINE 150 +# define ASN1_R_SIG_INVALID_MIME_TYPE 213 +# define ASN1_R_STREAMING_NOT_SUPPORTED 202 +# define ASN1_R_STRING_TOO_LONG 151 +# define ASN1_R_STRING_TOO_SHORT 152 +# define ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD 154 +# define ASN1_R_TIME_NOT_ASCII_FORMAT 193 +# define ASN1_R_TOO_LARGE 223 +# define ASN1_R_TOO_LONG 155 +# define ASN1_R_TOO_SMALL 224 +# define ASN1_R_TYPE_NOT_CONSTRUCTED 156 +# define ASN1_R_TYPE_NOT_PRIMITIVE 195 +# define ASN1_R_UNEXPECTED_EOC 159 +# define ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH 215 +# define ASN1_R_UNKNOWN_FORMAT 160 +# define ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM 161 +# define ASN1_R_UNKNOWN_OBJECT_TYPE 162 +# define ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE 163 +# define ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM 199 +# define ASN1_R_UNKNOWN_TAG 194 +# define ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE 164 +# define ASN1_R_UNSUPPORTED_CIPHER 228 +# define ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE 167 +# define ASN1_R_UNSUPPORTED_TYPE 196 +# define ASN1_R_WRONG_INTEGER_TYPE 225 +# define ASN1_R_WRONG_PUBLIC_KEY_TYPE 200 +# define ASN1_R_WRONG_TAG 168 + +#endif diff --git a/include/openssl/asn1t.h b/include/openssl/asn1t.h new file mode 100644 index 0000000..c629b62 --- /dev/null +++ b/include/openssl/asn1t.h @@ -0,0 +1,945 @@ +/* + * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ASN1T_H +# define HEADER_ASN1T_H + +# include +# include +# include + +# ifdef OPENSSL_BUILD_SHLIBCRYPTO +# undef OPENSSL_EXTERN +# define OPENSSL_EXTERN OPENSSL_EXPORT +# endif + +/* ASN1 template defines, structures and functions */ + +#ifdef __cplusplus +extern "C" { +#endif + +# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION + +/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */ +# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)(iptr)) + +/* Macros for start and end of ASN1_ITEM definition */ + +# define ASN1_ITEM_start(itname) \ + const ASN1_ITEM itname##_it = { + +# define static_ASN1_ITEM_start(itname) \ + static const ASN1_ITEM itname##_it = { + +# define ASN1_ITEM_end(itname) \ + }; + +# else + +/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */ +# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)((iptr)())) + +/* Macros for start and end of ASN1_ITEM definition */ + +# define ASN1_ITEM_start(itname) \ + const ASN1_ITEM * itname##_it(void) \ + { \ + static const ASN1_ITEM local_it = { + +# define static_ASN1_ITEM_start(itname) \ + static ASN1_ITEM_start(itname) + +# define ASN1_ITEM_end(itname) \ + }; \ + return &local_it; \ + } + +# endif + +/* Macros to aid ASN1 template writing */ + +# define ASN1_ITEM_TEMPLATE(tname) \ + static const ASN1_TEMPLATE tname##_item_tt + +# define ASN1_ITEM_TEMPLATE_END(tname) \ + ;\ + ASN1_ITEM_start(tname) \ + ASN1_ITYPE_PRIMITIVE,\ + -1,\ + &tname##_item_tt,\ + 0,\ + NULL,\ + 0,\ + #tname \ + ASN1_ITEM_end(tname) +# define static_ASN1_ITEM_TEMPLATE_END(tname) \ + ;\ + static_ASN1_ITEM_start(tname) \ + ASN1_ITYPE_PRIMITIVE,\ + -1,\ + &tname##_item_tt,\ + 0,\ + NULL,\ + 0,\ + #tname \ + ASN1_ITEM_end(tname) + +/* This is a ASN1 type which just embeds a template */ + +/*- + * This pair helps declare a SEQUENCE. We can do: + * + * ASN1_SEQUENCE(stname) = { + * ... SEQUENCE components ... + * } ASN1_SEQUENCE_END(stname) + * + * This will produce an ASN1_ITEM called stname_it + * for a structure called stname. + * + * If you want the same structure but a different + * name then use: + * + * ASN1_SEQUENCE(itname) = { + * ... SEQUENCE components ... + * } ASN1_SEQUENCE_END_name(stname, itname) + * + * This will create an item called itname_it using + * a structure called stname. + */ + +# define ASN1_SEQUENCE(tname) \ + static const ASN1_TEMPLATE tname##_seq_tt[] + +# define ASN1_SEQUENCE_END(stname) ASN1_SEQUENCE_END_name(stname, stname) + +# define static_ASN1_SEQUENCE_END(stname) static_ASN1_SEQUENCE_END_name(stname, stname) + +# define ASN1_SEQUENCE_END_name(stname, tname) \ + ;\ + ASN1_ITEM_start(tname) \ + ASN1_ITYPE_SEQUENCE,\ + V_ASN1_SEQUENCE,\ + tname##_seq_tt,\ + sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ + NULL,\ + sizeof(stname),\ + #tname \ + ASN1_ITEM_end(tname) + +# define static_ASN1_SEQUENCE_END_name(stname, tname) \ + ;\ + static_ASN1_ITEM_start(tname) \ + ASN1_ITYPE_SEQUENCE,\ + V_ASN1_SEQUENCE,\ + tname##_seq_tt,\ + sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ + NULL,\ + sizeof(stname),\ + #stname \ + ASN1_ITEM_end(tname) + +# define ASN1_NDEF_SEQUENCE(tname) \ + ASN1_SEQUENCE(tname) + +# define ASN1_NDEF_SEQUENCE_cb(tname, cb) \ + ASN1_SEQUENCE_cb(tname, cb) + +# define ASN1_SEQUENCE_cb(tname, cb) \ + static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0}; \ + ASN1_SEQUENCE(tname) + +# define ASN1_BROKEN_SEQUENCE(tname) \ + static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_BROKEN, 0, 0, 0, 0}; \ + ASN1_SEQUENCE(tname) + +# define ASN1_SEQUENCE_ref(tname, cb) \ + static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_REFCOUNT, offsetof(tname, references), offsetof(tname, lock), cb, 0}; \ + ASN1_SEQUENCE(tname) + +# define ASN1_SEQUENCE_enc(tname, enc, cb) \ + static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_ENCODING, 0, 0, cb, offsetof(tname, enc)}; \ + ASN1_SEQUENCE(tname) + +# define ASN1_NDEF_SEQUENCE_END(tname) \ + ;\ + ASN1_ITEM_start(tname) \ + ASN1_ITYPE_NDEF_SEQUENCE,\ + V_ASN1_SEQUENCE,\ + tname##_seq_tt,\ + sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ + NULL,\ + sizeof(tname),\ + #tname \ + ASN1_ITEM_end(tname) +# define static_ASN1_NDEF_SEQUENCE_END(tname) \ + ;\ + static_ASN1_ITEM_start(tname) \ + ASN1_ITYPE_NDEF_SEQUENCE,\ + V_ASN1_SEQUENCE,\ + tname##_seq_tt,\ + sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ + NULL,\ + sizeof(tname),\ + #tname \ + ASN1_ITEM_end(tname) + +# define ASN1_BROKEN_SEQUENCE_END(stname) ASN1_SEQUENCE_END_ref(stname, stname) +# define static_ASN1_BROKEN_SEQUENCE_END(stname) \ + static_ASN1_SEQUENCE_END_ref(stname, stname) + +# define ASN1_SEQUENCE_END_enc(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname) + +# define ASN1_SEQUENCE_END_cb(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname) +# define static_ASN1_SEQUENCE_END_cb(stname, tname) static_ASN1_SEQUENCE_END_ref(stname, tname) + +# define ASN1_SEQUENCE_END_ref(stname, tname) \ + ;\ + ASN1_ITEM_start(tname) \ + ASN1_ITYPE_SEQUENCE,\ + V_ASN1_SEQUENCE,\ + tname##_seq_tt,\ + sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ + &tname##_aux,\ + sizeof(stname),\ + #tname \ + ASN1_ITEM_end(tname) +# define static_ASN1_SEQUENCE_END_ref(stname, tname) \ + ;\ + static_ASN1_ITEM_start(tname) \ + ASN1_ITYPE_SEQUENCE,\ + V_ASN1_SEQUENCE,\ + tname##_seq_tt,\ + sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ + &tname##_aux,\ + sizeof(stname),\ + #stname \ + ASN1_ITEM_end(tname) + +# define ASN1_NDEF_SEQUENCE_END_cb(stname, tname) \ + ;\ + ASN1_ITEM_start(tname) \ + ASN1_ITYPE_NDEF_SEQUENCE,\ + V_ASN1_SEQUENCE,\ + tname##_seq_tt,\ + sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\ + &tname##_aux,\ + sizeof(stname),\ + #stname \ + ASN1_ITEM_end(tname) + +/*- + * This pair helps declare a CHOICE type. We can do: + * + * ASN1_CHOICE(chname) = { + * ... CHOICE options ... + * ASN1_CHOICE_END(chname) + * + * This will produce an ASN1_ITEM called chname_it + * for a structure called chname. The structure + * definition must look like this: + * typedef struct { + * int type; + * union { + * ASN1_SOMETHING *opt1; + * ASN1_SOMEOTHER *opt2; + * } value; + * } chname; + * + * the name of the selector must be 'type'. + * to use an alternative selector name use the + * ASN1_CHOICE_END_selector() version. + */ + +# define ASN1_CHOICE(tname) \ + static const ASN1_TEMPLATE tname##_ch_tt[] + +# define ASN1_CHOICE_cb(tname, cb) \ + static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0}; \ + ASN1_CHOICE(tname) + +# define ASN1_CHOICE_END(stname) ASN1_CHOICE_END_name(stname, stname) + +# define static_ASN1_CHOICE_END(stname) static_ASN1_CHOICE_END_name(stname, stname) + +# define ASN1_CHOICE_END_name(stname, tname) ASN1_CHOICE_END_selector(stname, tname, type) + +# define static_ASN1_CHOICE_END_name(stname, tname) static_ASN1_CHOICE_END_selector(stname, tname, type) + +# define ASN1_CHOICE_END_selector(stname, tname, selname) \ + ;\ + ASN1_ITEM_start(tname) \ + ASN1_ITYPE_CHOICE,\ + offsetof(stname,selname) ,\ + tname##_ch_tt,\ + sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\ + NULL,\ + sizeof(stname),\ + #stname \ + ASN1_ITEM_end(tname) + +# define static_ASN1_CHOICE_END_selector(stname, tname, selname) \ + ;\ + static_ASN1_ITEM_start(tname) \ + ASN1_ITYPE_CHOICE,\ + offsetof(stname,selname) ,\ + tname##_ch_tt,\ + sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\ + NULL,\ + sizeof(stname),\ + #stname \ + ASN1_ITEM_end(tname) + +# define ASN1_CHOICE_END_cb(stname, tname, selname) \ + ;\ + ASN1_ITEM_start(tname) \ + ASN1_ITYPE_CHOICE,\ + offsetof(stname,selname) ,\ + tname##_ch_tt,\ + sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\ + &tname##_aux,\ + sizeof(stname),\ + #stname \ + ASN1_ITEM_end(tname) + +/* This helps with the template wrapper form of ASN1_ITEM */ + +# define ASN1_EX_TEMPLATE_TYPE(flags, tag, name, type) { \ + (flags), (tag), 0,\ + #name, ASN1_ITEM_ref(type) } + +/* These help with SEQUENCE or CHOICE components */ + +/* used to declare other types */ + +# define ASN1_EX_TYPE(flags, tag, stname, field, type) { \ + (flags), (tag), offsetof(stname, field),\ + #field, ASN1_ITEM_ref(type) } + +/* implicit and explicit helper macros */ + +# define ASN1_IMP_EX(stname, field, type, tag, ex) \ + ASN1_EX_TYPE(ASN1_TFLG_IMPLICIT | (ex), tag, stname, field, type) + +# define ASN1_EXP_EX(stname, field, type, tag, ex) \ + ASN1_EX_TYPE(ASN1_TFLG_EXPLICIT | (ex), tag, stname, field, type) + +/* Any defined by macros: the field used is in the table itself */ + +# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION +# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) } +# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) } +# else +# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, tblname##_adb } +# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, tblname##_adb } +# endif +/* Plain simple type */ +# define ASN1_SIMPLE(stname, field, type) ASN1_EX_TYPE(0,0, stname, field, type) +/* Embedded simple type */ +# define ASN1_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_EMBED,0, stname, field, type) + +/* OPTIONAL simple type */ +# define ASN1_OPT(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL, 0, stname, field, type) +# define ASN1_OPT_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED, 0, stname, field, type) + +/* IMPLICIT tagged simple type */ +# define ASN1_IMP(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, 0) +# define ASN1_IMP_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_EMBED) + +/* IMPLICIT tagged OPTIONAL simple type */ +# define ASN1_IMP_OPT(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL) +# define ASN1_IMP_OPT_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED) + +/* Same as above but EXPLICIT */ + +# define ASN1_EXP(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, 0) +# define ASN1_EXP_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_EMBED) +# define ASN1_EXP_OPT(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL) +# define ASN1_EXP_OPT_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED) + +/* SEQUENCE OF type */ +# define ASN1_SEQUENCE_OF(stname, field, type) \ + ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, stname, field, type) + +/* OPTIONAL SEQUENCE OF */ +# define ASN1_SEQUENCE_OF_OPT(stname, field, type) \ + ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type) + +/* Same as above but for SET OF */ + +# define ASN1_SET_OF(stname, field, type) \ + ASN1_EX_TYPE(ASN1_TFLG_SET_OF, 0, stname, field, type) + +# define ASN1_SET_OF_OPT(stname, field, type) \ + ASN1_EX_TYPE(ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type) + +/* Finally compound types of SEQUENCE, SET, IMPLICIT, EXPLICIT and OPTIONAL */ + +# define ASN1_IMP_SET_OF(stname, field, type, tag) \ + ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF) + +# define ASN1_EXP_SET_OF(stname, field, type, tag) \ + ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF) + +# define ASN1_IMP_SET_OF_OPT(stname, field, type, tag) \ + ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL) + +# define ASN1_EXP_SET_OF_OPT(stname, field, type, tag) \ + ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL) + +# define ASN1_IMP_SEQUENCE_OF(stname, field, type, tag) \ + ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF) + +# define ASN1_IMP_SEQUENCE_OF_OPT(stname, field, type, tag) \ + ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL) + +# define ASN1_EXP_SEQUENCE_OF(stname, field, type, tag) \ + ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF) + +# define ASN1_EXP_SEQUENCE_OF_OPT(stname, field, type, tag) \ + ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL) + +/* EXPLICIT using indefinite length constructed form */ +# define ASN1_NDEF_EXP(stname, field, type, tag) \ + ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_NDEF) + +/* EXPLICIT OPTIONAL using indefinite length constructed form */ +# define ASN1_NDEF_EXP_OPT(stname, field, type, tag) \ + ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_NDEF) + +/* Macros for the ASN1_ADB structure */ + +# define ASN1_ADB(name) \ + static const ASN1_ADB_TABLE name##_adbtbl[] + +# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION + +# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \ + ;\ + static const ASN1_ADB name##_adb = {\ + flags,\ + offsetof(name, field),\ + adb_cb,\ + name##_adbtbl,\ + sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\ + def,\ + none\ + } + +# else + +# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \ + ;\ + static const ASN1_ITEM *name##_adb(void) \ + { \ + static const ASN1_ADB internal_adb = \ + {\ + flags,\ + offsetof(name, field),\ + adb_cb,\ + name##_adbtbl,\ + sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\ + def,\ + none\ + }; \ + return (const ASN1_ITEM *) &internal_adb; \ + } \ + void dummy_function(void) + +# endif + +# define ADB_ENTRY(val, template) {val, template} + +# define ASN1_ADB_TEMPLATE(name) \ + static const ASN1_TEMPLATE name##_tt + +/* + * This is the ASN1 template structure that defines a wrapper round the + * actual type. It determines the actual position of the field in the value + * structure, various flags such as OPTIONAL and the field name. + */ + +struct ASN1_TEMPLATE_st { + unsigned long flags; /* Various flags */ + long tag; /* tag, not used if no tagging */ + unsigned long offset; /* Offset of this field in structure */ + const char *field_name; /* Field name */ + ASN1_ITEM_EXP *item; /* Relevant ASN1_ITEM or ASN1_ADB */ +}; + +/* Macro to extract ASN1_ITEM and ASN1_ADB pointer from ASN1_TEMPLATE */ + +# define ASN1_TEMPLATE_item(t) (t->item_ptr) +# define ASN1_TEMPLATE_adb(t) (t->item_ptr) + +typedef struct ASN1_ADB_TABLE_st ASN1_ADB_TABLE; +typedef struct ASN1_ADB_st ASN1_ADB; + +struct ASN1_ADB_st { + unsigned long flags; /* Various flags */ + unsigned long offset; /* Offset of selector field */ + int (*adb_cb)(long *psel); /* Application callback */ + const ASN1_ADB_TABLE *tbl; /* Table of possible types */ + long tblcount; /* Number of entries in tbl */ + const ASN1_TEMPLATE *default_tt; /* Type to use if no match */ + const ASN1_TEMPLATE *null_tt; /* Type to use if selector is NULL */ +}; + +struct ASN1_ADB_TABLE_st { + long value; /* NID for an object or value for an int */ + const ASN1_TEMPLATE tt; /* item for this value */ +}; + +/* template flags */ + +/* Field is optional */ +# define ASN1_TFLG_OPTIONAL (0x1) + +/* Field is a SET OF */ +# define ASN1_TFLG_SET_OF (0x1 << 1) + +/* Field is a SEQUENCE OF */ +# define ASN1_TFLG_SEQUENCE_OF (0x2 << 1) + +/* + * Special case: this refers to a SET OF that will be sorted into DER order + * when encoded *and* the corresponding STACK will be modified to match the + * new order. + */ +# define ASN1_TFLG_SET_ORDER (0x3 << 1) + +/* Mask for SET OF or SEQUENCE OF */ +# define ASN1_TFLG_SK_MASK (0x3 << 1) + +/* + * These flags mean the tag should be taken from the tag field. If EXPLICIT + * then the underlying type is used for the inner tag. + */ + +/* IMPLICIT tagging */ +# define ASN1_TFLG_IMPTAG (0x1 << 3) + +/* EXPLICIT tagging, inner tag from underlying type */ +# define ASN1_TFLG_EXPTAG (0x2 << 3) + +# define ASN1_TFLG_TAG_MASK (0x3 << 3) + +/* context specific IMPLICIT */ +# define ASN1_TFLG_IMPLICIT (ASN1_TFLG_IMPTAG|ASN1_TFLG_CONTEXT) + +/* context specific EXPLICIT */ +# define ASN1_TFLG_EXPLICIT (ASN1_TFLG_EXPTAG|ASN1_TFLG_CONTEXT) + +/* + * If tagging is in force these determine the type of tag to use. Otherwise + * the tag is determined by the underlying type. These values reflect the + * actual octet format. + */ + +/* Universal tag */ +# define ASN1_TFLG_UNIVERSAL (0x0<<6) +/* Application tag */ +# define ASN1_TFLG_APPLICATION (0x1<<6) +/* Context specific tag */ +# define ASN1_TFLG_CONTEXT (0x2<<6) +/* Private tag */ +# define ASN1_TFLG_PRIVATE (0x3<<6) + +# define ASN1_TFLG_TAG_CLASS (0x3<<6) + +/* + * These are for ANY DEFINED BY type. In this case the 'item' field points to + * an ASN1_ADB structure which contains a table of values to decode the + * relevant type + */ + +# define ASN1_TFLG_ADB_MASK (0x3<<8) + +# define ASN1_TFLG_ADB_OID (0x1<<8) + +# define ASN1_TFLG_ADB_INT (0x1<<9) + +/* + * This flag when present in a SEQUENCE OF, SET OF or EXPLICIT causes + * indefinite length constructed encoding to be used if required. + */ + +# define ASN1_TFLG_NDEF (0x1<<11) + +/* Field is embedded and not a pointer */ +# define ASN1_TFLG_EMBED (0x1 << 12) + +/* This is the actual ASN1 item itself */ + +struct ASN1_ITEM_st { + char itype; /* The item type, primitive, SEQUENCE, CHOICE + * or extern */ + long utype; /* underlying type */ + const ASN1_TEMPLATE *templates; /* If SEQUENCE or CHOICE this contains + * the contents */ + long tcount; /* Number of templates if SEQUENCE or CHOICE */ + const void *funcs; /* functions that handle this type */ + long size; /* Structure size (usually) */ + const char *sname; /* Structure name */ +}; + +/*- + * These are values for the itype field and + * determine how the type is interpreted. + * + * For PRIMITIVE types the underlying type + * determines the behaviour if items is NULL. + * + * Otherwise templates must contain a single + * template and the type is treated in the + * same way as the type specified in the template. + * + * For SEQUENCE types the templates field points + * to the members, the size field is the + * structure size. + * + * For CHOICE types the templates field points + * to each possible member (typically a union) + * and the 'size' field is the offset of the + * selector. + * + * The 'funcs' field is used for application + * specific functions. + * + * The EXTERN type uses a new style d2i/i2d. + * The new style should be used where possible + * because it avoids things like the d2i IMPLICIT + * hack. + * + * MSTRING is a multiple string type, it is used + * for a CHOICE of character strings where the + * actual strings all occupy an ASN1_STRING + * structure. In this case the 'utype' field + * has a special meaning, it is used as a mask + * of acceptable types using the B_ASN1 constants. + * + * NDEF_SEQUENCE is the same as SEQUENCE except + * that it will use indefinite length constructed + * encoding if requested. + * + */ + +# define ASN1_ITYPE_PRIMITIVE 0x0 + +# define ASN1_ITYPE_SEQUENCE 0x1 + +# define ASN1_ITYPE_CHOICE 0x2 + +# define ASN1_ITYPE_EXTERN 0x4 + +# define ASN1_ITYPE_MSTRING 0x5 + +# define ASN1_ITYPE_NDEF_SEQUENCE 0x6 + +/* + * Cache for ASN1 tag and length, so we don't keep re-reading it for things + * like CHOICE + */ + +struct ASN1_TLC_st { + char valid; /* Values below are valid */ + int ret; /* return value */ + long plen; /* length */ + int ptag; /* class value */ + int pclass; /* class value */ + int hdrlen; /* header length */ +}; + +/* Typedefs for ASN1 function pointers */ +typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, + const ASN1_ITEM *it, int tag, int aclass, char opt, + ASN1_TLC *ctx); + +typedef int ASN1_ex_i2d(ASN1_VALUE **pval, unsigned char **out, + const ASN1_ITEM *it, int tag, int aclass); +typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it); +typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it); + +typedef int ASN1_ex_print_func(BIO *out, ASN1_VALUE **pval, + int indent, const char *fname, + const ASN1_PCTX *pctx); + +typedef int ASN1_primitive_i2c(ASN1_VALUE **pval, unsigned char *cont, + int *putype, const ASN1_ITEM *it); +typedef int ASN1_primitive_c2i(ASN1_VALUE **pval, const unsigned char *cont, + int len, int utype, char *free_cont, + const ASN1_ITEM *it); +typedef int ASN1_primitive_print(BIO *out, ASN1_VALUE **pval, + const ASN1_ITEM *it, int indent, + const ASN1_PCTX *pctx); + +typedef struct ASN1_EXTERN_FUNCS_st { + void *app_data; + ASN1_ex_new_func *asn1_ex_new; + ASN1_ex_free_func *asn1_ex_free; + ASN1_ex_free_func *asn1_ex_clear; + ASN1_ex_d2i *asn1_ex_d2i; + ASN1_ex_i2d *asn1_ex_i2d; + ASN1_ex_print_func *asn1_ex_print; +} ASN1_EXTERN_FUNCS; + +typedef struct ASN1_PRIMITIVE_FUNCS_st { + void *app_data; + unsigned long flags; + ASN1_ex_new_func *prim_new; + ASN1_ex_free_func *prim_free; + ASN1_ex_free_func *prim_clear; + ASN1_primitive_c2i *prim_c2i; + ASN1_primitive_i2c *prim_i2c; + ASN1_primitive_print *prim_print; +} ASN1_PRIMITIVE_FUNCS; + +/* + * This is the ASN1_AUX structure: it handles various miscellaneous + * requirements. For example the use of reference counts and an informational + * callback. The "informational callback" is called at various points during + * the ASN1 encoding and decoding. It can be used to provide minor + * customisation of the structures used. This is most useful where the + * supplied routines *almost* do the right thing but need some extra help at + * a few points. If the callback returns zero then it is assumed a fatal + * error has occurred and the main operation should be abandoned. If major + * changes in the default behaviour are required then an external type is + * more appropriate. + */ + +typedef int ASN1_aux_cb(int operation, ASN1_VALUE **in, const ASN1_ITEM *it, + void *exarg); + +typedef struct ASN1_AUX_st { + void *app_data; + int flags; + int ref_offset; /* Offset of reference value */ + int ref_lock; /* Lock type to use */ + ASN1_aux_cb *asn1_cb; + int enc_offset; /* Offset of ASN1_ENCODING structure */ +} ASN1_AUX; + +/* For print related callbacks exarg points to this structure */ +typedef struct ASN1_PRINT_ARG_st { + BIO *out; + int indent; + const ASN1_PCTX *pctx; +} ASN1_PRINT_ARG; + +/* For streaming related callbacks exarg points to this structure */ +typedef struct ASN1_STREAM_ARG_st { + /* BIO to stream through */ + BIO *out; + /* BIO with filters appended */ + BIO *ndef_bio; + /* Streaming I/O boundary */ + unsigned char **boundary; +} ASN1_STREAM_ARG; + +/* Flags in ASN1_AUX */ + +/* Use a reference count */ +# define ASN1_AFLG_REFCOUNT 1 +/* Save the encoding of structure (useful for signatures) */ +# define ASN1_AFLG_ENCODING 2 +/* The Sequence length is invalid */ +# define ASN1_AFLG_BROKEN 4 + +/* operation values for asn1_cb */ + +# define ASN1_OP_NEW_PRE 0 +# define ASN1_OP_NEW_POST 1 +# define ASN1_OP_FREE_PRE 2 +# define ASN1_OP_FREE_POST 3 +# define ASN1_OP_D2I_PRE 4 +# define ASN1_OP_D2I_POST 5 +# define ASN1_OP_I2D_PRE 6 +# define ASN1_OP_I2D_POST 7 +# define ASN1_OP_PRINT_PRE 8 +# define ASN1_OP_PRINT_POST 9 +# define ASN1_OP_STREAM_PRE 10 +# define ASN1_OP_STREAM_POST 11 +# define ASN1_OP_DETACHED_PRE 12 +# define ASN1_OP_DETACHED_POST 13 + +/* Macro to implement a primitive type */ +# define IMPLEMENT_ASN1_TYPE(stname) IMPLEMENT_ASN1_TYPE_ex(stname, stname, 0) +# define IMPLEMENT_ASN1_TYPE_ex(itname, vname, ex) \ + ASN1_ITEM_start(itname) \ + ASN1_ITYPE_PRIMITIVE, V_##vname, NULL, 0, NULL, ex, #itname \ + ASN1_ITEM_end(itname) + +/* Macro to implement a multi string type */ +# define IMPLEMENT_ASN1_MSTRING(itname, mask) \ + ASN1_ITEM_start(itname) \ + ASN1_ITYPE_MSTRING, mask, NULL, 0, NULL, sizeof(ASN1_STRING), #itname \ + ASN1_ITEM_end(itname) + +# define IMPLEMENT_EXTERN_ASN1(sname, tag, fptrs) \ + ASN1_ITEM_start(sname) \ + ASN1_ITYPE_EXTERN, \ + tag, \ + NULL, \ + 0, \ + &fptrs, \ + 0, \ + #sname \ + ASN1_ITEM_end(sname) + +/* Macro to implement standard functions in terms of ASN1_ITEM structures */ + +# define IMPLEMENT_ASN1_FUNCTIONS(stname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, stname, stname) + +# define IMPLEMENT_ASN1_FUNCTIONS_name(stname, itname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, itname) + +# define IMPLEMENT_ASN1_FUNCTIONS_ENCODE_name(stname, itname) \ + IMPLEMENT_ASN1_FUNCTIONS_ENCODE_fname(stname, itname, itname) + +# define IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(stname) \ + IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(static, stname, stname, stname) + +# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS(stname) \ + IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, stname, stname) + +# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(pre, stname, itname, fname) \ + pre stname *fname##_new(void) \ + { \ + return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \ + } \ + pre void fname##_free(stname *a) \ + { \ + ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \ + } + +# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) \ + stname *fname##_new(void) \ + { \ + return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \ + } \ + void fname##_free(stname *a) \ + { \ + ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \ + } + +# define IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, fname) \ + IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \ + IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) + +# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \ + stname *d2i_##fname(stname **a, const unsigned char **in, long len) \ + { \ + return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\ + } \ + int i2d_##fname(stname *a, unsigned char **out) \ + { \ + return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\ + } + +# define IMPLEMENT_ASN1_NDEF_FUNCTION(stname) \ + int i2d_##stname##_NDEF(stname *a, unsigned char **out) \ + { \ + return ASN1_item_ndef_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(stname));\ + } + +# define IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(stname) \ + static stname *d2i_##stname(stname **a, \ + const unsigned char **in, long len) \ + { \ + return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, \ + ASN1_ITEM_rptr(stname)); \ + } \ + static int i2d_##stname(stname *a, unsigned char **out) \ + { \ + return ASN1_item_i2d((ASN1_VALUE *)a, out, \ + ASN1_ITEM_rptr(stname)); \ + } + +/* + * This includes evil casts to remove const: they will go away when full ASN1 + * constification is done. + */ +# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \ + stname *d2i_##fname(stname **a, const unsigned char **in, long len) \ + { \ + return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\ + } \ + int i2d_##fname(const stname *a, unsigned char **out) \ + { \ + return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\ + } + +# define IMPLEMENT_ASN1_DUP_FUNCTION(stname) \ + stname * stname##_dup(stname *x) \ + { \ + return ASN1_item_dup(ASN1_ITEM_rptr(stname), x); \ + } + +# define IMPLEMENT_ASN1_PRINT_FUNCTION(stname) \ + IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, stname, stname) + +# define IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, itname, fname) \ + int fname##_print_ctx(BIO *out, stname *x, int indent, \ + const ASN1_PCTX *pctx) \ + { \ + return ASN1_item_print(out, (ASN1_VALUE *)x, indent, \ + ASN1_ITEM_rptr(itname), pctx); \ + } + +# define IMPLEMENT_ASN1_FUNCTIONS_const(name) \ + IMPLEMENT_ASN1_FUNCTIONS_const_fname(name, name, name) + +# define IMPLEMENT_ASN1_FUNCTIONS_const_fname(stname, itname, fname) \ + IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \ + IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) + +/* external definitions for primitive types */ + +DECLARE_ASN1_ITEM(ASN1_BOOLEAN) +DECLARE_ASN1_ITEM(ASN1_TBOOLEAN) +DECLARE_ASN1_ITEM(ASN1_FBOOLEAN) +DECLARE_ASN1_ITEM(ASN1_SEQUENCE) +DECLARE_ASN1_ITEM(CBIGNUM) +DECLARE_ASN1_ITEM(BIGNUM) +DECLARE_ASN1_ITEM(INT32) +DECLARE_ASN1_ITEM(ZINT32) +DECLARE_ASN1_ITEM(UINT32) +DECLARE_ASN1_ITEM(ZUINT32) +DECLARE_ASN1_ITEM(INT64) +DECLARE_ASN1_ITEM(ZINT64) +DECLARE_ASN1_ITEM(UINT64) +DECLARE_ASN1_ITEM(ZUINT64) + +# if OPENSSL_API_COMPAT < 0x10200000L +/* + * LONG and ZLONG are strongly discouraged for use as stored data, as the + * underlying C type (long) differs in size depending on the architecture. + * They are designed with 32-bit longs in mind. + */ +DECLARE_ASN1_ITEM(LONG) +DECLARE_ASN1_ITEM(ZLONG) +# endif + +DEFINE_STACK_OF(ASN1_VALUE) + +/* Functions used internally by the ASN1 code */ + +int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it); +void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it); + +int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, + const ASN1_ITEM *it, int tag, int aclass, char opt, + ASN1_TLC *ctx); + +int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out, + const ASN1_ITEM *it, int tag, int aclass); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/async.h b/include/openssl/async.h new file mode 100644 index 0000000..92e56e8 --- /dev/null +++ b/include/openssl/async.h @@ -0,0 +1,76 @@ +/* + * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +#ifndef HEADER_ASYNC_H +# define HEADER_ASYNC_H + +#if defined(_WIN32) +# if defined(BASETYPES) || defined(_WINDEF_H) +/* application has to include to use this */ +#define OSSL_ASYNC_FD HANDLE +#define OSSL_BAD_ASYNC_FD INVALID_HANDLE_VALUE +# endif +#else +#define OSSL_ASYNC_FD int +#define OSSL_BAD_ASYNC_FD -1 +#endif +# include + + +# ifdef __cplusplus +extern "C" { +# endif + +typedef struct async_job_st ASYNC_JOB; +typedef struct async_wait_ctx_st ASYNC_WAIT_CTX; + +#define ASYNC_ERR 0 +#define ASYNC_NO_JOBS 1 +#define ASYNC_PAUSE 2 +#define ASYNC_FINISH 3 + +int ASYNC_init_thread(size_t max_size, size_t init_size); +void ASYNC_cleanup_thread(void); + +#ifdef OSSL_ASYNC_FD +ASYNC_WAIT_CTX *ASYNC_WAIT_CTX_new(void); +void ASYNC_WAIT_CTX_free(ASYNC_WAIT_CTX *ctx); +int ASYNC_WAIT_CTX_set_wait_fd(ASYNC_WAIT_CTX *ctx, const void *key, + OSSL_ASYNC_FD fd, + void *custom_data, + void (*cleanup)(ASYNC_WAIT_CTX *, const void *, + OSSL_ASYNC_FD, void *)); +int ASYNC_WAIT_CTX_get_fd(ASYNC_WAIT_CTX *ctx, const void *key, + OSSL_ASYNC_FD *fd, void **custom_data); +int ASYNC_WAIT_CTX_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd, + size_t *numfds); +int ASYNC_WAIT_CTX_get_changed_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *addfd, + size_t *numaddfds, OSSL_ASYNC_FD *delfd, + size_t *numdelfds); +int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key); +#endif + +int ASYNC_is_capable(void); + +int ASYNC_start_job(ASYNC_JOB **job, ASYNC_WAIT_CTX *ctx, int *ret, + int (*func)(void *), void *args, size_t size); +int ASYNC_pause_job(void); + +ASYNC_JOB *ASYNC_get_current_job(void); +ASYNC_WAIT_CTX *ASYNC_get_wait_ctx(ASYNC_JOB *job); +void ASYNC_block_pause(void); +void ASYNC_unblock_pause(void); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/asyncerr.h b/include/openssl/asyncerr.h new file mode 100644 index 0000000..5497ba7 --- /dev/null +++ b/include/openssl/asyncerr.h @@ -0,0 +1,38 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ASYNCERR_H +# define HEADER_ASYNCERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_ASYNC_strings(void); + +/* + * ASYNC function codes. + */ +# define ASYNC_F_ASYNC_CTX_NEW 100 +# define ASYNC_F_ASYNC_INIT_THREAD 101 +# define ASYNC_F_ASYNC_JOB_NEW 102 +# define ASYNC_F_ASYNC_PAUSE_JOB 103 +# define ASYNC_F_ASYNC_START_FUNC 104 +# define ASYNC_F_ASYNC_START_JOB 105 +# define ASYNC_F_ASYNC_WAIT_CTX_SET_WAIT_FD 106 + +/* + * ASYNC reason codes. + */ +# define ASYNC_R_FAILED_TO_SET_POOL 101 +# define ASYNC_R_FAILED_TO_SWAP_CONTEXT 102 +# define ASYNC_R_INIT_FAILED 105 +# define ASYNC_R_INVALID_POOL_SIZE 103 + +#endif diff --git a/include/openssl/bio.h b/include/openssl/bio.h new file mode 100644 index 0000000..c0e85cc --- /dev/null +++ b/include/openssl/bio.h @@ -0,0 +1,804 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BIO_H +# define HEADER_BIO_H + +# include + +# ifndef OPENSSL_NO_STDIO +# include +# endif +# include + +# include +# include + +# ifndef OPENSSL_NO_SCTP +# include +# endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* There are the classes of BIOs */ +# define BIO_TYPE_DESCRIPTOR 0x0100 /* socket, fd, connect or accept */ +# define BIO_TYPE_FILTER 0x0200 +# define BIO_TYPE_SOURCE_SINK 0x0400 + +/* These are the 'types' of BIOs */ +# define BIO_TYPE_NONE 0 +# define BIO_TYPE_MEM ( 1|BIO_TYPE_SOURCE_SINK) +# define BIO_TYPE_FILE ( 2|BIO_TYPE_SOURCE_SINK) + +# define BIO_TYPE_FD ( 4|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR) +# define BIO_TYPE_SOCKET ( 5|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR) +# define BIO_TYPE_NULL ( 6|BIO_TYPE_SOURCE_SINK) +# define BIO_TYPE_SSL ( 7|BIO_TYPE_FILTER) +# define BIO_TYPE_MD ( 8|BIO_TYPE_FILTER) +# define BIO_TYPE_BUFFER ( 9|BIO_TYPE_FILTER) +# define BIO_TYPE_CIPHER (10|BIO_TYPE_FILTER) +# define BIO_TYPE_BASE64 (11|BIO_TYPE_FILTER) +# define BIO_TYPE_CONNECT (12|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR) +# define BIO_TYPE_ACCEPT (13|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR) + +# define BIO_TYPE_NBIO_TEST (16|BIO_TYPE_FILTER)/* server proxy BIO */ +# define BIO_TYPE_NULL_FILTER (17|BIO_TYPE_FILTER) +# define BIO_TYPE_BIO (19|BIO_TYPE_SOURCE_SINK)/* half a BIO pair */ +# define BIO_TYPE_LINEBUFFER (20|BIO_TYPE_FILTER) +# define BIO_TYPE_DGRAM (21|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR) +# define BIO_TYPE_ASN1 (22|BIO_TYPE_FILTER) +# define BIO_TYPE_COMP (23|BIO_TYPE_FILTER) +# ifndef OPENSSL_NO_SCTP +# define BIO_TYPE_DGRAM_SCTP (24|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR) +# endif + +#define BIO_TYPE_START 128 + +/* + * BIO_FILENAME_READ|BIO_CLOSE to open or close on free. + * BIO_set_fp(in,stdin,BIO_NOCLOSE); + */ +# define BIO_NOCLOSE 0x00 +# define BIO_CLOSE 0x01 + +/* + * These are used in the following macros and are passed to BIO_ctrl() + */ +# define BIO_CTRL_RESET 1/* opt - rewind/zero etc */ +# define BIO_CTRL_EOF 2/* opt - are we at the eof */ +# define BIO_CTRL_INFO 3/* opt - extra tit-bits */ +# define BIO_CTRL_SET 4/* man - set the 'IO' type */ +# define BIO_CTRL_GET 5/* man - get the 'IO' type */ +# define BIO_CTRL_PUSH 6/* opt - internal, used to signify change */ +# define BIO_CTRL_POP 7/* opt - internal, used to signify change */ +# define BIO_CTRL_GET_CLOSE 8/* man - set the 'close' on free */ +# define BIO_CTRL_SET_CLOSE 9/* man - set the 'close' on free */ +# define BIO_CTRL_PENDING 10/* opt - is their more data buffered */ +# define BIO_CTRL_FLUSH 11/* opt - 'flush' buffered output */ +# define BIO_CTRL_DUP 12/* man - extra stuff for 'duped' BIO */ +# define BIO_CTRL_WPENDING 13/* opt - number of bytes still to write */ +# define BIO_CTRL_SET_CALLBACK 14/* opt - set callback function */ +# define BIO_CTRL_GET_CALLBACK 15/* opt - set callback function */ + +# define BIO_CTRL_PEEK 29/* BIO_f_buffer special */ +# define BIO_CTRL_SET_FILENAME 30/* BIO_s_file special */ + +/* dgram BIO stuff */ +# define BIO_CTRL_DGRAM_CONNECT 31/* BIO dgram special */ +# define BIO_CTRL_DGRAM_SET_CONNECTED 32/* allow for an externally connected + * socket to be passed in */ +# define BIO_CTRL_DGRAM_SET_RECV_TIMEOUT 33/* setsockopt, essentially */ +# define BIO_CTRL_DGRAM_GET_RECV_TIMEOUT 34/* getsockopt, essentially */ +# define BIO_CTRL_DGRAM_SET_SEND_TIMEOUT 35/* setsockopt, essentially */ +# define BIO_CTRL_DGRAM_GET_SEND_TIMEOUT 36/* getsockopt, essentially */ + +# define BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP 37/* flag whether the last */ +# define BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP 38/* I/O operation tiemd out */ + +/* #ifdef IP_MTU_DISCOVER */ +# define BIO_CTRL_DGRAM_MTU_DISCOVER 39/* set DF bit on egress packets */ +/* #endif */ + +# define BIO_CTRL_DGRAM_QUERY_MTU 40/* as kernel for current MTU */ +# define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47 +# define BIO_CTRL_DGRAM_GET_MTU 41/* get cached value for MTU */ +# define BIO_CTRL_DGRAM_SET_MTU 42/* set cached value for MTU. + * want to use this if asking + * the kernel fails */ + +# define BIO_CTRL_DGRAM_MTU_EXCEEDED 43/* check whether the MTU was + * exceed in the previous write + * operation */ + +# define BIO_CTRL_DGRAM_GET_PEER 46 +# define BIO_CTRL_DGRAM_SET_PEER 44/* Destination for the data */ + +# define BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT 45/* Next DTLS handshake timeout + * to adjust socket timeouts */ +# define BIO_CTRL_DGRAM_SET_DONT_FRAG 48 + +# define BIO_CTRL_DGRAM_GET_MTU_OVERHEAD 49 + +/* Deliberately outside of OPENSSL_NO_SCTP - used in bss_dgram.c */ +# define BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE 50 +# ifndef OPENSSL_NO_SCTP +/* SCTP stuff */ +# define BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY 51 +# define BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY 52 +# define BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD 53 +# define BIO_CTRL_DGRAM_SCTP_GET_SNDINFO 60 +# define BIO_CTRL_DGRAM_SCTP_SET_SNDINFO 61 +# define BIO_CTRL_DGRAM_SCTP_GET_RCVINFO 62 +# define BIO_CTRL_DGRAM_SCTP_SET_RCVINFO 63 +# define BIO_CTRL_DGRAM_SCTP_GET_PRINFO 64 +# define BIO_CTRL_DGRAM_SCTP_SET_PRINFO 65 +# define BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN 70 +# endif + +# define BIO_CTRL_DGRAM_SET_PEEK_MODE 71 + +/* modifiers */ +# define BIO_FP_READ 0x02 +# define BIO_FP_WRITE 0x04 +# define BIO_FP_APPEND 0x08 +# define BIO_FP_TEXT 0x10 + +# define BIO_FLAGS_READ 0x01 +# define BIO_FLAGS_WRITE 0x02 +# define BIO_FLAGS_IO_SPECIAL 0x04 +# define BIO_FLAGS_RWS (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL) +# define BIO_FLAGS_SHOULD_RETRY 0x08 +# ifndef BIO_FLAGS_UPLINK +/* + * "UPLINK" flag denotes file descriptors provided by application. It + * defaults to 0, as most platforms don't require UPLINK interface. + */ +# define BIO_FLAGS_UPLINK 0 +# endif + +# define BIO_FLAGS_BASE64_NO_NL 0x100 + +/* + * This is used with memory BIOs: + * BIO_FLAGS_MEM_RDONLY means we shouldn't free up or change the data in any way; + * BIO_FLAGS_NONCLEAR_RST means we shouldn't clear data on reset. + */ +# define BIO_FLAGS_MEM_RDONLY 0x200 +# define BIO_FLAGS_NONCLEAR_RST 0x400 + +typedef union bio_addr_st BIO_ADDR; +typedef struct bio_addrinfo_st BIO_ADDRINFO; + +int BIO_get_new_index(void); +void BIO_set_flags(BIO *b, int flags); +int BIO_test_flags(const BIO *b, int flags); +void BIO_clear_flags(BIO *b, int flags); + +# define BIO_get_flags(b) BIO_test_flags(b, ~(0x0)) +# define BIO_set_retry_special(b) \ + BIO_set_flags(b, (BIO_FLAGS_IO_SPECIAL|BIO_FLAGS_SHOULD_RETRY)) +# define BIO_set_retry_read(b) \ + BIO_set_flags(b, (BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY)) +# define BIO_set_retry_write(b) \ + BIO_set_flags(b, (BIO_FLAGS_WRITE|BIO_FLAGS_SHOULD_RETRY)) + +/* These are normally used internally in BIOs */ +# define BIO_clear_retry_flags(b) \ + BIO_clear_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY)) +# define BIO_get_retry_flags(b) \ + BIO_test_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY)) + +/* These should be used by the application to tell why we should retry */ +# define BIO_should_read(a) BIO_test_flags(a, BIO_FLAGS_READ) +# define BIO_should_write(a) BIO_test_flags(a, BIO_FLAGS_WRITE) +# define BIO_should_io_special(a) BIO_test_flags(a, BIO_FLAGS_IO_SPECIAL) +# define BIO_retry_type(a) BIO_test_flags(a, BIO_FLAGS_RWS) +# define BIO_should_retry(a) BIO_test_flags(a, BIO_FLAGS_SHOULD_RETRY) + +/* + * The next three are used in conjunction with the BIO_should_io_special() + * condition. After this returns true, BIO *BIO_get_retry_BIO(BIO *bio, int + * *reason); will walk the BIO stack and return the 'reason' for the special + * and the offending BIO. Given a BIO, BIO_get_retry_reason(bio) will return + * the code. + */ +/* + * Returned from the SSL bio when the certificate retrieval code had an error + */ +# define BIO_RR_SSL_X509_LOOKUP 0x01 +/* Returned from the connect BIO when a connect would have blocked */ +# define BIO_RR_CONNECT 0x02 +/* Returned from the accept BIO when an accept would have blocked */ +# define BIO_RR_ACCEPT 0x03 + +/* These are passed by the BIO callback */ +# define BIO_CB_FREE 0x01 +# define BIO_CB_READ 0x02 +# define BIO_CB_WRITE 0x03 +# define BIO_CB_PUTS 0x04 +# define BIO_CB_GETS 0x05 +# define BIO_CB_CTRL 0x06 + +/* + * The callback is called before and after the underling operation, The + * BIO_CB_RETURN flag indicates if it is after the call + */ +# define BIO_CB_RETURN 0x80 +# define BIO_CB_return(a) ((a)|BIO_CB_RETURN) +# define BIO_cb_pre(a) (!((a)&BIO_CB_RETURN)) +# define BIO_cb_post(a) ((a)&BIO_CB_RETURN) + +typedef long (*BIO_callback_fn)(BIO *b, int oper, const char *argp, int argi, + long argl, long ret); +typedef long (*BIO_callback_fn_ex)(BIO *b, int oper, const char *argp, + size_t len, int argi, + long argl, int ret, size_t *processed); +BIO_callback_fn BIO_get_callback(const BIO *b); +void BIO_set_callback(BIO *b, BIO_callback_fn callback); + +BIO_callback_fn_ex BIO_get_callback_ex(const BIO *b); +void BIO_set_callback_ex(BIO *b, BIO_callback_fn_ex callback); + +char *BIO_get_callback_arg(const BIO *b); +void BIO_set_callback_arg(BIO *b, char *arg); + +typedef struct bio_method_st BIO_METHOD; + +const char *BIO_method_name(const BIO *b); +int BIO_method_type(const BIO *b); + +typedef int BIO_info_cb(BIO *, int, int); +typedef BIO_info_cb bio_info_cb; /* backward compatibility */ + +DEFINE_STACK_OF(BIO) + +/* Prefix and suffix callback in ASN1 BIO */ +typedef int asn1_ps_func (BIO *b, unsigned char **pbuf, int *plen, + void *parg); + +# ifndef OPENSSL_NO_SCTP +/* SCTP parameter structs */ +struct bio_dgram_sctp_sndinfo { + uint16_t snd_sid; + uint16_t snd_flags; + uint32_t snd_ppid; + uint32_t snd_context; +}; + +struct bio_dgram_sctp_rcvinfo { + uint16_t rcv_sid; + uint16_t rcv_ssn; + uint16_t rcv_flags; + uint32_t rcv_ppid; + uint32_t rcv_tsn; + uint32_t rcv_cumtsn; + uint32_t rcv_context; +}; + +struct bio_dgram_sctp_prinfo { + uint16_t pr_policy; + uint32_t pr_value; +}; +# endif + +/* + * #define BIO_CONN_get_param_hostname BIO_ctrl + */ + +# define BIO_C_SET_CONNECT 100 +# define BIO_C_DO_STATE_MACHINE 101 +# define BIO_C_SET_NBIO 102 +/* # define BIO_C_SET_PROXY_PARAM 103 */ +# define BIO_C_SET_FD 104 +# define BIO_C_GET_FD 105 +# define BIO_C_SET_FILE_PTR 106 +# define BIO_C_GET_FILE_PTR 107 +# define BIO_C_SET_FILENAME 108 +# define BIO_C_SET_SSL 109 +# define BIO_C_GET_SSL 110 +# define BIO_C_SET_MD 111 +# define BIO_C_GET_MD 112 +# define BIO_C_GET_CIPHER_STATUS 113 +# define BIO_C_SET_BUF_MEM 114 +# define BIO_C_GET_BUF_MEM_PTR 115 +# define BIO_C_GET_BUFF_NUM_LINES 116 +# define BIO_C_SET_BUFF_SIZE 117 +# define BIO_C_SET_ACCEPT 118 +# define BIO_C_SSL_MODE 119 +# define BIO_C_GET_MD_CTX 120 +/* # define BIO_C_GET_PROXY_PARAM 121 */ +# define BIO_C_SET_BUFF_READ_DATA 122/* data to read first */ +# define BIO_C_GET_CONNECT 123 +# define BIO_C_GET_ACCEPT 124 +# define BIO_C_SET_SSL_RENEGOTIATE_BYTES 125 +# define BIO_C_GET_SSL_NUM_RENEGOTIATES 126 +# define BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT 127 +# define BIO_C_FILE_SEEK 128 +# define BIO_C_GET_CIPHER_CTX 129 +# define BIO_C_SET_BUF_MEM_EOF_RETURN 130/* return end of input + * value */ +# define BIO_C_SET_BIND_MODE 131 +# define BIO_C_GET_BIND_MODE 132 +# define BIO_C_FILE_TELL 133 +# define BIO_C_GET_SOCKS 134 +# define BIO_C_SET_SOCKS 135 + +# define BIO_C_SET_WRITE_BUF_SIZE 136/* for BIO_s_bio */ +# define BIO_C_GET_WRITE_BUF_SIZE 137 +# define BIO_C_MAKE_BIO_PAIR 138 +# define BIO_C_DESTROY_BIO_PAIR 139 +# define BIO_C_GET_WRITE_GUARANTEE 140 +# define BIO_C_GET_READ_REQUEST 141 +# define BIO_C_SHUTDOWN_WR 142 +# define BIO_C_NREAD0 143 +# define BIO_C_NREAD 144 +# define BIO_C_NWRITE0 145 +# define BIO_C_NWRITE 146 +# define BIO_C_RESET_READ_REQUEST 147 +# define BIO_C_SET_MD_CTX 148 + +# define BIO_C_SET_PREFIX 149 +# define BIO_C_GET_PREFIX 150 +# define BIO_C_SET_SUFFIX 151 +# define BIO_C_GET_SUFFIX 152 + +# define BIO_C_SET_EX_ARG 153 +# define BIO_C_GET_EX_ARG 154 + +# define BIO_C_SET_CONNECT_MODE 155 + +# define BIO_set_app_data(s,arg) BIO_set_ex_data(s,0,arg) +# define BIO_get_app_data(s) BIO_get_ex_data(s,0) + +# define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL) + +# ifndef OPENSSL_NO_SOCK +/* IP families we support, for BIO_s_connect() and BIO_s_accept() */ +/* Note: the underlying operating system may not support some of them */ +# define BIO_FAMILY_IPV4 4 +# define BIO_FAMILY_IPV6 6 +# define BIO_FAMILY_IPANY 256 + +/* BIO_s_connect() */ +# define BIO_set_conn_hostname(b,name) BIO_ctrl(b,BIO_C_SET_CONNECT,0, \ + (char *)(name)) +# define BIO_set_conn_port(b,port) BIO_ctrl(b,BIO_C_SET_CONNECT,1, \ + (char *)(port)) +# define BIO_set_conn_address(b,addr) BIO_ctrl(b,BIO_C_SET_CONNECT,2, \ + (char *)(addr)) +# define BIO_set_conn_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_CONNECT,3,f) +# define BIO_get_conn_hostname(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,0)) +# define BIO_get_conn_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,1)) +# define BIO_get_conn_address(b) ((const BIO_ADDR *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,2)) +# define BIO_get_conn_ip_family(b) BIO_ctrl(b,BIO_C_GET_CONNECT,3,NULL) +# define BIO_set_conn_mode(b,n) BIO_ctrl(b,BIO_C_SET_CONNECT_MODE,(n),NULL) + +/* BIO_s_accept() */ +# define BIO_set_accept_name(b,name) BIO_ctrl(b,BIO_C_SET_ACCEPT,0, \ + (char *)(name)) +# define BIO_set_accept_port(b,port) BIO_ctrl(b,BIO_C_SET_ACCEPT,1, \ + (char *)(port)) +# define BIO_get_accept_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,0)) +# define BIO_get_accept_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,1)) +# define BIO_get_peer_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,2)) +# define BIO_get_peer_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,3)) +/* #define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL) */ +# define BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,2,(n)?(void *)"a":NULL) +# define BIO_set_accept_bios(b,bio) BIO_ctrl(b,BIO_C_SET_ACCEPT,3, \ + (char *)(bio)) +# define BIO_set_accept_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_ACCEPT,4,f) +# define BIO_get_accept_ip_family(b) BIO_ctrl(b,BIO_C_GET_ACCEPT,4,NULL) + +/* Aliases kept for backward compatibility */ +# define BIO_BIND_NORMAL 0 +# define BIO_BIND_REUSEADDR BIO_SOCK_REUSEADDR +# define BIO_BIND_REUSEADDR_IF_UNUSED BIO_SOCK_REUSEADDR +# define BIO_set_bind_mode(b,mode) BIO_ctrl(b,BIO_C_SET_BIND_MODE,mode,NULL) +# define BIO_get_bind_mode(b) BIO_ctrl(b,BIO_C_GET_BIND_MODE,0,NULL) + +/* BIO_s_accept() and BIO_s_connect() */ +# define BIO_do_connect(b) BIO_do_handshake(b) +# define BIO_do_accept(b) BIO_do_handshake(b) +# endif /* OPENSSL_NO_SOCK */ + +# define BIO_do_handshake(b) BIO_ctrl(b,BIO_C_DO_STATE_MACHINE,0,NULL) + +/* BIO_s_datagram(), BIO_s_fd(), BIO_s_socket(), BIO_s_accept() and BIO_s_connect() */ +# define BIO_set_fd(b,fd,c) BIO_int_ctrl(b,BIO_C_SET_FD,c,fd) +# define BIO_get_fd(b,c) BIO_ctrl(b,BIO_C_GET_FD,0,(char *)(c)) + +/* BIO_s_file() */ +# define BIO_set_fp(b,fp,c) BIO_ctrl(b,BIO_C_SET_FILE_PTR,c,(char *)(fp)) +# define BIO_get_fp(b,fpp) BIO_ctrl(b,BIO_C_GET_FILE_PTR,0,(char *)(fpp)) + +/* BIO_s_fd() and BIO_s_file() */ +# define BIO_seek(b,ofs) (int)BIO_ctrl(b,BIO_C_FILE_SEEK,ofs,NULL) +# define BIO_tell(b) (int)BIO_ctrl(b,BIO_C_FILE_TELL,0,NULL) + +/* + * name is cast to lose const, but might be better to route through a + * function so we can do it safely + */ +# ifdef CONST_STRICT +/* + * If you are wondering why this isn't defined, its because CONST_STRICT is + * purely a compile-time kludge to allow const to be checked. + */ +int BIO_read_filename(BIO *b, const char *name); +# else +# define BIO_read_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \ + BIO_CLOSE|BIO_FP_READ,(char *)(name)) +# endif +# define BIO_write_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \ + BIO_CLOSE|BIO_FP_WRITE,name) +# define BIO_append_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \ + BIO_CLOSE|BIO_FP_APPEND,name) +# define BIO_rw_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \ + BIO_CLOSE|BIO_FP_READ|BIO_FP_WRITE,name) + +/* + * WARNING WARNING, this ups the reference count on the read bio of the SSL + * structure. This is because the ssl read BIO is now pointed to by the + * next_bio field in the bio. So when you free the BIO, make sure you are + * doing a BIO_free_all() to catch the underlying BIO. + */ +# define BIO_set_ssl(b,ssl,c) BIO_ctrl(b,BIO_C_SET_SSL,c,(char *)(ssl)) +# define BIO_get_ssl(b,sslp) BIO_ctrl(b,BIO_C_GET_SSL,0,(char *)(sslp)) +# define BIO_set_ssl_mode(b,client) BIO_ctrl(b,BIO_C_SSL_MODE,client,NULL) +# define BIO_set_ssl_renegotiate_bytes(b,num) \ + BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_BYTES,num,NULL) +# define BIO_get_num_renegotiates(b) \ + BIO_ctrl(b,BIO_C_GET_SSL_NUM_RENEGOTIATES,0,NULL) +# define BIO_set_ssl_renegotiate_timeout(b,seconds) \ + BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT,seconds,NULL) + +/* defined in evp.h */ +/* #define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,1,(char *)(md)) */ + +# define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)(pp)) +# define BIO_set_mem_buf(b,bm,c) BIO_ctrl(b,BIO_C_SET_BUF_MEM,c,(char *)(bm)) +# define BIO_get_mem_ptr(b,pp) BIO_ctrl(b,BIO_C_GET_BUF_MEM_PTR,0, \ + (char *)(pp)) +# define BIO_set_mem_eof_return(b,v) \ + BIO_ctrl(b,BIO_C_SET_BUF_MEM_EOF_RETURN,v,NULL) + +/* For the BIO_f_buffer() type */ +# define BIO_get_buffer_num_lines(b) BIO_ctrl(b,BIO_C_GET_BUFF_NUM_LINES,0,NULL) +# define BIO_set_buffer_size(b,size) BIO_ctrl(b,BIO_C_SET_BUFF_SIZE,size,NULL) +# define BIO_set_read_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,0) +# define BIO_set_write_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,1) +# define BIO_set_buffer_read_data(b,buf,num) BIO_ctrl(b,BIO_C_SET_BUFF_READ_DATA,num,buf) + +/* Don't use the next one unless you know what you are doing :-) */ +# define BIO_dup_state(b,ret) BIO_ctrl(b,BIO_CTRL_DUP,0,(char *)(ret)) + +# define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL) +# define BIO_eof(b) (int)BIO_ctrl(b,BIO_CTRL_EOF,0,NULL) +# define BIO_set_close(b,c) (int)BIO_ctrl(b,BIO_CTRL_SET_CLOSE,(c),NULL) +# define BIO_get_close(b) (int)BIO_ctrl(b,BIO_CTRL_GET_CLOSE,0,NULL) +# define BIO_pending(b) (int)BIO_ctrl(b,BIO_CTRL_PENDING,0,NULL) +# define BIO_wpending(b) (int)BIO_ctrl(b,BIO_CTRL_WPENDING,0,NULL) +/* ...pending macros have inappropriate return type */ +size_t BIO_ctrl_pending(BIO *b); +size_t BIO_ctrl_wpending(BIO *b); +# define BIO_flush(b) (int)BIO_ctrl(b,BIO_CTRL_FLUSH,0,NULL) +# define BIO_get_info_callback(b,cbp) (int)BIO_ctrl(b,BIO_CTRL_GET_CALLBACK,0, \ + cbp) +# define BIO_set_info_callback(b,cb) (int)BIO_callback_ctrl(b,BIO_CTRL_SET_CALLBACK,cb) + +/* For the BIO_f_buffer() type */ +# define BIO_buffer_get_num_lines(b) BIO_ctrl(b,BIO_CTRL_GET,0,NULL) +# define BIO_buffer_peek(b,s,l) BIO_ctrl(b,BIO_CTRL_PEEK,(l),(s)) + +/* For BIO_s_bio() */ +# define BIO_set_write_buf_size(b,size) (int)BIO_ctrl(b,BIO_C_SET_WRITE_BUF_SIZE,size,NULL) +# define BIO_get_write_buf_size(b,size) (size_t)BIO_ctrl(b,BIO_C_GET_WRITE_BUF_SIZE,size,NULL) +# define BIO_make_bio_pair(b1,b2) (int)BIO_ctrl(b1,BIO_C_MAKE_BIO_PAIR,0,b2) +# define BIO_destroy_bio_pair(b) (int)BIO_ctrl(b,BIO_C_DESTROY_BIO_PAIR,0,NULL) +# define BIO_shutdown_wr(b) (int)BIO_ctrl(b, BIO_C_SHUTDOWN_WR, 0, NULL) +/* macros with inappropriate type -- but ...pending macros use int too: */ +# define BIO_get_write_guarantee(b) (int)BIO_ctrl(b,BIO_C_GET_WRITE_GUARANTEE,0,NULL) +# define BIO_get_read_request(b) (int)BIO_ctrl(b,BIO_C_GET_READ_REQUEST,0,NULL) +size_t BIO_ctrl_get_write_guarantee(BIO *b); +size_t BIO_ctrl_get_read_request(BIO *b); +int BIO_ctrl_reset_read_request(BIO *b); + +/* ctrl macros for dgram */ +# define BIO_ctrl_dgram_connect(b,peer) \ + (int)BIO_ctrl(b,BIO_CTRL_DGRAM_CONNECT,0, (char *)(peer)) +# define BIO_ctrl_set_connected(b,peer) \ + (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_CONNECTED, 0, (char *)(peer)) +# define BIO_dgram_recv_timedout(b) \ + (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL) +# define BIO_dgram_send_timedout(b) \ + (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP, 0, NULL) +# define BIO_dgram_get_peer(b,peer) \ + (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_PEER, 0, (char *)(peer)) +# define BIO_dgram_set_peer(b,peer) \ + (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, (char *)(peer)) +# define BIO_dgram_get_mtu_overhead(b) \ + (unsigned int)BIO_ctrl((b), BIO_CTRL_DGRAM_GET_MTU_OVERHEAD, 0, NULL) + +#define BIO_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_BIO, l, p, newf, dupf, freef) +int BIO_set_ex_data(BIO *bio, int idx, void *data); +void *BIO_get_ex_data(BIO *bio, int idx); +uint64_t BIO_number_read(BIO *bio); +uint64_t BIO_number_written(BIO *bio); + +/* For BIO_f_asn1() */ +int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix, + asn1_ps_func *prefix_free); +int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix, + asn1_ps_func **pprefix_free); +int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix, + asn1_ps_func *suffix_free); +int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix, + asn1_ps_func **psuffix_free); + +const BIO_METHOD *BIO_s_file(void); +BIO *BIO_new_file(const char *filename, const char *mode); +# ifndef OPENSSL_NO_STDIO +BIO *BIO_new_fp(FILE *stream, int close_flag); +# endif +BIO *BIO_new(const BIO_METHOD *type); +int BIO_free(BIO *a); +void BIO_set_data(BIO *a, void *ptr); +void *BIO_get_data(BIO *a); +void BIO_set_init(BIO *a, int init); +int BIO_get_init(BIO *a); +void BIO_set_shutdown(BIO *a, int shut); +int BIO_get_shutdown(BIO *a); +void BIO_vfree(BIO *a); +int BIO_up_ref(BIO *a); +int BIO_read(BIO *b, void *data, int dlen); +int BIO_read_ex(BIO *b, void *data, size_t dlen, size_t *readbytes); +int BIO_gets(BIO *bp, char *buf, int size); +int BIO_write(BIO *b, const void *data, int dlen); +int BIO_write_ex(BIO *b, const void *data, size_t dlen, size_t *written); +int BIO_puts(BIO *bp, const char *buf); +int BIO_indent(BIO *b, int indent, int max); +long BIO_ctrl(BIO *bp, int cmd, long larg, void *parg); +long BIO_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); +void *BIO_ptr_ctrl(BIO *bp, int cmd, long larg); +long BIO_int_ctrl(BIO *bp, int cmd, long larg, int iarg); +BIO *BIO_push(BIO *b, BIO *append); +BIO *BIO_pop(BIO *b); +void BIO_free_all(BIO *a); +BIO *BIO_find_type(BIO *b, int bio_type); +BIO *BIO_next(BIO *b); +void BIO_set_next(BIO *b, BIO *next); +BIO *BIO_get_retry_BIO(BIO *bio, int *reason); +int BIO_get_retry_reason(BIO *bio); +void BIO_set_retry_reason(BIO *bio, int reason); +BIO *BIO_dup_chain(BIO *in); + +int BIO_nread0(BIO *bio, char **buf); +int BIO_nread(BIO *bio, char **buf, int num); +int BIO_nwrite0(BIO *bio, char **buf); +int BIO_nwrite(BIO *bio, char **buf, int num); + +long BIO_debug_callback(BIO *bio, int cmd, const char *argp, int argi, + long argl, long ret); + +const BIO_METHOD *BIO_s_mem(void); +const BIO_METHOD *BIO_s_secmem(void); +BIO *BIO_new_mem_buf(const void *buf, int len); +# ifndef OPENSSL_NO_SOCK +const BIO_METHOD *BIO_s_socket(void); +const BIO_METHOD *BIO_s_connect(void); +const BIO_METHOD *BIO_s_accept(void); +# endif +const BIO_METHOD *BIO_s_fd(void); +const BIO_METHOD *BIO_s_log(void); +const BIO_METHOD *BIO_s_bio(void); +const BIO_METHOD *BIO_s_null(void); +const BIO_METHOD *BIO_f_null(void); +const BIO_METHOD *BIO_f_buffer(void); +const BIO_METHOD *BIO_f_linebuffer(void); +const BIO_METHOD *BIO_f_nbio_test(void); +# ifndef OPENSSL_NO_DGRAM +const BIO_METHOD *BIO_s_datagram(void); +int BIO_dgram_non_fatal_error(int error); +BIO *BIO_new_dgram(int fd, int close_flag); +# ifndef OPENSSL_NO_SCTP +const BIO_METHOD *BIO_s_datagram_sctp(void); +BIO *BIO_new_dgram_sctp(int fd, int close_flag); +int BIO_dgram_is_sctp(BIO *bio); +int BIO_dgram_sctp_notification_cb(BIO *b, + void (*handle_notifications) (BIO *bio, + void *context, + void *buf), + void *context); +int BIO_dgram_sctp_wait_for_dry(BIO *b); +int BIO_dgram_sctp_msg_waiting(BIO *b); +# endif +# endif + +# ifndef OPENSSL_NO_SOCK +int BIO_sock_should_retry(int i); +int BIO_sock_non_fatal_error(int error); +# endif + +int BIO_fd_should_retry(int i); +int BIO_fd_non_fatal_error(int error); +int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u), + void *u, const char *s, int len); +int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u), + void *u, const char *s, int len, int indent); +int BIO_dump(BIO *b, const char *bytes, int len); +int BIO_dump_indent(BIO *b, const char *bytes, int len, int indent); +# ifndef OPENSSL_NO_STDIO +int BIO_dump_fp(FILE *fp, const char *s, int len); +int BIO_dump_indent_fp(FILE *fp, const char *s, int len, int indent); +# endif +int BIO_hex_string(BIO *out, int indent, int width, unsigned char *data, + int datalen); + +# ifndef OPENSSL_NO_SOCK +BIO_ADDR *BIO_ADDR_new(void); +int BIO_ADDR_rawmake(BIO_ADDR *ap, int family, + const void *where, size_t wherelen, unsigned short port); +void BIO_ADDR_free(BIO_ADDR *); +void BIO_ADDR_clear(BIO_ADDR *ap); +int BIO_ADDR_family(const BIO_ADDR *ap); +int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l); +unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap); +char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric); +char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric); +char *BIO_ADDR_path_string(const BIO_ADDR *ap); + +const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai); +int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai); +int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai); +int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai); +const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai); +void BIO_ADDRINFO_free(BIO_ADDRINFO *bai); + +enum BIO_hostserv_priorities { + BIO_PARSE_PRIO_HOST, BIO_PARSE_PRIO_SERV +}; +int BIO_parse_hostserv(const char *hostserv, char **host, char **service, + enum BIO_hostserv_priorities hostserv_prio); +enum BIO_lookup_type { + BIO_LOOKUP_CLIENT, BIO_LOOKUP_SERVER +}; +int BIO_lookup(const char *host, const char *service, + enum BIO_lookup_type lookup_type, + int family, int socktype, BIO_ADDRINFO **res); +int BIO_lookup_ex(const char *host, const char *service, + int lookup_type, int family, int socktype, int protocol, + BIO_ADDRINFO **res); +int BIO_sock_error(int sock); +int BIO_socket_ioctl(int fd, long type, void *arg); +int BIO_socket_nbio(int fd, int mode); +int BIO_sock_init(void); +# if OPENSSL_API_COMPAT < 0x10100000L +# define BIO_sock_cleanup() while(0) continue +# endif +int BIO_set_tcp_ndelay(int sock, int turn_on); + +DEPRECATEDIN_1_1_0(struct hostent *BIO_gethostbyname(const char *name)) +DEPRECATEDIN_1_1_0(int BIO_get_port(const char *str, unsigned short *port_ptr)) +DEPRECATEDIN_1_1_0(int BIO_get_host_ip(const char *str, unsigned char *ip)) +DEPRECATEDIN_1_1_0(int BIO_get_accept_socket(char *host_port, int mode)) +DEPRECATEDIN_1_1_0(int BIO_accept(int sock, char **ip_port)) + +union BIO_sock_info_u { + BIO_ADDR *addr; +}; +enum BIO_sock_info_type { + BIO_SOCK_INFO_ADDRESS +}; +int BIO_sock_info(int sock, + enum BIO_sock_info_type type, union BIO_sock_info_u *info); + +# define BIO_SOCK_REUSEADDR 0x01 +# define BIO_SOCK_V6_ONLY 0x02 +# define BIO_SOCK_KEEPALIVE 0x04 +# define BIO_SOCK_NONBLOCK 0x08 +# define BIO_SOCK_NODELAY 0x10 + +int BIO_socket(int domain, int socktype, int protocol, int options); +int BIO_connect(int sock, const BIO_ADDR *addr, int options); +int BIO_bind(int sock, const BIO_ADDR *addr, int options); +int BIO_listen(int sock, const BIO_ADDR *addr, int options); +int BIO_accept_ex(int accept_sock, BIO_ADDR *addr, int options); +int BIO_closesocket(int sock); + +BIO *BIO_new_socket(int sock, int close_flag); +BIO *BIO_new_connect(const char *host_port); +BIO *BIO_new_accept(const char *host_port); +# endif /* OPENSSL_NO_SOCK*/ + +BIO *BIO_new_fd(int fd, int close_flag); + +int BIO_new_bio_pair(BIO **bio1, size_t writebuf1, + BIO **bio2, size_t writebuf2); +/* + * If successful, returns 1 and in *bio1, *bio2 two BIO pair endpoints. + * Otherwise returns 0 and sets *bio1 and *bio2 to NULL. Size 0 uses default + * value. + */ + +void BIO_copy_next_retry(BIO *b); + +/* + * long BIO_ghbn_ctrl(int cmd,int iarg,char *parg); + */ + +# define ossl_bio__attr__(x) +# if defined(__GNUC__) && defined(__STDC_VERSION__) \ + && !defined(__APPLE__) + /* + * Because we support the 'z' modifier, which made its appearance in C99, + * we can't use __attribute__ with pre C99 dialects. + */ +# if __STDC_VERSION__ >= 199901L +# undef ossl_bio__attr__ +# define ossl_bio__attr__ __attribute__ +# if __GNUC__*10 + __GNUC_MINOR__ >= 44 +# define ossl_bio__printf__ __gnu_printf__ +# else +# define ossl_bio__printf__ __printf__ +# endif +# endif +# endif +int BIO_printf(BIO *bio, const char *format, ...) +ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 3))); +int BIO_vprintf(BIO *bio, const char *format, va_list args) +ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 0))); +int BIO_snprintf(char *buf, size_t n, const char *format, ...) +ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 4))); +int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args) +ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 0))); +# undef ossl_bio__attr__ +# undef ossl_bio__printf__ + + +BIO_METHOD *BIO_meth_new(int type, const char *name); +void BIO_meth_free(BIO_METHOD *biom); +int (*BIO_meth_get_write(const BIO_METHOD *biom)) (BIO *, const char *, int); +int (*BIO_meth_get_write_ex(const BIO_METHOD *biom)) (BIO *, const char *, size_t, + size_t *); +int BIO_meth_set_write(BIO_METHOD *biom, + int (*write) (BIO *, const char *, int)); +int BIO_meth_set_write_ex(BIO_METHOD *biom, + int (*bwrite) (BIO *, const char *, size_t, size_t *)); +int (*BIO_meth_get_read(const BIO_METHOD *biom)) (BIO *, char *, int); +int (*BIO_meth_get_read_ex(const BIO_METHOD *biom)) (BIO *, char *, size_t, size_t *); +int BIO_meth_set_read(BIO_METHOD *biom, + int (*read) (BIO *, char *, int)); +int BIO_meth_set_read_ex(BIO_METHOD *biom, + int (*bread) (BIO *, char *, size_t, size_t *)); +int (*BIO_meth_get_puts(const BIO_METHOD *biom)) (BIO *, const char *); +int BIO_meth_set_puts(BIO_METHOD *biom, + int (*puts) (BIO *, const char *)); +int (*BIO_meth_get_gets(const BIO_METHOD *biom)) (BIO *, char *, int); +int BIO_meth_set_gets(BIO_METHOD *biom, + int (*gets) (BIO *, char *, int)); +long (*BIO_meth_get_ctrl(const BIO_METHOD *biom)) (BIO *, int, long, void *); +int BIO_meth_set_ctrl(BIO_METHOD *biom, + long (*ctrl) (BIO *, int, long, void *)); +int (*BIO_meth_get_create(const BIO_METHOD *bion)) (BIO *); +int BIO_meth_set_create(BIO_METHOD *biom, int (*create) (BIO *)); +int (*BIO_meth_get_destroy(const BIO_METHOD *biom)) (BIO *); +int BIO_meth_set_destroy(BIO_METHOD *biom, int (*destroy) (BIO *)); +long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *biom)) + (BIO *, int, BIO_info_cb *); +int BIO_meth_set_callback_ctrl(BIO_METHOD *biom, + long (*callback_ctrl) (BIO *, int, + BIO_info_cb *)); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/bioerr.h b/include/openssl/bioerr.h new file mode 100644 index 0000000..f119a59 --- /dev/null +++ b/include/openssl/bioerr.h @@ -0,0 +1,120 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BIOERR_H +# define HEADER_BIOERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_BIO_strings(void); + +/* + * BIO function codes. + */ +# define BIO_F_ACPT_STATE 100 +# define BIO_F_ADDRINFO_WRAP 148 +# define BIO_F_ADDR_STRINGS 134 +# define BIO_F_BIO_ACCEPT 101 +# define BIO_F_BIO_ACCEPT_EX 137 +# define BIO_F_BIO_ACCEPT_NEW 152 +# define BIO_F_BIO_ADDR_NEW 144 +# define BIO_F_BIO_BIND 147 +# define BIO_F_BIO_CALLBACK_CTRL 131 +# define BIO_F_BIO_CONNECT 138 +# define BIO_F_BIO_CONNECT_NEW 153 +# define BIO_F_BIO_CTRL 103 +# define BIO_F_BIO_GETS 104 +# define BIO_F_BIO_GET_HOST_IP 106 +# define BIO_F_BIO_GET_NEW_INDEX 102 +# define BIO_F_BIO_GET_PORT 107 +# define BIO_F_BIO_LISTEN 139 +# define BIO_F_BIO_LOOKUP 135 +# define BIO_F_BIO_LOOKUP_EX 143 +# define BIO_F_BIO_MAKE_PAIR 121 +# define BIO_F_BIO_METH_NEW 146 +# define BIO_F_BIO_NEW 108 +# define BIO_F_BIO_NEW_DGRAM_SCTP 145 +# define BIO_F_BIO_NEW_FILE 109 +# define BIO_F_BIO_NEW_MEM_BUF 126 +# define BIO_F_BIO_NREAD 123 +# define BIO_F_BIO_NREAD0 124 +# define BIO_F_BIO_NWRITE 125 +# define BIO_F_BIO_NWRITE0 122 +# define BIO_F_BIO_PARSE_HOSTSERV 136 +# define BIO_F_BIO_PUTS 110 +# define BIO_F_BIO_READ 111 +# define BIO_F_BIO_READ_EX 105 +# define BIO_F_BIO_READ_INTERN 120 +# define BIO_F_BIO_SOCKET 140 +# define BIO_F_BIO_SOCKET_NBIO 142 +# define BIO_F_BIO_SOCK_INFO 141 +# define BIO_F_BIO_SOCK_INIT 112 +# define BIO_F_BIO_WRITE 113 +# define BIO_F_BIO_WRITE_EX 119 +# define BIO_F_BIO_WRITE_INTERN 128 +# define BIO_F_BUFFER_CTRL 114 +# define BIO_F_CONN_CTRL 127 +# define BIO_F_CONN_STATE 115 +# define BIO_F_DGRAM_SCTP_NEW 149 +# define BIO_F_DGRAM_SCTP_READ 132 +# define BIO_F_DGRAM_SCTP_WRITE 133 +# define BIO_F_DOAPR_OUTCH 150 +# define BIO_F_FILE_CTRL 116 +# define BIO_F_FILE_READ 130 +# define BIO_F_LINEBUFFER_CTRL 129 +# define BIO_F_LINEBUFFER_NEW 151 +# define BIO_F_MEM_WRITE 117 +# define BIO_F_NBIOF_NEW 154 +# define BIO_F_SLG_WRITE 155 +# define BIO_F_SSL_NEW 118 + +/* + * BIO reason codes. + */ +# define BIO_R_ACCEPT_ERROR 100 +# define BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET 141 +# define BIO_R_AMBIGUOUS_HOST_OR_SERVICE 129 +# define BIO_R_BAD_FOPEN_MODE 101 +# define BIO_R_BROKEN_PIPE 124 +# define BIO_R_CONNECT_ERROR 103 +# define BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET 107 +# define BIO_R_GETSOCKNAME_ERROR 132 +# define BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS 133 +# define BIO_R_GETTING_SOCKTYPE 134 +# define BIO_R_INVALID_ARGUMENT 125 +# define BIO_R_INVALID_SOCKET 135 +# define BIO_R_IN_USE 123 +# define BIO_R_LENGTH_TOO_LONG 102 +# define BIO_R_LISTEN_V6_ONLY 136 +# define BIO_R_LOOKUP_RETURNED_NOTHING 142 +# define BIO_R_MALFORMED_HOST_OR_SERVICE 130 +# define BIO_R_NBIO_CONNECT_ERROR 110 +# define BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED 143 +# define BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED 144 +# define BIO_R_NO_PORT_DEFINED 113 +# define BIO_R_NO_SUCH_FILE 128 +# define BIO_R_NULL_PARAMETER 115 +# define BIO_R_UNABLE_TO_BIND_SOCKET 117 +# define BIO_R_UNABLE_TO_CREATE_SOCKET 118 +# define BIO_R_UNABLE_TO_KEEPALIVE 137 +# define BIO_R_UNABLE_TO_LISTEN_SOCKET 119 +# define BIO_R_UNABLE_TO_NODELAY 138 +# define BIO_R_UNABLE_TO_REUSEADDR 139 +# define BIO_R_UNAVAILABLE_IP_FAMILY 145 +# define BIO_R_UNINITIALIZED 120 +# define BIO_R_UNKNOWN_INFO_TYPE 140 +# define BIO_R_UNSUPPORTED_IP_FAMILY 146 +# define BIO_R_UNSUPPORTED_METHOD 121 +# define BIO_R_UNSUPPORTED_PROTOCOL_FAMILY 131 +# define BIO_R_WRITE_TO_READ_ONLY_BIO 126 +# define BIO_R_WSASTARTUP 122 + +#endif diff --git a/include/openssl/blowfish.h b/include/openssl/blowfish.h new file mode 100644 index 0000000..62cf9db --- /dev/null +++ b/include/openssl/blowfish.h @@ -0,0 +1,61 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BLOWFISH_H +# define HEADER_BLOWFISH_H + +# include + +# ifndef OPENSSL_NO_BF +# include +# ifdef __cplusplus +extern "C" { +# endif + +# define BF_ENCRYPT 1 +# define BF_DECRYPT 0 + +/*- + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + * ! BF_LONG has to be at least 32 bits wide. ! + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + */ +# define BF_LONG unsigned int + +# define BF_ROUNDS 16 +# define BF_BLOCK 8 + +typedef struct bf_key_st { + BF_LONG P[BF_ROUNDS + 2]; + BF_LONG S[4 * 256]; +} BF_KEY; + +void BF_set_key(BF_KEY *key, int len, const unsigned char *data); + +void BF_encrypt(BF_LONG *data, const BF_KEY *key); +void BF_decrypt(BF_LONG *data, const BF_KEY *key); + +void BF_ecb_encrypt(const unsigned char *in, unsigned char *out, + const BF_KEY *key, int enc); +void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, + const BF_KEY *schedule, unsigned char *ivec, int enc); +void BF_cfb64_encrypt(const unsigned char *in, unsigned char *out, + long length, const BF_KEY *schedule, + unsigned char *ivec, int *num, int enc); +void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out, + long length, const BF_KEY *schedule, + unsigned char *ivec, int *num); +const char *BF_options(void); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/bn.h b/include/openssl/bn.h new file mode 100644 index 0000000..ff3c663 --- /dev/null +++ b/include/openssl/bn.h @@ -0,0 +1,539 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BN_H +# define HEADER_BN_H + +# include +# ifndef OPENSSL_NO_STDIO +# include +# endif +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * 64-bit processor with LP64 ABI + */ +# ifdef SIXTY_FOUR_BIT_LONG +# define BN_ULONG unsigned long +# define BN_BYTES 8 +# endif + +/* + * 64-bit processor other than LP64 ABI + */ +# ifdef SIXTY_FOUR_BIT +# define BN_ULONG unsigned long long +# define BN_BYTES 8 +# endif + +# ifdef THIRTY_TWO_BIT +# define BN_ULONG unsigned int +# define BN_BYTES 4 +# endif + +# define BN_BITS2 (BN_BYTES * 8) +# define BN_BITS (BN_BITS2 * 2) +# define BN_TBIT ((BN_ULONG)1 << (BN_BITS2 - 1)) + +# define BN_FLG_MALLOCED 0x01 +# define BN_FLG_STATIC_DATA 0x02 + +/* + * avoid leaking exponent information through timing, + * BN_mod_exp_mont() will call BN_mod_exp_mont_consttime, + * BN_div() will call BN_div_no_branch, + * BN_mod_inverse() will call BN_mod_inverse_no_branch. + */ +# define BN_FLG_CONSTTIME 0x04 +# define BN_FLG_SECURE 0x08 + +# if OPENSSL_API_COMPAT < 0x00908000L +/* deprecated name for the flag */ +# define BN_FLG_EXP_CONSTTIME BN_FLG_CONSTTIME +# define BN_FLG_FREE 0x8000 /* used for debugging */ +# endif + +void BN_set_flags(BIGNUM *b, int n); +int BN_get_flags(const BIGNUM *b, int n); + +/* Values for |top| in BN_rand() */ +#define BN_RAND_TOP_ANY -1 +#define BN_RAND_TOP_ONE 0 +#define BN_RAND_TOP_TWO 1 + +/* Values for |bottom| in BN_rand() */ +#define BN_RAND_BOTTOM_ANY 0 +#define BN_RAND_BOTTOM_ODD 1 + +/* + * get a clone of a BIGNUM with changed flags, for *temporary* use only (the + * two BIGNUMs cannot be used in parallel!). Also only for *read only* use. The + * value |dest| should be a newly allocated BIGNUM obtained via BN_new() that + * has not been otherwise initialised or used. + */ +void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags); + +/* Wrapper function to make using BN_GENCB easier */ +int BN_GENCB_call(BN_GENCB *cb, int a, int b); + +BN_GENCB *BN_GENCB_new(void); +void BN_GENCB_free(BN_GENCB *cb); + +/* Populate a BN_GENCB structure with an "old"-style callback */ +void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback) (int, int, void *), + void *cb_arg); + +/* Populate a BN_GENCB structure with a "new"-style callback */ +void BN_GENCB_set(BN_GENCB *gencb, int (*callback) (int, int, BN_GENCB *), + void *cb_arg); + +void *BN_GENCB_get_arg(BN_GENCB *cb); + +# define BN_prime_checks 0 /* default: select number of iterations based + * on the size of the number */ + +/* + * BN_prime_checks_for_size() returns the number of Miller-Rabin iterations + * that will be done for checking that a random number is probably prime. The + * error rate for accepting a composite number as prime depends on the size of + * the prime |b|. The error rates used are for calculating an RSA key with 2 primes, + * and so the level is what you would expect for a key of double the size of the + * prime. + * + * This table is generated using the algorithm of FIPS PUB 186-4 + * Digital Signature Standard (DSS), section F.1, page 117. + * (https://dx.doi.org/10.6028/NIST.FIPS.186-4) + * + * The following magma script was used to generate the output: + * securitybits:=125; + * k:=1024; + * for t:=1 to 65 do + * for M:=3 to Floor(2*Sqrt(k-1)-1) do + * S:=0; + * // Sum over m + * for m:=3 to M do + * s:=0; + * // Sum over j + * for j:=2 to m do + * s+:=(RealField(32)!2)^-(j+(k-1)/j); + * end for; + * S+:=2^(m-(m-1)*t)*s; + * end for; + * A:=2^(k-2-M*t); + * B:=8*(Pi(RealField(32))^2-6)/3*2^(k-2)*S; + * pkt:=2.00743*Log(2)*k*2^-k*(A+B); + * seclevel:=Floor(-Log(2,pkt)); + * if seclevel ge securitybits then + * printf "k: %5o, security: %o bits (t: %o, M: %o)\n",k,seclevel,t,M; + * break; + * end if; + * end for; + * if seclevel ge securitybits then break; end if; + * end for; + * + * It can be run online at: + * http://magma.maths.usyd.edu.au/calc + * + * And will output: + * k: 1024, security: 129 bits (t: 6, M: 23) + * + * k is the number of bits of the prime, securitybits is the level we want to + * reach. + * + * prime length | RSA key size | # MR tests | security level + * -------------+--------------|------------+--------------- + * (b) >= 6394 | >= 12788 | 3 | 256 bit + * (b) >= 3747 | >= 7494 | 3 | 192 bit + * (b) >= 1345 | >= 2690 | 4 | 128 bit + * (b) >= 1080 | >= 2160 | 5 | 128 bit + * (b) >= 852 | >= 1704 | 5 | 112 bit + * (b) >= 476 | >= 952 | 5 | 80 bit + * (b) >= 400 | >= 800 | 6 | 80 bit + * (b) >= 347 | >= 694 | 7 | 80 bit + * (b) >= 308 | >= 616 | 8 | 80 bit + * (b) >= 55 | >= 110 | 27 | 64 bit + * (b) >= 6 | >= 12 | 34 | 64 bit + */ + +# define BN_prime_checks_for_size(b) ((b) >= 3747 ? 3 : \ + (b) >= 1345 ? 4 : \ + (b) >= 476 ? 5 : \ + (b) >= 400 ? 6 : \ + (b) >= 347 ? 7 : \ + (b) >= 308 ? 8 : \ + (b) >= 55 ? 27 : \ + /* b >= 6 */ 34) + +# define BN_num_bytes(a) ((BN_num_bits(a)+7)/8) + +int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w); +int BN_is_zero(const BIGNUM *a); +int BN_is_one(const BIGNUM *a); +int BN_is_word(const BIGNUM *a, const BN_ULONG w); +int BN_is_odd(const BIGNUM *a); + +# define BN_one(a) (BN_set_word((a),1)) + +void BN_zero_ex(BIGNUM *a); + +# if OPENSSL_API_COMPAT >= 0x00908000L +# define BN_zero(a) BN_zero_ex(a) +# else +# define BN_zero(a) (BN_set_word((a),0)) +# endif + +const BIGNUM *BN_value_one(void); +char *BN_options(void); +BN_CTX *BN_CTX_new(void); +BN_CTX *BN_CTX_secure_new(void); +void BN_CTX_free(BN_CTX *c); +void BN_CTX_start(BN_CTX *ctx); +BIGNUM *BN_CTX_get(BN_CTX *ctx); +void BN_CTX_end(BN_CTX *ctx); +int BN_rand(BIGNUM *rnd, int bits, int top, int bottom); +int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom); +int BN_rand_range(BIGNUM *rnd, const BIGNUM *range); +int BN_priv_rand_range(BIGNUM *rnd, const BIGNUM *range); +int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom); +int BN_pseudo_rand_range(BIGNUM *rnd, const BIGNUM *range); +int BN_num_bits(const BIGNUM *a); +int BN_num_bits_word(BN_ULONG l); +int BN_security_bits(int L, int N); +BIGNUM *BN_new(void); +BIGNUM *BN_secure_new(void); +void BN_clear_free(BIGNUM *a); +BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b); +void BN_swap(BIGNUM *a, BIGNUM *b); +BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret); +int BN_bn2bin(const BIGNUM *a, unsigned char *to); +int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen); +BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret); +int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen); +BIGNUM *BN_mpi2bn(const unsigned char *s, int len, BIGNUM *ret); +int BN_bn2mpi(const BIGNUM *a, unsigned char *to); +int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); +int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); +int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); +int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); +int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); +int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx); +/** BN_set_negative sets sign of a BIGNUM + * \param b pointer to the BIGNUM object + * \param n 0 if the BIGNUM b should be positive and a value != 0 otherwise + */ +void BN_set_negative(BIGNUM *b, int n); +/** BN_is_negative returns 1 if the BIGNUM is negative + * \param b pointer to the BIGNUM object + * \return 1 if a < 0 and 0 otherwise + */ +int BN_is_negative(const BIGNUM *b); + +int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d, + BN_CTX *ctx); +# define BN_mod(rem,m,d,ctx) BN_div(NULL,(rem),(m),(d),(ctx)) +int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx); +int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, + BN_CTX *ctx); +int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *m); +int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, + BN_CTX *ctx); +int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *m); +int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, + BN_CTX *ctx); +int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx); +int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx); +int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m); +int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, + BN_CTX *ctx); +int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m); + +BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w); +BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w); +int BN_mul_word(BIGNUM *a, BN_ULONG w); +int BN_add_word(BIGNUM *a, BN_ULONG w); +int BN_sub_word(BIGNUM *a, BN_ULONG w); +int BN_set_word(BIGNUM *a, BN_ULONG w); +BN_ULONG BN_get_word(const BIGNUM *a); + +int BN_cmp(const BIGNUM *a, const BIGNUM *b); +void BN_free(BIGNUM *a); +int BN_is_bit_set(const BIGNUM *a, int n); +int BN_lshift(BIGNUM *r, const BIGNUM *a, int n); +int BN_lshift1(BIGNUM *r, const BIGNUM *a); +int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx); + +int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); +int BN_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *in_mont); +int BN_mod_exp_mont_word(BIGNUM *r, BN_ULONG a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +int BN_mod_exp2_mont(BIGNUM *r, const BIGNUM *a1, const BIGNUM *p1, + const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *m_ctx); +int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); + +int BN_mask_bits(BIGNUM *a, int n); +# ifndef OPENSSL_NO_STDIO +int BN_print_fp(FILE *fp, const BIGNUM *a); +# endif +int BN_print(BIO *bio, const BIGNUM *a); +int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx); +int BN_rshift(BIGNUM *r, const BIGNUM *a, int n); +int BN_rshift1(BIGNUM *r, const BIGNUM *a); +void BN_clear(BIGNUM *a); +BIGNUM *BN_dup(const BIGNUM *a); +int BN_ucmp(const BIGNUM *a, const BIGNUM *b); +int BN_set_bit(BIGNUM *a, int n); +int BN_clear_bit(BIGNUM *a, int n); +char *BN_bn2hex(const BIGNUM *a); +char *BN_bn2dec(const BIGNUM *a); +int BN_hex2bn(BIGNUM **a, const char *str); +int BN_dec2bn(BIGNUM **a, const char *str); +int BN_asc2bn(BIGNUM **a, const char *str); +int BN_gcd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); +int BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); /* returns + * -2 for + * error */ +BIGNUM *BN_mod_inverse(BIGNUM *ret, + const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx); +BIGNUM *BN_mod_sqrt(BIGNUM *ret, + const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx); + +void BN_consttime_swap(BN_ULONG swap, BIGNUM *a, BIGNUM *b, int nwords); + +/* Deprecated versions */ +DEPRECATEDIN_0_9_8(BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe, + const BIGNUM *add, + const BIGNUM *rem, + void (*callback) (int, int, + void *), + void *cb_arg)) +DEPRECATEDIN_0_9_8(int + BN_is_prime(const BIGNUM *p, int nchecks, + void (*callback) (int, int, void *), + BN_CTX *ctx, void *cb_arg)) +DEPRECATEDIN_0_9_8(int + BN_is_prime_fasttest(const BIGNUM *p, int nchecks, + void (*callback) (int, int, void *), + BN_CTX *ctx, void *cb_arg, + int do_trial_division)) + +/* Newer versions */ +int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add, + const BIGNUM *rem, BN_GENCB *cb); +int BN_is_prime_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx, BN_GENCB *cb); +int BN_is_prime_fasttest_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx, + int do_trial_division, BN_GENCB *cb); + +int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx); + +int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, + const BIGNUM *Xp, const BIGNUM *Xp1, + const BIGNUM *Xp2, const BIGNUM *e, BN_CTX *ctx, + BN_GENCB *cb); +int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, BIGNUM *Xp1, + BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *e, + BN_CTX *ctx, BN_GENCB *cb); + +BN_MONT_CTX *BN_MONT_CTX_new(void); +int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + BN_MONT_CTX *mont, BN_CTX *ctx); +int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont, + BN_CTX *ctx); +int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont, + BN_CTX *ctx); +void BN_MONT_CTX_free(BN_MONT_CTX *mont); +int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx); +BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from); +BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock, + const BIGNUM *mod, BN_CTX *ctx); + +/* BN_BLINDING flags */ +# define BN_BLINDING_NO_UPDATE 0x00000001 +# define BN_BLINDING_NO_RECREATE 0x00000002 + +BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod); +void BN_BLINDING_free(BN_BLINDING *b); +int BN_BLINDING_update(BN_BLINDING *b, BN_CTX *ctx); +int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx); +int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx); +int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *); +int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b, + BN_CTX *); + +int BN_BLINDING_is_current_thread(BN_BLINDING *b); +void BN_BLINDING_set_current_thread(BN_BLINDING *b); +int BN_BLINDING_lock(BN_BLINDING *b); +int BN_BLINDING_unlock(BN_BLINDING *b); + +unsigned long BN_BLINDING_get_flags(const BN_BLINDING *); +void BN_BLINDING_set_flags(BN_BLINDING *, unsigned long); +BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b, + const BIGNUM *e, BIGNUM *m, BN_CTX *ctx, + int (*bn_mod_exp) (BIGNUM *r, + const BIGNUM *a, + const BIGNUM *p, + const BIGNUM *m, + BN_CTX *ctx, + BN_MONT_CTX *m_ctx), + BN_MONT_CTX *m_ctx); + +DEPRECATEDIN_0_9_8(void BN_set_params(int mul, int high, int low, int mont)) +DEPRECATEDIN_0_9_8(int BN_get_params(int which)) /* 0, mul, 1 high, 2 low, 3 + * mont */ + +BN_RECP_CTX *BN_RECP_CTX_new(void); +void BN_RECP_CTX_free(BN_RECP_CTX *recp); +int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *rdiv, BN_CTX *ctx); +int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, + BN_RECP_CTX *recp, BN_CTX *ctx); +int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx); +int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, + BN_RECP_CTX *recp, BN_CTX *ctx); + +# ifndef OPENSSL_NO_EC2M + +/* + * Functions for arithmetic over binary polynomials represented by BIGNUMs. + * The BIGNUM::neg property of BIGNUMs representing binary polynomials is + * ignored. Note that input arguments are not const so that their bit arrays + * can be expanded to the appropriate size if needed. + */ + +/* + * r = a + b + */ +int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); +# define BN_GF2m_sub(r, a, b) BN_GF2m_add(r, a, b) +/* + * r=a mod p + */ +int BN_GF2m_mod(BIGNUM *r, const BIGNUM *a, const BIGNUM *p); +/* r = (a * b) mod p */ +int BN_GF2m_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *p, BN_CTX *ctx); +/* r = (a * a) mod p */ +int BN_GF2m_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx); +/* r = (1 / b) mod p */ +int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx); +/* r = (a / b) mod p */ +int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *p, BN_CTX *ctx); +/* r = (a ^ b) mod p */ +int BN_GF2m_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *p, BN_CTX *ctx); +/* r = sqrt(a) mod p */ +int BN_GF2m_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + BN_CTX *ctx); +/* r^2 + r = a mod p */ +int BN_GF2m_mod_solve_quad(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + BN_CTX *ctx); +# define BN_GF2m_cmp(a, b) BN_ucmp((a), (b)) +/*- + * Some functions allow for representation of the irreducible polynomials + * as an unsigned int[], say p. The irreducible f(t) is then of the form: + * t^p[0] + t^p[1] + ... + t^p[k] + * where m = p[0] > p[1] > ... > p[k] = 0. + */ +/* r = a mod p */ +int BN_GF2m_mod_arr(BIGNUM *r, const BIGNUM *a, const int p[]); +/* r = (a * b) mod p */ +int BN_GF2m_mod_mul_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const int p[], BN_CTX *ctx); +/* r = (a * a) mod p */ +int BN_GF2m_mod_sqr_arr(BIGNUM *r, const BIGNUM *a, const int p[], + BN_CTX *ctx); +/* r = (1 / b) mod p */ +int BN_GF2m_mod_inv_arr(BIGNUM *r, const BIGNUM *b, const int p[], + BN_CTX *ctx); +/* r = (a / b) mod p */ +int BN_GF2m_mod_div_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const int p[], BN_CTX *ctx); +/* r = (a ^ b) mod p */ +int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const int p[], BN_CTX *ctx); +/* r = sqrt(a) mod p */ +int BN_GF2m_mod_sqrt_arr(BIGNUM *r, const BIGNUM *a, + const int p[], BN_CTX *ctx); +/* r^2 + r = a mod p */ +int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a, + const int p[], BN_CTX *ctx); +int BN_GF2m_poly2arr(const BIGNUM *a, int p[], int max); +int BN_GF2m_arr2poly(const int p[], BIGNUM *a); + +# endif + +/* + * faster mod functions for the 'NIST primes' 0 <= a < p^2 + */ +int BN_nist_mod_192(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx); +int BN_nist_mod_224(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx); +int BN_nist_mod_256(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx); +int BN_nist_mod_384(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx); +int BN_nist_mod_521(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx); + +const BIGNUM *BN_get0_nist_prime_192(void); +const BIGNUM *BN_get0_nist_prime_224(void); +const BIGNUM *BN_get0_nist_prime_256(void); +const BIGNUM *BN_get0_nist_prime_384(void); +const BIGNUM *BN_get0_nist_prime_521(void); + +int (*BN_nist_mod_func(const BIGNUM *p)) (BIGNUM *r, const BIGNUM *a, + const BIGNUM *field, BN_CTX *ctx); + +int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range, + const BIGNUM *priv, const unsigned char *message, + size_t message_len, BN_CTX *ctx); + +/* Primes from RFC 2409 */ +BIGNUM *BN_get_rfc2409_prime_768(BIGNUM *bn); +BIGNUM *BN_get_rfc2409_prime_1024(BIGNUM *bn); + +/* Primes from RFC 3526 */ +BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *bn); +BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *bn); +BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *bn); +BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *bn); +BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *bn); +BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *bn); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define get_rfc2409_prime_768 BN_get_rfc2409_prime_768 +# define get_rfc2409_prime_1024 BN_get_rfc2409_prime_1024 +# define get_rfc3526_prime_1536 BN_get_rfc3526_prime_1536 +# define get_rfc3526_prime_2048 BN_get_rfc3526_prime_2048 +# define get_rfc3526_prime_3072 BN_get_rfc3526_prime_3072 +# define get_rfc3526_prime_4096 BN_get_rfc3526_prime_4096 +# define get_rfc3526_prime_6144 BN_get_rfc3526_prime_6144 +# define get_rfc3526_prime_8192 BN_get_rfc3526_prime_8192 +# endif + +int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/bnerr.h b/include/openssl/bnerr.h new file mode 100644 index 0000000..8a022cc --- /dev/null +++ b/include/openssl/bnerr.h @@ -0,0 +1,96 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BNERR_H +# define HEADER_BNERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_BN_strings(void); + +/* + * BN function codes. + */ +# define BN_F_BNRAND 127 +# define BN_F_BNRAND_RANGE 138 +# define BN_F_BN_BLINDING_CONVERT_EX 100 +# define BN_F_BN_BLINDING_CREATE_PARAM 128 +# define BN_F_BN_BLINDING_INVERT_EX 101 +# define BN_F_BN_BLINDING_NEW 102 +# define BN_F_BN_BLINDING_UPDATE 103 +# define BN_F_BN_BN2DEC 104 +# define BN_F_BN_BN2HEX 105 +# define BN_F_BN_COMPUTE_WNAF 142 +# define BN_F_BN_CTX_GET 116 +# define BN_F_BN_CTX_NEW 106 +# define BN_F_BN_CTX_START 129 +# define BN_F_BN_DIV 107 +# define BN_F_BN_DIV_RECP 130 +# define BN_F_BN_EXP 123 +# define BN_F_BN_EXPAND_INTERNAL 120 +# define BN_F_BN_GENCB_NEW 143 +# define BN_F_BN_GENERATE_DSA_NONCE 140 +# define BN_F_BN_GENERATE_PRIME_EX 141 +# define BN_F_BN_GF2M_MOD 131 +# define BN_F_BN_GF2M_MOD_EXP 132 +# define BN_F_BN_GF2M_MOD_MUL 133 +# define BN_F_BN_GF2M_MOD_SOLVE_QUAD 134 +# define BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR 135 +# define BN_F_BN_GF2M_MOD_SQR 136 +# define BN_F_BN_GF2M_MOD_SQRT 137 +# define BN_F_BN_LSHIFT 145 +# define BN_F_BN_MOD_EXP2_MONT 118 +# define BN_F_BN_MOD_EXP_MONT 109 +# define BN_F_BN_MOD_EXP_MONT_CONSTTIME 124 +# define BN_F_BN_MOD_EXP_MONT_WORD 117 +# define BN_F_BN_MOD_EXP_RECP 125 +# define BN_F_BN_MOD_EXP_SIMPLE 126 +# define BN_F_BN_MOD_INVERSE 110 +# define BN_F_BN_MOD_INVERSE_NO_BRANCH 139 +# define BN_F_BN_MOD_LSHIFT_QUICK 119 +# define BN_F_BN_MOD_SQRT 121 +# define BN_F_BN_MONT_CTX_NEW 149 +# define BN_F_BN_MPI2BN 112 +# define BN_F_BN_NEW 113 +# define BN_F_BN_POOL_GET 147 +# define BN_F_BN_RAND 114 +# define BN_F_BN_RAND_RANGE 122 +# define BN_F_BN_RECP_CTX_NEW 150 +# define BN_F_BN_RSHIFT 146 +# define BN_F_BN_SET_WORDS 144 +# define BN_F_BN_STACK_PUSH 148 +# define BN_F_BN_USUB 115 + +/* + * BN reason codes. + */ +# define BN_R_ARG2_LT_ARG3 100 +# define BN_R_BAD_RECIPROCAL 101 +# define BN_R_BIGNUM_TOO_LONG 114 +# define BN_R_BITS_TOO_SMALL 118 +# define BN_R_CALLED_WITH_EVEN_MODULUS 102 +# define BN_R_DIV_BY_ZERO 103 +# define BN_R_ENCODING_ERROR 104 +# define BN_R_EXPAND_ON_STATIC_BIGNUM_DATA 105 +# define BN_R_INPUT_NOT_REDUCED 110 +# define BN_R_INVALID_LENGTH 106 +# define BN_R_INVALID_RANGE 115 +# define BN_R_INVALID_SHIFT 119 +# define BN_R_NOT_A_SQUARE 111 +# define BN_R_NOT_INITIALIZED 107 +# define BN_R_NO_INVERSE 108 +# define BN_R_NO_SOLUTION 116 +# define BN_R_PRIVATE_KEY_TOO_LARGE 117 +# define BN_R_P_IS_NOT_PRIME 112 +# define BN_R_TOO_MANY_ITERATIONS 113 +# define BN_R_TOO_MANY_TEMPORARY_VARIABLES 109 + +#endif diff --git a/include/openssl/buffer.h b/include/openssl/buffer.h new file mode 100644 index 0000000..45dc975 --- /dev/null +++ b/include/openssl/buffer.h @@ -0,0 +1,58 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BUFFER_H +# define HEADER_BUFFER_H + +# include +# ifndef HEADER_CRYPTO_H +# include +# endif +# include + + +#ifdef __cplusplus +extern "C" { +#endif + +# include +# include + +/* + * These names are outdated as of OpenSSL 1.1; a future release + * will move them to be deprecated. + */ +# define BUF_strdup(s) OPENSSL_strdup(s) +# define BUF_strndup(s, size) OPENSSL_strndup(s, size) +# define BUF_memdup(data, size) OPENSSL_memdup(data, size) +# define BUF_strlcpy(dst, src, size) OPENSSL_strlcpy(dst, src, size) +# define BUF_strlcat(dst, src, size) OPENSSL_strlcat(dst, src, size) +# define BUF_strnlen(str, maxlen) OPENSSL_strnlen(str, maxlen) + +struct buf_mem_st { + size_t length; /* current number of bytes */ + char *data; + size_t max; /* size of buffer */ + unsigned long flags; +}; + +# define BUF_MEM_FLAG_SECURE 0x01 + +BUF_MEM *BUF_MEM_new(void); +BUF_MEM *BUF_MEM_new_ex(unsigned long flags); +void BUF_MEM_free(BUF_MEM *a); +size_t BUF_MEM_grow(BUF_MEM *str, size_t len); +size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len); +void BUF_reverse(unsigned char *out, const unsigned char *in, size_t siz); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/buffererr.h b/include/openssl/buffererr.h new file mode 100644 index 0000000..3aee132 --- /dev/null +++ b/include/openssl/buffererr.h @@ -0,0 +1,30 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BUFERR_H +# define HEADER_BUFERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_BUF_strings(void); + +/* + * BUF function codes. + */ +# define BUF_F_BUF_MEM_GROW 100 +# define BUF_F_BUF_MEM_GROW_CLEAN 105 +# define BUF_F_BUF_MEM_NEW 101 + +/* + * BUF reason codes. + */ + +#endif diff --git a/include/openssl/camellia.h b/include/openssl/camellia.h new file mode 100644 index 0000000..c3fa2f4 --- /dev/null +++ b/include/openssl/camellia.h @@ -0,0 +1,83 @@ +/* + * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CAMELLIA_H +# define HEADER_CAMELLIA_H + +# include + +# ifndef OPENSSL_NO_CAMELLIA +# include +#ifdef __cplusplus +extern "C" { +#endif + +# define CAMELLIA_ENCRYPT 1 +# define CAMELLIA_DECRYPT 0 + +/* + * Because array size can't be a const in C, the following two are macros. + * Both sizes are in bytes. + */ + +/* This should be a hidden type, but EVP requires that the size be known */ + +# define CAMELLIA_BLOCK_SIZE 16 +# define CAMELLIA_TABLE_BYTE_LEN 272 +# define CAMELLIA_TABLE_WORD_LEN (CAMELLIA_TABLE_BYTE_LEN / 4) + +typedef unsigned int KEY_TABLE_TYPE[CAMELLIA_TABLE_WORD_LEN]; /* to match + * with WORD */ + +struct camellia_key_st { + union { + double d; /* ensures 64-bit align */ + KEY_TABLE_TYPE rd_key; + } u; + int grand_rounds; +}; +typedef struct camellia_key_st CAMELLIA_KEY; + +int Camellia_set_key(const unsigned char *userKey, const int bits, + CAMELLIA_KEY *key); + +void Camellia_encrypt(const unsigned char *in, unsigned char *out, + const CAMELLIA_KEY *key); +void Camellia_decrypt(const unsigned char *in, unsigned char *out, + const CAMELLIA_KEY *key); + +void Camellia_ecb_encrypt(const unsigned char *in, unsigned char *out, + const CAMELLIA_KEY *key, const int enc); +void Camellia_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const CAMELLIA_KEY *key, + unsigned char *ivec, const int enc); +void Camellia_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const CAMELLIA_KEY *key, + unsigned char *ivec, int *num, const int enc); +void Camellia_cfb1_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const CAMELLIA_KEY *key, + unsigned char *ivec, int *num, const int enc); +void Camellia_cfb8_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const CAMELLIA_KEY *key, + unsigned char *ivec, int *num, const int enc); +void Camellia_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const CAMELLIA_KEY *key, + unsigned char *ivec, int *num); +void Camellia_ctr128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const CAMELLIA_KEY *key, + unsigned char ivec[CAMELLIA_BLOCK_SIZE], + unsigned char ecount_buf[CAMELLIA_BLOCK_SIZE], + unsigned int *num); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/cast.h b/include/openssl/cast.h new file mode 100644 index 0000000..74dad83 --- /dev/null +++ b/include/openssl/cast.h @@ -0,0 +1,53 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CAST_H +# define HEADER_CAST_H + +# include + +# ifndef OPENSSL_NO_CAST +# ifdef __cplusplus +extern "C" { +# endif + +# define CAST_ENCRYPT 1 +# define CAST_DECRYPT 0 + +# define CAST_LONG unsigned int + +# define CAST_BLOCK 8 +# define CAST_KEY_LENGTH 16 + +typedef struct cast_key_st { + CAST_LONG data[32]; + int short_key; /* Use reduced rounds for short key */ +} CAST_KEY; + +void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data); +void CAST_ecb_encrypt(const unsigned char *in, unsigned char *out, + const CAST_KEY *key, int enc); +void CAST_encrypt(CAST_LONG *data, const CAST_KEY *key); +void CAST_decrypt(CAST_LONG *data, const CAST_KEY *key); +void CAST_cbc_encrypt(const unsigned char *in, unsigned char *out, + long length, const CAST_KEY *ks, unsigned char *iv, + int enc); +void CAST_cfb64_encrypt(const unsigned char *in, unsigned char *out, + long length, const CAST_KEY *schedule, + unsigned char *ivec, int *num, int enc); +void CAST_ofb64_encrypt(const unsigned char *in, unsigned char *out, + long length, const CAST_KEY *schedule, + unsigned char *ivec, int *num); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/cmac.h b/include/openssl/cmac.h new file mode 100644 index 0000000..3e64bdd --- /dev/null +++ b/include/openssl/cmac.h @@ -0,0 +1,41 @@ +/* + * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CMAC_H +# define HEADER_CMAC_H + +# ifndef OPENSSL_NO_CMAC + +#ifdef __cplusplus +extern "C" { +#endif + +# include + +/* Opaque */ +typedef struct CMAC_CTX_st CMAC_CTX; + +CMAC_CTX *CMAC_CTX_new(void); +void CMAC_CTX_cleanup(CMAC_CTX *ctx); +void CMAC_CTX_free(CMAC_CTX *ctx); +EVP_CIPHER_CTX *CMAC_CTX_get0_cipher_ctx(CMAC_CTX *ctx); +int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in); + +int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t keylen, + const EVP_CIPHER *cipher, ENGINE *impl); +int CMAC_Update(CMAC_CTX *ctx, const void *data, size_t dlen); +int CMAC_Final(CMAC_CTX *ctx, unsigned char *out, size_t *poutlen); +int CMAC_resume(CMAC_CTX *ctx); + +#ifdef __cplusplus +} +#endif + +# endif +#endif diff --git a/include/openssl/cms.h b/include/openssl/cms.h new file mode 100644 index 0000000..1859f15 --- /dev/null +++ b/include/openssl/cms.h @@ -0,0 +1,342 @@ +/* + * Copyright 2008-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CMS_H +# define HEADER_CMS_H + +# include + +# ifndef OPENSSL_NO_CMS +# include +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +typedef struct CMS_ContentInfo_st CMS_ContentInfo; +typedef struct CMS_SignerInfo_st CMS_SignerInfo; +typedef struct CMS_CertificateChoices CMS_CertificateChoices; +typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; +typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; +typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; +typedef struct CMS_Receipt_st CMS_Receipt; +typedef struct CMS_RecipientEncryptedKey_st CMS_RecipientEncryptedKey; +typedef struct CMS_OtherKeyAttribute_st CMS_OtherKeyAttribute; + +DEFINE_STACK_OF(CMS_SignerInfo) +DEFINE_STACK_OF(CMS_RecipientEncryptedKey) +DEFINE_STACK_OF(CMS_RecipientInfo) +DEFINE_STACK_OF(CMS_RevocationInfoChoice) +DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) + +# define CMS_SIGNERINFO_ISSUER_SERIAL 0 +# define CMS_SIGNERINFO_KEYIDENTIFIER 1 + +# define CMS_RECIPINFO_NONE -1 +# define CMS_RECIPINFO_TRANS 0 +# define CMS_RECIPINFO_AGREE 1 +# define CMS_RECIPINFO_KEK 2 +# define CMS_RECIPINFO_PASS 3 +# define CMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +# define CMS_TEXT 0x1 +# define CMS_NOCERTS 0x2 +# define CMS_NO_CONTENT_VERIFY 0x4 +# define CMS_NO_ATTR_VERIFY 0x8 +# define CMS_NOSIGS \ + (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) +# define CMS_NOINTERN 0x10 +# define CMS_NO_SIGNER_CERT_VERIFY 0x20 +# define CMS_NOVERIFY 0x20 +# define CMS_DETACHED 0x40 +# define CMS_BINARY 0x80 +# define CMS_NOATTR 0x100 +# define CMS_NOSMIMECAP 0x200 +# define CMS_NOOLDMIMETYPE 0x400 +# define CMS_CRLFEOL 0x800 +# define CMS_STREAM 0x1000 +# define CMS_NOCRL 0x2000 +# define CMS_PARTIAL 0x4000 +# define CMS_REUSE_DIGEST 0x8000 +# define CMS_USE_KEYID 0x10000 +# define CMS_DEBUG_DECRYPT 0x20000 +# define CMS_KEY_PARAM 0x40000 +# define CMS_ASCIICRLF 0x80000 + +const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms); + +BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); +int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); + +ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); +int CMS_is_detached(CMS_ContentInfo *cms); +int CMS_set_detached(CMS_ContentInfo *cms, int detached); + +# ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) +# endif +int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); +CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); +int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); + +BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); +int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, + int flags); +CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); +int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); + +int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, + unsigned int flags); + +CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, BIO *data, + unsigned int flags); + +CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, unsigned int flags); + +int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); +CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); + +int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, + size_t keylen, unsigned int flags); + +int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); + +CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, unsigned int flags); + +int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); +int CMS_decrypt_set1_key(CMS_ContentInfo *cms, + unsigned char *key, size_t keylen, + const unsigned char *id, size_t idlen); +int CMS_decrypt_set1_password(CMS_ContentInfo *cms, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); +int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); +EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri); +CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); +CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, + X509 *recip, unsigned int flags); +int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); +int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); +int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, + ASN1_INTEGER **sno); + +CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, + int iter, int wrap_nid, + int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); +int CMS_RecipientInfo_encrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); + +int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); +const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); + +CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); +int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); +int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); +STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); + +CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); +int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); +int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); +STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); + +int CMS_SignedData_init(CMS_ContentInfo *cms); +CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si); +EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si); +STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); + +void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); +int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); +int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + unsigned int flags); +void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, + X509 **signer, X509_ALGOR **pdig, + X509_ALGOR **psig); +ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si); +int CMS_SignerInfo_sign(CMS_SignerInfo *si); +int CMS_SignerInfo_verify(CMS_SignerInfo *si); +int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); + +int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int CMS_signed_get_attr_count(const CMS_SignerInfo *si); +int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *oid, + int lastpos, int type); + +int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); +int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int lastpos); +X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +# ifdef HEADER_X509V3_H + +int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); +CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) + *receiptList, STACK_OF(GENERAL_NAMES) + *receiptsTo); +int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); +void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); +# endif +int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pukm); +STACK_OF(CMS_RecipientEncryptedKey) +*CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri); + +int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri, + X509_ALGOR **pubalg, + ASN1_BIT_STRING **pubkey, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, + ASN1_INTEGER **sno); + +int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert); + +int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek, + ASN1_OCTET_STRING **keyid, + ASN1_GENERALIZEDTIME **tm, + CMS_OtherKeyAttribute **other, + X509_NAME **issuer, ASN1_INTEGER **sno); +int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek, + X509 *cert); +int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk); +EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri); +int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms, + CMS_RecipientInfo *ri, + CMS_RecipientEncryptedKey *rek); + +int CMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg, + ASN1_OCTET_STRING *ukm, int keylen); + +/* Backward compatibility for spelling errors. */ +# define CMS_R_UNKNOWN_DIGEST_ALGORITM CMS_R_UNKNOWN_DIGEST_ALGORITHM +# define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \ + CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/cmserr.h b/include/openssl/cmserr.h new file mode 100644 index 0000000..7225243 --- /dev/null +++ b/include/openssl/cmserr.h @@ -0,0 +1,196 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CMSERR_H +# define HEADER_CMSERR_H + +# include + +# ifndef OPENSSL_NO_CMS + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_CMS_strings(void); + +/* + * CMS function codes. + */ +# define CMS_F_CHECK_CONTENT 99 +# define CMS_F_CMS_ADD0_CERT 164 +# define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 +# define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 +# define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 +# define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 +# define CMS_F_CMS_ADD1_SIGNER 102 +# define CMS_F_CMS_ADD1_SIGNINGTIME 103 +# define CMS_F_CMS_COMPRESS 104 +# define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 +# define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 +# define CMS_F_CMS_COPY_CONTENT 107 +# define CMS_F_CMS_COPY_MESSAGEDIGEST 108 +# define CMS_F_CMS_DATA 109 +# define CMS_F_CMS_DATAFINAL 110 +# define CMS_F_CMS_DATAINIT 111 +# define CMS_F_CMS_DECRYPT 112 +# define CMS_F_CMS_DECRYPT_SET1_KEY 113 +# define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 +# define CMS_F_CMS_DECRYPT_SET1_PKEY 114 +# define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 +# define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 +# define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 +# define CMS_F_CMS_DIGEST_VERIFY 118 +# define CMS_F_CMS_ENCODE_RECEIPT 161 +# define CMS_F_CMS_ENCRYPT 119 +# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT 179 +# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 +# define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 +# define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 +# define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 +# define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 +# define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 +# define CMS_F_CMS_ENVELOPED_DATA_INIT 126 +# define CMS_F_CMS_ENV_ASN1_CTRL 171 +# define CMS_F_CMS_FINAL 127 +# define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 +# define CMS_F_CMS_GET0_CONTENT 129 +# define CMS_F_CMS_GET0_ECONTENT_TYPE 130 +# define CMS_F_CMS_GET0_ENVELOPED 131 +# define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 +# define CMS_F_CMS_GET0_SIGNED 133 +# define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 +# define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 +# define CMS_F_CMS_RECEIPT_VERIFY 160 +# define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 +# define CMS_F_CMS_RECIPIENTINFO_ENCRYPT 169 +# define CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT 178 +# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG 175 +# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID 173 +# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS 172 +# define CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP 174 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +# define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 +# define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 +# define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 +# define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 +# define CMS_F_CMS_SD_ASN1_CTRL 170 +# define CMS_F_CMS_SET1_IAS 176 +# define CMS_F_CMS_SET1_KEYID 177 +# define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 +# define CMS_F_CMS_SET_DETACHED 147 +# define CMS_F_CMS_SIGN 148 +# define CMS_F_CMS_SIGNED_DATA_INIT 149 +# define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 +# define CMS_F_CMS_SIGNERINFO_SIGN 151 +# define CMS_F_CMS_SIGNERINFO_VERIFY 152 +# define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 +# define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 +# define CMS_F_CMS_SIGN_RECEIPT 163 +# define CMS_F_CMS_STREAM 155 +# define CMS_F_CMS_UNCOMPRESS 156 +# define CMS_F_CMS_VERIFY 157 +# define CMS_F_KEK_UNWRAP_KEY 180 + +/* + * CMS reason codes. + */ +# define CMS_R_ADD_SIGNER_ERROR 99 +# define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 +# define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 +# define CMS_R_CERTIFICATE_VERIFY_ERROR 100 +# define CMS_R_CIPHER_INITIALISATION_ERROR 101 +# define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +# define CMS_R_CMS_DATAFINAL_ERROR 103 +# define CMS_R_CMS_LIB 104 +# define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 +# define CMS_R_CONTENT_NOT_FOUND 105 +# define CMS_R_CONTENT_TYPE_MISMATCH 171 +# define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +# define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +# define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +# define CMS_R_CONTENT_VERIFY_ERROR 109 +# define CMS_R_CTRL_ERROR 110 +# define CMS_R_CTRL_FAILURE 111 +# define CMS_R_DECRYPT_ERROR 112 +# define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 +# define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +# define CMS_R_ERROR_SETTING_KEY 115 +# define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 +# define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +# define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +# define CMS_R_INVALID_KEY_LENGTH 118 +# define CMS_R_MD_BIO_INIT_ERROR 119 +# define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +# define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +# define CMS_R_MSGSIGDIGEST_ERROR 172 +# define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +# define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +# define CMS_R_NEED_ONE_SIGNER 164 +# define CMS_R_NOT_A_SIGNED_RECEIPT 165 +# define CMS_R_NOT_ENCRYPTED_DATA 122 +# define CMS_R_NOT_KEK 123 +# define CMS_R_NOT_KEY_AGREEMENT 181 +# define CMS_R_NOT_KEY_TRANSPORT 124 +# define CMS_R_NOT_PWRI 177 +# define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +# define CMS_R_NO_CIPHER 126 +# define CMS_R_NO_CONTENT 127 +# define CMS_R_NO_CONTENT_TYPE 173 +# define CMS_R_NO_DEFAULT_DIGEST 128 +# define CMS_R_NO_DIGEST_SET 129 +# define CMS_R_NO_KEY 130 +# define CMS_R_NO_KEY_OR_CERT 174 +# define CMS_R_NO_MATCHING_DIGEST 131 +# define CMS_R_NO_MATCHING_RECIPIENT 132 +# define CMS_R_NO_MATCHING_SIGNATURE 166 +# define CMS_R_NO_MSGSIGDIGEST 167 +# define CMS_R_NO_PASSWORD 178 +# define CMS_R_NO_PRIVATE_KEY 133 +# define CMS_R_NO_PUBLIC_KEY 134 +# define CMS_R_NO_RECEIPT_REQUEST 168 +# define CMS_R_NO_SIGNERS 135 +# define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +# define CMS_R_RECEIPT_DECODE_ERROR 169 +# define CMS_R_RECIPIENT_ERROR 137 +# define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +# define CMS_R_SIGNFINAL_ERROR 139 +# define CMS_R_SMIME_TEXT_ERROR 140 +# define CMS_R_STORE_INIT_ERROR 141 +# define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 +# define CMS_R_TYPE_NOT_DATA 143 +# define CMS_R_TYPE_NOT_DIGESTED_DATA 144 +# define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +# define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 +# define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +# define CMS_R_UNKNOWN_CIPHER 148 +# define CMS_R_UNKNOWN_DIGEST_ALGORITHM 149 +# define CMS_R_UNKNOWN_ID 150 +# define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +# define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 +# define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +# define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +# define CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE 155 +# define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +# define CMS_R_UNSUPPORTED_TYPE 156 +# define CMS_R_UNWRAP_ERROR 157 +# define CMS_R_UNWRAP_FAILURE 180 +# define CMS_R_VERIFICATION_FAILURE 158 +# define CMS_R_WRAP_ERROR 159 + +# endif +#endif diff --git a/include/openssl/comp.h b/include/openssl/comp.h new file mode 100644 index 0000000..a337bd6 --- /dev/null +++ b/include/openssl/comp.h @@ -0,0 +1,53 @@ +/* + * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_COMP_H +# define HEADER_COMP_H + +# include + +# ifndef OPENSSL_NO_COMP +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + + + +COMP_CTX *COMP_CTX_new(COMP_METHOD *meth); +const COMP_METHOD *COMP_CTX_get_method(const COMP_CTX *ctx); +int COMP_CTX_get_type(const COMP_CTX* comp); +int COMP_get_type(const COMP_METHOD *meth); +const char *COMP_get_name(const COMP_METHOD *meth); +void COMP_CTX_free(COMP_CTX *ctx); + +int COMP_compress_block(COMP_CTX *ctx, unsigned char *out, int olen, + unsigned char *in, int ilen); +int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen, + unsigned char *in, int ilen); + +COMP_METHOD *COMP_zlib(void); + +#if OPENSSL_API_COMPAT < 0x10100000L +#define COMP_zlib_cleanup() while(0) continue +#endif + +# ifdef HEADER_BIO_H +# ifdef ZLIB +const BIO_METHOD *BIO_f_zlib(void); +# endif +# endif + + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/comperr.h b/include/openssl/comperr.h new file mode 100644 index 0000000..49a589f --- /dev/null +++ b/include/openssl/comperr.h @@ -0,0 +1,40 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_COMPERR_H +# define HEADER_COMPERR_H + +# include + +# ifndef OPENSSL_NO_COMP + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_COMP_strings(void); + +/* + * COMP function codes. + */ +# define COMP_F_BIO_ZLIB_FLUSH 99 +# define COMP_F_BIO_ZLIB_NEW 100 +# define COMP_F_BIO_ZLIB_READ 101 +# define COMP_F_BIO_ZLIB_WRITE 102 +# define COMP_F_COMP_CTX_NEW 103 + +/* + * COMP reason codes. + */ +# define COMP_R_ZLIB_DEFLATE_ERROR 99 +# define COMP_R_ZLIB_INFLATE_ERROR 100 +# define COMP_R_ZLIB_NOT_SUPPORTED 101 + +# endif +#endif diff --git a/include/openssl/conf.h b/include/openssl/conf.h new file mode 100644 index 0000000..f57d321 --- /dev/null +++ b/include/openssl/conf.h @@ -0,0 +1,168 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CONF_H +# define HEADER_CONF_H + +# include +# include +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + char *section; + char *name; + char *value; +} CONF_VALUE; + +DEFINE_STACK_OF(CONF_VALUE) +DEFINE_LHASH_OF(CONF_VALUE); + +struct conf_st; +struct conf_method_st; +typedef struct conf_method_st CONF_METHOD; + +struct conf_method_st { + const char *name; + CONF *(*create) (CONF_METHOD *meth); + int (*init) (CONF *conf); + int (*destroy) (CONF *conf); + int (*destroy_data) (CONF *conf); + int (*load_bio) (CONF *conf, BIO *bp, long *eline); + int (*dump) (const CONF *conf, BIO *bp); + int (*is_number) (const CONF *conf, char c); + int (*to_int) (const CONF *conf, char c); + int (*load) (CONF *conf, const char *name, long *eline); +}; + +/* Module definitions */ + +typedef struct conf_imodule_st CONF_IMODULE; +typedef struct conf_module_st CONF_MODULE; + +DEFINE_STACK_OF(CONF_MODULE) +DEFINE_STACK_OF(CONF_IMODULE) + +/* DSO module function typedefs */ +typedef int conf_init_func (CONF_IMODULE *md, const CONF *cnf); +typedef void conf_finish_func (CONF_IMODULE *md); + +# define CONF_MFLAGS_IGNORE_ERRORS 0x1 +# define CONF_MFLAGS_IGNORE_RETURN_CODES 0x2 +# define CONF_MFLAGS_SILENT 0x4 +# define CONF_MFLAGS_NO_DSO 0x8 +# define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10 +# define CONF_MFLAGS_DEFAULT_SECTION 0x20 + +int CONF_set_default_method(CONF_METHOD *meth); +void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash); +LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file, + long *eline); +# ifndef OPENSSL_NO_STDIO +LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp, + long *eline); +# endif +LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp, + long *eline); +STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf, + const char *section); +char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group, + const char *name); +long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group, + const char *name); +void CONF_free(LHASH_OF(CONF_VALUE) *conf); +#ifndef OPENSSL_NO_STDIO +int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out); +#endif +int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out); + +DEPRECATEDIN_1_1_0(void OPENSSL_config(const char *config_name)) + +#if OPENSSL_API_COMPAT < 0x10100000L +# define OPENSSL_no_config() \ + OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, NULL) +#endif + +/* + * New conf code. The semantics are different from the functions above. If + * that wasn't the case, the above functions would have been replaced + */ + +struct conf_st { + CONF_METHOD *meth; + void *meth_data; + LHASH_OF(CONF_VALUE) *data; +}; + +CONF *NCONF_new(CONF_METHOD *meth); +CONF_METHOD *NCONF_default(void); +CONF_METHOD *NCONF_WIN32(void); +void NCONF_free(CONF *conf); +void NCONF_free_data(CONF *conf); + +int NCONF_load(CONF *conf, const char *file, long *eline); +# ifndef OPENSSL_NO_STDIO +int NCONF_load_fp(CONF *conf, FILE *fp, long *eline); +# endif +int NCONF_load_bio(CONF *conf, BIO *bp, long *eline); +STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, + const char *section); +char *NCONF_get_string(const CONF *conf, const char *group, const char *name); +int NCONF_get_number_e(const CONF *conf, const char *group, const char *name, + long *result); +#ifndef OPENSSL_NO_STDIO +int NCONF_dump_fp(const CONF *conf, FILE *out); +#endif +int NCONF_dump_bio(const CONF *conf, BIO *out); + +#define NCONF_get_number(c,g,n,r) NCONF_get_number_e(c,g,n,r) + +/* Module functions */ + +int CONF_modules_load(const CONF *cnf, const char *appname, + unsigned long flags); +int CONF_modules_load_file(const char *filename, const char *appname, + unsigned long flags); +void CONF_modules_unload(int all); +void CONF_modules_finish(void); +#if OPENSSL_API_COMPAT < 0x10100000L +# define CONF_modules_free() while(0) continue +#endif +int CONF_module_add(const char *name, conf_init_func *ifunc, + conf_finish_func *ffunc); + +const char *CONF_imodule_get_name(const CONF_IMODULE *md); +const char *CONF_imodule_get_value(const CONF_IMODULE *md); +void *CONF_imodule_get_usr_data(const CONF_IMODULE *md); +void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data); +CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md); +unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md); +void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags); +void *CONF_module_get_usr_data(CONF_MODULE *pmod); +void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data); + +char *CONF_get1_default_config_file(void); + +int CONF_parse_list(const char *list, int sep, int nospc, + int (*list_cb) (const char *elem, int len, void *usr), + void *arg); + +void OPENSSL_load_builtin_modules(void); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/conf_api.h b/include/openssl/conf_api.h new file mode 100644 index 0000000..6ae8a30 --- /dev/null +++ b/include/openssl/conf_api.h @@ -0,0 +1,40 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CONF_API_H +# define HEADER_CONF_API_H + +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Up until OpenSSL 0.9.5a, this was new_section */ +CONF_VALUE *_CONF_new_section(CONF *conf, const char *section); +/* Up until OpenSSL 0.9.5a, this was get_section */ +CONF_VALUE *_CONF_get_section(const CONF *conf, const char *section); +/* Up until OpenSSL 0.9.5a, this was CONF_get_section */ +STACK_OF(CONF_VALUE) *_CONF_get_section_values(const CONF *conf, + const char *section); + +int _CONF_add_string(CONF *conf, CONF_VALUE *section, CONF_VALUE *value); +char *_CONF_get_string(const CONF *conf, const char *section, + const char *name); +long _CONF_get_number(const CONF *conf, const char *section, + const char *name); + +int _CONF_new_data(CONF *conf); +void _CONF_free_data(CONF *conf); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/conferr.h b/include/openssl/conferr.h new file mode 100644 index 0000000..d1c92f4 --- /dev/null +++ b/include/openssl/conferr.h @@ -0,0 +1,72 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CONFERR_H +# define HEADER_CONFERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_CONF_strings(void); + +/* + * CONF function codes. + */ +# define CONF_F_CONF_DUMP_FP 104 +# define CONF_F_CONF_LOAD 100 +# define CONF_F_CONF_LOAD_FP 103 +# define CONF_F_CONF_PARSE_LIST 119 +# define CONF_F_DEF_LOAD 120 +# define CONF_F_DEF_LOAD_BIO 121 +# define CONF_F_GET_NEXT_FILE 107 +# define CONF_F_MODULE_ADD 122 +# define CONF_F_MODULE_INIT 115 +# define CONF_F_MODULE_LOAD_DSO 117 +# define CONF_F_MODULE_RUN 118 +# define CONF_F_NCONF_DUMP_BIO 105 +# define CONF_F_NCONF_DUMP_FP 106 +# define CONF_F_NCONF_GET_NUMBER_E 112 +# define CONF_F_NCONF_GET_SECTION 108 +# define CONF_F_NCONF_GET_STRING 109 +# define CONF_F_NCONF_LOAD 113 +# define CONF_F_NCONF_LOAD_BIO 110 +# define CONF_F_NCONF_LOAD_FP 114 +# define CONF_F_NCONF_NEW 111 +# define CONF_F_PROCESS_INCLUDE 116 +# define CONF_F_SSL_MODULE_INIT 123 +# define CONF_F_STR_COPY 101 + +/* + * CONF reason codes. + */ +# define CONF_R_ERROR_LOADING_DSO 110 +# define CONF_R_LIST_CANNOT_BE_NULL 115 +# define CONF_R_MISSING_CLOSE_SQUARE_BRACKET 100 +# define CONF_R_MISSING_EQUAL_SIGN 101 +# define CONF_R_MISSING_INIT_FUNCTION 112 +# define CONF_R_MODULE_INITIALIZATION_ERROR 109 +# define CONF_R_NO_CLOSE_BRACE 102 +# define CONF_R_NO_CONF 105 +# define CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE 106 +# define CONF_R_NO_SECTION 107 +# define CONF_R_NO_SUCH_FILE 114 +# define CONF_R_NO_VALUE 108 +# define CONF_R_NUMBER_TOO_LARGE 121 +# define CONF_R_RECURSIVE_DIRECTORY_INCLUDE 111 +# define CONF_R_SSL_COMMAND_SECTION_EMPTY 117 +# define CONF_R_SSL_COMMAND_SECTION_NOT_FOUND 118 +# define CONF_R_SSL_SECTION_EMPTY 119 +# define CONF_R_SSL_SECTION_NOT_FOUND 120 +# define CONF_R_UNABLE_TO_CREATE_NEW_SECTION 103 +# define CONF_R_UNKNOWN_MODULE_NAME 113 +# define CONF_R_VARIABLE_EXPANSION_TOO_LONG 116 +# define CONF_R_VARIABLE_HAS_NO_VALUE 104 + +#endif diff --git a/include/openssl/crypto.h b/include/openssl/crypto.h new file mode 100644 index 0000000..cc7c565 --- /dev/null +++ b/include/openssl/crypto.h @@ -0,0 +1,445 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CRYPTO_H +# define HEADER_CRYPTO_H + +# include +# include + +# include + +# ifndef OPENSSL_NO_STDIO +# include +# endif + +# include +# include +# include +# include +# include + +# ifdef CHARSET_EBCDIC +# include +# endif + +/* + * Resolve problems on some operating systems with symbol names that clash + * one way or another + */ +# include + +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# endif + +#ifdef __cplusplus +extern "C" { +#endif + +# if OPENSSL_API_COMPAT < 0x10100000L +# define SSLeay OpenSSL_version_num +# define SSLeay_version OpenSSL_version +# define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER +# define SSLEAY_VERSION OPENSSL_VERSION +# define SSLEAY_CFLAGS OPENSSL_CFLAGS +# define SSLEAY_BUILT_ON OPENSSL_BUILT_ON +# define SSLEAY_PLATFORM OPENSSL_PLATFORM +# define SSLEAY_DIR OPENSSL_DIR + +/* + * Old type for allocating dynamic locks. No longer used. Use the new thread + * API instead. + */ +typedef struct { + int dummy; +} CRYPTO_dynlock; + +# endif /* OPENSSL_API_COMPAT */ + +typedef void CRYPTO_RWLOCK; + +CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void); +int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock); +int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock); +int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock); +void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock); + +int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock); + +/* + * The following can be used to detect memory leaks in the library. If + * used, it turns on malloc checking + */ +# define CRYPTO_MEM_CHECK_OFF 0x0 /* Control only */ +# define CRYPTO_MEM_CHECK_ON 0x1 /* Control and mode bit */ +# define CRYPTO_MEM_CHECK_ENABLE 0x2 /* Control and mode bit */ +# define CRYPTO_MEM_CHECK_DISABLE 0x3 /* Control only */ + +struct crypto_ex_data_st { + STACK_OF(void) *sk; +}; +DEFINE_STACK_OF(void) + +/* + * Per class, we have a STACK of function pointers. + */ +# define CRYPTO_EX_INDEX_SSL 0 +# define CRYPTO_EX_INDEX_SSL_CTX 1 +# define CRYPTO_EX_INDEX_SSL_SESSION 2 +# define CRYPTO_EX_INDEX_X509 3 +# define CRYPTO_EX_INDEX_X509_STORE 4 +# define CRYPTO_EX_INDEX_X509_STORE_CTX 5 +# define CRYPTO_EX_INDEX_DH 6 +# define CRYPTO_EX_INDEX_DSA 7 +# define CRYPTO_EX_INDEX_EC_KEY 8 +# define CRYPTO_EX_INDEX_RSA 9 +# define CRYPTO_EX_INDEX_ENGINE 10 +# define CRYPTO_EX_INDEX_UI 11 +# define CRYPTO_EX_INDEX_BIO 12 +# define CRYPTO_EX_INDEX_APP 13 +# define CRYPTO_EX_INDEX_UI_METHOD 14 +# define CRYPTO_EX_INDEX_DRBG 15 +# define CRYPTO_EX_INDEX__COUNT 16 + +/* + * This is the default callbacks, but we can have others as well: this is + * needed in Win32 where the application malloc and the library malloc may + * not be the same. + */ +#define OPENSSL_malloc_init() \ + CRYPTO_set_mem_functions(CRYPTO_malloc, CRYPTO_realloc, CRYPTO_free) + +int CRYPTO_mem_ctrl(int mode); + +# define OPENSSL_malloc(num) \ + CRYPTO_malloc(num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_zalloc(num) \ + CRYPTO_zalloc(num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_realloc(addr, num) \ + CRYPTO_realloc(addr, num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_clear_realloc(addr, old_num, num) \ + CRYPTO_clear_realloc(addr, old_num, num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_clear_free(addr, num) \ + CRYPTO_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_free(addr) \ + CRYPTO_free(addr, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_memdup(str, s) \ + CRYPTO_memdup((str), s, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_strdup(str) \ + CRYPTO_strdup(str, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_strndup(str, n) \ + CRYPTO_strndup(str, n, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_secure_malloc(num) \ + CRYPTO_secure_malloc(num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_secure_zalloc(num) \ + CRYPTO_secure_zalloc(num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_secure_free(addr) \ + CRYPTO_secure_free(addr, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_secure_clear_free(addr, num) \ + CRYPTO_secure_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_secure_actual_size(ptr) \ + CRYPTO_secure_actual_size(ptr) + +size_t OPENSSL_strlcpy(char *dst, const char *src, size_t siz); +size_t OPENSSL_strlcat(char *dst, const char *src, size_t siz); +size_t OPENSSL_strnlen(const char *str, size_t maxlen); +char *OPENSSL_buf2hexstr(const unsigned char *buffer, long len); +unsigned char *OPENSSL_hexstr2buf(const char *str, long *len); +int OPENSSL_hexchar2int(unsigned char c); + +# define OPENSSL_MALLOC_MAX_NELEMS(type) (((1U<<(sizeof(int)*8-1))-1)/sizeof(type)) + +unsigned long OpenSSL_version_num(void); +const char *OpenSSL_version(int type); +# define OPENSSL_VERSION 0 +# define OPENSSL_CFLAGS 1 +# define OPENSSL_BUILT_ON 2 +# define OPENSSL_PLATFORM 3 +# define OPENSSL_DIR 4 +# define OPENSSL_ENGINES_DIR 5 + +int OPENSSL_issetugid(void); + +typedef void CRYPTO_EX_new (void *parent, void *ptr, CRYPTO_EX_DATA *ad, + int idx, long argl, void *argp); +typedef void CRYPTO_EX_free (void *parent, void *ptr, CRYPTO_EX_DATA *ad, + int idx, long argl, void *argp); +typedef int CRYPTO_EX_dup (CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, + void *from_d, int idx, long argl, void *argp); +__owur int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp, + CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, + CRYPTO_EX_free *free_func); +/* No longer use an index. */ +int CRYPTO_free_ex_index(int class_index, int idx); + +/* + * Initialise/duplicate/free CRYPTO_EX_DATA variables corresponding to a + * given class (invokes whatever per-class callbacks are applicable) + */ +int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad); +int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to, + const CRYPTO_EX_DATA *from); + +void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad); + +/* + * Get/set data in a CRYPTO_EX_DATA variable corresponding to a particular + * index (relative to the class type involved) + */ +int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val); +void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx); + +# if OPENSSL_API_COMPAT < 0x10100000L +/* + * This function cleans up all "ex_data" state. It mustn't be called under + * potential race-conditions. + */ +# define CRYPTO_cleanup_all_ex_data() while(0) continue + +/* + * The old locking functions have been removed completely without compatibility + * macros. This is because the old functions either could not properly report + * errors, or the returned error values were not clearly documented. + * Replacing the locking functions with no-ops would cause race condition + * issues in the affected applications. It is far better for them to fail at + * compile time. + * On the other hand, the locking callbacks are no longer used. Consequently, + * the callback management functions can be safely replaced with no-op macros. + */ +# define CRYPTO_num_locks() (1) +# define CRYPTO_set_locking_callback(func) +# define CRYPTO_get_locking_callback() (NULL) +# define CRYPTO_set_add_lock_callback(func) +# define CRYPTO_get_add_lock_callback() (NULL) + +/* + * These defines where used in combination with the old locking callbacks, + * they are not called anymore, but old code that's not called might still + * use them. + */ +# define CRYPTO_LOCK 1 +# define CRYPTO_UNLOCK 2 +# define CRYPTO_READ 4 +# define CRYPTO_WRITE 8 + +/* This structure is no longer used */ +typedef struct crypto_threadid_st { + int dummy; +} CRYPTO_THREADID; +/* Only use CRYPTO_THREADID_set_[numeric|pointer]() within callbacks */ +# define CRYPTO_THREADID_set_numeric(id, val) +# define CRYPTO_THREADID_set_pointer(id, ptr) +# define CRYPTO_THREADID_set_callback(threadid_func) (0) +# define CRYPTO_THREADID_get_callback() (NULL) +# define CRYPTO_THREADID_current(id) +# define CRYPTO_THREADID_cmp(a, b) (-1) +# define CRYPTO_THREADID_cpy(dest, src) +# define CRYPTO_THREADID_hash(id) (0UL) + +# if OPENSSL_API_COMPAT < 0x10000000L +# define CRYPTO_set_id_callback(func) +# define CRYPTO_get_id_callback() (NULL) +# define CRYPTO_thread_id() (0UL) +# endif /* OPENSSL_API_COMPAT < 0x10000000L */ + +# define CRYPTO_set_dynlock_create_callback(dyn_create_function) +# define CRYPTO_set_dynlock_lock_callback(dyn_lock_function) +# define CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function) +# define CRYPTO_get_dynlock_create_callback() (NULL) +# define CRYPTO_get_dynlock_lock_callback() (NULL) +# define CRYPTO_get_dynlock_destroy_callback() (NULL) +# endif /* OPENSSL_API_COMPAT < 0x10100000L */ + +int CRYPTO_set_mem_functions( + void *(*m) (size_t, const char *, int), + void *(*r) (void *, size_t, const char *, int), + void (*f) (void *, const char *, int)); +int CRYPTO_set_mem_debug(int flag); +void CRYPTO_get_mem_functions( + void *(**m) (size_t, const char *, int), + void *(**r) (void *, size_t, const char *, int), + void (**f) (void *, const char *, int)); + +void *CRYPTO_malloc(size_t num, const char *file, int line); +void *CRYPTO_zalloc(size_t num, const char *file, int line); +void *CRYPTO_memdup(const void *str, size_t siz, const char *file, int line); +char *CRYPTO_strdup(const char *str, const char *file, int line); +char *CRYPTO_strndup(const char *str, size_t s, const char *file, int line); +void CRYPTO_free(void *ptr, const char *file, int line); +void CRYPTO_clear_free(void *ptr, size_t num, const char *file, int line); +void *CRYPTO_realloc(void *addr, size_t num, const char *file, int line); +void *CRYPTO_clear_realloc(void *addr, size_t old_num, size_t num, + const char *file, int line); + +int CRYPTO_secure_malloc_init(size_t sz, int minsize); +int CRYPTO_secure_malloc_done(void); +void *CRYPTO_secure_malloc(size_t num, const char *file, int line); +void *CRYPTO_secure_zalloc(size_t num, const char *file, int line); +void CRYPTO_secure_free(void *ptr, const char *file, int line); +void CRYPTO_secure_clear_free(void *ptr, size_t num, + const char *file, int line); +int CRYPTO_secure_allocated(const void *ptr); +int CRYPTO_secure_malloc_initialized(void); +size_t CRYPTO_secure_actual_size(void *ptr); +size_t CRYPTO_secure_used(void); + +void OPENSSL_cleanse(void *ptr, size_t len); + +# ifndef OPENSSL_NO_CRYPTO_MDEBUG +# define OPENSSL_mem_debug_push(info) \ + CRYPTO_mem_debug_push(info, OPENSSL_FILE, OPENSSL_LINE) +# define OPENSSL_mem_debug_pop() \ + CRYPTO_mem_debug_pop() +int CRYPTO_mem_debug_push(const char *info, const char *file, int line); +int CRYPTO_mem_debug_pop(void); +void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount); + +/*- + * Debugging functions (enabled by CRYPTO_set_mem_debug(1)) + * The flag argument has the following significance: + * 0: called before the actual memory allocation has taken place + * 1: called after the actual memory allocation has taken place + */ +void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag, + const char *file, int line); +void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag, + const char *file, int line); +void CRYPTO_mem_debug_free(void *addr, int flag, + const char *file, int line); + +int CRYPTO_mem_leaks_cb(int (*cb) (const char *str, size_t len, void *u), + void *u); +# ifndef OPENSSL_NO_STDIO +int CRYPTO_mem_leaks_fp(FILE *); +# endif +int CRYPTO_mem_leaks(BIO *bio); +# endif + +/* die if we have to */ +ossl_noreturn void OPENSSL_die(const char *assertion, const char *file, int line); +# if OPENSSL_API_COMPAT < 0x10100000L +# define OpenSSLDie(f,l,a) OPENSSL_die((a),(f),(l)) +# endif +# define OPENSSL_assert(e) \ + (void)((e) ? 0 : (OPENSSL_die("assertion failed: " #e, OPENSSL_FILE, OPENSSL_LINE), 1)) + +int OPENSSL_isservice(void); + +int FIPS_mode(void); +int FIPS_mode_set(int r); + +void OPENSSL_init(void); +# ifdef OPENSSL_SYS_UNIX +void OPENSSL_fork_prepare(void); +void OPENSSL_fork_parent(void); +void OPENSSL_fork_child(void); +# endif + +struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result); +int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, long offset_sec); +int OPENSSL_gmtime_diff(int *pday, int *psec, + const struct tm *from, const struct tm *to); + +/* + * CRYPTO_memcmp returns zero iff the |len| bytes at |a| and |b| are equal. + * It takes an amount of time dependent on |len|, but independent of the + * contents of |a| and |b|. Unlike memcmp, it cannot be used to put elements + * into a defined order as the return value when a != b is undefined, other + * than to be non-zero. + */ +int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len); + +/* Standard initialisation options */ +# define OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS 0x00000001L +# define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L +# define OPENSSL_INIT_ADD_ALL_CIPHERS 0x00000004L +# define OPENSSL_INIT_ADD_ALL_DIGESTS 0x00000008L +# define OPENSSL_INIT_NO_ADD_ALL_CIPHERS 0x00000010L +# define OPENSSL_INIT_NO_ADD_ALL_DIGESTS 0x00000020L +# define OPENSSL_INIT_LOAD_CONFIG 0x00000040L +# define OPENSSL_INIT_NO_LOAD_CONFIG 0x00000080L +# define OPENSSL_INIT_ASYNC 0x00000100L +# define OPENSSL_INIT_ENGINE_RDRAND 0x00000200L +# define OPENSSL_INIT_ENGINE_DYNAMIC 0x00000400L +# define OPENSSL_INIT_ENGINE_OPENSSL 0x00000800L +# define OPENSSL_INIT_ENGINE_CRYPTODEV 0x00001000L +# define OPENSSL_INIT_ENGINE_CAPI 0x00002000L +# define OPENSSL_INIT_ENGINE_PADLOCK 0x00004000L +# define OPENSSL_INIT_ENGINE_AFALG 0x00008000L +/* OPENSSL_INIT_ZLIB 0x00010000L */ +# define OPENSSL_INIT_ATFORK 0x00020000L +/* OPENSSL_INIT_BASE_ONLY 0x00040000L */ +/* OPENSSL_INIT flag range 0xfff00000 reserved for OPENSSL_init_ssl() */ +/* Max OPENSSL_INIT flag value is 0x80000000 */ + +/* openssl and dasync not counted as builtin */ +# define OPENSSL_INIT_ENGINE_ALL_BUILTIN \ + (OPENSSL_INIT_ENGINE_RDRAND | OPENSSL_INIT_ENGINE_DYNAMIC \ + | OPENSSL_INIT_ENGINE_CRYPTODEV | OPENSSL_INIT_ENGINE_CAPI | \ + OPENSSL_INIT_ENGINE_PADLOCK) + + +/* Library initialisation functions */ +void OPENSSL_cleanup(void); +int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings); +int OPENSSL_atexit(void (*handler)(void)); +void OPENSSL_thread_stop(void); + +/* Low-level control of initialization */ +OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void); +# ifndef OPENSSL_NO_STDIO +int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *settings, + const char *config_file); +# endif +void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *settings); + +# if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) +# if defined(_WIN32) +# if defined(BASETYPES) || defined(_WINDEF_H) +/* application has to include in order to use this */ +typedef DWORD CRYPTO_THREAD_LOCAL; +typedef DWORD CRYPTO_THREAD_ID; + +typedef LONG CRYPTO_ONCE; +# define CRYPTO_ONCE_STATIC_INIT 0 +# endif +# else +# include +typedef pthread_once_t CRYPTO_ONCE; +typedef pthread_key_t CRYPTO_THREAD_LOCAL; +typedef pthread_t CRYPTO_THREAD_ID; + +# define CRYPTO_ONCE_STATIC_INIT PTHREAD_ONCE_INIT +# endif +# endif + +# if !defined(CRYPTO_ONCE_STATIC_INIT) +typedef unsigned int CRYPTO_ONCE; +typedef unsigned int CRYPTO_THREAD_LOCAL; +typedef unsigned int CRYPTO_THREAD_ID; +# define CRYPTO_ONCE_STATIC_INIT 0 +# endif + +int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void)); + +int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *)); +void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key); +int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val); +int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key); + +CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void); +int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/crypto/arm_arch.h b/include/openssl/crypto/arm_arch.h new file mode 100644 index 0000000..f11b543 --- /dev/null +++ b/include/openssl/crypto/arm_arch.h @@ -0,0 +1,84 @@ +/* + * Copyright 2011-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef __ARM_ARCH_H__ +# define __ARM_ARCH_H__ + +# if !defined(__ARM_ARCH__) +# if defined(__CC_ARM) +# define __ARM_ARCH__ __TARGET_ARCH_ARM +# if defined(__BIG_ENDIAN) +# define __ARMEB__ +# else +# define __ARMEL__ +# endif +# elif defined(__GNUC__) +# if defined(__aarch64__) +# define __ARM_ARCH__ 8 +# if __BYTE_ORDER__==__ORDER_BIG_ENDIAN__ +# define __ARMEB__ +# else +# define __ARMEL__ +# endif + /* + * Why doesn't gcc define __ARM_ARCH__? Instead it defines + * bunch of below macros. See all_architectures[] table in + * gcc/config/arm/arm.c. On a side note it defines + * __ARMEL__/__ARMEB__ for little-/big-endian. + */ +# elif defined(__ARM_ARCH) +# define __ARM_ARCH__ __ARM_ARCH +# elif defined(__ARM_ARCH_8A__) +# define __ARM_ARCH__ 8 +# elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \ + defined(__ARM_ARCH_7R__)|| defined(__ARM_ARCH_7M__) || \ + defined(__ARM_ARCH_7EM__) +# define __ARM_ARCH__ 7 +# elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \ + defined(__ARM_ARCH_6K__)|| defined(__ARM_ARCH_6M__) || \ + defined(__ARM_ARCH_6Z__)|| defined(__ARM_ARCH_6ZK__) || \ + defined(__ARM_ARCH_6T2__) +# define __ARM_ARCH__ 6 +# elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) || \ + defined(__ARM_ARCH_5E__)|| defined(__ARM_ARCH_5TE__) || \ + defined(__ARM_ARCH_5TEJ__) +# define __ARM_ARCH__ 5 +# elif defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) +# define __ARM_ARCH__ 4 +# else +# error "unsupported ARM architecture" +# endif +# endif +# endif + +# if !defined(__ARM_MAX_ARCH__) +# define __ARM_MAX_ARCH__ __ARM_ARCH__ +# endif + +# if __ARM_MAX_ARCH__<__ARM_ARCH__ +# error "__ARM_MAX_ARCH__ can't be less than __ARM_ARCH__" +# elif __ARM_MAX_ARCH__!=__ARM_ARCH__ +# if __ARM_ARCH__<7 && __ARM_MAX_ARCH__>=7 && defined(__ARMEB__) +# error "can't build universal big-endian binary" +# endif +# endif + +# ifndef __ASSEMBLER__ +extern unsigned int OPENSSL_armcap_P; +# endif + +# define ARMV7_NEON (1<<0) +# define ARMV7_TICK (1<<1) +# define ARMV8_AES (1<<2) +# define ARMV8_SHA1 (1<<3) +# define ARMV8_SHA256 (1<<4) +# define ARMV8_PMULL (1<<5) +# define ARMV8_SHA512 (1<<6) + +#endif diff --git a/include/openssl/crypto/buildinf.h b/include/openssl/crypto/buildinf.h new file mode 100644 index 0000000..20e1249 --- /dev/null +++ b/include/openssl/crypto/buildinf.h @@ -0,0 +1,47 @@ +/* + * WARNING: do not edit! + * Generated by util/mkbuildinf.pl + * + * Copyright 2014-2017 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#define PLATFORM "platform: mingw64" +#define DATE "built on: Sat Jul 11 20:24:19 2020 UTC" + +/* + * Generate compiler_flags as an array of individual characters. This is a + * workaround for the situation where CFLAGS gets too long for a C90 string + * literal + */ +static const char compiler_flags[] = { + 'c','o','m','p','i','l','e','r',':',' ','g','c','c',' ','-','m', + '6','4',' ','-','W','a','l','l',' ','-','O','3',' ','-','D','L', + '_','E','N','D','I','A','N',' ','-','D','O','P','E','N','S','S', + 'L','_','P','I','C',' ','-','D','O','P','E','N','S','S','L','_', + 'C','P','U','I','D','_','O','B','J',' ','-','D','O','P','E','N', + 'S','S','L','_','I','A','3','2','_','S','S','E','2',' ','-','D', + 'O','P','E','N','S','S','L','_','B','N','_','A','S','M','_','M', + 'O','N','T',' ','-','D','O','P','E','N','S','S','L','_','B','N', + '_','A','S','M','_','M','O','N','T','5',' ','-','D','O','P','E', + 'N','S','S','L','_','B','N','_','A','S','M','_','G','F','2','m', + ' ','-','D','S','H','A','1','_','A','S','M',' ','-','D','S','H', + 'A','2','5','6','_','A','S','M',' ','-','D','S','H','A','5','1', + '2','_','A','S','M',' ','-','D','K','E','C','C','A','K','1','6', + '0','0','_','A','S','M',' ','-','D','R','C','4','_','A','S','M', + ' ','-','D','M','D','5','_','A','S','M',' ','-','D','A','E','S', + '_','A','S','M',' ','-','D','V','P','A','E','S','_','A','S','M', + ' ','-','D','B','S','A','E','S','_','A','S','M',' ','-','D','G', + 'H','A','S','H','_','A','S','M',' ','-','D','E','C','P','_','N', + 'I','S','T','Z','2','5','6','_','A','S','M',' ','-','D','X','2', + '5','5','1','9','_','A','S','M',' ','-','D','P','A','D','L','O', + 'C','K','_','A','S','M',' ','-','D','P','O','L','Y','1','3','0', + '5','_','A','S','M',' ','-','D','U','N','I','C','O','D','E',' ', + '-','D','_','U','N','I','C','O','D','E',' ','-','D','W','I','N', + '3','2','_','L','E','A','N','_','A','N','D','_','M','E','A','N', + ' ','-','D','_','M','T',' ','-','D','N','D','E','B','U','G','\0' +}; diff --git a/include/openssl/crypto/internal/__DECC_INCLUDE_EPILOGUE.H b/include/openssl/crypto/internal/__DECC_INCLUDE_EPILOGUE.H new file mode 100644 index 0000000..c350018 --- /dev/null +++ b/include/openssl/crypto/internal/__DECC_INCLUDE_EPILOGUE.H @@ -0,0 +1,16 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* restore state. Must correspond to the save in __decc_include_prologue.h */ +#pragma names restore diff --git a/include/openssl/crypto/internal/__DECC_INCLUDE_PROLOGUE.H b/include/openssl/crypto/internal/__DECC_INCLUDE_PROLOGUE.H new file mode 100644 index 0000000..9a9c777 --- /dev/null +++ b/include/openssl/crypto/internal/__DECC_INCLUDE_PROLOGUE.H @@ -0,0 +1,20 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* save state */ +#pragma names save +/* have the compiler shorten symbols larger than 31 chars to 23 chars + * followed by a 8 hex char CRC + */ +#pragma names as_is,shortened diff --git a/include/openssl/crypto/internal/aria.h b/include/openssl/crypto/internal/aria.h new file mode 100644 index 0000000..df86996 --- /dev/null +++ b/include/openssl/crypto/internal/aria.h @@ -0,0 +1,50 @@ +/* + * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + + /* Copyright (c) 2017 National Security Research Institute. All rights reserved. */ + +#ifndef HEADER_ARIA_H +# define HEADER_ARIA_H + +# include + +# ifdef OPENSSL_NO_ARIA +# error ARIA is disabled. +# endif + +# define ARIA_ENCRYPT 1 +# define ARIA_DECRYPT 0 + +# define ARIA_BLOCK_SIZE 16 /* Size of each encryption/decryption block */ +# define ARIA_MAX_KEYS 17 /* Number of keys needed in the worst case */ + +typedef union { + unsigned char c[ARIA_BLOCK_SIZE]; + unsigned int u[ARIA_BLOCK_SIZE / sizeof(unsigned int)]; +} ARIA_u128; + +typedef unsigned char ARIA_c128[ARIA_BLOCK_SIZE]; + +struct aria_key_st { + ARIA_u128 rd_key[ARIA_MAX_KEYS]; + unsigned int rounds; +}; +typedef struct aria_key_st ARIA_KEY; + + +int aria_set_encrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key); +int aria_set_decrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key); + +void aria_encrypt(const unsigned char *in, unsigned char *out, + const ARIA_KEY *key); + +#endif diff --git a/include/openssl/crypto/internal/asn1_int.h b/include/openssl/crypto/internal/asn1_int.h new file mode 100644 index 0000000..5c72a55 --- /dev/null +++ b/include/openssl/crypto/internal/asn1_int.h @@ -0,0 +1,115 @@ +/* + * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* Internal ASN1 structures and functions: not for application use */ + +/* ASN1 public key method structure */ + +#include "include/openssl/asn1.h" + +struct evp_pkey_asn1_method_st { + int pkey_id; + int pkey_base_id; + unsigned long pkey_flags; + char *pem_str; + char *info; + int (*pub_decode) (EVP_PKEY *pk, X509_PUBKEY *pub); + int (*pub_encode) (X509_PUBKEY *pub, const EVP_PKEY *pk); + int (*pub_cmp) (const EVP_PKEY *a, const EVP_PKEY *b); + int (*pub_print) (BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx); + int (*priv_decode) (EVP_PKEY *pk, const PKCS8_PRIV_KEY_INFO *p8inf); + int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pk); + int (*priv_print) (BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx); + int (*pkey_size) (const EVP_PKEY *pk); + int (*pkey_bits) (const EVP_PKEY *pk); + int (*pkey_security_bits) (const EVP_PKEY *pk); + int (*param_decode) (EVP_PKEY *pkey, + const unsigned char **pder, int derlen); + int (*param_encode) (const EVP_PKEY *pkey, unsigned char **pder); + int (*param_missing) (const EVP_PKEY *pk); + int (*param_copy) (EVP_PKEY *to, const EVP_PKEY *from); + int (*param_cmp) (const EVP_PKEY *a, const EVP_PKEY *b); + int (*param_print) (BIO *out, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *pctx); + int (*sig_print) (BIO *out, + const X509_ALGOR *sigalg, const ASN1_STRING *sig, + int indent, ASN1_PCTX *pctx); + void (*pkey_free) (EVP_PKEY *pkey); + int (*pkey_ctrl) (EVP_PKEY *pkey, int op, long arg1, void *arg2); + /* Legacy functions for old PEM */ + int (*old_priv_decode) (EVP_PKEY *pkey, + const unsigned char **pder, int derlen); + int (*old_priv_encode) (const EVP_PKEY *pkey, unsigned char **pder); + /* Custom ASN1 signature verification */ + int (*item_verify) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, + X509_ALGOR *a, ASN1_BIT_STRING *sig, EVP_PKEY *pkey); + int (*item_sign) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, + X509_ALGOR *alg1, X509_ALGOR *alg2, + ASN1_BIT_STRING *sig); + int (*siginf_set) (X509_SIG_INFO *siginf, const X509_ALGOR *alg, + const ASN1_STRING *sig); + /* Check */ + int (*pkey_check) (const EVP_PKEY *pk); + int (*pkey_public_check) (const EVP_PKEY *pk); + int (*pkey_param_check) (const EVP_PKEY *pk); + /* Get/set raw private/public key data */ + int (*set_priv_key) (EVP_PKEY *pk, const unsigned char *priv, size_t len); + int (*set_pub_key) (EVP_PKEY *pk, const unsigned char *pub, size_t len); + int (*get_priv_key) (const EVP_PKEY *pk, unsigned char *priv, size_t *len); + int (*get_pub_key) (const EVP_PKEY *pk, unsigned char *pub, size_t *len); +} /* EVP_PKEY_ASN1_METHOD */ ; + +DEFINE_STACK_OF_CONST(EVP_PKEY_ASN1_METHOD) + +extern const EVP_PKEY_ASN1_METHOD cmac_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD dh_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD dhx_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD dsa_asn1_meths[5]; +extern const EVP_PKEY_ASN1_METHOD eckey_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD ecx25519_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD ecx448_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD ed448_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD sm2_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD poly1305_asn1_meth; + +extern const EVP_PKEY_ASN1_METHOD hmac_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[2]; +extern const EVP_PKEY_ASN1_METHOD rsa_pss_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD siphash_asn1_meth; + +/* + * These are used internally in the ASN1_OBJECT to keep track of whether the + * names and data need to be free()ed + */ +# define ASN1_OBJECT_FLAG_DYNAMIC 0x01/* internal use */ +# define ASN1_OBJECT_FLAG_CRITICAL 0x02/* critical x509v3 object id */ +# define ASN1_OBJECT_FLAG_DYNAMIC_STRINGS 0x04/* internal use */ +# define ASN1_OBJECT_FLAG_DYNAMIC_DATA 0x08/* internal use */ +struct asn1_object_st { + const char *sn, *ln; + int nid; + int length; + const unsigned char *data; /* data remains const after init */ + int flags; /* Should we free this one */ +}; + +/* ASN1 print context structure */ + +struct asn1_pctx_st { + unsigned long flags; + unsigned long nm_flags; + unsigned long cert_flags; + unsigned long oid_flags; + unsigned long str_flags; +} /* ASN1_PCTX */ ; + +int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb); diff --git a/include/openssl/crypto/internal/async.h b/include/openssl/crypto/internal/async.h new file mode 100644 index 0000000..736cd87 --- /dev/null +++ b/include/openssl/crypto/internal/async.h @@ -0,0 +1,15 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +int async_init(void); +void async_deinit(void); +void async_delete_thread_state(void); + diff --git a/include/openssl/crypto/internal/bn_conf.h b/include/openssl/crypto/internal/bn_conf.h new file mode 100644 index 0000000..0d071bd --- /dev/null +++ b/include/openssl/crypto/internal/bn_conf.h @@ -0,0 +1,28 @@ +/* WARNING: do not edit! */ +/* Generated by Makefile from crypto/include/internal/bn_conf.h.in */ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BN_CONF_H +# define HEADER_BN_CONF_H + +/* + * The contents of this file are not used in the UEFI build, as + * both 32-bit and 64-bit builds are supported from a single run + * of the Configure script. + */ + +/* Should we define BN_DIV2W here? */ + +/* Only one for the following should be defined */ +#undef SIXTY_FOUR_BIT_LONG +#define SIXTY_FOUR_BIT +#undef THIRTY_TWO_BIT + +#endif diff --git a/include/openssl/crypto/internal/bn_dh.h b/include/openssl/crypto/internal/bn_dh.h new file mode 100644 index 0000000..22635cb --- /dev/null +++ b/include/openssl/crypto/internal/bn_dh.h @@ -0,0 +1,26 @@ +/* + * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include "include/openssl/bn.h" + +#define declare_dh_bn(x) \ + extern const BIGNUM _bignum_dh##x##_p; \ + extern const BIGNUM _bignum_dh##x##_g; \ + extern const BIGNUM _bignum_dh##x##_q; + +declare_dh_bn(1024_160) +declare_dh_bn(2048_224) +declare_dh_bn(2048_256) + +extern const BIGNUM _bignum_ffdhe2048_p; +extern const BIGNUM _bignum_ffdhe3072_p; +extern const BIGNUM _bignum_ffdhe4096_p; +extern const BIGNUM _bignum_ffdhe6144_p; +extern const BIGNUM _bignum_ffdhe8192_p; +extern const BIGNUM _bignum_const_2; diff --git a/include/openssl/crypto/internal/bn_int.h b/include/openssl/crypto/internal/bn_int.h new file mode 100644 index 0000000..ec9e9f7 --- /dev/null +++ b/include/openssl/crypto/internal/bn_int.h @@ -0,0 +1,83 @@ +/* + * Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_BN_INT_H +# define HEADER_BN_INT_H + +# include +# include + +BIGNUM *bn_wexpand(BIGNUM *a, int words); +BIGNUM *bn_expand2(BIGNUM *a, int words); + +void bn_correct_top(BIGNUM *a); + +/* + * Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'. + * This is an array r[] of values that are either zero or odd with an + * absolute value less than 2^w satisfying scalar = \sum_j r[j]*2^j where at + * most one of any w+1 consecutive digits is non-zero with the exception that + * the most significant digit may be only w-1 zeros away from that next + * non-zero digit. + */ +signed char *bn_compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len); + +int bn_get_top(const BIGNUM *a); + +int bn_get_dmax(const BIGNUM *a); + +/* Set all words to zero */ +void bn_set_all_zero(BIGNUM *a); + +/* + * Copy the internal BIGNUM words into out which holds size elements (and size + * must be bigger than top) + */ +int bn_copy_words(BN_ULONG *out, const BIGNUM *in, int size); + +BN_ULONG *bn_get_words(const BIGNUM *a); + +/* + * Set the internal data words in a to point to words which contains size + * elements. The BN_FLG_STATIC_DATA flag is set + */ +void bn_set_static_words(BIGNUM *a, const BN_ULONG *words, int size); + +/* + * Copy words into the BIGNUM |a|, reallocating space as necessary. + * The negative flag of |a| is not modified. + * Returns 1 on success and 0 on failure. + */ +/* + * |num_words| is int because bn_expand2 takes an int. This is an internal + * function so we simply trust callers not to pass negative values. + */ +int bn_set_words(BIGNUM *a, const BN_ULONG *words, int num_words); + +/* + * Some BIGNUM functions assume most significant limb to be non-zero, which + * is customarily arranged by bn_correct_top. Output from below functions + * is not processed with bn_correct_top, and for this reason it may not be + * returned out of public API. It may only be passed internally into other + * functions known to support non-minimal or zero-padded BIGNUMs. + */ +int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + BN_MONT_CTX *mont, BN_CTX *ctx); +int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont, + BN_CTX *ctx); +int bn_from_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont, + BN_CTX *ctx); +int bn_mod_add_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *m); +int bn_mod_sub_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, + const BIGNUM *m); +int bn_mul_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); +int bn_sqr_fixed_top(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx); + +#endif diff --git a/include/openssl/crypto/internal/bn_srp.h b/include/openssl/crypto/internal/bn_srp.h new file mode 100644 index 0000000..f50575d --- /dev/null +++ b/include/openssl/crypto/internal/bn_srp.h @@ -0,0 +1,34 @@ +/* + * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include "include/openssl/bn.h" + +#ifndef OPENSSL_NO_SRP + +extern const BIGNUM bn_group_1024; + +extern const BIGNUM bn_group_1536; + +extern const BIGNUM bn_group_2048; + +extern const BIGNUM bn_group_3072; + +extern const BIGNUM bn_group_4096; + +extern const BIGNUM bn_group_6144; + +extern const BIGNUM bn_group_8192; + +extern const BIGNUM bn_generator_19; + +extern const BIGNUM bn_generator_5; + +extern const BIGNUM bn_generator_2; + +#endif diff --git a/include/openssl/crypto/internal/chacha.h b/include/openssl/crypto/internal/chacha.h new file mode 100644 index 0000000..67243f2 --- /dev/null +++ b/include/openssl/crypto/internal/chacha.h @@ -0,0 +1,42 @@ +/* + * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CHACHA_H +#define HEADER_CHACHA_H + +#include + +/* + * ChaCha20_ctr32 encrypts |len| bytes from |inp| with the given key and + * nonce and writes the result to |out|, which may be equal to |inp|. + * The |key| is not 32 bytes of verbatim key material though, but the + * said material collected into 8 32-bit elements array in host byte + * order. Same approach applies to nonce: the |counter| argument is + * pointer to concatenated nonce and counter values collected into 4 + * 32-bit elements. This, passing crypto material collected into 32-bit + * elements as opposite to passing verbatim byte vectors, is chosen for + * efficiency in multi-call scenarios. + */ +void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp, + size_t len, const unsigned int key[8], + const unsigned int counter[4]); +/* + * You can notice that there is no key setup procedure. Because it's + * as trivial as collecting bytes into 32-bit elements, it's reckoned + * that below macro is sufficient. + */ +#define CHACHA_U8TOU32(p) ( \ + ((unsigned int)(p)[0]) | ((unsigned int)(p)[1]<<8) | \ + ((unsigned int)(p)[2]<<16) | ((unsigned int)(p)[3]<<24) ) + +#define CHACHA_KEY_SIZE 32 +#define CHACHA_CTR_SIZE 16 +#define CHACHA_BLK_SIZE 64 + +#endif diff --git a/include/openssl/crypto/internal/cryptlib_int.h b/include/openssl/crypto/internal/cryptlib_int.h new file mode 100644 index 0000000..bdb9757 --- /dev/null +++ b/include/openssl/crypto/internal/cryptlib_int.h @@ -0,0 +1,35 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include "include/openssl/internal/cryptlib.h" + +/* This file is not scanned by mkdef.pl, whereas cryptlib.h is */ + +struct thread_local_inits_st { + int async; + int err_state; + int rand; +}; + +int ossl_init_thread_start(uint64_t opts); + +/* + * OPENSSL_INIT flags. The primary list of these is in crypto.h. Flags below + * are those omitted from crypto.h because they are "reserved for internal + * use". + */ +# define OPENSSL_INIT_ZLIB 0x00010000L +# define OPENSSL_INIT_BASE_ONLY 0x00040000L + +/* OPENSSL_INIT_THREAD flags */ +# define OPENSSL_INIT_THREAD_ASYNC 0x01 +# define OPENSSL_INIT_THREAD_ERR_STATE 0x02 +# define OPENSSL_INIT_THREAD_RAND 0x04 + +void ossl_malloc_setup_failures(void); diff --git a/include/openssl/crypto/internal/ctype.h b/include/openssl/crypto/internal/ctype.h new file mode 100644 index 0000000..a35b12b --- /dev/null +++ b/include/openssl/crypto/internal/ctype.h @@ -0,0 +1,80 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This version of ctype.h provides a standardised and platform + * independent implementation that supports seven bit ASCII characters. + * The specific intent is to not pass extended ASCII characters (> 127) + * even if the host operating system would. + * + * There is EBCDIC support included for machines which use this. However, + * there are a number of concerns about how well EBCDIC is supported + * throughout the rest of the source code. Refer to issue #4154 for + * details. + */ +#ifndef INTERNAL_CTYPE_H +# define INTERNAL_CTYPE_H + +# define CTYPE_MASK_lower 0x1 +# define CTYPE_MASK_upper 0x2 +# define CTYPE_MASK_digit 0x4 +# define CTYPE_MASK_space 0x8 +# define CTYPE_MASK_xdigit 0x10 +# define CTYPE_MASK_blank 0x20 +# define CTYPE_MASK_cntrl 0x40 +# define CTYPE_MASK_graph 0x80 +# define CTYPE_MASK_print 0x100 +# define CTYPE_MASK_punct 0x200 +# define CTYPE_MASK_base64 0x400 +# define CTYPE_MASK_asn1print 0x800 + +# define CTYPE_MASK_alpha (CTYPE_MASK_lower | CTYPE_MASK_upper) +# define CTYPE_MASK_alnum (CTYPE_MASK_alpha | CTYPE_MASK_digit) + +/* + * The ascii mask assumes that any other classification implies that + * the character is ASCII and that there are no ASCII characters + * that aren't in any of the classifications. + * + * This assumption holds at the moment, but it might not in the future. + */ +# define CTYPE_MASK_ascii (~0) + +# ifdef CHARSET_EBCDIC +int ossl_toascii(int c); +int ossl_fromascii(int c); +# else +# define ossl_toascii(c) (c) +# define ossl_fromascii(c) (c) +# endif +int ossl_ctype_check(int c, unsigned int mask); +int ossl_tolower(int c); +int ossl_toupper(int c); + +# define ossl_isalnum(c) (ossl_ctype_check((c), CTYPE_MASK_alnum)) +# define ossl_isalpha(c) (ossl_ctype_check((c), CTYPE_MASK_alpha)) +# ifdef CHARSET_EBCDIC +# define ossl_isascii(c) (ossl_ctype_check((c), CTYPE_MASK_ascii)) +# else +# define ossl_isascii(c) (((c) & ~127) == 0) +# endif +# define ossl_isblank(c) (ossl_ctype_check((c), CTYPE_MASK_blank)) +# define ossl_iscntrl(c) (ossl_ctype_check((c), CTYPE_MASK_cntrl)) +# define ossl_isdigit(c) (ossl_ctype_check((c), CTYPE_MASK_digit)) +# define ossl_isgraph(c) (ossl_ctype_check((c), CTYPE_MASK_graph)) +# define ossl_islower(c) (ossl_ctype_check((c), CTYPE_MASK_lower)) +# define ossl_isprint(c) (ossl_ctype_check((c), CTYPE_MASK_print)) +# define ossl_ispunct(c) (ossl_ctype_check((c), CTYPE_MASK_punct)) +# define ossl_isspace(c) (ossl_ctype_check((c), CTYPE_MASK_space)) +# define ossl_isupper(c) (ossl_ctype_check((c), CTYPE_MASK_upper)) +# define ossl_isxdigit(c) (ossl_ctype_check((c), CTYPE_MASK_xdigit)) +# define ossl_isbase64(c) (ossl_ctype_check((c), CTYPE_MASK_base64)) +# define ossl_isasn1print(c) (ossl_ctype_check((c), CTYPE_MASK_asn1print)) + +#endif diff --git a/include/openssl/crypto/internal/dso_conf.h b/include/openssl/crypto/internal/dso_conf.h new file mode 100644 index 0000000..d476661 --- /dev/null +++ b/include/openssl/crypto/internal/dso_conf.h @@ -0,0 +1,18 @@ +/* WARNING: do not edit! */ +/* Generated by Makefile from crypto/include/internal/dso_conf.h.in */ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DSO_CONF_H +# define HEADER_DSO_CONF_H + +# define DSO_WIN32 +# define DSO_EXTENSION ".dll" + +#endif diff --git a/include/openssl/crypto/internal/ec_int.h b/include/openssl/crypto/internal/ec_int.h new file mode 100644 index 0000000..0b45562 --- /dev/null +++ b/include/openssl/crypto/internal/ec_int.h @@ -0,0 +1,45 @@ +/* + * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* Internal EC functions for other submodules: not for application use */ + +#ifndef HEADER_OSSL_EC_INTERNAL_H +# define HEADER_OSSL_EC_INTERNAL_H +# include + +# ifndef OPENSSL_NO_EC + +# include + +/*- + * Computes the multiplicative inverse of x in the range + * [1,EC_GROUP::order), where EC_GROUP::order is the cardinality of the + * subgroup generated by the generator G: + * + * res := x^(-1) (mod EC_GROUP::order). + * + * This function expects the following two conditions to hold: + * - the EC_GROUP order is prime, and + * - x is included in the range [1, EC_GROUP::order). + * + * This function returns 1 on success, 0 on error. + * + * If the EC_GROUP order is even, this function explicitly returns 0 as + * an error. + * In case any of the two conditions stated above is not satisfied, + * the correctness of its output is not guaranteed, even if the return + * value could still be 1 (as primality testing and a conditional modular + * reduction round on the input can be omitted by the underlying + * implementations for better SCA properties on regular input values). + */ +__owur int ec_group_do_inverse_ord(const EC_GROUP *group, BIGNUM *res, + const BIGNUM *x, BN_CTX *ctx); + +# endif /* OPENSSL_NO_EC */ +#endif diff --git a/include/openssl/crypto/internal/engine.h b/include/openssl/crypto/internal/engine.h new file mode 100644 index 0000000..cc2bdac --- /dev/null +++ b/include/openssl/crypto/internal/engine.h @@ -0,0 +1,20 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +void engine_load_openssl_int(void); +void engine_load_devcrypto_int(void); +void engine_load_rdrand_int(void); +void engine_load_dynamic_int(void); +void engine_load_padlock_int(void); +void engine_load_capi_int(void); +void engine_load_dasync_int(void); +void engine_load_afalg_int(void); +void engine_cleanup_int(void); diff --git a/include/openssl/crypto/internal/err_int.h b/include/openssl/crypto/internal/err_int.h new file mode 100644 index 0000000..44ac944 --- /dev/null +++ b/include/openssl/crypto/internal/err_int.h @@ -0,0 +1,19 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef INTERNAL_ERR_INT_H +# define INTERNAL_ERR_INT_H + +int err_load_crypto_strings_int(void); +void err_cleanup(void); +void err_delete_thread_state(void); +int err_shelve_state(void **); +void err_unshelve_state(void *); + +#endif diff --git a/include/openssl/crypto/internal/evp_int.h b/include/openssl/crypto/internal/evp_int.h new file mode 100644 index 0000000..2a40d7d --- /dev/null +++ b/include/openssl/crypto/internal/evp_int.h @@ -0,0 +1,442 @@ +/* + * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include +#include "include/openssl/internal/refcount.h" + +/* + * Don't free up md_ctx->pctx in EVP_MD_CTX_reset, use the reserved flag + * values in evp.h + */ +#define EVP_MD_CTX_FLAG_KEEP_PKEY_CTX 0x0400 + +struct evp_pkey_ctx_st { + /* Method associated with this operation */ + const EVP_PKEY_METHOD *pmeth; + /* Engine that implements this method or NULL if builtin */ + ENGINE *engine; + /* Key: may be NULL */ + EVP_PKEY *pkey; + /* Peer key for key agreement, may be NULL */ + EVP_PKEY *peerkey; + /* Actual operation */ + int operation; + /* Algorithm specific data */ + void *data; + /* Application specific data */ + void *app_data; + /* Keygen callback */ + EVP_PKEY_gen_cb *pkey_gencb; + /* implementation specific keygen data */ + int *keygen_info; + int keygen_info_count; +} /* EVP_PKEY_CTX */ ; + +#define EVP_PKEY_FLAG_DYNAMIC 1 + +struct evp_pkey_method_st { + int pkey_id; + int flags; + int (*init) (EVP_PKEY_CTX *ctx); + int (*copy) (EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src); + void (*cleanup) (EVP_PKEY_CTX *ctx); + int (*paramgen_init) (EVP_PKEY_CTX *ctx); + int (*paramgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey); + int (*keygen_init) (EVP_PKEY_CTX *ctx); + int (*keygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey); + int (*sign_init) (EVP_PKEY_CTX *ctx); + int (*sign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen); + int (*verify_init) (EVP_PKEY_CTX *ctx); + int (*verify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, size_t siglen, + const unsigned char *tbs, size_t tbslen); + int (*verify_recover_init) (EVP_PKEY_CTX *ctx); + int (*verify_recover) (EVP_PKEY_CTX *ctx, + unsigned char *rout, size_t *routlen, + const unsigned char *sig, size_t siglen); + int (*signctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx); + int (*signctx) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + EVP_MD_CTX *mctx); + int (*verifyctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx); + int (*verifyctx) (EVP_PKEY_CTX *ctx, const unsigned char *sig, int siglen, + EVP_MD_CTX *mctx); + int (*encrypt_init) (EVP_PKEY_CTX *ctx); + int (*encrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); + int (*decrypt_init) (EVP_PKEY_CTX *ctx); + int (*decrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); + int (*derive_init) (EVP_PKEY_CTX *ctx); + int (*derive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen); + int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1, void *p2); + int (*ctrl_str) (EVP_PKEY_CTX *ctx, const char *type, const char *value); + int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen); + int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig, + size_t siglen, const unsigned char *tbs, + size_t tbslen); + int (*check) (EVP_PKEY *pkey); + int (*public_check) (EVP_PKEY *pkey); + int (*param_check) (EVP_PKEY *pkey); + + int (*digest_custom) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx); +} /* EVP_PKEY_METHOD */ ; + +DEFINE_STACK_OF_CONST(EVP_PKEY_METHOD) + +void evp_pkey_set_cb_translate(BN_GENCB *cb, EVP_PKEY_CTX *ctx); + +extern const EVP_PKEY_METHOD cmac_pkey_meth; +extern const EVP_PKEY_METHOD dh_pkey_meth; +extern const EVP_PKEY_METHOD dhx_pkey_meth; +extern const EVP_PKEY_METHOD dsa_pkey_meth; +extern const EVP_PKEY_METHOD ec_pkey_meth; +extern const EVP_PKEY_METHOD sm2_pkey_meth; +extern const EVP_PKEY_METHOD ecx25519_pkey_meth; +extern const EVP_PKEY_METHOD ecx448_pkey_meth; +extern const EVP_PKEY_METHOD ed25519_pkey_meth; +extern const EVP_PKEY_METHOD ed448_pkey_meth; +extern const EVP_PKEY_METHOD hmac_pkey_meth; +extern const EVP_PKEY_METHOD rsa_pkey_meth; +extern const EVP_PKEY_METHOD rsa_pss_pkey_meth; +extern const EVP_PKEY_METHOD scrypt_pkey_meth; +extern const EVP_PKEY_METHOD tls1_prf_pkey_meth; +extern const EVP_PKEY_METHOD hkdf_pkey_meth; +extern const EVP_PKEY_METHOD poly1305_pkey_meth; +extern const EVP_PKEY_METHOD siphash_pkey_meth; + +struct evp_md_st { + int type; + int pkey_type; + int md_size; + unsigned long flags; + int (*init) (EVP_MD_CTX *ctx); + int (*update) (EVP_MD_CTX *ctx, const void *data, size_t count); + int (*final) (EVP_MD_CTX *ctx, unsigned char *md); + int (*copy) (EVP_MD_CTX *to, const EVP_MD_CTX *from); + int (*cleanup) (EVP_MD_CTX *ctx); + int block_size; + int ctx_size; /* how big does the ctx->md_data need to be */ + /* control function */ + int (*md_ctrl) (EVP_MD_CTX *ctx, int cmd, int p1, void *p2); +} /* EVP_MD */ ; + +struct evp_cipher_st { + int nid; + int block_size; + /* Default value for variable length ciphers */ + int key_len; + int iv_len; + /* Various flags */ + unsigned long flags; + /* init key */ + int (*init) (EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc); + /* encrypt/decrypt data */ + int (*do_cipher) (EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t inl); + /* cleanup ctx */ + int (*cleanup) (EVP_CIPHER_CTX *); + /* how big ctx->cipher_data needs to be */ + int ctx_size; + /* Populate a ASN1_TYPE with parameters */ + int (*set_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *); + /* Get parameters from a ASN1_TYPE */ + int (*get_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *); + /* Miscellaneous operations */ + int (*ctrl) (EVP_CIPHER_CTX *, int type, int arg, void *ptr); + /* Application data */ + void *app_data; +} /* EVP_CIPHER */ ; + +/* Macros to code block cipher wrappers */ + +/* Wrapper functions for each cipher mode */ + +#define EVP_C_DATA(kstruct, ctx) \ + ((kstruct *)EVP_CIPHER_CTX_get_cipher_data(ctx)) + +#define BLOCK_CIPHER_ecb_loop() \ + size_t i, bl; \ + bl = EVP_CIPHER_CTX_cipher(ctx)->block_size; \ + if (inl < bl) return 1;\ + inl -= bl; \ + for (i=0; i <= inl; i+=bl) + +#define BLOCK_CIPHER_func_ecb(cname, cprefix, kstruct, ksched) \ +static int cname##_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \ +{\ + BLOCK_CIPHER_ecb_loop() \ + cprefix##_ecb_encrypt(in + i, out + i, &EVP_C_DATA(kstruct,ctx)->ksched, EVP_CIPHER_CTX_encrypting(ctx)); \ + return 1;\ +} + +#define EVP_MAXCHUNK ((size_t)1<<(sizeof(long)*8-2)) + +#define BLOCK_CIPHER_func_ofb(cname, cprefix, cbits, kstruct, ksched) \ + static int cname##_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \ +{\ + while(inl>=EVP_MAXCHUNK) {\ + int num = EVP_CIPHER_CTX_num(ctx);\ + cprefix##_ofb##cbits##_encrypt(in, out, (long)EVP_MAXCHUNK, &EVP_C_DATA(kstruct,ctx)->ksched, EVP_CIPHER_CTX_iv_noconst(ctx), &num); \ + EVP_CIPHER_CTX_set_num(ctx, num);\ + inl-=EVP_MAXCHUNK;\ + in +=EVP_MAXCHUNK;\ + out+=EVP_MAXCHUNK;\ + }\ + if (inl) {\ + int num = EVP_CIPHER_CTX_num(ctx);\ + cprefix##_ofb##cbits##_encrypt(in, out, (long)inl, &EVP_C_DATA(kstruct,ctx)->ksched, EVP_CIPHER_CTX_iv_noconst(ctx), &num); \ + EVP_CIPHER_CTX_set_num(ctx, num);\ + }\ + return 1;\ +} + +#define BLOCK_CIPHER_func_cbc(cname, cprefix, kstruct, ksched) \ +static int cname##_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \ +{\ + while(inl>=EVP_MAXCHUNK) \ + {\ + cprefix##_cbc_encrypt(in, out, (long)EVP_MAXCHUNK, &EVP_C_DATA(kstruct,ctx)->ksched, EVP_CIPHER_CTX_iv_noconst(ctx), EVP_CIPHER_CTX_encrypting(ctx));\ + inl-=EVP_MAXCHUNK;\ + in +=EVP_MAXCHUNK;\ + out+=EVP_MAXCHUNK;\ + }\ + if (inl)\ + cprefix##_cbc_encrypt(in, out, (long)inl, &EVP_C_DATA(kstruct,ctx)->ksched, EVP_CIPHER_CTX_iv_noconst(ctx), EVP_CIPHER_CTX_encrypting(ctx));\ + return 1;\ +} + +#define BLOCK_CIPHER_func_cfb(cname, cprefix, cbits, kstruct, ksched) \ +static int cname##_cfb##cbits##_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \ +{\ + size_t chunk = EVP_MAXCHUNK;\ + if (cbits == 1) chunk >>= 3;\ + if (inl < chunk) chunk = inl;\ + while (inl && inl >= chunk)\ + {\ + int num = EVP_CIPHER_CTX_num(ctx);\ + cprefix##_cfb##cbits##_encrypt(in, out, (long) \ + ((cbits == 1) \ + && !EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS) \ + ? chunk*8 : chunk), \ + &EVP_C_DATA(kstruct, ctx)->ksched, EVP_CIPHER_CTX_iv_noconst(ctx),\ + &num, EVP_CIPHER_CTX_encrypting(ctx));\ + EVP_CIPHER_CTX_set_num(ctx, num);\ + inl -= chunk;\ + in += chunk;\ + out += chunk;\ + if (inl < chunk) chunk = inl;\ + }\ + return 1;\ +} + +#define BLOCK_CIPHER_all_funcs(cname, cprefix, cbits, kstruct, ksched) \ + BLOCK_CIPHER_func_cbc(cname, cprefix, kstruct, ksched) \ + BLOCK_CIPHER_func_cfb(cname, cprefix, cbits, kstruct, ksched) \ + BLOCK_CIPHER_func_ecb(cname, cprefix, kstruct, ksched) \ + BLOCK_CIPHER_func_ofb(cname, cprefix, cbits, kstruct, ksched) + +#define BLOCK_CIPHER_def1(cname, nmode, mode, MODE, kstruct, nid, block_size, \ + key_len, iv_len, flags, init_key, cleanup, \ + set_asn1, get_asn1, ctrl) \ +static const EVP_CIPHER cname##_##mode = { \ + nid##_##nmode, block_size, key_len, iv_len, \ + flags | EVP_CIPH_##MODE##_MODE, \ + init_key, \ + cname##_##mode##_cipher, \ + cleanup, \ + sizeof(kstruct), \ + set_asn1, get_asn1,\ + ctrl, \ + NULL \ +}; \ +const EVP_CIPHER *EVP_##cname##_##mode(void) { return &cname##_##mode; } + +#define BLOCK_CIPHER_def_cbc(cname, kstruct, nid, block_size, key_len, \ + iv_len, flags, init_key, cleanup, set_asn1, \ + get_asn1, ctrl) \ +BLOCK_CIPHER_def1(cname, cbc, cbc, CBC, kstruct, nid, block_size, key_len, \ + iv_len, flags, init_key, cleanup, set_asn1, get_asn1, ctrl) + +#define BLOCK_CIPHER_def_cfb(cname, kstruct, nid, key_len, \ + iv_len, cbits, flags, init_key, cleanup, \ + set_asn1, get_asn1, ctrl) \ +BLOCK_CIPHER_def1(cname, cfb##cbits, cfb##cbits, CFB, kstruct, nid, 1, \ + key_len, iv_len, flags, init_key, cleanup, set_asn1, \ + get_asn1, ctrl) + +#define BLOCK_CIPHER_def_ofb(cname, kstruct, nid, key_len, \ + iv_len, cbits, flags, init_key, cleanup, \ + set_asn1, get_asn1, ctrl) \ +BLOCK_CIPHER_def1(cname, ofb##cbits, ofb, OFB, kstruct, nid, 1, \ + key_len, iv_len, flags, init_key, cleanup, set_asn1, \ + get_asn1, ctrl) + +#define BLOCK_CIPHER_def_ecb(cname, kstruct, nid, block_size, key_len, \ + flags, init_key, cleanup, set_asn1, \ + get_asn1, ctrl) \ +BLOCK_CIPHER_def1(cname, ecb, ecb, ECB, kstruct, nid, block_size, key_len, \ + 0, flags, init_key, cleanup, set_asn1, get_asn1, ctrl) + +#define BLOCK_CIPHER_defs(cname, kstruct, \ + nid, block_size, key_len, iv_len, cbits, flags, \ + init_key, cleanup, set_asn1, get_asn1, ctrl) \ +BLOCK_CIPHER_def_cbc(cname, kstruct, nid, block_size, key_len, iv_len, flags, \ + init_key, cleanup, set_asn1, get_asn1, ctrl) \ +BLOCK_CIPHER_def_cfb(cname, kstruct, nid, key_len, iv_len, cbits, \ + flags, init_key, cleanup, set_asn1, get_asn1, ctrl) \ +BLOCK_CIPHER_def_ofb(cname, kstruct, nid, key_len, iv_len, cbits, \ + flags, init_key, cleanup, set_asn1, get_asn1, ctrl) \ +BLOCK_CIPHER_def_ecb(cname, kstruct, nid, block_size, key_len, flags, \ + init_key, cleanup, set_asn1, get_asn1, ctrl) + +/*- +#define BLOCK_CIPHER_defs(cname, kstruct, \ + nid, block_size, key_len, iv_len, flags,\ + init_key, cleanup, set_asn1, get_asn1, ctrl)\ +static const EVP_CIPHER cname##_cbc = {\ + nid##_cbc, block_size, key_len, iv_len, \ + flags | EVP_CIPH_CBC_MODE,\ + init_key,\ + cname##_cbc_cipher,\ + cleanup,\ + sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\ + sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\ + set_asn1, get_asn1,\ + ctrl, \ + NULL \ +};\ +const EVP_CIPHER *EVP_##cname##_cbc(void) { return &cname##_cbc; }\ +static const EVP_CIPHER cname##_cfb = {\ + nid##_cfb64, 1, key_len, iv_len, \ + flags | EVP_CIPH_CFB_MODE,\ + init_key,\ + cname##_cfb_cipher,\ + cleanup,\ + sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\ + sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\ + set_asn1, get_asn1,\ + ctrl,\ + NULL \ +};\ +const EVP_CIPHER *EVP_##cname##_cfb(void) { return &cname##_cfb; }\ +static const EVP_CIPHER cname##_ofb = {\ + nid##_ofb64, 1, key_len, iv_len, \ + flags | EVP_CIPH_OFB_MODE,\ + init_key,\ + cname##_ofb_cipher,\ + cleanup,\ + sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\ + sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\ + set_asn1, get_asn1,\ + ctrl,\ + NULL \ +};\ +const EVP_CIPHER *EVP_##cname##_ofb(void) { return &cname##_ofb; }\ +static const EVP_CIPHER cname##_ecb = {\ + nid##_ecb, block_size, key_len, iv_len, \ + flags | EVP_CIPH_ECB_MODE,\ + init_key,\ + cname##_ecb_cipher,\ + cleanup,\ + sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\ + sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\ + set_asn1, get_asn1,\ + ctrl,\ + NULL \ +};\ +const EVP_CIPHER *EVP_##cname##_ecb(void) { return &cname##_ecb; } +*/ + +#define IMPLEMENT_BLOCK_CIPHER(cname, ksched, cprefix, kstruct, nid, \ + block_size, key_len, iv_len, cbits, \ + flags, init_key, \ + cleanup, set_asn1, get_asn1, ctrl) \ + BLOCK_CIPHER_all_funcs(cname, cprefix, cbits, kstruct, ksched) \ + BLOCK_CIPHER_defs(cname, kstruct, nid, block_size, key_len, iv_len, \ + cbits, flags, init_key, cleanup, set_asn1, \ + get_asn1, ctrl) + +#define IMPLEMENT_CFBR(cipher,cprefix,kstruct,ksched,keysize,cbits,iv_len,fl) \ + BLOCK_CIPHER_func_cfb(cipher##_##keysize,cprefix,cbits,kstruct,ksched) \ + BLOCK_CIPHER_def_cfb(cipher##_##keysize,kstruct, \ + NID_##cipher##_##keysize, keysize/8, iv_len, cbits, \ + (fl)|EVP_CIPH_FLAG_DEFAULT_ASN1, \ + cipher##_init_key, NULL, NULL, NULL, NULL) + + +# ifndef OPENSSL_NO_EC + +#define X25519_KEYLEN 32 +#define X448_KEYLEN 56 +#define ED448_KEYLEN 57 + +#define MAX_KEYLEN ED448_KEYLEN + +typedef struct { + unsigned char pubkey[MAX_KEYLEN]; + unsigned char *privkey; +} ECX_KEY; + +#endif + +/* + * Type needs to be a bit field Sub-type needs to be for variations on the + * method, as in, can it do arbitrary encryption.... + */ +struct evp_pkey_st { + int type; + int save_type; + CRYPTO_REF_COUNT references; + const EVP_PKEY_ASN1_METHOD *ameth; + ENGINE *engine; + ENGINE *pmeth_engine; /* If not NULL public key ENGINE to use */ + union { + void *ptr; +# ifndef OPENSSL_NO_RSA + struct rsa_st *rsa; /* RSA */ +# endif +# ifndef OPENSSL_NO_DSA + struct dsa_st *dsa; /* DSA */ +# endif +# ifndef OPENSSL_NO_DH + struct dh_st *dh; /* DH */ +# endif +# ifndef OPENSSL_NO_EC + struct ec_key_st *ec; /* ECC */ + ECX_KEY *ecx; /* X25519, X448, Ed25519, Ed448 */ +# endif + } pkey; + int save_parameters; + STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */ + CRYPTO_RWLOCK *lock; +} /* EVP_PKEY */ ; + + +void openssl_add_all_ciphers_int(void); +void openssl_add_all_digests_int(void); +void evp_cleanup_int(void); +void evp_app_cleanup_int(void); + +/* Pulling defines out of C source files */ + +#define EVP_RC4_KEY_SIZE 16 +#ifndef TLS1_1_VERSION +# define TLS1_1_VERSION 0x0302 +#endif + +void evp_encode_ctx_set_flags(EVP_ENCODE_CTX *ctx, unsigned int flags); + +/* EVP_ENCODE_CTX flags */ +/* Don't generate new lines when encoding */ +#define EVP_ENCODE_CTX_NO_NEWLINES 1 +/* Use the SRP base64 alphabet instead of the standard one */ +#define EVP_ENCODE_CTX_USE_SRP_ALPHABET 2 diff --git a/include/openssl/crypto/internal/lhash.h b/include/openssl/crypto/internal/lhash.h new file mode 100644 index 0000000..200ba86 --- /dev/null +++ b/include/openssl/crypto/internal/lhash.h @@ -0,0 +1,15 @@ +/* + * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef INTERNAL_LHASH_H +# define INTERNAL_LHASH_H + +unsigned long openssl_lh_strcasehash(const char *); + +#endif diff --git a/include/openssl/crypto/internal/md32_common.h b/include/openssl/crypto/internal/md32_common.h new file mode 100644 index 0000000..3f00b23 --- /dev/null +++ b/include/openssl/crypto/internal/md32_common.h @@ -0,0 +1,259 @@ +/* + * Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include +#include + +/*- + * This is a generic 32 bit "collector" for message digest algorithms. + * Whenever needed it collects input character stream into chunks of + * 32 bit values and invokes a block function that performs actual hash + * calculations. + * + * Porting guide. + * + * Obligatory macros: + * + * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN + * this macro defines byte order of input stream. + * HASH_CBLOCK + * size of a unit chunk HASH_BLOCK operates on. + * HASH_LONG + * has to be at least 32 bit wide. + * HASH_CTX + * context structure that at least contains following + * members: + * typedef struct { + * ... + * HASH_LONG Nl,Nh; + * either { + * HASH_LONG data[HASH_LBLOCK]; + * unsigned char data[HASH_CBLOCK]; + * }; + * unsigned int num; + * ... + * } HASH_CTX; + * data[] vector is expected to be zeroed upon first call to + * HASH_UPDATE. + * HASH_UPDATE + * name of "Update" function, implemented here. + * HASH_TRANSFORM + * name of "Transform" function, implemented here. + * HASH_FINAL + * name of "Final" function, implemented here. + * HASH_BLOCK_DATA_ORDER + * name of "block" function capable of treating *unaligned* input + * message in original (data) byte order, implemented externally. + * HASH_MAKE_STRING + * macro converting context variables to an ASCII hash string. + * + * MD5 example: + * + * #define DATA_ORDER_IS_LITTLE_ENDIAN + * + * #define HASH_LONG MD5_LONG + * #define HASH_CTX MD5_CTX + * #define HASH_CBLOCK MD5_CBLOCK + * #define HASH_UPDATE MD5_Update + * #define HASH_TRANSFORM MD5_Transform + * #define HASH_FINAL MD5_Final + * #define HASH_BLOCK_DATA_ORDER md5_block_data_order + */ + +#include + +#if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN) +# error "DATA_ORDER must be defined!" +#endif + +#ifndef HASH_CBLOCK +# error "HASH_CBLOCK must be defined!" +#endif +#ifndef HASH_LONG +# error "HASH_LONG must be defined!" +#endif +#ifndef HASH_CTX +# error "HASH_CTX must be defined!" +#endif + +#ifndef HASH_UPDATE +# error "HASH_UPDATE must be defined!" +#endif +#ifndef HASH_TRANSFORM +# error "HASH_TRANSFORM must be defined!" +#endif +#ifndef HASH_FINAL +# error "HASH_FINAL must be defined!" +#endif + +#ifndef HASH_BLOCK_DATA_ORDER +# error "HASH_BLOCK_DATA_ORDER must be defined!" +#endif + +#define ROTATE(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n)))) + +#if defined(DATA_ORDER_IS_BIG_ENDIAN) + +# define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++)))<<24), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++))) ) ) +# define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l) )&0xff), \ + l) + +#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) + +# define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<<24) ) +# define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>>24)&0xff), \ + l) + +#endif + +/* + * Time for some action :-) + */ + +int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) +{ + const unsigned char *data = data_; + unsigned char *p; + HASH_LONG l; + size_t n; + + if (len == 0) + return 1; + + l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL; + if (l < c->Nl) /* overflow */ + c->Nh++; + c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on + * 16-bit */ + c->Nl = l; + + n = c->num; + if (n != 0) { + p = (unsigned char *)c->data; + + if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) { + memcpy(p + n, data, HASH_CBLOCK - n); + HASH_BLOCK_DATA_ORDER(c, p, 1); + n = HASH_CBLOCK - n; + data += n; + len -= n; + c->num = 0; + /* + * We use memset rather than OPENSSL_cleanse() here deliberately. + * Using OPENSSL_cleanse() here could be a performance issue. It + * will get properly cleansed on finalisation so this isn't a + * security problem. + */ + memset(p, 0, HASH_CBLOCK); /* keep it zeroed */ + } else { + memcpy(p + n, data, len); + c->num += (unsigned int)len; + return 1; + } + } + + n = len / HASH_CBLOCK; + if (n > 0) { + HASH_BLOCK_DATA_ORDER(c, data, n); + n *= HASH_CBLOCK; + data += n; + len -= n; + } + + if (len != 0) { + p = (unsigned char *)c->data; + c->num = (unsigned int)len; + memcpy(p, data, len); + } + return 1; +} + +void HASH_TRANSFORM(HASH_CTX *c, const unsigned char *data) +{ + HASH_BLOCK_DATA_ORDER(c, data, 1); +} + +int HASH_FINAL(unsigned char *md, HASH_CTX *c) +{ + unsigned char *p = (unsigned char *)c->data; + size_t n = c->num; + + p[n] = 0x80; /* there is always room for one */ + n++; + + if (n > (HASH_CBLOCK - 8)) { + memset(p + n, 0, HASH_CBLOCK - n); + n = 0; + HASH_BLOCK_DATA_ORDER(c, p, 1); + } + memset(p + n, 0, HASH_CBLOCK - 8 - n); + + p += HASH_CBLOCK - 8; +#if defined(DATA_ORDER_IS_BIG_ENDIAN) + (void)HOST_l2c(c->Nh, p); + (void)HOST_l2c(c->Nl, p); +#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) + (void)HOST_l2c(c->Nl, p); + (void)HOST_l2c(c->Nh, p); +#endif + p -= HASH_CBLOCK; + HASH_BLOCK_DATA_ORDER(c, p, 1); + c->num = 0; + OPENSSL_cleanse(p, HASH_CBLOCK); + +#ifndef HASH_MAKE_STRING +# error "HASH_MAKE_STRING must be defined!" +#else + HASH_MAKE_STRING(c, md); +#endif + + return 1; +} + +#ifndef MD32_REG_T +# if defined(__alpha) || defined(__sparcv9) || defined(__mips) +# define MD32_REG_T long +/* + * This comment was originally written for MD5, which is why it + * discusses A-D. But it basically applies to all 32-bit digests, + * which is why it was moved to common header file. + * + * In case you wonder why A-D are declared as long and not + * as MD5_LONG. Doing so results in slight performance + * boost on LP64 architectures. The catch is we don't + * really care if 32 MSBs of a 64-bit register get polluted + * with eventual overflows as we *save* only 32 LSBs in + * *either* case. Now declaring 'em long excuses the compiler + * from keeping 32 MSBs zeroed resulting in 13% performance + * improvement under SPARC Solaris7/64 and 5% under AlphaLinux. + * Well, to be honest it should say that this *prevents* + * performance degradation. + */ +# else +/* + * Above is not absolute and there are LP64 compilers that + * generate better code if MD32_REG_T is defined int. The above + * pre-processor condition reflects the circumstances under which + * the conclusion was made and is subject to further extension. + */ +# define MD32_REG_T int +# endif +#endif diff --git a/include/openssl/crypto/internal/objects.h b/include/openssl/crypto/internal/objects.h new file mode 100644 index 0000000..686ba13 --- /dev/null +++ b/include/openssl/crypto/internal/objects.h @@ -0,0 +1,12 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +void obj_cleanup_int(void); diff --git a/include/openssl/crypto/internal/poly1305.h b/include/openssl/crypto/internal/poly1305.h new file mode 100644 index 0000000..5fef239 --- /dev/null +++ b/include/openssl/crypto/internal/poly1305.h @@ -0,0 +1,21 @@ +/* + * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +#define POLY1305_BLOCK_SIZE 16 +#define POLY1305_DIGEST_SIZE 16 +#define POLY1305_KEY_SIZE 32 + +typedef struct poly1305_context POLY1305; + +size_t Poly1305_ctx_size(void); +void Poly1305_Init(POLY1305 *ctx, const unsigned char key[32]); +void Poly1305_Update(POLY1305 *ctx, const unsigned char *inp, size_t len); +void Poly1305_Final(POLY1305 *ctx, unsigned char mac[16]); diff --git a/include/openssl/crypto/internal/rand_int.h b/include/openssl/crypto/internal/rand_int.h new file mode 100644 index 0000000..e025ec9 --- /dev/null +++ b/include/openssl/crypto/internal/rand_int.h @@ -0,0 +1,131 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * Licensed under the OpenSSL licenses, (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * https://www.openssl.org/source/license.html + * or in the file LICENSE in the source distribution. + */ + +#ifndef HEADER_RAND_INT_H +# define HEADER_RAND_INT_H + +# include + +/* forward declaration */ +typedef struct rand_pool_st RAND_POOL; + +void rand_cleanup_int(void); +void rand_drbg_cleanup_int(void); +void drbg_delete_thread_state(void); +void rand_fork(void); + +/* Hardware-based seeding functions. */ +size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool); +size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool); + +/* DRBG entropy callbacks. */ +size_t rand_drbg_get_entropy(RAND_DRBG *drbg, + unsigned char **pout, + int entropy, size_t min_len, size_t max_len, + int prediction_resistance); +void rand_drbg_cleanup_entropy(RAND_DRBG *drbg, + unsigned char *out, size_t outlen); +size_t rand_drbg_get_nonce(RAND_DRBG *drbg, + unsigned char **pout, + int entropy, size_t min_len, size_t max_len); +void rand_drbg_cleanup_nonce(RAND_DRBG *drbg, + unsigned char *out, size_t outlen); + +size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len); + +void rand_drbg_cleanup_additional_data(unsigned char *out, size_t outlen); + +/* + * RAND_POOL functions + */ +RAND_POOL *rand_pool_new(int entropy_requested, size_t min_len, size_t max_len); +void rand_pool_free(RAND_POOL *pool); + +const unsigned char *rand_pool_buffer(RAND_POOL *pool); +unsigned char *rand_pool_detach(RAND_POOL *pool); + +size_t rand_pool_entropy(RAND_POOL *pool); +size_t rand_pool_length(RAND_POOL *pool); + +size_t rand_pool_entropy_available(RAND_POOL *pool); +size_t rand_pool_entropy_needed(RAND_POOL *pool); +/* |entropy_factor| expresses how many bits of data contain 1 bit of entropy */ +size_t rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor); +size_t rand_pool_bytes_remaining(RAND_POOL *pool); + +int rand_pool_add(RAND_POOL *pool, + const unsigned char *buffer, size_t len, size_t entropy); +unsigned char *rand_pool_add_begin(RAND_POOL *pool, size_t len); +int rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy); + + +/* + * Add random bytes to the pool to acquire requested amount of entropy + * + * This function is platform specific and tries to acquire the requested + * amount of entropy by polling platform specific entropy sources. + * + * If the function succeeds in acquiring at least |entropy_requested| bits + * of entropy, the total entropy count is returned. If it fails, it returns + * an entropy count of 0. + */ +size_t rand_pool_acquire_entropy(RAND_POOL *pool); + +/* + * Add some application specific nonce data + * + * This function is platform specific and adds some application specific + * data to the nonce used for instantiating the drbg. + * + * This data currently consists of the process and thread id, and a high + * resolution timestamp. The data does not include an atomic counter, + * because that is added by the calling function rand_drbg_get_nonce(). + * + * Returns 1 on success and 0 on failure. + */ +int rand_pool_add_nonce_data(RAND_POOL *pool); + + +/* + * Add some platform specific additional data + * + * This function is platform specific and adds some random noise to the + * additional data used for generating random bytes and for reseeding + * the drbg. + * + * Returns 1 on success and 0 on failure. + */ +int rand_pool_add_additional_data(RAND_POOL *pool); + +/* + * Initialise the random pool reseeding sources. + * + * Returns 1 on success and 0 on failure. + */ +int rand_pool_init(void); + +/* + * Finalise the random pool reseeding sources. + */ +void rand_pool_cleanup(void); + +/* + * Control the random pool use of open file descriptors. + */ +void rand_pool_keep_random_devices_open(int keep); + +#endif diff --git a/include/openssl/crypto/internal/sha.h b/include/openssl/crypto/internal/sha.h new file mode 100644 index 0000000..6d4af2b --- /dev/null +++ b/include/openssl/crypto/internal/sha.h @@ -0,0 +1,21 @@ +/* + * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include "include/openssl/sha.h" + +#ifndef HEADER_INTERNAL_SHA_H +# define HEADER_INTERNAL_SHA_H + +# include + +int sha512_224_init(SHA512_CTX *); +int sha512_256_init(SHA512_CTX *); + +#endif diff --git a/include/openssl/crypto/internal/siphash.h b/include/openssl/crypto/internal/siphash.h new file mode 100644 index 0000000..9573680 --- /dev/null +++ b/include/openssl/crypto/internal/siphash.h @@ -0,0 +1,25 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +#define SIPHASH_BLOCK_SIZE 8 +#define SIPHASH_KEY_SIZE 16 +#define SIPHASH_MIN_DIGEST_SIZE 8 +#define SIPHASH_MAX_DIGEST_SIZE 16 + +typedef struct siphash_st SIPHASH; + +size_t SipHash_ctx_size(void); +size_t SipHash_hash_size(SIPHASH *ctx); +int SipHash_set_hash_size(SIPHASH *ctx, size_t hash_size); +int SipHash_Init(SIPHASH *ctx, const unsigned char *k, + int crounds, int drounds); +void SipHash_Update(SIPHASH *ctx, const unsigned char *in, size_t inlen); +int SipHash_Final(SIPHASH *ctx, unsigned char *out, size_t outlen); diff --git a/include/openssl/crypto/internal/sm2.h b/include/openssl/crypto/internal/sm2.h new file mode 100644 index 0000000..fc64c76 --- /dev/null +++ b/include/openssl/crypto/internal/sm2.h @@ -0,0 +1,78 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. All Rights Reserved. + * Ported from Ribose contributions from Botan. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SM2_H +# define HEADER_SM2_H +# include + +# ifndef OPENSSL_NO_SM2 + +# include + +/* The default user id as specified in GM/T 0009-2012 */ +# define SM2_DEFAULT_USERID "1234567812345678" + +int sm2_compute_z_digest(uint8_t *out, + const EVP_MD *digest, + const uint8_t *id, + const size_t id_len, + const EC_KEY *key); + +/* + * SM2 signature operation. Computes Z and then signs H(Z || msg) using SM2 + */ +ECDSA_SIG *sm2_do_sign(const EC_KEY *key, + const EVP_MD *digest, + const uint8_t *id, + const size_t id_len, + const uint8_t *msg, size_t msg_len); + +int sm2_do_verify(const EC_KEY *key, + const EVP_MD *digest, + const ECDSA_SIG *signature, + const uint8_t *id, + const size_t id_len, + const uint8_t *msg, size_t msg_len); + +/* + * SM2 signature generation. + */ +int sm2_sign(const unsigned char *dgst, int dgstlen, + unsigned char *sig, unsigned int *siglen, EC_KEY *eckey); + +/* + * SM2 signature verification. + */ +int sm2_verify(const unsigned char *dgst, int dgstlen, + const unsigned char *sig, int siglen, EC_KEY *eckey); + +/* + * SM2 encryption + */ +int sm2_ciphertext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len, + size_t *ct_size); + +int sm2_plaintext_size(const EC_KEY *key, const EVP_MD *digest, size_t msg_len, + size_t *pt_size); + +int sm2_encrypt(const EC_KEY *key, + const EVP_MD *digest, + const uint8_t *msg, + size_t msg_len, + uint8_t *ciphertext_buf, size_t *ciphertext_len); + +int sm2_decrypt(const EC_KEY *key, + const EVP_MD *digest, + const uint8_t *ciphertext, + size_t ciphertext_len, uint8_t *ptext_buf, size_t *ptext_len); + +# endif /* OPENSSL_NO_SM2 */ +#endif diff --git a/include/openssl/crypto/internal/sm2err.h b/include/openssl/crypto/internal/sm2err.h new file mode 100644 index 0000000..d5e8f75 --- /dev/null +++ b/include/openssl/crypto/internal/sm2err.h @@ -0,0 +1,61 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SM2ERR_H +# define HEADER_SM2ERR_H + +# include + +# ifndef OPENSSL_NO_SM2 + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_SM2_strings(void); + +/* + * SM2 function codes. + */ +# define SM2_F_PKEY_SM2_COPY 115 +# define SM2_F_PKEY_SM2_CTRL 109 +# define SM2_F_PKEY_SM2_CTRL_STR 110 +# define SM2_F_PKEY_SM2_DIGEST_CUSTOM 114 +# define SM2_F_PKEY_SM2_INIT 111 +# define SM2_F_PKEY_SM2_SIGN 112 +# define SM2_F_SM2_COMPUTE_MSG_HASH 100 +# define SM2_F_SM2_COMPUTE_USERID_DIGEST 101 +# define SM2_F_SM2_COMPUTE_Z_DIGEST 113 +# define SM2_F_SM2_DECRYPT 102 +# define SM2_F_SM2_ENCRYPT 103 +# define SM2_F_SM2_PLAINTEXT_SIZE 104 +# define SM2_F_SM2_SIGN 105 +# define SM2_F_SM2_SIG_GEN 106 +# define SM2_F_SM2_SIG_VERIFY 107 +# define SM2_F_SM2_VERIFY 108 + +/* + * SM2 reason codes. + */ +# define SM2_R_ASN1_ERROR 100 +# define SM2_R_BAD_SIGNATURE 101 +# define SM2_R_BUFFER_TOO_SMALL 107 +# define SM2_R_DIST_ID_TOO_LARGE 110 +# define SM2_R_ID_NOT_SET 112 +# define SM2_R_ID_TOO_LARGE 111 +# define SM2_R_INVALID_CURVE 108 +# define SM2_R_INVALID_DIGEST 102 +# define SM2_R_INVALID_DIGEST_TYPE 103 +# define SM2_R_INVALID_ENCODING 104 +# define SM2_R_INVALID_FIELD 105 +# define SM2_R_NO_PARAMETERS_SET 109 +# define SM2_R_USER_ID_TOO_LARGE 106 + +# endif +#endif diff --git a/include/openssl/crypto/internal/sm3.h b/include/openssl/crypto/internal/sm3.h new file mode 100644 index 0000000..d7a3aee --- /dev/null +++ b/include/openssl/crypto/internal/sm3.h @@ -0,0 +1,39 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SM3_H +# define HEADER_SM3_H + +# include +# include +# ifdef OPENSSL_NO_SM3 +# error SM3 is disabled. +# endif + +# define SM3_DIGEST_LENGTH 32 +# define SM3_WORD unsigned int + +# define SM3_CBLOCK 64 +# define SM3_LBLOCK (SM3_CBLOCK/4) + +typedef struct SM3state_st { + SM3_WORD A, B, C, D, E, F, G, H; + SM3_WORD Nl, Nh; + SM3_WORD data[SM3_LBLOCK]; + unsigned int num; +} SM3_CTX; + +int sm3_init(SM3_CTX *c); +int sm3_update(SM3_CTX *c, const void *data, size_t len); +int sm3_final(unsigned char *md, SM3_CTX *c); + +void sm3_block_data_order(SM3_CTX *c, const void *p, size_t num); + +#endif diff --git a/include/openssl/crypto/internal/sm4.h b/include/openssl/crypto/internal/sm4.h new file mode 100644 index 0000000..24d6155 --- /dev/null +++ b/include/openssl/crypto/internal/sm4.h @@ -0,0 +1,37 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SM4_H +# define HEADER_SM4_H + +# include +# include + +# ifdef OPENSSL_NO_SM4 +# error SM4 is disabled. +# endif + +# define SM4_ENCRYPT 1 +# define SM4_DECRYPT 0 + +# define SM4_BLOCK_SIZE 16 +# define SM4_KEY_SCHEDULE 32 + +typedef struct SM4_KEY_st { + uint32_t rk[SM4_KEY_SCHEDULE]; +} SM4_KEY; + +int SM4_set_key(const uint8_t *key, SM4_KEY *ks); + +void SM4_encrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks); + +void SM4_decrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks); + +#endif diff --git a/include/openssl/crypto/internal/store.h b/include/openssl/crypto/internal/store.h new file mode 100644 index 0000000..f5013dc --- /dev/null +++ b/include/openssl/crypto/internal/store.h @@ -0,0 +1,10 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +void ossl_store_cleanup_int(void); diff --git a/include/openssl/crypto/internal/store_int.h b/include/openssl/crypto/internal/store_int.h new file mode 100644 index 0000000..2f95885 --- /dev/null +++ b/include/openssl/crypto/internal/store_int.h @@ -0,0 +1,26 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_STORE_INT_H +# define HEADER_STORE_INT_H + +# include +# include +# include + +/* + * Two functions to read PEM data off an already opened BIO. To be used + * instead of OSSLSTORE_open() and OSSLSTORE_close(). Everything is done + * as usual with OSSLSTORE_load() and OSSLSTORE_eof(). + */ +OSSL_STORE_CTX *ossl_store_attach_pem_bio(BIO *bp, const UI_METHOD *ui_method, + void *ui_data); +int ossl_store_detach_pem_bio(OSSL_STORE_CTX *ctx); + +#endif diff --git a/include/openssl/crypto/internal/x509_int.h b/include/openssl/crypto/internal/x509_int.h new file mode 100644 index 0000000..d863423 --- /dev/null +++ b/include/openssl/crypto/internal/x509_int.h @@ -0,0 +1,287 @@ +/* + * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include "include/openssl/internal/refcount.h" +#include "include/openssl/x509.h" + +/* Internal X509 structures and functions: not for application use */ + +/* Note: unless otherwise stated a field pointer is mandatory and should + * never be set to NULL: the ASN.1 code and accessors rely on mandatory + * fields never being NULL. + */ + +/* + * name entry structure, equivalent to AttributeTypeAndValue defined + * in RFC5280 et al. + */ +struct X509_name_entry_st { + ASN1_OBJECT *object; /* AttributeType */ + ASN1_STRING *value; /* AttributeValue */ + int set; /* index of RDNSequence for this entry */ + int size; /* temp variable */ +}; + +/* Name from RFC 5280. */ +struct X509_name_st { + STACK_OF(X509_NAME_ENTRY) *entries; /* DN components */ + int modified; /* true if 'bytes' needs to be built */ + BUF_MEM *bytes; /* cached encoding: cannot be NULL */ + /* canonical encoding used for rapid Name comparison */ + unsigned char *canon_enc; + int canon_enclen; +} /* X509_NAME */ ; + +/* Signature info structure */ + +struct x509_sig_info_st { + /* NID of message digest */ + int mdnid; + /* NID of public key algorithm */ + int pknid; + /* Security bits */ + int secbits; + /* Various flags */ + uint32_t flags; +}; + +/* PKCS#10 certificate request */ + +struct X509_req_info_st { + ASN1_ENCODING enc; /* cached encoding of signed part */ + ASN1_INTEGER *version; /* version, defaults to v1(0) so can be NULL */ + X509_NAME *subject; /* certificate request DN */ + X509_PUBKEY *pubkey; /* public key of request */ + /* + * Zero or more attributes. + * NB: although attributes is a mandatory field some broken + * encodings omit it so this may be NULL in that case. + */ + STACK_OF(X509_ATTRIBUTE) *attributes; +}; + +struct X509_req_st { + X509_REQ_INFO req_info; /* signed certificate request data */ + X509_ALGOR sig_alg; /* signature algorithm */ + ASN1_BIT_STRING *signature; /* signature */ + CRYPTO_REF_COUNT references; + CRYPTO_RWLOCK *lock; +}; + +struct X509_crl_info_st { + ASN1_INTEGER *version; /* version: defaults to v1(0) so may be NULL */ + X509_ALGOR sig_alg; /* signature algorithm */ + X509_NAME *issuer; /* CRL issuer name */ + ASN1_TIME *lastUpdate; /* lastUpdate field */ + ASN1_TIME *nextUpdate; /* nextUpdate field: optional */ + STACK_OF(X509_REVOKED) *revoked; /* revoked entries: optional */ + STACK_OF(X509_EXTENSION) *extensions; /* extensions: optional */ + ASN1_ENCODING enc; /* encoding of signed portion of CRL */ +}; + +struct X509_crl_st { + X509_CRL_INFO crl; /* signed CRL data */ + X509_ALGOR sig_alg; /* CRL signature algorithm */ + ASN1_BIT_STRING signature; /* CRL signature */ + CRYPTO_REF_COUNT references; + int flags; + /* + * Cached copies of decoded extension values, since extensions + * are optional any of these can be NULL. + */ + AUTHORITY_KEYID *akid; + ISSUING_DIST_POINT *idp; + /* Convenient breakdown of IDP */ + int idp_flags; + int idp_reasons; + /* CRL and base CRL numbers for delta processing */ + ASN1_INTEGER *crl_number; + ASN1_INTEGER *base_crl_number; + STACK_OF(GENERAL_NAMES) *issuers; + /* hash of CRL */ + unsigned char sha1_hash[SHA_DIGEST_LENGTH]; + /* alternative method to handle this CRL */ + const X509_CRL_METHOD *meth; + void *meth_data; + CRYPTO_RWLOCK *lock; +}; + +struct x509_revoked_st { + ASN1_INTEGER serialNumber; /* revoked entry serial number */ + ASN1_TIME *revocationDate; /* revocation date */ + STACK_OF(X509_EXTENSION) *extensions; /* CRL entry extensions: optional */ + /* decoded value of CRLissuer extension: set if indirect CRL */ + STACK_OF(GENERAL_NAME) *issuer; + /* revocation reason: set to CRL_REASON_NONE if reason extension absent */ + int reason; + /* + * CRL entries are reordered for faster lookup of serial numbers. This + * field contains the original load sequence for this entry. + */ + int sequence; +}; + +/* + * This stuff is certificate "auxiliary info": it contains details which are + * useful in certificate stores and databases. When used this is tagged onto + * the end of the certificate itself. OpenSSL specific structure not defined + * in any RFC. + */ + +struct x509_cert_aux_st { + STACK_OF(ASN1_OBJECT) *trust; /* trusted uses */ + STACK_OF(ASN1_OBJECT) *reject; /* rejected uses */ + ASN1_UTF8STRING *alias; /* "friendly name" */ + ASN1_OCTET_STRING *keyid; /* key id of private key */ + STACK_OF(X509_ALGOR) *other; /* other unspecified info */ +}; + +struct x509_cinf_st { + ASN1_INTEGER *version; /* [ 0 ] default of v1 */ + ASN1_INTEGER serialNumber; + X509_ALGOR signature; + X509_NAME *issuer; + X509_VAL validity; + X509_NAME *subject; + X509_PUBKEY *key; + ASN1_BIT_STRING *issuerUID; /* [ 1 ] optional in v2 */ + ASN1_BIT_STRING *subjectUID; /* [ 2 ] optional in v2 */ + STACK_OF(X509_EXTENSION) *extensions; /* [ 3 ] optional in v3 */ + ASN1_ENCODING enc; +}; + +struct x509_st { + X509_CINF cert_info; + X509_ALGOR sig_alg; + ASN1_BIT_STRING signature; + X509_SIG_INFO siginf; + CRYPTO_REF_COUNT references; + CRYPTO_EX_DATA ex_data; + /* These contain copies of various extension values */ + long ex_pathlen; + long ex_pcpathlen; + uint32_t ex_flags; + uint32_t ex_kusage; + uint32_t ex_xkusage; + uint32_t ex_nscert; + ASN1_OCTET_STRING *skid; + AUTHORITY_KEYID *akid; + X509_POLICY_CACHE *policy_cache; + STACK_OF(DIST_POINT) *crldp; + STACK_OF(GENERAL_NAME) *altname; + NAME_CONSTRAINTS *nc; +#ifndef OPENSSL_NO_RFC3779 + STACK_OF(IPAddressFamily) *rfc3779_addr; + struct ASIdentifiers_st *rfc3779_asid; +# endif + unsigned char sha1_hash[SHA_DIGEST_LENGTH]; + X509_CERT_AUX *aux; + CRYPTO_RWLOCK *lock; + volatile int ex_cached; +} /* X509 */ ; + +/* + * This is a used when verifying cert chains. Since the gathering of the + * cert chain can take some time (and have to be 'retried', this needs to be + * kept and passed around. + */ +struct x509_store_ctx_st { /* X509_STORE_CTX */ + X509_STORE *ctx; + /* The following are set by the caller */ + /* The cert to check */ + X509 *cert; + /* chain of X509s - untrusted - passed in */ + STACK_OF(X509) *untrusted; + /* set of CRLs passed in */ + STACK_OF(X509_CRL) *crls; + X509_VERIFY_PARAM *param; + /* Other info for use with get_issuer() */ + void *other_ctx; + /* Callbacks for various operations */ + /* called to verify a certificate */ + int (*verify) (X509_STORE_CTX *ctx); + /* error callback */ + int (*verify_cb) (int ok, X509_STORE_CTX *ctx); + /* get issuers cert from ctx */ + int (*get_issuer) (X509 **issuer, X509_STORE_CTX *ctx, X509 *x); + /* check issued */ + int (*check_issued) (X509_STORE_CTX *ctx, X509 *x, X509 *issuer); + /* Check revocation status of chain */ + int (*check_revocation) (X509_STORE_CTX *ctx); + /* retrieve CRL */ + int (*get_crl) (X509_STORE_CTX *ctx, X509_CRL **crl, X509 *x); + /* Check CRL validity */ + int (*check_crl) (X509_STORE_CTX *ctx, X509_CRL *crl); + /* Check certificate against CRL */ + int (*cert_crl) (X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x); + /* Check policy status of the chain */ + int (*check_policy) (X509_STORE_CTX *ctx); + STACK_OF(X509) *(*lookup_certs) (X509_STORE_CTX *ctx, X509_NAME *nm); + STACK_OF(X509_CRL) *(*lookup_crls) (X509_STORE_CTX *ctx, X509_NAME *nm); + int (*cleanup) (X509_STORE_CTX *ctx); + /* The following is built up */ + /* if 0, rebuild chain */ + int valid; + /* number of untrusted certs */ + int num_untrusted; + /* chain of X509s - built up and trusted */ + STACK_OF(X509) *chain; + /* Valid policy tree */ + X509_POLICY_TREE *tree; + /* Require explicit policy value */ + int explicit_policy; + /* When something goes wrong, this is why */ + int error_depth; + int error; + X509 *current_cert; + /* cert currently being tested as valid issuer */ + X509 *current_issuer; + /* current CRL */ + X509_CRL *current_crl; + /* score of current CRL */ + int current_crl_score; + /* Reason mask */ + unsigned int current_reasons; + /* For CRL path validation: parent context */ + X509_STORE_CTX *parent; + CRYPTO_EX_DATA ex_data; + SSL_DANE *dane; + /* signed via bare TA public key, rather than CA certificate */ + int bare_ta_signed; +}; + +/* PKCS#8 private key info structure */ + +struct pkcs8_priv_key_info_st { + ASN1_INTEGER *version; + X509_ALGOR *pkeyalg; + ASN1_OCTET_STRING *pkey; + STACK_OF(X509_ATTRIBUTE) *attributes; +}; + +struct X509_sig_st { + X509_ALGOR *algor; + ASN1_OCTET_STRING *digest; +}; + +struct x509_object_st { + /* one of the above types */ + X509_LOOKUP_TYPE type; + union { + char *ptr; + X509 *x509; + X509_CRL *crl; + EVP_PKEY *pkey; + } data; +}; + +int a2i_ipadd(unsigned char *ipout, const char *ipasc); +int x509_set1_time(ASN1_TIME **ptm, const ASN1_TIME *tm); + +void x509_init_sig_info(X509 *x); diff --git a/include/openssl/crypto/mips_arch.h b/include/openssl/crypto/mips_arch.h new file mode 100644 index 0000000..75043e7 --- /dev/null +++ b/include/openssl/crypto/mips_arch.h @@ -0,0 +1,40 @@ +/* + * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef __MIPS_ARCH_H__ +# define __MIPS_ARCH_H__ + +# if (defined(__mips_smartmips) || defined(_MIPS_ARCH_MIPS32R3) || \ + defined(_MIPS_ARCH_MIPS32R5) || defined(_MIPS_ARCH_MIPS32R6)) + && !defined(_MIPS_ARCH_MIPS32R2) +# define _MIPS_ARCH_MIPS32R2 +# endif + +# if (defined(_MIPS_ARCH_MIPS64R3) || defined(_MIPS_ARCH_MIPS64R5) || \ + defined(_MIPS_ARCH_MIPS64R6)) \ + && !defined(_MIPS_ARCH_MIPS64R2) +# define _MIPS_ARCH_MIPS64R2 +# endif + +# if defined(_MIPS_ARCH_MIPS64R6) +# define dmultu(rs,rt) +# define mflo(rd,rs,rt) dmulu rd,rs,rt +# define mfhi(rd,rs,rt) dmuhu rd,rs,rt +# elif defined(_MIPS_ARCH_MIPS32R6) +# define multu(rs,rt) +# define mflo(rd,rs,rt) mulu rd,rs,rt +# define mfhi(rd,rs,rt) muhu rd,rs,rt +# else +# define dmultu(rs,rt) dmultu rs,rt +# define multu(rs,rt) multu rs,rt +# define mflo(rd,rs,rt) mflo rd +# define mfhi(rd,rs,rt) mfhi rd +# endif + +#endif diff --git a/include/openssl/crypto/ppc_arch.h b/include/openssl/crypto/ppc_arch.h new file mode 100644 index 0000000..65cf96f --- /dev/null +++ b/include/openssl/crypto/ppc_arch.h @@ -0,0 +1,26 @@ +/* + * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PPC_ARCH_H +# define HEADER_PPC_ARCH_H + +extern unsigned int OPENSSL_ppccap_P; + +/* + * Flags' usage can appear ambiguous, because they are set rather + * to reflect OpenSSL performance preferences than actual processor + * capabilities. + */ +# define PPC_FPU64 (1<<0) +# define PPC_ALTIVEC (1<<1) +# define PPC_CRYPTO207 (1<<2) +# define PPC_FPU (1<<3) +# define PPC_MADD300 (1<<4) + +#endif diff --git a/include/openssl/crypto/s390x_arch.h b/include/openssl/crypto/s390x_arch.h new file mode 100644 index 0000000..4a775a9 --- /dev/null +++ b/include/openssl/crypto/s390x_arch.h @@ -0,0 +1,103 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef S390X_ARCH_H +# define S390X_ARCH_H + +# ifndef __ASSEMBLER__ + +void s390x_kimd(const unsigned char *in, size_t len, unsigned int fc, + void *param); +void s390x_klmd(const unsigned char *in, size_t inlen, unsigned char *out, + size_t outlen, unsigned int fc, void *param); +void s390x_km(const unsigned char *in, size_t len, unsigned char *out, + unsigned int fc, void *param); +void s390x_kmac(const unsigned char *in, size_t len, unsigned int fc, + void *param); +void s390x_kmo(const unsigned char *in, size_t len, unsigned char *out, + unsigned int fc, void *param); +void s390x_kmf(const unsigned char *in, size_t len, unsigned char *out, + unsigned int fc, void *param); +void s390x_kma(const unsigned char *aad, size_t alen, const unsigned char *in, + size_t len, unsigned char *out, unsigned int fc, void *param); + +/* + * The field elements of OPENSSL_s390xcap_P are the 64-bit words returned by + * the STFLE instruction followed by the 64-bit word pairs returned by + * instructions' QUERY functions. If STFLE returns fewer data or an instruction + * is not supported, the corresponding field elements are zero. + */ +struct OPENSSL_s390xcap_st { + unsigned long long stfle[4]; + unsigned long long kimd[2]; + unsigned long long klmd[2]; + unsigned long long km[2]; + unsigned long long kmc[2]; + unsigned long long kmac[2]; + unsigned long long kmctr[2]; + unsigned long long kmo[2]; + unsigned long long kmf[2]; + unsigned long long prno[2]; + unsigned long long kma[2]; +}; + +extern struct OPENSSL_s390xcap_st OPENSSL_s390xcap_P; + +/* convert facility bit number or function code to bit mask */ +# define S390X_CAPBIT(i) (1ULL << (63 - (i) % 64)) + +# endif + +/* OPENSSL_s390xcap_P offsets [bytes] */ +# define S390X_STFLE 0x00 +# define S390X_KIMD 0x20 +# define S390X_KLMD 0x30 +# define S390X_KM 0x40 +# define S390X_KMC 0x50 +# define S390X_KMAC 0x60 +# define S390X_KMCTR 0x70 +# define S390X_KMO 0x80 +# define S390X_KMF 0x90 +# define S390X_PRNO 0xa0 +# define S390X_KMA 0xb0 + +/* Facility Bit Numbers */ +# define S390X_VX 129 +# define S390X_VXD 134 +# define S390X_VXE 135 + +/* Function Codes */ + +/* all instructions */ +# define S390X_QUERY 0 + +/* kimd/klmd */ +# define S390X_SHA3_224 32 +# define S390X_SHA3_256 33 +# define S390X_SHA3_384 34 +# define S390X_SHA3_512 35 +# define S390X_SHAKE_128 36 +# define S390X_SHAKE_256 37 +# define S390X_GHASH 65 + +/* km/kmc/kmac/kmctr/kmo/kmf/kma */ +# define S390X_AES_128 18 +# define S390X_AES_192 19 +# define S390X_AES_256 20 + +/* prno */ +# define S390X_TRNG 114 + +/* Register 0 Flags */ +# define S390X_DECRYPT 0x80 +# define S390X_KMA_LPC 0x100 +# define S390X_KMA_LAAD 0x200 +# define S390X_KMA_HS 0x400 + +#endif diff --git a/include/openssl/crypto/sparc_arch.h b/include/openssl/crypto/sparc_arch.h new file mode 100644 index 0000000..99eafb3 --- /dev/null +++ b/include/openssl/crypto/sparc_arch.h @@ -0,0 +1,118 @@ +/* + * Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef __SPARC_ARCH_H__ +# define __SPARC_ARCH_H__ + +# define SPARCV9_TICK_PRIVILEGED (1<<0) +# define SPARCV9_PREFER_FPU (1<<1) +# define SPARCV9_VIS1 (1<<2) +# define SPARCV9_VIS2 (1<<3)/* reserved */ +# define SPARCV9_FMADD (1<<4) +# define SPARCV9_BLK (1<<5)/* VIS1 block copy */ +# define SPARCV9_VIS3 (1<<6) +# define SPARCV9_RANDOM (1<<7) +# define SPARCV9_64BIT_STACK (1<<8) +# define SPARCV9_FJAESX (1<<9)/* Fujitsu SPARC64 X AES */ +# define SPARCV9_FJDESX (1<<10)/* Fujitsu SPARC64 X DES, reserved */ +# define SPARCV9_FJHPCACE (1<<11)/* Fujitsu HPC-ACE, reserved */ +# define SPARCV9_IMA (1<<13)/* reserved */ +# define SPARCV9_VIS4 (1<<14)/* reserved */ + +/* + * OPENSSL_sparcv9cap_P[1] is copy of Compatibility Feature Register, + * %asr26, SPARC-T4 and later. There is no SPARCV9_CFR bit in + * OPENSSL_sparcv9cap_P[0], as %cfr copy is sufficient... + */ +# define CFR_AES 0x00000001/* Supports AES opcodes */ +# define CFR_DES 0x00000002/* Supports DES opcodes */ +# define CFR_KASUMI 0x00000004/* Supports KASUMI opcodes */ +# define CFR_CAMELLIA 0x00000008/* Supports CAMELLIA opcodes */ +# define CFR_MD5 0x00000010/* Supports MD5 opcodes */ +# define CFR_SHA1 0x00000020/* Supports SHA1 opcodes */ +# define CFR_SHA256 0x00000040/* Supports SHA256 opcodes */ +# define CFR_SHA512 0x00000080/* Supports SHA512 opcodes */ +# define CFR_MPMUL 0x00000100/* Supports MPMUL opcodes */ +# define CFR_MONTMUL 0x00000200/* Supports MONTMUL opcodes */ +# define CFR_MONTSQR 0x00000400/* Supports MONTSQR opcodes */ +# define CFR_CRC32C 0x00000800/* Supports CRC32C opcodes */ +# define CFR_XMPMUL 0x00001000/* Supports XMPMUL opcodes */ +# define CFR_XMONTMUL 0x00002000/* Supports XMONTMUL opcodes */ +# define CFR_XMONTSQR 0x00004000/* Supports XMONTSQR opcodes */ + +# if defined(OPENSSL_PIC) && !defined(__PIC__) +# define __PIC__ +# endif + +# if defined(__SUNPRO_C) && defined(__sparcv9) && !defined(__arch64__) +# define __arch64__ +# endif + +# define SPARC_PIC_THUNK(reg) \ + .align 32; \ +.Lpic_thunk: \ + jmp %o7 + 8; \ + add %o7, reg, reg; + +# define SPARC_PIC_THUNK_CALL(reg) \ + sethi %hi(_GLOBAL_OFFSET_TABLE_-4), reg; \ + call .Lpic_thunk; \ + or reg, %lo(_GLOBAL_OFFSET_TABLE_+4), reg; + +# if 1 +# define SPARC_SETUP_GOT_REG(reg) SPARC_PIC_THUNK_CALL(reg) +# else +# define SPARC_SETUP_GOT_REG(reg) \ + sethi %hi(_GLOBAL_OFFSET_TABLE_-4), reg; \ + call .+8; \ + or reg,%lo(_GLOBAL_OFFSET_TABLE_+4), reg; \ + add %o7, reg, reg +# endif + +# if defined(__arch64__) + +# define SPARC_LOAD_ADDRESS(SYM, reg) \ + setx SYM, %o7, reg; +# define LDPTR ldx +# define SIZE_T_CC %xcc +# define STACK_FRAME 192 +# define STACK_BIAS 2047 +# define STACK_7thARG (STACK_BIAS+176) + +# else + +# define SPARC_LOAD_ADDRESS(SYM, reg) \ + set SYM, reg; +# define LDPTR ld +# define SIZE_T_CC %icc +# define STACK_FRAME 112 +# define STACK_BIAS 0 +# define STACK_7thARG 92 +# define SPARC_LOAD_ADDRESS_LEAF(SYM,reg,tmp) SPARC_LOAD_ADDRESS(SYM,reg) + +# endif + +# ifdef __PIC__ +# undef SPARC_LOAD_ADDRESS +# undef SPARC_LOAD_ADDRESS_LEAF +# define SPARC_LOAD_ADDRESS(SYM, reg) \ + SPARC_SETUP_GOT_REG(reg); \ + sethi %hi(SYM), %o7; \ + or %o7, %lo(SYM), %o7; \ + LDPTR [reg + %o7], reg; +# endif + +# ifndef SPARC_LOAD_ADDRESS_LEAF +# define SPARC_LOAD_ADDRESS_LEAF(SYM, reg, tmp) \ + mov %o7, tmp; \ + SPARC_LOAD_ADDRESS(SYM, reg) \ + mov tmp, %o7; +# endif + +#endif /* __SPARC_ARCH_H__ */ diff --git a/include/openssl/crypto/vms_rms.h b/include/openssl/crypto/vms_rms.h new file mode 100644 index 0000000..3b994a0 --- /dev/null +++ b/include/openssl/crypto/vms_rms.h @@ -0,0 +1,58 @@ +/* + * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifdef NAML$C_MAXRSS + +# define CC_RMS_NAMX cc$rms_naml +# define FAB_NAMX fab$l_naml +# define FAB_OR_NAML( fab, naml) naml +# define FAB_OR_NAML_DNA naml$l_long_defname +# define FAB_OR_NAML_DNS naml$l_long_defname_size +# define FAB_OR_NAML_FNA naml$l_long_filename +# define FAB_OR_NAML_FNS naml$l_long_filename_size +# define NAMX_ESA naml$l_long_expand +# define NAMX_ESL naml$l_long_expand_size +# define NAMX_ESS naml$l_long_expand_alloc +# define NAMX_NOP naml$b_nop +# define SET_NAMX_NO_SHORT_UPCASE( nam) nam.naml$v_no_short_upcase = 1 + +# if __INITIAL_POINTER_SIZE == 64 +# define NAMX_DNA_FNA_SET(fab) fab.fab$l_dna = (__char_ptr32) -1; \ + fab.fab$l_fna = (__char_ptr32) -1; +# else /* __INITIAL_POINTER_SIZE == 64 */ +# define NAMX_DNA_FNA_SET(fab) fab.fab$l_dna = (char *) -1; \ + fab.fab$l_fna = (char *) -1; +# endif /* __INITIAL_POINTER_SIZE == 64 [else] */ + +# define NAMX_MAXRSS NAML$C_MAXRSS +# define NAMX_STRUCT NAML + +#else /* def NAML$C_MAXRSS */ + +# define CC_RMS_NAMX cc$rms_nam +# define FAB_NAMX fab$l_nam +# define FAB_OR_NAML( fab, naml) fab +# define FAB_OR_NAML_DNA fab$l_dna +# define FAB_OR_NAML_DNS fab$b_dns +# define FAB_OR_NAML_FNA fab$l_fna +# define FAB_OR_NAML_FNS fab$b_fns +# define NAMX_ESA nam$l_esa +# define NAMX_ESL nam$b_esl +# define NAMX_ESS nam$b_ess +# define NAMX_NOP nam$b_nop +# define NAMX_DNA_FNA_SET(fab) +# define NAMX_MAXRSS NAM$C_MAXRSS +# define NAMX_STRUCT NAM +# ifdef NAM$M_NO_SHORT_UPCASE +# define SET_NAMX_NO_SHORT_UPCASE( nam) naml.naml$v_no_short_upcase = 1 +# else /* def NAM$M_NO_SHORT_UPCASE */ +# define SET_NAMX_NO_SHORT_UPCASE( nam) +# endif /* def NAM$M_NO_SHORT_UPCASE [else] */ + +#endif /* def NAML$C_MAXRSS [else] */ diff --git a/include/openssl/cryptoerr.h b/include/openssl/cryptoerr.h new file mode 100644 index 0000000..e127ff6 --- /dev/null +++ b/include/openssl/cryptoerr.h @@ -0,0 +1,53 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CRYPTOERR_H +# define HEADER_CRYPTOERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_CRYPTO_strings(void); + +/* + * CRYPTO function codes. + */ +# define CRYPTO_F_CMAC_CTX_NEW 120 +# define CRYPTO_F_CRYPTO_DUP_EX_DATA 110 +# define CRYPTO_F_CRYPTO_FREE_EX_DATA 111 +# define CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX 100 +# define CRYPTO_F_CRYPTO_MEMDUP 115 +# define CRYPTO_F_CRYPTO_NEW_EX_DATA 112 +# define CRYPTO_F_CRYPTO_OCB128_COPY_CTX 121 +# define CRYPTO_F_CRYPTO_OCB128_INIT 122 +# define CRYPTO_F_CRYPTO_SET_EX_DATA 102 +# define CRYPTO_F_FIPS_MODE_SET 109 +# define CRYPTO_F_GET_AND_LOCK 113 +# define CRYPTO_F_OPENSSL_ATEXIT 114 +# define CRYPTO_F_OPENSSL_BUF2HEXSTR 117 +# define CRYPTO_F_OPENSSL_FOPEN 119 +# define CRYPTO_F_OPENSSL_HEXSTR2BUF 118 +# define CRYPTO_F_OPENSSL_INIT_CRYPTO 116 +# define CRYPTO_F_OPENSSL_LH_NEW 126 +# define CRYPTO_F_OPENSSL_SK_DEEP_COPY 127 +# define CRYPTO_F_OPENSSL_SK_DUP 128 +# define CRYPTO_F_PKEY_HMAC_INIT 123 +# define CRYPTO_F_PKEY_POLY1305_INIT 124 +# define CRYPTO_F_PKEY_SIPHASH_INIT 125 +# define CRYPTO_F_SK_RESERVE 129 + +/* + * CRYPTO reason codes. + */ +# define CRYPTO_R_FIPS_MODE_NOT_SUPPORTED 101 +# define CRYPTO_R_ILLEGAL_HEX_DIGIT 102 +# define CRYPTO_R_ODD_NUMBER_OF_DIGITS 103 + +#endif diff --git a/include/openssl/ct.h b/include/openssl/ct.h new file mode 100644 index 0000000..6444c38 --- /dev/null +++ b/include/openssl/ct.h @@ -0,0 +1,476 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CT_H +# define HEADER_CT_H + +# include + +# ifndef OPENSSL_NO_CT +# include +# include +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + + +/* Minimum RSA key size, from RFC6962 */ +# define SCT_MIN_RSA_BITS 2048 + +/* All hashes are SHA256 in v1 of Certificate Transparency */ +# define CT_V1_HASHLEN SHA256_DIGEST_LENGTH + +typedef enum { + CT_LOG_ENTRY_TYPE_NOT_SET = -1, + CT_LOG_ENTRY_TYPE_X509 = 0, + CT_LOG_ENTRY_TYPE_PRECERT = 1 +} ct_log_entry_type_t; + +typedef enum { + SCT_VERSION_NOT_SET = -1, + SCT_VERSION_V1 = 0 +} sct_version_t; + +typedef enum { + SCT_SOURCE_UNKNOWN, + SCT_SOURCE_TLS_EXTENSION, + SCT_SOURCE_X509V3_EXTENSION, + SCT_SOURCE_OCSP_STAPLED_RESPONSE +} sct_source_t; + +typedef enum { + SCT_VALIDATION_STATUS_NOT_SET, + SCT_VALIDATION_STATUS_UNKNOWN_LOG, + SCT_VALIDATION_STATUS_VALID, + SCT_VALIDATION_STATUS_INVALID, + SCT_VALIDATION_STATUS_UNVERIFIED, + SCT_VALIDATION_STATUS_UNKNOWN_VERSION +} sct_validation_status_t; + +DEFINE_STACK_OF(SCT) +DEFINE_STACK_OF(CTLOG) + +/****************************************** + * CT policy evaluation context functions * + ******************************************/ + +/* + * Creates a new, empty policy evaluation context. + * The caller is responsible for calling CT_POLICY_EVAL_CTX_free when finished + * with the CT_POLICY_EVAL_CTX. + */ +CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new(void); + +/* Deletes a policy evaluation context and anything it owns. */ +void CT_POLICY_EVAL_CTX_free(CT_POLICY_EVAL_CTX *ctx); + +/* Gets the peer certificate that the SCTs are for */ +X509* CT_POLICY_EVAL_CTX_get0_cert(const CT_POLICY_EVAL_CTX *ctx); + +/* + * Sets the certificate associated with the received SCTs. + * Increments the reference count of cert. + * Returns 1 on success, 0 otherwise. + */ +int CT_POLICY_EVAL_CTX_set1_cert(CT_POLICY_EVAL_CTX *ctx, X509 *cert); + +/* Gets the issuer of the aforementioned certificate */ +X509* CT_POLICY_EVAL_CTX_get0_issuer(const CT_POLICY_EVAL_CTX *ctx); + +/* + * Sets the issuer of the certificate associated with the received SCTs. + * Increments the reference count of issuer. + * Returns 1 on success, 0 otherwise. + */ +int CT_POLICY_EVAL_CTX_set1_issuer(CT_POLICY_EVAL_CTX *ctx, X509 *issuer); + +/* Gets the CT logs that are trusted sources of SCTs */ +const CTLOG_STORE *CT_POLICY_EVAL_CTX_get0_log_store(const CT_POLICY_EVAL_CTX *ctx); + +/* Sets the log store that is in use. It must outlive the CT_POLICY_EVAL_CTX. */ +void CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(CT_POLICY_EVAL_CTX *ctx, + CTLOG_STORE *log_store); + +/* + * Gets the time, in milliseconds since the Unix epoch, that will be used as the + * current time when checking whether an SCT was issued in the future. + * Such SCTs will fail validation, as required by RFC6962. + */ +uint64_t CT_POLICY_EVAL_CTX_get_time(const CT_POLICY_EVAL_CTX *ctx); + +/* + * Sets the time to evaluate SCTs against, in milliseconds since the Unix epoch. + * If an SCT's timestamp is after this time, it will be interpreted as having + * been issued in the future. RFC6962 states that "TLS clients MUST reject SCTs + * whose timestamp is in the future", so an SCT will not validate in this case. + */ +void CT_POLICY_EVAL_CTX_set_time(CT_POLICY_EVAL_CTX *ctx, uint64_t time_in_ms); + +/***************** + * SCT functions * + *****************/ + +/* + * Creates a new, blank SCT. + * The caller is responsible for calling SCT_free when finished with the SCT. + */ +SCT *SCT_new(void); + +/* + * Creates a new SCT from some base64-encoded strings. + * The caller is responsible for calling SCT_free when finished with the SCT. + */ +SCT *SCT_new_from_base64(unsigned char version, + const char *logid_base64, + ct_log_entry_type_t entry_type, + uint64_t timestamp, + const char *extensions_base64, + const char *signature_base64); + +/* + * Frees the SCT and the underlying data structures. + */ +void SCT_free(SCT *sct); + +/* + * Free a stack of SCTs, and the underlying SCTs themselves. + * Intended to be compatible with X509V3_EXT_FREE. + */ +void SCT_LIST_free(STACK_OF(SCT) *a); + +/* + * Returns the version of the SCT. + */ +sct_version_t SCT_get_version(const SCT *sct); + +/* + * Set the version of an SCT. + * Returns 1 on success, 0 if the version is unrecognized. + */ +__owur int SCT_set_version(SCT *sct, sct_version_t version); + +/* + * Returns the log entry type of the SCT. + */ +ct_log_entry_type_t SCT_get_log_entry_type(const SCT *sct); + +/* + * Set the log entry type of an SCT. + * Returns 1 on success, 0 otherwise. + */ +__owur int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type); + +/* + * Gets the ID of the log that an SCT came from. + * Ownership of the log ID remains with the SCT. + * Returns the length of the log ID. + */ +size_t SCT_get0_log_id(const SCT *sct, unsigned char **log_id); + +/* + * Set the log ID of an SCT to point directly to the *log_id specified. + * The SCT takes ownership of the specified pointer. + * Returns 1 on success, 0 otherwise. + */ +__owur int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len); + +/* + * Set the log ID of an SCT. + * This makes a copy of the log_id. + * Returns 1 on success, 0 otherwise. + */ +__owur int SCT_set1_log_id(SCT *sct, const unsigned char *log_id, + size_t log_id_len); + +/* + * Returns the timestamp for the SCT (epoch time in milliseconds). + */ +uint64_t SCT_get_timestamp(const SCT *sct); + +/* + * Set the timestamp of an SCT (epoch time in milliseconds). + */ +void SCT_set_timestamp(SCT *sct, uint64_t timestamp); + +/* + * Return the NID for the signature used by the SCT. + * For CT v1, this will be either NID_sha256WithRSAEncryption or + * NID_ecdsa_with_SHA256 (or NID_undef if incorrect/unset). + */ +int SCT_get_signature_nid(const SCT *sct); + +/* + * Set the signature type of an SCT + * For CT v1, this should be either NID_sha256WithRSAEncryption or + * NID_ecdsa_with_SHA256. + * Returns 1 on success, 0 otherwise. + */ +__owur int SCT_set_signature_nid(SCT *sct, int nid); + +/* + * Set *ext to point to the extension data for the SCT. ext must not be NULL. + * The SCT retains ownership of this pointer. + * Returns length of the data pointed to. + */ +size_t SCT_get0_extensions(const SCT *sct, unsigned char **ext); + +/* + * Set the extensions of an SCT to point directly to the *ext specified. + * The SCT takes ownership of the specified pointer. + */ +void SCT_set0_extensions(SCT *sct, unsigned char *ext, size_t ext_len); + +/* + * Set the extensions of an SCT. + * This takes a copy of the ext. + * Returns 1 on success, 0 otherwise. + */ +__owur int SCT_set1_extensions(SCT *sct, const unsigned char *ext, + size_t ext_len); + +/* + * Set *sig to point to the signature for the SCT. sig must not be NULL. + * The SCT retains ownership of this pointer. + * Returns length of the data pointed to. + */ +size_t SCT_get0_signature(const SCT *sct, unsigned char **sig); + +/* + * Set the signature of an SCT to point directly to the *sig specified. + * The SCT takes ownership of the specified pointer. + */ +void SCT_set0_signature(SCT *sct, unsigned char *sig, size_t sig_len); + +/* + * Set the signature of an SCT to be a copy of the *sig specified. + * Returns 1 on success, 0 otherwise. + */ +__owur int SCT_set1_signature(SCT *sct, const unsigned char *sig, + size_t sig_len); + +/* + * The origin of this SCT, e.g. TLS extension, OCSP response, etc. + */ +sct_source_t SCT_get_source(const SCT *sct); + +/* + * Set the origin of this SCT, e.g. TLS extension, OCSP response, etc. + * Returns 1 on success, 0 otherwise. + */ +__owur int SCT_set_source(SCT *sct, sct_source_t source); + +/* + * Returns a text string describing the validation status of |sct|. + */ +const char *SCT_validation_status_string(const SCT *sct); + +/* + * Pretty-prints an |sct| to |out|. + * It will be indented by the number of spaces specified by |indent|. + * If |logs| is not NULL, it will be used to lookup the CT log that the SCT came + * from, so that the log name can be printed. + */ +void SCT_print(const SCT *sct, BIO *out, int indent, const CTLOG_STORE *logs); + +/* + * Pretty-prints an |sct_list| to |out|. + * It will be indented by the number of spaces specified by |indent|. + * SCTs will be delimited by |separator|. + * If |logs| is not NULL, it will be used to lookup the CT log that each SCT + * came from, so that the log names can be printed. + */ +void SCT_LIST_print(const STACK_OF(SCT) *sct_list, BIO *out, int indent, + const char *separator, const CTLOG_STORE *logs); + +/* + * Gets the last result of validating this SCT. + * If it has not been validated yet, returns SCT_VALIDATION_STATUS_NOT_SET. + */ +sct_validation_status_t SCT_get_validation_status(const SCT *sct); + +/* + * Validates the given SCT with the provided context. + * Sets the "validation_status" field of the SCT. + * Returns 1 if the SCT is valid and the signature verifies. + * Returns 0 if the SCT is invalid or could not be verified. + * Returns -1 if an error occurs. + */ +__owur int SCT_validate(SCT *sct, const CT_POLICY_EVAL_CTX *ctx); + +/* + * Validates the given list of SCTs with the provided context. + * Sets the "validation_status" field of each SCT. + * Returns 1 if there are no invalid SCTs and all signatures verify. + * Returns 0 if at least one SCT is invalid or could not be verified. + * Returns a negative integer if an error occurs. + */ +__owur int SCT_LIST_validate(const STACK_OF(SCT) *scts, + CT_POLICY_EVAL_CTX *ctx); + + +/********************************* + * SCT parsing and serialisation * + *********************************/ + +/* + * Serialize (to TLS format) a stack of SCTs and return the length. + * "a" must not be NULL. + * If "pp" is NULL, just return the length of what would have been serialized. + * If "pp" is not NULL and "*pp" is null, function will allocate a new pointer + * for data that caller is responsible for freeing (only if function returns + * successfully). + * If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring + * that "*pp" is large enough to accept all of the serialized data. + * Returns < 0 on error, >= 0 indicating bytes written (or would have been) + * on success. + */ +__owur int i2o_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp); + +/* + * Convert TLS format SCT list to a stack of SCTs. + * If "a" or "*a" is NULL, a new stack will be created that the caller is + * responsible for freeing (by calling SCT_LIST_free). + * "**pp" and "*pp" must not be NULL. + * Upon success, "*pp" will point to after the last bytes read, and a stack + * will be returned. + * Upon failure, a NULL pointer will be returned, and the position of "*pp" is + * not defined. + */ +STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, + size_t len); + +/* + * Serialize (to DER format) a stack of SCTs and return the length. + * "a" must not be NULL. + * If "pp" is NULL, just returns the length of what would have been serialized. + * If "pp" is not NULL and "*pp" is null, function will allocate a new pointer + * for data that caller is responsible for freeing (only if function returns + * successfully). + * If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring + * that "*pp" is large enough to accept all of the serialized data. + * Returns < 0 on error, >= 0 indicating bytes written (or would have been) + * on success. + */ +__owur int i2d_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp); + +/* + * Parses an SCT list in DER format and returns it. + * If "a" or "*a" is NULL, a new stack will be created that the caller is + * responsible for freeing (by calling SCT_LIST_free). + * "**pp" and "*pp" must not be NULL. + * Upon success, "*pp" will point to after the last bytes read, and a stack + * will be returned. + * Upon failure, a NULL pointer will be returned, and the position of "*pp" is + * not defined. + */ +STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, + long len); + +/* + * Serialize (to TLS format) an |sct| and write it to |out|. + * If |out| is null, no SCT will be output but the length will still be returned. + * If |out| points to a null pointer, a string will be allocated to hold the + * TLS-format SCT. It is the responsibility of the caller to free it. + * If |out| points to an allocated string, the TLS-format SCT will be written + * to it. + * The length of the SCT in TLS format will be returned. + */ +__owur int i2o_SCT(const SCT *sct, unsigned char **out); + +/* + * Parses an SCT in TLS format and returns it. + * If |psct| is not null, it will end up pointing to the parsed SCT. If it + * already points to a non-null pointer, the pointer will be free'd. + * |in| should be a pointer to a string containing the TLS-format SCT. + * |in| will be advanced to the end of the SCT if parsing succeeds. + * |len| should be the length of the SCT in |in|. + * Returns NULL if an error occurs. + * If the SCT is an unsupported version, only the SCT's 'sct' and 'sct_len' + * fields will be populated (with |in| and |len| respectively). + */ +SCT *o2i_SCT(SCT **psct, const unsigned char **in, size_t len); + +/******************** + * CT log functions * + ********************/ + +/* + * Creates a new CT log instance with the given |public_key| and |name|. + * Takes ownership of |public_key| but copies |name|. + * Returns NULL if malloc fails or if |public_key| cannot be converted to DER. + * Should be deleted by the caller using CTLOG_free when no longer needed. + */ +CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name); + +/* + * Creates a new CTLOG instance with the base64-encoded SubjectPublicKeyInfo DER + * in |pkey_base64|. The |name| is a string to help users identify this log. + * Returns 1 on success, 0 on failure. + * Should be deleted by the caller using CTLOG_free when no longer needed. + */ +int CTLOG_new_from_base64(CTLOG ** ct_log, + const char *pkey_base64, const char *name); + +/* + * Deletes a CT log instance and its fields. + */ +void CTLOG_free(CTLOG *log); + +/* Gets the name of the CT log */ +const char *CTLOG_get0_name(const CTLOG *log); +/* Gets the ID of the CT log */ +void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id, + size_t *log_id_len); +/* Gets the public key of the CT log */ +EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log); + +/************************** + * CT log store functions * + **************************/ + +/* + * Creates a new CT log store. + * Should be deleted by the caller using CTLOG_STORE_free when no longer needed. + */ +CTLOG_STORE *CTLOG_STORE_new(void); + +/* + * Deletes a CT log store and all of the CT log instances held within. + */ +void CTLOG_STORE_free(CTLOG_STORE *store); + +/* + * Finds a CT log in the store based on its log ID. + * Returns the CT log, or NULL if no match is found. + */ +const CTLOG *CTLOG_STORE_get0_log_by_id(const CTLOG_STORE *store, + const uint8_t *log_id, + size_t log_id_len); + +/* + * Loads a CT log list into a |store| from a |file|. + * Returns 1 if loading is successful, or 0 otherwise. + */ +__owur int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file); + +/* + * Loads the default CT log list into a |store|. + * See internal/cryptlib.h for the environment variable and file path that are + * consulted to find the default file. + * Returns 1 if loading is successful, or 0 otherwise. + */ +__owur int CTLOG_STORE_load_default_file(CTLOG_STORE *store); + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/cterr.h b/include/openssl/cterr.h new file mode 100644 index 0000000..5dda41f --- /dev/null +++ b/include/openssl/cterr.h @@ -0,0 +1,76 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CTERR_H +# define HEADER_CTERR_H + +# include + +# ifndef OPENSSL_NO_CT + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_CT_strings(void); + +/* + * CT function codes. + */ +# define CT_F_CTLOG_NEW 117 +# define CT_F_CTLOG_NEW_FROM_BASE64 118 +# define CT_F_CTLOG_NEW_FROM_CONF 119 +# define CT_F_CTLOG_STORE_LOAD_CTX_NEW 122 +# define CT_F_CTLOG_STORE_LOAD_FILE 123 +# define CT_F_CTLOG_STORE_LOAD_LOG 130 +# define CT_F_CTLOG_STORE_NEW 131 +# define CT_F_CT_BASE64_DECODE 124 +# define CT_F_CT_POLICY_EVAL_CTX_NEW 133 +# define CT_F_CT_V1_LOG_ID_FROM_PKEY 125 +# define CT_F_I2O_SCT 107 +# define CT_F_I2O_SCT_LIST 108 +# define CT_F_I2O_SCT_SIGNATURE 109 +# define CT_F_O2I_SCT 110 +# define CT_F_O2I_SCT_LIST 111 +# define CT_F_O2I_SCT_SIGNATURE 112 +# define CT_F_SCT_CTX_NEW 126 +# define CT_F_SCT_CTX_VERIFY 128 +# define CT_F_SCT_NEW 100 +# define CT_F_SCT_NEW_FROM_BASE64 127 +# define CT_F_SCT_SET0_LOG_ID 101 +# define CT_F_SCT_SET1_EXTENSIONS 114 +# define CT_F_SCT_SET1_LOG_ID 115 +# define CT_F_SCT_SET1_SIGNATURE 116 +# define CT_F_SCT_SET_LOG_ENTRY_TYPE 102 +# define CT_F_SCT_SET_SIGNATURE_NID 103 +# define CT_F_SCT_SET_VERSION 104 + +/* + * CT reason codes. + */ +# define CT_R_BASE64_DECODE_ERROR 108 +# define CT_R_INVALID_LOG_ID_LENGTH 100 +# define CT_R_LOG_CONF_INVALID 109 +# define CT_R_LOG_CONF_INVALID_KEY 110 +# define CT_R_LOG_CONF_MISSING_DESCRIPTION 111 +# define CT_R_LOG_CONF_MISSING_KEY 112 +# define CT_R_LOG_KEY_INVALID 113 +# define CT_R_SCT_FUTURE_TIMESTAMP 116 +# define CT_R_SCT_INVALID 104 +# define CT_R_SCT_INVALID_SIGNATURE 107 +# define CT_R_SCT_LIST_INVALID 105 +# define CT_R_SCT_LOG_ID_MISMATCH 114 +# define CT_R_SCT_NOT_SET 106 +# define CT_R_SCT_UNSUPPORTED_VERSION 115 +# define CT_R_UNRECOGNIZED_SIGNATURE_NID 101 +# define CT_R_UNSUPPORTED_ENTRY_TYPE 102 +# define CT_R_UNSUPPORTED_VERSION 103 + +# endif +#endif diff --git a/include/openssl/des.h b/include/openssl/des.h new file mode 100644 index 0000000..bf164b8 --- /dev/null +++ b/include/openssl/des.h @@ -0,0 +1,174 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DES_H +# define HEADER_DES_H + +# include + +# ifndef OPENSSL_NO_DES +# ifdef __cplusplus +extern "C" { +# endif +# include + +typedef unsigned int DES_LONG; + +# ifdef OPENSSL_BUILD_SHLIBCRYPTO +# undef OPENSSL_EXTERN +# define OPENSSL_EXTERN OPENSSL_EXPORT +# endif + +typedef unsigned char DES_cblock[8]; +typedef /* const */ unsigned char const_DES_cblock[8]; +/* + * With "const", gcc 2.8.1 on Solaris thinks that DES_cblock * and + * const_DES_cblock * are incompatible pointer types. + */ + +typedef struct DES_ks { + union { + DES_cblock cblock; + /* + * make sure things are correct size on machines with 8 byte longs + */ + DES_LONG deslong[2]; + } ks[16]; +} DES_key_schedule; + +# define DES_KEY_SZ (sizeof(DES_cblock)) +# define DES_SCHEDULE_SZ (sizeof(DES_key_schedule)) + +# define DES_ENCRYPT 1 +# define DES_DECRYPT 0 + +# define DES_CBC_MODE 0 +# define DES_PCBC_MODE 1 + +# define DES_ecb2_encrypt(i,o,k1,k2,e) \ + DES_ecb3_encrypt((i),(o),(k1),(k2),(k1),(e)) + +# define DES_ede2_cbc_encrypt(i,o,l,k1,k2,iv,e) \ + DES_ede3_cbc_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(e)) + +# define DES_ede2_cfb64_encrypt(i,o,l,k1,k2,iv,n,e) \ + DES_ede3_cfb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n),(e)) + +# define DES_ede2_ofb64_encrypt(i,o,l,k1,k2,iv,n) \ + DES_ede3_ofb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n)) + +OPENSSL_DECLARE_GLOBAL(int, DES_check_key); /* defaults to false */ +# define DES_check_key OPENSSL_GLOBAL_REF(DES_check_key) + +const char *DES_options(void); +void DES_ecb3_encrypt(const_DES_cblock *input, DES_cblock *output, + DES_key_schedule *ks1, DES_key_schedule *ks2, + DES_key_schedule *ks3, int enc); +DES_LONG DES_cbc_cksum(const unsigned char *input, DES_cblock *output, + long length, DES_key_schedule *schedule, + const_DES_cblock *ivec); +/* DES_cbc_encrypt does not update the IV! Use DES_ncbc_encrypt instead. */ +void DES_cbc_encrypt(const unsigned char *input, unsigned char *output, + long length, DES_key_schedule *schedule, + DES_cblock *ivec, int enc); +void DES_ncbc_encrypt(const unsigned char *input, unsigned char *output, + long length, DES_key_schedule *schedule, + DES_cblock *ivec, int enc); +void DES_xcbc_encrypt(const unsigned char *input, unsigned char *output, + long length, DES_key_schedule *schedule, + DES_cblock *ivec, const_DES_cblock *inw, + const_DES_cblock *outw, int enc); +void DES_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits, + long length, DES_key_schedule *schedule, + DES_cblock *ivec, int enc); +void DES_ecb_encrypt(const_DES_cblock *input, DES_cblock *output, + DES_key_schedule *ks, int enc); + +/* + * This is the DES encryption function that gets called by just about every + * other DES routine in the library. You should not use this function except + * to implement 'modes' of DES. I say this because the functions that call + * this routine do the conversion from 'char *' to long, and this needs to be + * done to make sure 'non-aligned' memory access do not occur. The + * characters are loaded 'little endian'. Data is a pointer to 2 unsigned + * long's and ks is the DES_key_schedule to use. enc, is non zero specifies + * encryption, zero if decryption. + */ +void DES_encrypt1(DES_LONG *data, DES_key_schedule *ks, int enc); + +/* + * This functions is the same as DES_encrypt1() except that the DES initial + * permutation (IP) and final permutation (FP) have been left out. As for + * DES_encrypt1(), you should not use this function. It is used by the + * routines in the library that implement triple DES. IP() DES_encrypt2() + * DES_encrypt2() DES_encrypt2() FP() is the same as DES_encrypt1() + * DES_encrypt1() DES_encrypt1() except faster :-). + */ +void DES_encrypt2(DES_LONG *data, DES_key_schedule *ks, int enc); + +void DES_encrypt3(DES_LONG *data, DES_key_schedule *ks1, + DES_key_schedule *ks2, DES_key_schedule *ks3); +void DES_decrypt3(DES_LONG *data, DES_key_schedule *ks1, + DES_key_schedule *ks2, DES_key_schedule *ks3); +void DES_ede3_cbc_encrypt(const unsigned char *input, unsigned char *output, + long length, + DES_key_schedule *ks1, DES_key_schedule *ks2, + DES_key_schedule *ks3, DES_cblock *ivec, int enc); +void DES_ede3_cfb64_encrypt(const unsigned char *in, unsigned char *out, + long length, DES_key_schedule *ks1, + DES_key_schedule *ks2, DES_key_schedule *ks3, + DES_cblock *ivec, int *num, int enc); +void DES_ede3_cfb_encrypt(const unsigned char *in, unsigned char *out, + int numbits, long length, DES_key_schedule *ks1, + DES_key_schedule *ks2, DES_key_schedule *ks3, + DES_cblock *ivec, int enc); +void DES_ede3_ofb64_encrypt(const unsigned char *in, unsigned char *out, + long length, DES_key_schedule *ks1, + DES_key_schedule *ks2, DES_key_schedule *ks3, + DES_cblock *ivec, int *num); +char *DES_fcrypt(const char *buf, const char *salt, char *ret); +char *DES_crypt(const char *buf, const char *salt); +void DES_ofb_encrypt(const unsigned char *in, unsigned char *out, int numbits, + long length, DES_key_schedule *schedule, + DES_cblock *ivec); +void DES_pcbc_encrypt(const unsigned char *input, unsigned char *output, + long length, DES_key_schedule *schedule, + DES_cblock *ivec, int enc); +DES_LONG DES_quad_cksum(const unsigned char *input, DES_cblock output[], + long length, int out_count, DES_cblock *seed); +int DES_random_key(DES_cblock *ret); +void DES_set_odd_parity(DES_cblock *key); +int DES_check_key_parity(const_DES_cblock *key); +int DES_is_weak_key(const_DES_cblock *key); +/* + * DES_set_key (= set_key = DES_key_sched = key_sched) calls + * DES_set_key_checked if global variable DES_check_key is set, + * DES_set_key_unchecked otherwise. + */ +int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule); +int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule); +int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule); +void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule); +void DES_string_to_key(const char *str, DES_cblock *key); +void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2); +void DES_cfb64_encrypt(const unsigned char *in, unsigned char *out, + long length, DES_key_schedule *schedule, + DES_cblock *ivec, int *num, int enc); +void DES_ofb64_encrypt(const unsigned char *in, unsigned char *out, + long length, DES_key_schedule *schedule, + DES_cblock *ivec, int *num); + +# define DES_fixup_key_parity DES_set_odd_parity + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/dh.h b/include/openssl/dh.h new file mode 100644 index 0000000..f9d793a --- /dev/null +++ b/include/openssl/dh.h @@ -0,0 +1,340 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DH_H +# define HEADER_DH_H + +# include + +# ifndef OPENSSL_NO_DH +# include +# include +# include +# include +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# endif +# include + +# ifdef __cplusplus +extern "C" { +# endif + +# ifndef OPENSSL_DH_MAX_MODULUS_BITS +# define OPENSSL_DH_MAX_MODULUS_BITS 10000 +# endif + +# define OPENSSL_DH_FIPS_MIN_MODULUS_BITS 1024 + +# define DH_FLAG_CACHE_MONT_P 0x01 + +# if OPENSSL_API_COMPAT < 0x10100000L +/* + * Does nothing. Previously this switched off constant time behaviour. + */ +# define DH_FLAG_NO_EXP_CONSTTIME 0x00 +# endif + +/* + * If this flag is set the DH method is FIPS compliant and can be used in + * FIPS mode. This is set in the validated module method. If an application + * sets this flag in its own methods it is its responsibility to ensure the + * result is compliant. + */ + +# define DH_FLAG_FIPS_METHOD 0x0400 + +/* + * If this flag is set the operations normally disabled in FIPS mode are + * permitted it is then the applications responsibility to ensure that the + * usage is compliant. + */ + +# define DH_FLAG_NON_FIPS_ALLOW 0x0400 + +/* Already defined in ossl_typ.h */ +/* typedef struct dh_st DH; */ +/* typedef struct dh_method DH_METHOD; */ + +DECLARE_ASN1_ITEM(DHparams) + +# define DH_GENERATOR_2 2 +/* #define DH_GENERATOR_3 3 */ +# define DH_GENERATOR_5 5 + +/* DH_check error codes */ +# define DH_CHECK_P_NOT_PRIME 0x01 +# define DH_CHECK_P_NOT_SAFE_PRIME 0x02 +# define DH_UNABLE_TO_CHECK_GENERATOR 0x04 +# define DH_NOT_SUITABLE_GENERATOR 0x08 +# define DH_CHECK_Q_NOT_PRIME 0x10 +# define DH_CHECK_INVALID_Q_VALUE 0x20 +# define DH_CHECK_INVALID_J_VALUE 0x40 + +/* DH_check_pub_key error codes */ +# define DH_CHECK_PUBKEY_TOO_SMALL 0x01 +# define DH_CHECK_PUBKEY_TOO_LARGE 0x02 +# define DH_CHECK_PUBKEY_INVALID 0x04 + +/* + * primes p where (p-1)/2 is prime too are called "safe"; we define this for + * backward compatibility: + */ +# define DH_CHECK_P_NOT_STRONG_PRIME DH_CHECK_P_NOT_SAFE_PRIME + +# define d2i_DHparams_fp(fp,x) \ + (DH *)ASN1_d2i_fp((char *(*)())DH_new, \ + (char *(*)())d2i_DHparams, \ + (fp), \ + (unsigned char **)(x)) +# define i2d_DHparams_fp(fp,x) \ + ASN1_i2d_fp(i2d_DHparams,(fp), (unsigned char *)(x)) +# define d2i_DHparams_bio(bp,x) \ + ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, bp, x) +# define i2d_DHparams_bio(bp,x) \ + ASN1_i2d_bio_of_const(DH,i2d_DHparams,bp,x) + +# define d2i_DHxparams_fp(fp,x) \ + (DH *)ASN1_d2i_fp((char *(*)())DH_new, \ + (char *(*)())d2i_DHxparams, \ + (fp), \ + (unsigned char **)(x)) +# define i2d_DHxparams_fp(fp,x) \ + ASN1_i2d_fp(i2d_DHxparams,(fp), (unsigned char *)(x)) +# define d2i_DHxparams_bio(bp,x) \ + ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, bp, x) +# define i2d_DHxparams_bio(bp,x) \ + ASN1_i2d_bio_of_const(DH, i2d_DHxparams, bp, x) + +DH *DHparams_dup(DH *); + +const DH_METHOD *DH_OpenSSL(void); + +void DH_set_default_method(const DH_METHOD *meth); +const DH_METHOD *DH_get_default_method(void); +int DH_set_method(DH *dh, const DH_METHOD *meth); +DH *DH_new_method(ENGINE *engine); + +DH *DH_new(void); +void DH_free(DH *dh); +int DH_up_ref(DH *dh); +int DH_bits(const DH *dh); +int DH_size(const DH *dh); +int DH_security_bits(const DH *dh); +#define DH_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_DH, l, p, newf, dupf, freef) +int DH_set_ex_data(DH *d, int idx, void *arg); +void *DH_get_ex_data(DH *d, int idx); + +/* Deprecated version */ +DEPRECATEDIN_0_9_8(DH *DH_generate_parameters(int prime_len, int generator, + void (*callback) (int, int, + void *), + void *cb_arg)) + +/* New version */ +int DH_generate_parameters_ex(DH *dh, int prime_len, int generator, + BN_GENCB *cb); + +int DH_check_params_ex(const DH *dh); +int DH_check_ex(const DH *dh); +int DH_check_pub_key_ex(const DH *dh, const BIGNUM *pub_key); +int DH_check_params(const DH *dh, int *ret); +int DH_check(const DH *dh, int *codes); +int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *codes); +int DH_generate_key(DH *dh); +int DH_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh); +int DH_compute_key_padded(unsigned char *key, const BIGNUM *pub_key, DH *dh); +DH *d2i_DHparams(DH **a, const unsigned char **pp, long length); +int i2d_DHparams(const DH *a, unsigned char **pp); +DH *d2i_DHxparams(DH **a, const unsigned char **pp, long length); +int i2d_DHxparams(const DH *a, unsigned char **pp); +# ifndef OPENSSL_NO_STDIO +int DHparams_print_fp(FILE *fp, const DH *x); +# endif +int DHparams_print(BIO *bp, const DH *x); + +/* RFC 5114 parameters */ +DH *DH_get_1024_160(void); +DH *DH_get_2048_224(void); +DH *DH_get_2048_256(void); + +/* Named parameters, currently RFC7919 */ +DH *DH_new_by_nid(int nid); +int DH_get_nid(const DH *dh); + +# ifndef OPENSSL_NO_CMS +/* RFC2631 KDF */ +int DH_KDF_X9_42(unsigned char *out, size_t outlen, + const unsigned char *Z, size_t Zlen, + ASN1_OBJECT *key_oid, + const unsigned char *ukm, size_t ukmlen, const EVP_MD *md); +# endif + +void DH_get0_pqg(const DH *dh, + const BIGNUM **p, const BIGNUM **q, const BIGNUM **g); +int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g); +void DH_get0_key(const DH *dh, + const BIGNUM **pub_key, const BIGNUM **priv_key); +int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key); +const BIGNUM *DH_get0_p(const DH *dh); +const BIGNUM *DH_get0_q(const DH *dh); +const BIGNUM *DH_get0_g(const DH *dh); +const BIGNUM *DH_get0_priv_key(const DH *dh); +const BIGNUM *DH_get0_pub_key(const DH *dh); +void DH_clear_flags(DH *dh, int flags); +int DH_test_flags(const DH *dh, int flags); +void DH_set_flags(DH *dh, int flags); +ENGINE *DH_get0_engine(DH *d); +long DH_get_length(const DH *dh); +int DH_set_length(DH *dh, long length); + +DH_METHOD *DH_meth_new(const char *name, int flags); +void DH_meth_free(DH_METHOD *dhm); +DH_METHOD *DH_meth_dup(const DH_METHOD *dhm); +const char *DH_meth_get0_name(const DH_METHOD *dhm); +int DH_meth_set1_name(DH_METHOD *dhm, const char *name); +int DH_meth_get_flags(const DH_METHOD *dhm); +int DH_meth_set_flags(DH_METHOD *dhm, int flags); +void *DH_meth_get0_app_data(const DH_METHOD *dhm); +int DH_meth_set0_app_data(DH_METHOD *dhm, void *app_data); +int (*DH_meth_get_generate_key(const DH_METHOD *dhm)) (DH *); +int DH_meth_set_generate_key(DH_METHOD *dhm, int (*generate_key) (DH *)); +int (*DH_meth_get_compute_key(const DH_METHOD *dhm)) + (unsigned char *key, const BIGNUM *pub_key, DH *dh); +int DH_meth_set_compute_key(DH_METHOD *dhm, + int (*compute_key) (unsigned char *key, const BIGNUM *pub_key, DH *dh)); +int (*DH_meth_get_bn_mod_exp(const DH_METHOD *dhm)) + (const DH *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, + BN_CTX *, BN_MONT_CTX *); +int DH_meth_set_bn_mod_exp(DH_METHOD *dhm, + int (*bn_mod_exp) (const DH *, BIGNUM *, const BIGNUM *, const BIGNUM *, + const BIGNUM *, BN_CTX *, BN_MONT_CTX *)); +int (*DH_meth_get_init(const DH_METHOD *dhm))(DH *); +int DH_meth_set_init(DH_METHOD *dhm, int (*init)(DH *)); +int (*DH_meth_get_finish(const DH_METHOD *dhm)) (DH *); +int DH_meth_set_finish(DH_METHOD *dhm, int (*finish) (DH *)); +int (*DH_meth_get_generate_params(const DH_METHOD *dhm)) + (DH *, int, int, BN_GENCB *); +int DH_meth_set_generate_params(DH_METHOD *dhm, + int (*generate_params) (DH *, int, int, BN_GENCB *)); + + +# define EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, len) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \ + EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, len, NULL) + +# define EVP_PKEY_CTX_set_dh_paramgen_subprime_len(ctx, len) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \ + EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN, len, NULL) + +# define EVP_PKEY_CTX_set_dh_paramgen_type(ctx, typ) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \ + EVP_PKEY_CTRL_DH_PARAMGEN_TYPE, typ, NULL) + +# define EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, gen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_PARAMGEN, \ + EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR, gen, NULL) + +# define EVP_PKEY_CTX_set_dh_rfc5114(ctx, gen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \ + EVP_PKEY_CTRL_DH_RFC5114, gen, NULL) + +# define EVP_PKEY_CTX_set_dhx_rfc5114(ctx, gen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, EVP_PKEY_OP_PARAMGEN, \ + EVP_PKEY_CTRL_DH_RFC5114, gen, NULL) + +# define EVP_PKEY_CTX_set_dh_nid(ctx, nid) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, \ + EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_DH_NID, nid, NULL) + +# define EVP_PKEY_CTX_set_dh_pad(ctx, pad) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DH, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_DH_PAD, pad, NULL) + +# define EVP_PKEY_CTX_set_dh_kdf_type(ctx, kdf) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_DH_KDF_TYPE, kdf, NULL) + +# define EVP_PKEY_CTX_get_dh_kdf_type(ctx) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_DH_KDF_TYPE, -2, NULL) + +# define EVP_PKEY_CTX_set0_dh_kdf_oid(ctx, oid) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_DH_KDF_OID, 0, (void *)(oid)) + +# define EVP_PKEY_CTX_get0_dh_kdf_oid(ctx, poid) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_GET_DH_KDF_OID, 0, (void *)(poid)) + +# define EVP_PKEY_CTX_set_dh_kdf_md(ctx, md) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_DH_KDF_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_get_dh_kdf_md(ctx, pmd) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_GET_DH_KDF_MD, 0, (void *)(pmd)) + +# define EVP_PKEY_CTX_set_dh_kdf_outlen(ctx, len) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_DH_KDF_OUTLEN, len, NULL) + +# define EVP_PKEY_CTX_get_dh_kdf_outlen(ctx, plen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN, 0, (void *)(plen)) + +# define EVP_PKEY_CTX_set0_dh_kdf_ukm(ctx, p, plen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_DH_KDF_UKM, plen, (void *)(p)) + +# define EVP_PKEY_CTX_get0_dh_kdf_ukm(ctx, p) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DHX, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_GET_DH_KDF_UKM, 0, (void *)(p)) + +# define EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN (EVP_PKEY_ALG_CTRL + 1) +# define EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR (EVP_PKEY_ALG_CTRL + 2) +# define EVP_PKEY_CTRL_DH_RFC5114 (EVP_PKEY_ALG_CTRL + 3) +# define EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN (EVP_PKEY_ALG_CTRL + 4) +# define EVP_PKEY_CTRL_DH_PARAMGEN_TYPE (EVP_PKEY_ALG_CTRL + 5) +# define EVP_PKEY_CTRL_DH_KDF_TYPE (EVP_PKEY_ALG_CTRL + 6) +# define EVP_PKEY_CTRL_DH_KDF_MD (EVP_PKEY_ALG_CTRL + 7) +# define EVP_PKEY_CTRL_GET_DH_KDF_MD (EVP_PKEY_ALG_CTRL + 8) +# define EVP_PKEY_CTRL_DH_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 9) +# define EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 10) +# define EVP_PKEY_CTRL_DH_KDF_UKM (EVP_PKEY_ALG_CTRL + 11) +# define EVP_PKEY_CTRL_GET_DH_KDF_UKM (EVP_PKEY_ALG_CTRL + 12) +# define EVP_PKEY_CTRL_DH_KDF_OID (EVP_PKEY_ALG_CTRL + 13) +# define EVP_PKEY_CTRL_GET_DH_KDF_OID (EVP_PKEY_ALG_CTRL + 14) +# define EVP_PKEY_CTRL_DH_NID (EVP_PKEY_ALG_CTRL + 15) +# define EVP_PKEY_CTRL_DH_PAD (EVP_PKEY_ALG_CTRL + 16) + +/* KDF types */ +# define EVP_PKEY_DH_KDF_NONE 1 +# ifndef OPENSSL_NO_CMS +# define EVP_PKEY_DH_KDF_X9_42 2 +# endif + + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/dherr.h b/include/openssl/dherr.h new file mode 100644 index 0000000..98334c4 --- /dev/null +++ b/include/openssl/dherr.h @@ -0,0 +1,84 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DHERR_H +# define HEADER_DHERR_H + +# include + +# ifndef OPENSSL_NO_DH + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_DH_strings(void); + +/* + * DH function codes. + */ +# define DH_F_COMPUTE_KEY 102 +# define DH_F_DHPARAMS_PRINT_FP 101 +# define DH_F_DH_BUILTIN_GENPARAMS 106 +# define DH_F_DH_CHECK_EX 121 +# define DH_F_DH_CHECK_PARAMS_EX 122 +# define DH_F_DH_CHECK_PUB_KEY_EX 123 +# define DH_F_DH_CMS_DECRYPT 114 +# define DH_F_DH_CMS_SET_PEERKEY 115 +# define DH_F_DH_CMS_SET_SHARED_INFO 116 +# define DH_F_DH_METH_DUP 117 +# define DH_F_DH_METH_NEW 118 +# define DH_F_DH_METH_SET1_NAME 119 +# define DH_F_DH_NEW_BY_NID 104 +# define DH_F_DH_NEW_METHOD 105 +# define DH_F_DH_PARAM_DECODE 107 +# define DH_F_DH_PKEY_PUBLIC_CHECK 124 +# define DH_F_DH_PRIV_DECODE 110 +# define DH_F_DH_PRIV_ENCODE 111 +# define DH_F_DH_PUB_DECODE 108 +# define DH_F_DH_PUB_ENCODE 109 +# define DH_F_DO_DH_PRINT 100 +# define DH_F_GENERATE_KEY 103 +# define DH_F_PKEY_DH_CTRL_STR 120 +# define DH_F_PKEY_DH_DERIVE 112 +# define DH_F_PKEY_DH_INIT 125 +# define DH_F_PKEY_DH_KEYGEN 113 + +/* + * DH reason codes. + */ +# define DH_R_BAD_GENERATOR 101 +# define DH_R_BN_DECODE_ERROR 109 +# define DH_R_BN_ERROR 106 +# define DH_R_CHECK_INVALID_J_VALUE 115 +# define DH_R_CHECK_INVALID_Q_VALUE 116 +# define DH_R_CHECK_PUBKEY_INVALID 122 +# define DH_R_CHECK_PUBKEY_TOO_LARGE 123 +# define DH_R_CHECK_PUBKEY_TOO_SMALL 124 +# define DH_R_CHECK_P_NOT_PRIME 117 +# define DH_R_CHECK_P_NOT_SAFE_PRIME 118 +# define DH_R_CHECK_Q_NOT_PRIME 119 +# define DH_R_DECODE_ERROR 104 +# define DH_R_INVALID_PARAMETER_NAME 110 +# define DH_R_INVALID_PARAMETER_NID 114 +# define DH_R_INVALID_PUBKEY 102 +# define DH_R_KDF_PARAMETER_ERROR 112 +# define DH_R_KEYS_NOT_SET 108 +# define DH_R_MISSING_PUBKEY 125 +# define DH_R_MODULUS_TOO_LARGE 103 +# define DH_R_NOT_SUITABLE_GENERATOR 120 +# define DH_R_NO_PARAMETERS_SET 107 +# define DH_R_NO_PRIVATE_VALUE 100 +# define DH_R_PARAMETER_ENCODING_ERROR 105 +# define DH_R_PEER_KEY_ERROR 111 +# define DH_R_SHARED_INFO_ERROR 113 +# define DH_R_UNABLE_TO_CHECK_GENERATOR 121 + +# endif +#endif diff --git a/include/openssl/dsa.h b/include/openssl/dsa.h new file mode 100644 index 0000000..34dc83d --- /dev/null +++ b/include/openssl/dsa.h @@ -0,0 +1,238 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DSA_H +# define HEADER_DSA_H + +# include + +# ifndef OPENSSL_NO_DSA +# ifdef __cplusplus +extern "C" { +# endif +# include +# include +# include +# include +# include +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# endif +# include + +# ifndef OPENSSL_DSA_MAX_MODULUS_BITS +# define OPENSSL_DSA_MAX_MODULUS_BITS 10000 +# endif + +# define OPENSSL_DSA_FIPS_MIN_MODULUS_BITS 1024 + +# define DSA_FLAG_CACHE_MONT_P 0x01 +# if OPENSSL_API_COMPAT < 0x10100000L +/* + * Does nothing. Previously this switched off constant time behaviour. + */ +# define DSA_FLAG_NO_EXP_CONSTTIME 0x00 +# endif + +/* + * If this flag is set the DSA method is FIPS compliant and can be used in + * FIPS mode. This is set in the validated module method. If an application + * sets this flag in its own methods it is its responsibility to ensure the + * result is compliant. + */ + +# define DSA_FLAG_FIPS_METHOD 0x0400 + +/* + * If this flag is set the operations normally disabled in FIPS mode are + * permitted it is then the applications responsibility to ensure that the + * usage is compliant. + */ + +# define DSA_FLAG_NON_FIPS_ALLOW 0x0400 +# define DSA_FLAG_FIPS_CHECKED 0x0800 + +/* Already defined in ossl_typ.h */ +/* typedef struct dsa_st DSA; */ +/* typedef struct dsa_method DSA_METHOD; */ + +typedef struct DSA_SIG_st DSA_SIG; + +# define d2i_DSAparams_fp(fp,x) (DSA *)ASN1_d2i_fp((char *(*)())DSA_new, \ + (char *(*)())d2i_DSAparams,(fp),(unsigned char **)(x)) +# define i2d_DSAparams_fp(fp,x) ASN1_i2d_fp(i2d_DSAparams,(fp), \ + (unsigned char *)(x)) +# define d2i_DSAparams_bio(bp,x) ASN1_d2i_bio_of(DSA,DSA_new,d2i_DSAparams,bp,x) +# define i2d_DSAparams_bio(bp,x) ASN1_i2d_bio_of_const(DSA,i2d_DSAparams,bp,x) + +DSA *DSAparams_dup(DSA *x); +DSA_SIG *DSA_SIG_new(void); +void DSA_SIG_free(DSA_SIG *a); +int i2d_DSA_SIG(const DSA_SIG *a, unsigned char **pp); +DSA_SIG *d2i_DSA_SIG(DSA_SIG **v, const unsigned char **pp, long length); +void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps); +int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s); + +DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); +int DSA_do_verify(const unsigned char *dgst, int dgst_len, + DSA_SIG *sig, DSA *dsa); + +const DSA_METHOD *DSA_OpenSSL(void); + +void DSA_set_default_method(const DSA_METHOD *); +const DSA_METHOD *DSA_get_default_method(void); +int DSA_set_method(DSA *dsa, const DSA_METHOD *); +const DSA_METHOD *DSA_get_method(DSA *d); + +DSA *DSA_new(void); +DSA *DSA_new_method(ENGINE *engine); +void DSA_free(DSA *r); +/* "up" the DSA object's reference count */ +int DSA_up_ref(DSA *r); +int DSA_size(const DSA *); +int DSA_bits(const DSA *d); +int DSA_security_bits(const DSA *d); + /* next 4 return -1 on error */ +DEPRECATEDIN_1_2_0(int DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)) +int DSA_sign(int type, const unsigned char *dgst, int dlen, + unsigned char *sig, unsigned int *siglen, DSA *dsa); +int DSA_verify(int type, const unsigned char *dgst, int dgst_len, + const unsigned char *sigbuf, int siglen, DSA *dsa); +#define DSA_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_DSA, l, p, newf, dupf, freef) +int DSA_set_ex_data(DSA *d, int idx, void *arg); +void *DSA_get_ex_data(DSA *d, int idx); + +DSA *d2i_DSAPublicKey(DSA **a, const unsigned char **pp, long length); +DSA *d2i_DSAPrivateKey(DSA **a, const unsigned char **pp, long length); +DSA *d2i_DSAparams(DSA **a, const unsigned char **pp, long length); + +/* Deprecated version */ +DEPRECATEDIN_0_9_8(DSA *DSA_generate_parameters(int bits, + unsigned char *seed, + int seed_len, + int *counter_ret, + unsigned long *h_ret, void + (*callback) (int, int, + void *), + void *cb_arg)) + +/* New version */ +int DSA_generate_parameters_ex(DSA *dsa, int bits, + const unsigned char *seed, int seed_len, + int *counter_ret, unsigned long *h_ret, + BN_GENCB *cb); + +int DSA_generate_key(DSA *a); +int i2d_DSAPublicKey(const DSA *a, unsigned char **pp); +int i2d_DSAPrivateKey(const DSA *a, unsigned char **pp); +int i2d_DSAparams(const DSA *a, unsigned char **pp); + +int DSAparams_print(BIO *bp, const DSA *x); +int DSA_print(BIO *bp, const DSA *x, int off); +# ifndef OPENSSL_NO_STDIO +int DSAparams_print_fp(FILE *fp, const DSA *x); +int DSA_print_fp(FILE *bp, const DSA *x, int off); +# endif + +# define DSS_prime_checks 64 +/* + * Primality test according to FIPS PUB 186-4, Appendix C.3. Since we only + * have one value here we set the number of checks to 64 which is the 128 bit + * security level that is the highest level and valid for creating a 3072 bit + * DSA key. + */ +# define DSA_is_prime(n, callback, cb_arg) \ + BN_is_prime(n, DSS_prime_checks, callback, NULL, cb_arg) + +# ifndef OPENSSL_NO_DH +/* + * Convert DSA structure (key or just parameters) into DH structure (be + * careful to avoid small subgroup attacks when using this!) + */ +DH *DSA_dup_DH(const DSA *r); +# endif + +# define EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, nbits) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_DSA, EVP_PKEY_OP_PARAMGEN, \ + EVP_PKEY_CTRL_DSA_PARAMGEN_BITS, nbits, NULL) + +# define EVP_PKEY_CTRL_DSA_PARAMGEN_BITS (EVP_PKEY_ALG_CTRL + 1) +# define EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS (EVP_PKEY_ALG_CTRL + 2) +# define EVP_PKEY_CTRL_DSA_PARAMGEN_MD (EVP_PKEY_ALG_CTRL + 3) + +void DSA_get0_pqg(const DSA *d, + const BIGNUM **p, const BIGNUM **q, const BIGNUM **g); +int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g); +void DSA_get0_key(const DSA *d, + const BIGNUM **pub_key, const BIGNUM **priv_key); +int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key); +const BIGNUM *DSA_get0_p(const DSA *d); +const BIGNUM *DSA_get0_q(const DSA *d); +const BIGNUM *DSA_get0_g(const DSA *d); +const BIGNUM *DSA_get0_pub_key(const DSA *d); +const BIGNUM *DSA_get0_priv_key(const DSA *d); +void DSA_clear_flags(DSA *d, int flags); +int DSA_test_flags(const DSA *d, int flags); +void DSA_set_flags(DSA *d, int flags); +ENGINE *DSA_get0_engine(DSA *d); + +DSA_METHOD *DSA_meth_new(const char *name, int flags); +void DSA_meth_free(DSA_METHOD *dsam); +DSA_METHOD *DSA_meth_dup(const DSA_METHOD *dsam); +const char *DSA_meth_get0_name(const DSA_METHOD *dsam); +int DSA_meth_set1_name(DSA_METHOD *dsam, const char *name); +int DSA_meth_get_flags(const DSA_METHOD *dsam); +int DSA_meth_set_flags(DSA_METHOD *dsam, int flags); +void *DSA_meth_get0_app_data(const DSA_METHOD *dsam); +int DSA_meth_set0_app_data(DSA_METHOD *dsam, void *app_data); +DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam)) + (const unsigned char *, int, DSA *); +int DSA_meth_set_sign(DSA_METHOD *dsam, + DSA_SIG *(*sign) (const unsigned char *, int, DSA *)); +int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam)) + (DSA *, BN_CTX *, BIGNUM **, BIGNUM **); +int DSA_meth_set_sign_setup(DSA_METHOD *dsam, + int (*sign_setup) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **)); +int (*DSA_meth_get_verify(const DSA_METHOD *dsam)) + (const unsigned char *, int, DSA_SIG *, DSA *); +int DSA_meth_set_verify(DSA_METHOD *dsam, + int (*verify) (const unsigned char *, int, DSA_SIG *, DSA *)); +int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam)) + (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, + const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *); +int DSA_meth_set_mod_exp(DSA_METHOD *dsam, + int (*mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, + const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *, + BN_MONT_CTX *)); +int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam)) + (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, + BN_CTX *, BN_MONT_CTX *); +int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam, + int (*bn_mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, + const BIGNUM *, BN_CTX *, BN_MONT_CTX *)); +int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *); +int DSA_meth_set_init(DSA_METHOD *dsam, int (*init)(DSA *)); +int (*DSA_meth_get_finish(const DSA_METHOD *dsam)) (DSA *); +int DSA_meth_set_finish(DSA_METHOD *dsam, int (*finish) (DSA *)); +int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam)) + (DSA *, int, const unsigned char *, int, int *, unsigned long *, + BN_GENCB *); +int DSA_meth_set_paramgen(DSA_METHOD *dsam, + int (*paramgen) (DSA *, int, const unsigned char *, int, int *, + unsigned long *, BN_GENCB *)); +int (*DSA_meth_get_keygen(const DSA_METHOD *dsam)) (DSA *); +int DSA_meth_set_keygen(DSA_METHOD *dsam, int (*keygen) (DSA *)); + + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/dsaerr.h b/include/openssl/dsaerr.h new file mode 100644 index 0000000..915b515 --- /dev/null +++ b/include/openssl/dsaerr.h @@ -0,0 +1,67 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DSAERR_H +# define HEADER_DSAERR_H + +# include + +# ifndef OPENSSL_NO_DSA + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_DSA_strings(void); + +/* + * DSA function codes. + */ +# define DSA_F_DSAPARAMS_PRINT 100 +# define DSA_F_DSAPARAMS_PRINT_FP 101 +# define DSA_F_DSA_BUILTIN_PARAMGEN 125 +# define DSA_F_DSA_BUILTIN_PARAMGEN2 126 +# define DSA_F_DSA_DO_SIGN 112 +# define DSA_F_DSA_DO_VERIFY 113 +# define DSA_F_DSA_METH_DUP 127 +# define DSA_F_DSA_METH_NEW 128 +# define DSA_F_DSA_METH_SET1_NAME 129 +# define DSA_F_DSA_NEW_METHOD 103 +# define DSA_F_DSA_PARAM_DECODE 119 +# define DSA_F_DSA_PRINT_FP 105 +# define DSA_F_DSA_PRIV_DECODE 115 +# define DSA_F_DSA_PRIV_ENCODE 116 +# define DSA_F_DSA_PUB_DECODE 117 +# define DSA_F_DSA_PUB_ENCODE 118 +# define DSA_F_DSA_SIGN 106 +# define DSA_F_DSA_SIGN_SETUP 107 +# define DSA_F_DSA_SIG_NEW 102 +# define DSA_F_OLD_DSA_PRIV_DECODE 122 +# define DSA_F_PKEY_DSA_CTRL 120 +# define DSA_F_PKEY_DSA_CTRL_STR 104 +# define DSA_F_PKEY_DSA_KEYGEN 121 + +/* + * DSA reason codes. + */ +# define DSA_R_BAD_Q_VALUE 102 +# define DSA_R_BN_DECODE_ERROR 108 +# define DSA_R_BN_ERROR 109 +# define DSA_R_DECODE_ERROR 104 +# define DSA_R_INVALID_DIGEST_TYPE 106 +# define DSA_R_INVALID_PARAMETERS 112 +# define DSA_R_MISSING_PARAMETERS 101 +# define DSA_R_MODULUS_TOO_LARGE 103 +# define DSA_R_NO_PARAMETERS_SET 107 +# define DSA_R_PARAMETER_ENCODING_ERROR 105 +# define DSA_R_Q_NOT_PRIME 113 +# define DSA_R_SEED_LEN_SMALL 110 + +# endif +#endif diff --git a/include/openssl/dtls1.h b/include/openssl/dtls1.h new file mode 100644 index 0000000..a312e38 --- /dev/null +++ b/include/openssl/dtls1.h @@ -0,0 +1,55 @@ +/* + * Copyright 2005-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DTLS1_H +# define HEADER_DTLS1_H + +#ifdef __cplusplus +extern "C" { +#endif + +# define DTLS1_VERSION 0xFEFF +# define DTLS1_2_VERSION 0xFEFD +# define DTLS_MIN_VERSION DTLS1_VERSION +# define DTLS_MAX_VERSION DTLS1_2_VERSION +# define DTLS1_VERSION_MAJOR 0xFE + +# define DTLS1_BAD_VER 0x0100 + +/* Special value for method supporting multiple versions */ +# define DTLS_ANY_VERSION 0x1FFFF + +/* lengths of messages */ +/* + * Actually the max cookie length in DTLS is 255. But we can't change this now + * due to compatibility concerns. + */ +# define DTLS1_COOKIE_LENGTH 256 + +# define DTLS1_RT_HEADER_LENGTH 13 + +# define DTLS1_HM_HEADER_LENGTH 12 + +# define DTLS1_HM_BAD_FRAGMENT -2 +# define DTLS1_HM_FRAGMENT_RETRY -3 + +# define DTLS1_CCS_HEADER_LENGTH 1 + +# define DTLS1_AL_HEADER_LENGTH 2 + +/* Timeout multipliers (timeout slice is defined in apps/timeouts.h */ +# define DTLS1_TMO_READ_COUNT 2 +# define DTLS1_TMO_WRITE_COUNT 2 + +# define DTLS1_TMO_ALERT_COUNT 12 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/e_os2.h b/include/openssl/e_os2.h new file mode 100644 index 0000000..e576357 --- /dev/null +++ b/include/openssl/e_os2.h @@ -0,0 +1,293 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_E_OS2_H +# define HEADER_E_OS2_H + +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** + * Detect operating systems. This probably needs completing. + * The result is that at least one OPENSSL_SYS_os macro should be defined. + * However, if none is defined, Unix is assumed. + **/ + +# define OPENSSL_SYS_UNIX + +/* --------------------- Microsoft operating systems ---------------------- */ + +/* + * Note that MSDOS actually denotes 32-bit environments running on top of + * MS-DOS, such as DJGPP one. + */ +# if defined(OPENSSL_SYS_MSDOS) +# undef OPENSSL_SYS_UNIX +# endif + +/* + * For 32 bit environment, there seems to be the CygWin environment and then + * all the others that try to do the same thing Microsoft does... + */ +/* + * UEFI lives here because it might be built with a Microsoft toolchain and + * we need to avoid the false positive match on Windows. + */ +# if defined(OPENSSL_SYS_UEFI) +# undef OPENSSL_SYS_UNIX +# elif defined(OPENSSL_SYS_UWIN) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WIN32_UWIN +# else +# if defined(__CYGWIN__) || defined(OPENSSL_SYS_CYGWIN) +# define OPENSSL_SYS_WIN32_CYGWIN +# else +# if defined(_WIN32) || defined(OPENSSL_SYS_WIN32) +# undef OPENSSL_SYS_UNIX +# if !defined(OPENSSL_SYS_WIN32) +# define OPENSSL_SYS_WIN32 +# endif +# endif +# if defined(_WIN64) || defined(OPENSSL_SYS_WIN64) +# undef OPENSSL_SYS_UNIX +# if !defined(OPENSSL_SYS_WIN64) +# define OPENSSL_SYS_WIN64 +# endif +# endif +# if defined(OPENSSL_SYS_WINNT) +# undef OPENSSL_SYS_UNIX +# endif +# if defined(OPENSSL_SYS_WINCE) +# undef OPENSSL_SYS_UNIX +# endif +# endif +# endif + +/* Anything that tries to look like Microsoft is "Windows" */ +# if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN64) || defined(OPENSSL_SYS_WINNT) || defined(OPENSSL_SYS_WINCE) +# undef OPENSSL_SYS_UNIX +# define OPENSSL_SYS_WINDOWS +# ifndef OPENSSL_SYS_MSDOS +# define OPENSSL_SYS_MSDOS +# endif +# endif + +/* + * DLL settings. This part is a bit tough, because it's up to the + * application implementor how he or she will link the application, so it + * requires some macro to be used. + */ +# ifdef OPENSSL_SYS_WINDOWS +# ifndef OPENSSL_OPT_WINDLL +# if defined(_WINDLL) /* This is used when building OpenSSL to + * indicate that DLL linkage should be used */ +# define OPENSSL_OPT_WINDLL +# endif +# endif +# endif + +/* ------------------------------- OpenVMS -------------------------------- */ +# if defined(__VMS) || defined(VMS) || defined(OPENSSL_SYS_VMS) +# if !defined(OPENSSL_SYS_VMS) +# undef OPENSSL_SYS_UNIX +# endif +# define OPENSSL_SYS_VMS +# if defined(__DECC) +# define OPENSSL_SYS_VMS_DECC +# elif defined(__DECCXX) +# define OPENSSL_SYS_VMS_DECC +# define OPENSSL_SYS_VMS_DECCXX +# else +# define OPENSSL_SYS_VMS_NODECC +# endif +# endif + +/* -------------------------------- Unix ---------------------------------- */ +# ifdef OPENSSL_SYS_UNIX +# if defined(linux) || defined(__linux__) && !defined(OPENSSL_SYS_LINUX) +# define OPENSSL_SYS_LINUX +# endif +# if defined(_AIX) && !defined(OPENSSL_SYS_AIX) +# define OPENSSL_SYS_AIX +# endif +# endif + +/* -------------------------------- VOS ----------------------------------- */ +# if defined(__VOS__) && !defined(OPENSSL_SYS_VOS) +# define OPENSSL_SYS_VOS +# ifdef __HPPA__ +# define OPENSSL_SYS_VOS_HPPA +# endif +# ifdef __IA32__ +# define OPENSSL_SYS_VOS_IA32 +# endif +# endif + +/** + * That's it for OS-specific stuff + *****************************************************************************/ + +/* Specials for I/O an exit */ +# ifdef OPENSSL_SYS_MSDOS +# define OPENSSL_UNISTD_IO +# define OPENSSL_DECLARE_EXIT extern void exit(int); +# else +# define OPENSSL_UNISTD_IO OPENSSL_UNISTD +# define OPENSSL_DECLARE_EXIT /* declared in unistd.h */ +# endif + +/*- + * OPENSSL_EXTERN is normally used to declare a symbol with possible extra + * attributes to handle its presence in a shared library. + * OPENSSL_EXPORT is used to define a symbol with extra possible attributes + * to make it visible in a shared library. + * Care needs to be taken when a header file is used both to declare and + * define symbols. Basically, for any library that exports some global + * variables, the following code must be present in the header file that + * declares them, before OPENSSL_EXTERN is used: + * + * #ifdef SOME_BUILD_FLAG_MACRO + * # undef OPENSSL_EXTERN + * # define OPENSSL_EXTERN OPENSSL_EXPORT + * #endif + * + * The default is to have OPENSSL_EXPORT and OPENSSL_EXTERN + * have some generally sensible values. + */ + +# if defined(OPENSSL_SYS_WINDOWS) && defined(OPENSSL_OPT_WINDLL) +# define OPENSSL_EXPORT extern __declspec(dllexport) +# define OPENSSL_EXTERN extern __declspec(dllimport) +# else +# define OPENSSL_EXPORT extern +# define OPENSSL_EXTERN extern +# endif + +/*- + * Macros to allow global variables to be reached through function calls when + * required (if a shared library version requires it, for example. + * The way it's done allows definitions like this: + * + * // in foobar.c + * OPENSSL_IMPLEMENT_GLOBAL(int,foobar,0) + * // in foobar.h + * OPENSSL_DECLARE_GLOBAL(int,foobar); + * #define foobar OPENSSL_GLOBAL_REF(foobar) + */ +# ifdef OPENSSL_EXPORT_VAR_AS_FUNCTION +# define OPENSSL_IMPLEMENT_GLOBAL(type,name,value) \ + type *_shadow_##name(void) \ + { static type _hide_##name=value; return &_hide_##name; } +# define OPENSSL_DECLARE_GLOBAL(type,name) type *_shadow_##name(void) +# define OPENSSL_GLOBAL_REF(name) (*(_shadow_##name())) +# else +# define OPENSSL_IMPLEMENT_GLOBAL(type,name,value) type _shadow_##name=value; +# define OPENSSL_DECLARE_GLOBAL(type,name) OPENSSL_EXPORT type _shadow_##name +# define OPENSSL_GLOBAL_REF(name) _shadow_##name +# endif + +# ifdef _WIN32 +# ifdef _WIN64 +# define ossl_ssize_t __int64 +# define OSSL_SSIZE_MAX _I64_MAX +# else +# define ossl_ssize_t int +# define OSSL_SSIZE_MAX INT_MAX +# endif +# endif + +# if defined(OPENSSL_SYS_UEFI) && !defined(ossl_ssize_t) +# define ossl_ssize_t INTN +# define OSSL_SSIZE_MAX MAX_INTN +# endif + +# ifndef ossl_ssize_t +# define ossl_ssize_t ssize_t +# if defined(SSIZE_MAX) +# define OSSL_SSIZE_MAX SSIZE_MAX +# elif defined(_POSIX_SSIZE_MAX) +# define OSSL_SSIZE_MAX _POSIX_SSIZE_MAX +# else +# define OSSL_SSIZE_MAX ((ssize_t)(SIZE_MAX>>1)) +# endif +# endif + +# ifdef DEBUG_UNUSED +# define __owur __attribute__((__warn_unused_result__)) +# else +# define __owur +# endif + +/* Standard integer types */ +# if defined(OPENSSL_SYS_UEFI) +typedef INT8 int8_t; +typedef UINT8 uint8_t; +typedef INT16 int16_t; +typedef UINT16 uint16_t; +typedef INT32 int32_t; +typedef UINT32 uint32_t; +typedef INT64 int64_t; +typedef UINT64 uint64_t; +# elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \ + defined(__osf__) || defined(__sgi) || defined(__hpux) || \ + defined(OPENSSL_SYS_VMS) || defined (__OpenBSD__) +# include +# elif defined(_MSC_VER) && _MSC_VER<=1500 +/* + * minimally required typdefs for systems not supporting inttypes.h or + * stdint.h: currently just older VC++ + */ +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef int int32_t; +typedef unsigned int uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +# else +# include +# endif + +/* ossl_inline: portable inline definition usable in public headers */ +# if !defined(inline) && !defined(__cplusplus) +# if defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L + /* just use inline */ +# define ossl_inline inline +# elif defined(__GNUC__) && __GNUC__>=2 +# define ossl_inline __inline__ +# elif defined(_MSC_VER) + /* + * Visual Studio: inline is available in C++ only, however + * __inline is available for C, see + * http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx + */ +# define ossl_inline __inline +# else +# define ossl_inline +# endif +# else +# define ossl_inline inline +# endif + +# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +# define ossl_noreturn _Noreturn +# elif defined(__GNUC__) && __GNUC__ >= 2 +# define ossl_noreturn __attribute__((noreturn)) +# else +# define ossl_noreturn +# endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/ebcdic.h b/include/openssl/ebcdic.h new file mode 100644 index 0000000..aa01285 --- /dev/null +++ b/include/openssl/ebcdic.h @@ -0,0 +1,33 @@ +/* + * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_EBCDIC_H +# define HEADER_EBCDIC_H + +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Avoid name clashes with other applications */ +# define os_toascii _openssl_os_toascii +# define os_toebcdic _openssl_os_toebcdic +# define ebcdic2ascii _openssl_ebcdic2ascii +# define ascii2ebcdic _openssl_ascii2ebcdic + +extern const unsigned char os_toascii[256]; +extern const unsigned char os_toebcdic[256]; +void *ebcdic2ascii(void *dest, const void *srce, size_t count); +void *ascii2ebcdic(void *dest, const void *srce, size_t count); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/ec.h b/include/openssl/ec.h new file mode 100644 index 0000000..81c6820 --- /dev/null +++ b/include/openssl/ec.h @@ -0,0 +1,1467 @@ +/* + * Copyright 2002-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_EC_H +# define HEADER_EC_H + +# include + +# ifndef OPENSSL_NO_EC +# include +# include +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# endif +# include +# ifdef __cplusplus +extern "C" { +# endif + +# ifndef OPENSSL_ECC_MAX_FIELD_BITS +# define OPENSSL_ECC_MAX_FIELD_BITS 661 +# endif + +/** Enum for the point conversion form as defined in X9.62 (ECDSA) + * for the encoding of a elliptic curve point (x,y) */ +typedef enum { + /** the point is encoded as z||x, where the octet z specifies + * which solution of the quadratic equation y is */ + POINT_CONVERSION_COMPRESSED = 2, + /** the point is encoded as z||x||y, where z is the octet 0x04 */ + POINT_CONVERSION_UNCOMPRESSED = 4, + /** the point is encoded as z||x||y, where the octet z specifies + * which solution of the quadratic equation y is */ + POINT_CONVERSION_HYBRID = 6 +} point_conversion_form_t; + +typedef struct ec_method_st EC_METHOD; +typedef struct ec_group_st EC_GROUP; +typedef struct ec_point_st EC_POINT; +typedef struct ecpk_parameters_st ECPKPARAMETERS; +typedef struct ec_parameters_st ECPARAMETERS; + +/********************************************************************/ +/* EC_METHODs for curves over GF(p) */ +/********************************************************************/ + +/** Returns the basic GFp ec methods which provides the basis for the + * optimized methods. + * \return EC_METHOD object + */ +const EC_METHOD *EC_GFp_simple_method(void); + +/** Returns GFp methods using montgomery multiplication. + * \return EC_METHOD object + */ +const EC_METHOD *EC_GFp_mont_method(void); + +/** Returns GFp methods using optimized methods for NIST recommended curves + * \return EC_METHOD object + */ +const EC_METHOD *EC_GFp_nist_method(void); + +# ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 +/** Returns 64-bit optimized methods for nistp224 + * \return EC_METHOD object + */ +const EC_METHOD *EC_GFp_nistp224_method(void); + +/** Returns 64-bit optimized methods for nistp256 + * \return EC_METHOD object + */ +const EC_METHOD *EC_GFp_nistp256_method(void); + +/** Returns 64-bit optimized methods for nistp521 + * \return EC_METHOD object + */ +const EC_METHOD *EC_GFp_nistp521_method(void); +# endif + +# ifndef OPENSSL_NO_EC2M +/********************************************************************/ +/* EC_METHOD for curves over GF(2^m) */ +/********************************************************************/ + +/** Returns the basic GF2m ec method + * \return EC_METHOD object + */ +const EC_METHOD *EC_GF2m_simple_method(void); + +# endif + +/********************************************************************/ +/* EC_GROUP functions */ +/********************************************************************/ + +/** Creates a new EC_GROUP object + * \param meth EC_METHOD to use + * \return newly created EC_GROUP object or NULL in case of an error. + */ +EC_GROUP *EC_GROUP_new(const EC_METHOD *meth); + +/** Frees a EC_GROUP object + * \param group EC_GROUP object to be freed. + */ +void EC_GROUP_free(EC_GROUP *group); + +/** Clears and frees a EC_GROUP object + * \param group EC_GROUP object to be cleared and freed. + */ +void EC_GROUP_clear_free(EC_GROUP *group); + +/** Copies EC_GROUP objects. Note: both EC_GROUPs must use the same EC_METHOD. + * \param dst destination EC_GROUP object + * \param src source EC_GROUP object + * \return 1 on success and 0 if an error occurred. + */ +int EC_GROUP_copy(EC_GROUP *dst, const EC_GROUP *src); + +/** Creates a new EC_GROUP object and copies the copies the content + * form src to the newly created EC_KEY object + * \param src source EC_GROUP object + * \return newly created EC_GROUP object or NULL in case of an error. + */ +EC_GROUP *EC_GROUP_dup(const EC_GROUP *src); + +/** Returns the EC_METHOD of the EC_GROUP object. + * \param group EC_GROUP object + * \return EC_METHOD used in this EC_GROUP object. + */ +const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group); + +/** Returns the field type of the EC_METHOD. + * \param meth EC_METHOD object + * \return NID of the underlying field type OID. + */ +int EC_METHOD_get_field_type(const EC_METHOD *meth); + +/** Sets the generator and it's order/cofactor of a EC_GROUP object. + * \param group EC_GROUP object + * \param generator EC_POINT object with the generator. + * \param order the order of the group generated by the generator. + * \param cofactor the index of the sub-group generated by the generator + * in the group of all points on the elliptic curve. + * \return 1 on success and 0 if an error occurred + */ +int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, + const BIGNUM *order, const BIGNUM *cofactor); + +/** Returns the generator of a EC_GROUP object. + * \param group EC_GROUP object + * \return the currently used generator (possibly NULL). + */ +const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group); + +/** Returns the montgomery data for order(Generator) + * \param group EC_GROUP object + * \return the currently used montgomery data (possibly NULL). +*/ +BN_MONT_CTX *EC_GROUP_get_mont_data(const EC_GROUP *group); + +/** Gets the order of a EC_GROUP + * \param group EC_GROUP object + * \param order BIGNUM to which the order is copied + * \param ctx unused + * \return 1 on success and 0 if an error occurred + */ +int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx); + +/** Gets the order of an EC_GROUP + * \param group EC_GROUP object + * \return the group order + */ +const BIGNUM *EC_GROUP_get0_order(const EC_GROUP *group); + +/** Gets the number of bits of the order of an EC_GROUP + * \param group EC_GROUP object + * \return number of bits of group order. + */ +int EC_GROUP_order_bits(const EC_GROUP *group); + +/** Gets the cofactor of a EC_GROUP + * \param group EC_GROUP object + * \param cofactor BIGNUM to which the cofactor is copied + * \param ctx unused + * \return 1 on success and 0 if an error occurred + */ +int EC_GROUP_get_cofactor(const EC_GROUP *group, BIGNUM *cofactor, + BN_CTX *ctx); + +/** Gets the cofactor of an EC_GROUP + * \param group EC_GROUP object + * \return the group cofactor + */ +const BIGNUM *EC_GROUP_get0_cofactor(const EC_GROUP *group); + +/** Sets the name of a EC_GROUP object + * \param group EC_GROUP object + * \param nid NID of the curve name OID + */ +void EC_GROUP_set_curve_name(EC_GROUP *group, int nid); + +/** Returns the curve name of a EC_GROUP object + * \param group EC_GROUP object + * \return NID of the curve name OID or 0 if not set. + */ +int EC_GROUP_get_curve_name(const EC_GROUP *group); + +void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag); +int EC_GROUP_get_asn1_flag(const EC_GROUP *group); + +void EC_GROUP_set_point_conversion_form(EC_GROUP *group, + point_conversion_form_t form); +point_conversion_form_t EC_GROUP_get_point_conversion_form(const EC_GROUP *); + +unsigned char *EC_GROUP_get0_seed(const EC_GROUP *x); +size_t EC_GROUP_get_seed_len(const EC_GROUP *); +size_t EC_GROUP_set_seed(EC_GROUP *, const unsigned char *, size_t len); + +/** Sets the parameters of a ec curve defined by y^2 = x^3 + a*x + b (for GFp) + * or y^2 + x*y = x^3 + a*x^2 + b (for GF2m) + * \param group EC_GROUP object + * \param p BIGNUM with the prime number (GFp) or the polynomial + * defining the underlying field (GF2m) + * \param a BIGNUM with parameter a of the equation + * \param b BIGNUM with parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_GROUP_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, + const BIGNUM *b, BN_CTX *ctx); + +/** Gets the parameters of the ec curve defined by y^2 = x^3 + a*x + b (for GFp) + * or y^2 + x*y = x^3 + a*x^2 + b (for GF2m) + * \param group EC_GROUP object + * \param p BIGNUM with the prime number (GFp) or the polynomial + * defining the underlying field (GF2m) + * \param a BIGNUM for parameter a of the equation + * \param b BIGNUM for parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_GROUP_get_curve(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, BIGNUM *b, + BN_CTX *ctx); + +/** Sets the parameters of an ec curve. Synonym for EC_GROUP_set_curve + * \param group EC_GROUP object + * \param p BIGNUM with the prime number (GFp) or the polynomial + * defining the underlying field (GF2m) + * \param a BIGNUM with parameter a of the equation + * \param b BIGNUM with parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_GROUP_set_curve_GFp(EC_GROUP *group, const BIGNUM *p, + const BIGNUM *a, const BIGNUM *b, + BN_CTX *ctx)) + +/** Gets the parameters of an ec curve. Synonym for EC_GROUP_get_curve + * \param group EC_GROUP object + * \param p BIGNUM with the prime number (GFp) or the polynomial + * defining the underlying field (GF2m) + * \param a BIGNUM for parameter a of the equation + * \param b BIGNUM for parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *p, + BIGNUM *a, BIGNUM *b, + BN_CTX *ctx)) + +# ifndef OPENSSL_NO_EC2M +/** Sets the parameter of an ec curve. Synonym for EC_GROUP_set_curve + * \param group EC_GROUP object + * \param p BIGNUM with the prime number (GFp) or the polynomial + * defining the underlying field (GF2m) + * \param a BIGNUM with parameter a of the equation + * \param b BIGNUM with parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_GROUP_set_curve_GF2m(EC_GROUP *group, const BIGNUM *p, + const BIGNUM *a, const BIGNUM *b, + BN_CTX *ctx)) + +/** Gets the parameters of an ec curve. Synonym for EC_GROUP_get_curve + * \param group EC_GROUP object + * \param p BIGNUM with the prime number (GFp) or the polynomial + * defining the underlying field (GF2m) + * \param a BIGNUM for parameter a of the equation + * \param b BIGNUM for parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_GROUP_get_curve_GF2m(const EC_GROUP *group, BIGNUM *p, + BIGNUM *a, BIGNUM *b, + BN_CTX *ctx)) +# endif +/** Returns the number of bits needed to represent a field element + * \param group EC_GROUP object + * \return number of bits needed to represent a field element + */ +int EC_GROUP_get_degree(const EC_GROUP *group); + +/** Checks whether the parameter in the EC_GROUP define a valid ec group + * \param group EC_GROUP object + * \param ctx BN_CTX object (optional) + * \return 1 if group is a valid ec group and 0 otherwise + */ +int EC_GROUP_check(const EC_GROUP *group, BN_CTX *ctx); + +/** Checks whether the discriminant of the elliptic curve is zero or not + * \param group EC_GROUP object + * \param ctx BN_CTX object (optional) + * \return 1 if the discriminant is not zero and 0 otherwise + */ +int EC_GROUP_check_discriminant(const EC_GROUP *group, BN_CTX *ctx); + +/** Compares two EC_GROUP objects + * \param a first EC_GROUP object + * \param b second EC_GROUP object + * \param ctx BN_CTX object (optional) + * \return 0 if the groups are equal, 1 if not, or -1 on error + */ +int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ctx); + +/* + * EC_GROUP_new_GF*() calls EC_GROUP_new() and EC_GROUP_set_GF*() after + * choosing an appropriate EC_METHOD + */ + +/** Creates a new EC_GROUP object with the specified parameters defined + * over GFp (defined by the equation y^2 = x^3 + a*x + b) + * \param p BIGNUM with the prime number + * \param a BIGNUM with the parameter a of the equation + * \param b BIGNUM with the parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return newly created EC_GROUP object with the specified parameters + */ +EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a, + const BIGNUM *b, BN_CTX *ctx); +# ifndef OPENSSL_NO_EC2M +/** Creates a new EC_GROUP object with the specified parameters defined + * over GF2m (defined by the equation y^2 + x*y = x^3 + a*x^2 + b) + * \param p BIGNUM with the polynomial defining the underlying field + * \param a BIGNUM with the parameter a of the equation + * \param b BIGNUM with the parameter b of the equation + * \param ctx BN_CTX object (optional) + * \return newly created EC_GROUP object with the specified parameters + */ +EC_GROUP *EC_GROUP_new_curve_GF2m(const BIGNUM *p, const BIGNUM *a, + const BIGNUM *b, BN_CTX *ctx); +# endif + +/** Creates a EC_GROUP object with a curve specified by a NID + * \param nid NID of the OID of the curve name + * \return newly created EC_GROUP object with specified curve or NULL + * if an error occurred + */ +EC_GROUP *EC_GROUP_new_by_curve_name(int nid); + +/** Creates a new EC_GROUP object from an ECPARAMETERS object + * \param params pointer to the ECPARAMETERS object + * \return newly created EC_GROUP object with specified curve or NULL + * if an error occurred + */ +EC_GROUP *EC_GROUP_new_from_ecparameters(const ECPARAMETERS *params); + +/** Creates an ECPARAMETERS object for the given EC_GROUP object. + * \param group pointer to the EC_GROUP object + * \param params pointer to an existing ECPARAMETERS object or NULL + * \return pointer to the new ECPARAMETERS object or NULL + * if an error occurred. + */ +ECPARAMETERS *EC_GROUP_get_ecparameters(const EC_GROUP *group, + ECPARAMETERS *params); + +/** Creates a new EC_GROUP object from an ECPKPARAMETERS object + * \param params pointer to an existing ECPKPARAMETERS object, or NULL + * \return newly created EC_GROUP object with specified curve, or NULL + * if an error occurred + */ +EC_GROUP *EC_GROUP_new_from_ecpkparameters(const ECPKPARAMETERS *params); + +/** Creates an ECPKPARAMETERS object for the given EC_GROUP object. + * \param group pointer to the EC_GROUP object + * \param params pointer to an existing ECPKPARAMETERS object or NULL + * \return pointer to the new ECPKPARAMETERS object or NULL + * if an error occurred. + */ +ECPKPARAMETERS *EC_GROUP_get_ecpkparameters(const EC_GROUP *group, + ECPKPARAMETERS *params); + +/********************************************************************/ +/* handling of internal curves */ +/********************************************************************/ + +typedef struct { + int nid; + const char *comment; +} EC_builtin_curve; + +/* + * EC_builtin_curves(EC_builtin_curve *r, size_t size) returns number of all + * available curves or zero if a error occurred. In case r is not zero, + * nitems EC_builtin_curve structures are filled with the data of the first + * nitems internal groups + */ +size_t EC_get_builtin_curves(EC_builtin_curve *r, size_t nitems); + +const char *EC_curve_nid2nist(int nid); +int EC_curve_nist2nid(const char *name); + +/********************************************************************/ +/* EC_POINT functions */ +/********************************************************************/ + +/** Creates a new EC_POINT object for the specified EC_GROUP + * \param group EC_GROUP the underlying EC_GROUP object + * \return newly created EC_POINT object or NULL if an error occurred + */ +EC_POINT *EC_POINT_new(const EC_GROUP *group); + +/** Frees a EC_POINT object + * \param point EC_POINT object to be freed + */ +void EC_POINT_free(EC_POINT *point); + +/** Clears and frees a EC_POINT object + * \param point EC_POINT object to be cleared and freed + */ +void EC_POINT_clear_free(EC_POINT *point); + +/** Copies EC_POINT object + * \param dst destination EC_POINT object + * \param src source EC_POINT object + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_copy(EC_POINT *dst, const EC_POINT *src); + +/** Creates a new EC_POINT object and copies the content of the supplied + * EC_POINT + * \param src source EC_POINT object + * \param group underlying the EC_GROUP object + * \return newly created EC_POINT object or NULL if an error occurred + */ +EC_POINT *EC_POINT_dup(const EC_POINT *src, const EC_GROUP *group); + +/** Returns the EC_METHOD used in EC_POINT object + * \param point EC_POINT object + * \return the EC_METHOD used + */ +const EC_METHOD *EC_POINT_method_of(const EC_POINT *point); + +/** Sets a point to infinity (neutral element) + * \param group underlying EC_GROUP object + * \param point EC_POINT to set to infinity + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point); + +/** Sets the jacobian projective coordinates of a EC_POINT over GFp + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM with the x-coordinate + * \param y BIGNUM with the y-coordinate + * \param z BIGNUM with the z-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_set_Jprojective_coordinates_GFp(const EC_GROUP *group, + EC_POINT *p, const BIGNUM *x, + const BIGNUM *y, const BIGNUM *z, + BN_CTX *ctx); + +/** Gets the jacobian projective coordinates of a EC_POINT over GFp + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM for the x-coordinate + * \param y BIGNUM for the y-coordinate + * \param z BIGNUM for the z-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_get_Jprojective_coordinates_GFp(const EC_GROUP *group, + const EC_POINT *p, BIGNUM *x, + BIGNUM *y, BIGNUM *z, + BN_CTX *ctx); + +/** Sets the affine coordinates of an EC_POINT + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM with the x-coordinate + * \param y BIGNUM with the y-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_set_affine_coordinates(const EC_GROUP *group, EC_POINT *p, + const BIGNUM *x, const BIGNUM *y, + BN_CTX *ctx); + +/** Gets the affine coordinates of an EC_POINT. + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM for the x-coordinate + * \param y BIGNUM for the y-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *p, + BIGNUM *x, BIGNUM *y, BN_CTX *ctx); + +/** Sets the affine coordinates of an EC_POINT. A synonym of + * EC_POINT_set_affine_coordinates + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM with the x-coordinate + * \param y BIGNUM with the y-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group, + EC_POINT *p, + const BIGNUM *x, + const BIGNUM *y, + BN_CTX *ctx)) + +/** Gets the affine coordinates of an EC_POINT. A synonym of + * EC_POINT_get_affine_coordinates + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM for the x-coordinate + * \param y BIGNUM for the y-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group, + const EC_POINT *p, + BIGNUM *x, + BIGNUM *y, + BN_CTX *ctx)) + +/** Sets the x9.62 compressed coordinates of a EC_POINT + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM with x-coordinate + * \param y_bit integer with the y-Bit (either 0 or 1) + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_set_compressed_coordinates(const EC_GROUP *group, EC_POINT *p, + const BIGNUM *x, int y_bit, + BN_CTX *ctx); + +/** Sets the x9.62 compressed coordinates of a EC_POINT. A synonym of + * EC_POINT_set_compressed_coordinates + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM with x-coordinate + * \param y_bit integer with the y-Bit (either 0 or 1) + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_POINT_set_compressed_coordinates_GFp(const EC_GROUP *group, + EC_POINT *p, + const BIGNUM *x, + int y_bit, + BN_CTX *ctx)) +# ifndef OPENSSL_NO_EC2M +/** Sets the affine coordinates of an EC_POINT. A synonym of + * EC_POINT_set_affine_coordinates + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM with the x-coordinate + * \param y BIGNUM with the y-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_POINT_set_affine_coordinates_GF2m(const EC_GROUP *group, + EC_POINT *p, + const BIGNUM *x, + const BIGNUM *y, + BN_CTX *ctx)) + +/** Gets the affine coordinates of an EC_POINT. A synonym of + * EC_POINT_get_affine_coordinates + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM for the x-coordinate + * \param y BIGNUM for the y-coordinate + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_POINT_get_affine_coordinates_GF2m(const EC_GROUP *group, + const EC_POINT *p, + BIGNUM *x, + BIGNUM *y, + BN_CTX *ctx)) + +/** Sets the x9.62 compressed coordinates of a EC_POINT. A synonym of + * EC_POINT_set_compressed_coordinates + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param x BIGNUM with x-coordinate + * \param y_bit integer with the y-Bit (either 0 or 1) + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +DEPRECATEDIN_1_2_0(int EC_POINT_set_compressed_coordinates_GF2m(const EC_GROUP *group, + EC_POINT *p, + const BIGNUM *x, + int y_bit, + BN_CTX *ctx)) +# endif +/** Encodes a EC_POINT object to a octet string + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param form point conversion form + * \param buf memory buffer for the result. If NULL the function returns + * required buffer size. + * \param len length of the memory buffer + * \param ctx BN_CTX object (optional) + * \return the length of the encoded octet string or 0 if an error occurred + */ +size_t EC_POINT_point2oct(const EC_GROUP *group, const EC_POINT *p, + point_conversion_form_t form, + unsigned char *buf, size_t len, BN_CTX *ctx); + +/** Decodes a EC_POINT from a octet string + * \param group underlying EC_GROUP object + * \param p EC_POINT object + * \param buf memory buffer with the encoded ec point + * \param len length of the encoded ec point + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *p, + const unsigned char *buf, size_t len, BN_CTX *ctx); + +/** Encodes an EC_POINT object to an allocated octet string + * \param group underlying EC_GROUP object + * \param point EC_POINT object + * \param form point conversion form + * \param pbuf returns pointer to allocated buffer + * \param ctx BN_CTX object (optional) + * \return the length of the encoded octet string or 0 if an error occurred + */ +size_t EC_POINT_point2buf(const EC_GROUP *group, const EC_POINT *point, + point_conversion_form_t form, + unsigned char **pbuf, BN_CTX *ctx); + +/* other interfaces to point2oct/oct2point: */ +BIGNUM *EC_POINT_point2bn(const EC_GROUP *, const EC_POINT *, + point_conversion_form_t form, BIGNUM *, BN_CTX *); +EC_POINT *EC_POINT_bn2point(const EC_GROUP *, const BIGNUM *, + EC_POINT *, BN_CTX *); +char *EC_POINT_point2hex(const EC_GROUP *, const EC_POINT *, + point_conversion_form_t form, BN_CTX *); +EC_POINT *EC_POINT_hex2point(const EC_GROUP *, const char *, + EC_POINT *, BN_CTX *); + +/********************************************************************/ +/* functions for doing EC_POINT arithmetic */ +/********************************************************************/ + +/** Computes the sum of two EC_POINT + * \param group underlying EC_GROUP object + * \param r EC_POINT object for the result (r = a + b) + * \param a EC_POINT object with the first summand + * \param b EC_POINT object with the second summand + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, + const EC_POINT *b, BN_CTX *ctx); + +/** Computes the double of a EC_POINT + * \param group underlying EC_GROUP object + * \param r EC_POINT object for the result (r = 2 * a) + * \param a EC_POINT object + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, + BN_CTX *ctx); + +/** Computes the inverse of a EC_POINT + * \param group underlying EC_GROUP object + * \param a EC_POINT object to be inverted (it's used for the result as well) + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx); + +/** Checks whether the point is the neutral element of the group + * \param group the underlying EC_GROUP object + * \param p EC_POINT object + * \return 1 if the point is the neutral element and 0 otherwise + */ +int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *p); + +/** Checks whether the point is on the curve + * \param group underlying EC_GROUP object + * \param point EC_POINT object to check + * \param ctx BN_CTX object (optional) + * \return 1 if the point is on the curve, 0 if not, or -1 on error + */ +int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point, + BN_CTX *ctx); + +/** Compares two EC_POINTs + * \param group underlying EC_GROUP object + * \param a first EC_POINT object + * \param b second EC_POINT object + * \param ctx BN_CTX object (optional) + * \return 1 if the points are not equal, 0 if they are, or -1 on error + */ +int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b, + BN_CTX *ctx); + +int EC_POINT_make_affine(const EC_GROUP *group, EC_POINT *point, BN_CTX *ctx); +int EC_POINTs_make_affine(const EC_GROUP *group, size_t num, + EC_POINT *points[], BN_CTX *ctx); + +/** Computes r = generator * n + sum_{i=0}^{num-1} p[i] * m[i] + * \param group underlying EC_GROUP object + * \param r EC_POINT object for the result + * \param n BIGNUM with the multiplier for the group generator (optional) + * \param num number further summands + * \param p array of size num of EC_POINT objects + * \param m array of size num of BIGNUM objects + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, + size_t num, const EC_POINT *p[], const BIGNUM *m[], + BN_CTX *ctx); + +/** Computes r = generator * n + q * m + * \param group underlying EC_GROUP object + * \param r EC_POINT object for the result + * \param n BIGNUM with the multiplier for the group generator (optional) + * \param q EC_POINT object with the first factor of the second summand + * \param m BIGNUM with the second factor of the second summand + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, + const EC_POINT *q, const BIGNUM *m, BN_CTX *ctx); + +/** Stores multiples of generator for faster point multiplication + * \param group EC_GROUP object + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ +int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx); + +/** Reports whether a precomputation has been done + * \param group EC_GROUP object + * \return 1 if a pre-computation has been done and 0 otherwise + */ +int EC_GROUP_have_precompute_mult(const EC_GROUP *group); + +/********************************************************************/ +/* ASN1 stuff */ +/********************************************************************/ + +DECLARE_ASN1_ITEM(ECPKPARAMETERS) +DECLARE_ASN1_ALLOC_FUNCTIONS(ECPKPARAMETERS) +DECLARE_ASN1_ITEM(ECPARAMETERS) +DECLARE_ASN1_ALLOC_FUNCTIONS(ECPARAMETERS) + +/* + * EC_GROUP_get_basis_type() returns the NID of the basis type used to + * represent the field elements + */ +int EC_GROUP_get_basis_type(const EC_GROUP *); +# ifndef OPENSSL_NO_EC2M +int EC_GROUP_get_trinomial_basis(const EC_GROUP *, unsigned int *k); +int EC_GROUP_get_pentanomial_basis(const EC_GROUP *, unsigned int *k1, + unsigned int *k2, unsigned int *k3); +# endif + +# define OPENSSL_EC_EXPLICIT_CURVE 0x000 +# define OPENSSL_EC_NAMED_CURVE 0x001 + +EC_GROUP *d2i_ECPKParameters(EC_GROUP **, const unsigned char **in, long len); +int i2d_ECPKParameters(const EC_GROUP *, unsigned char **out); + +# define d2i_ECPKParameters_bio(bp,x) ASN1_d2i_bio_of(EC_GROUP,NULL,d2i_ECPKParameters,bp,x) +# define i2d_ECPKParameters_bio(bp,x) ASN1_i2d_bio_of_const(EC_GROUP,i2d_ECPKParameters,bp,x) +# define d2i_ECPKParameters_fp(fp,x) (EC_GROUP *)ASN1_d2i_fp(NULL, \ + (char *(*)())d2i_ECPKParameters,(fp),(unsigned char **)(x)) +# define i2d_ECPKParameters_fp(fp,x) ASN1_i2d_fp(i2d_ECPKParameters,(fp), \ + (unsigned char *)(x)) + +int ECPKParameters_print(BIO *bp, const EC_GROUP *x, int off); +# ifndef OPENSSL_NO_STDIO +int ECPKParameters_print_fp(FILE *fp, const EC_GROUP *x, int off); +# endif + +/********************************************************************/ +/* EC_KEY functions */ +/********************************************************************/ + +/* some values for the encoding_flag */ +# define EC_PKEY_NO_PARAMETERS 0x001 +# define EC_PKEY_NO_PUBKEY 0x002 + +/* some values for the flags field */ +# define EC_FLAG_NON_FIPS_ALLOW 0x1 +# define EC_FLAG_FIPS_CHECKED 0x2 +# define EC_FLAG_COFACTOR_ECDH 0x1000 + +/** Creates a new EC_KEY object. + * \return EC_KEY object or NULL if an error occurred. + */ +EC_KEY *EC_KEY_new(void); + +int EC_KEY_get_flags(const EC_KEY *key); + +void EC_KEY_set_flags(EC_KEY *key, int flags); + +void EC_KEY_clear_flags(EC_KEY *key, int flags); + +/** Creates a new EC_KEY object using a named curve as underlying + * EC_GROUP object. + * \param nid NID of the named curve. + * \return EC_KEY object or NULL if an error occurred. + */ +EC_KEY *EC_KEY_new_by_curve_name(int nid); + +/** Frees a EC_KEY object. + * \param key EC_KEY object to be freed. + */ +void EC_KEY_free(EC_KEY *key); + +/** Copies a EC_KEY object. + * \param dst destination EC_KEY object + * \param src src EC_KEY object + * \return dst or NULL if an error occurred. + */ +EC_KEY *EC_KEY_copy(EC_KEY *dst, const EC_KEY *src); + +/** Creates a new EC_KEY object and copies the content from src to it. + * \param src the source EC_KEY object + * \return newly created EC_KEY object or NULL if an error occurred. + */ +EC_KEY *EC_KEY_dup(const EC_KEY *src); + +/** Increases the internal reference count of a EC_KEY object. + * \param key EC_KEY object + * \return 1 on success and 0 if an error occurred. + */ +int EC_KEY_up_ref(EC_KEY *key); + +/** Returns the ENGINE object of a EC_KEY object + * \param eckey EC_KEY object + * \return the ENGINE object (possibly NULL). + */ +ENGINE *EC_KEY_get0_engine(const EC_KEY *eckey); + +/** Returns the EC_GROUP object of a EC_KEY object + * \param key EC_KEY object + * \return the EC_GROUP object (possibly NULL). + */ +const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key); + +/** Sets the EC_GROUP of a EC_KEY object. + * \param key EC_KEY object + * \param group EC_GROUP to use in the EC_KEY object (note: the EC_KEY + * object will use an own copy of the EC_GROUP). + * \return 1 on success and 0 if an error occurred. + */ +int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group); + +/** Returns the private key of a EC_KEY object. + * \param key EC_KEY object + * \return a BIGNUM with the private key (possibly NULL). + */ +const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key); + +/** Sets the private key of a EC_KEY object. + * \param key EC_KEY object + * \param prv BIGNUM with the private key (note: the EC_KEY object + * will use an own copy of the BIGNUM). + * \return 1 on success and 0 if an error occurred. + */ +int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *prv); + +/** Returns the public key of a EC_KEY object. + * \param key the EC_KEY object + * \return a EC_POINT object with the public key (possibly NULL) + */ +const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key); + +/** Sets the public key of a EC_KEY object. + * \param key EC_KEY object + * \param pub EC_POINT object with the public key (note: the EC_KEY object + * will use an own copy of the EC_POINT object). + * \return 1 on success and 0 if an error occurred. + */ +int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub); + +unsigned EC_KEY_get_enc_flags(const EC_KEY *key); +void EC_KEY_set_enc_flags(EC_KEY *eckey, unsigned int flags); +point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key); +void EC_KEY_set_conv_form(EC_KEY *eckey, point_conversion_form_t cform); + +#define EC_KEY_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_EC_KEY, l, p, newf, dupf, freef) +int EC_KEY_set_ex_data(EC_KEY *key, int idx, void *arg); +void *EC_KEY_get_ex_data(const EC_KEY *key, int idx); + +/* wrapper functions for the underlying EC_GROUP object */ +void EC_KEY_set_asn1_flag(EC_KEY *eckey, int asn1_flag); + +/** Creates a table of pre-computed multiples of the generator to + * accelerate further EC_KEY operations. + * \param key EC_KEY object + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred. + */ +int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx); + +/** Creates a new ec private (and optional a new public) key. + * \param key EC_KEY object + * \return 1 on success and 0 if an error occurred. + */ +int EC_KEY_generate_key(EC_KEY *key); + +/** Verifies that a private and/or public key is valid. + * \param key the EC_KEY object + * \return 1 on success and 0 otherwise. + */ +int EC_KEY_check_key(const EC_KEY *key); + +/** Indicates if an EC_KEY can be used for signing. + * \param eckey the EC_KEY object + * \return 1 if can can sign and 0 otherwise. + */ +int EC_KEY_can_sign(const EC_KEY *eckey); + +/** Sets a public key from affine coordinates performing + * necessary NIST PKV tests. + * \param key the EC_KEY object + * \param x public key x coordinate + * \param y public key y coordinate + * \return 1 on success and 0 otherwise. + */ +int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, BIGNUM *x, + BIGNUM *y); + +/** Encodes an EC_KEY public key to an allocated octet string + * \param key key to encode + * \param form point conversion form + * \param pbuf returns pointer to allocated buffer + * \param ctx BN_CTX object (optional) + * \return the length of the encoded octet string or 0 if an error occurred + */ +size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form, + unsigned char **pbuf, BN_CTX *ctx); + +/** Decodes a EC_KEY public key from a octet string + * \param key key to decode + * \param buf memory buffer with the encoded ec point + * \param len length of the encoded ec point + * \param ctx BN_CTX object (optional) + * \return 1 on success and 0 if an error occurred + */ + +int EC_KEY_oct2key(EC_KEY *key, const unsigned char *buf, size_t len, + BN_CTX *ctx); + +/** Decodes an EC_KEY private key from an octet string + * \param key key to decode + * \param buf memory buffer with the encoded private key + * \param len length of the encoded key + * \return 1 on success and 0 if an error occurred + */ + +int EC_KEY_oct2priv(EC_KEY *key, const unsigned char *buf, size_t len); + +/** Encodes a EC_KEY private key to an octet string + * \param key key to encode + * \param buf memory buffer for the result. If NULL the function returns + * required buffer size. + * \param len length of the memory buffer + * \return the length of the encoded octet string or 0 if an error occurred + */ + +size_t EC_KEY_priv2oct(const EC_KEY *key, unsigned char *buf, size_t len); + +/** Encodes an EC_KEY private key to an allocated octet string + * \param eckey key to encode + * \param pbuf returns pointer to allocated buffer + * \return the length of the encoded octet string or 0 if an error occurred + */ +size_t EC_KEY_priv2buf(const EC_KEY *eckey, unsigned char **pbuf); + +/********************************************************************/ +/* de- and encoding functions for SEC1 ECPrivateKey */ +/********************************************************************/ + +/** Decodes a private key from a memory buffer. + * \param key a pointer to a EC_KEY object which should be used (or NULL) + * \param in pointer to memory with the DER encoded private key + * \param len length of the DER encoded private key + * \return the decoded private key or NULL if an error occurred. + */ +EC_KEY *d2i_ECPrivateKey(EC_KEY **key, const unsigned char **in, long len); + +/** Encodes a private key object and stores the result in a buffer. + * \param key the EC_KEY object to encode + * \param out the buffer for the result (if NULL the function returns number + * of bytes needed). + * \return 1 on success and 0 if an error occurred. + */ +int i2d_ECPrivateKey(EC_KEY *key, unsigned char **out); + +/********************************************************************/ +/* de- and encoding functions for EC parameters */ +/********************************************************************/ + +/** Decodes ec parameter from a memory buffer. + * \param key a pointer to a EC_KEY object which should be used (or NULL) + * \param in pointer to memory with the DER encoded ec parameters + * \param len length of the DER encoded ec parameters + * \return a EC_KEY object with the decoded parameters or NULL if an error + * occurred. + */ +EC_KEY *d2i_ECParameters(EC_KEY **key, const unsigned char **in, long len); + +/** Encodes ec parameter and stores the result in a buffer. + * \param key the EC_KEY object with ec parameters to encode + * \param out the buffer for the result (if NULL the function returns number + * of bytes needed). + * \return 1 on success and 0 if an error occurred. + */ +int i2d_ECParameters(EC_KEY *key, unsigned char **out); + +/********************************************************************/ +/* de- and encoding functions for EC public key */ +/* (octet string, not DER -- hence 'o2i' and 'i2o') */ +/********************************************************************/ + +/** Decodes a ec public key from a octet string. + * \param key a pointer to a EC_KEY object which should be used + * \param in memory buffer with the encoded public key + * \param len length of the encoded public key + * \return EC_KEY object with decoded public key or NULL if an error + * occurred. + */ +EC_KEY *o2i_ECPublicKey(EC_KEY **key, const unsigned char **in, long len); + +/** Encodes a ec public key in an octet string. + * \param key the EC_KEY object with the public key + * \param out the buffer for the result (if NULL the function returns number + * of bytes needed). + * \return 1 on success and 0 if an error occurred + */ +int i2o_ECPublicKey(const EC_KEY *key, unsigned char **out); + +/** Prints out the ec parameters on human readable form. + * \param bp BIO object to which the information is printed + * \param key EC_KEY object + * \return 1 on success and 0 if an error occurred + */ +int ECParameters_print(BIO *bp, const EC_KEY *key); + +/** Prints out the contents of a EC_KEY object + * \param bp BIO object to which the information is printed + * \param key EC_KEY object + * \param off line offset + * \return 1 on success and 0 if an error occurred + */ +int EC_KEY_print(BIO *bp, const EC_KEY *key, int off); + +# ifndef OPENSSL_NO_STDIO +/** Prints out the ec parameters on human readable form. + * \param fp file descriptor to which the information is printed + * \param key EC_KEY object + * \return 1 on success and 0 if an error occurred + */ +int ECParameters_print_fp(FILE *fp, const EC_KEY *key); + +/** Prints out the contents of a EC_KEY object + * \param fp file descriptor to which the information is printed + * \param key EC_KEY object + * \param off line offset + * \return 1 on success and 0 if an error occurred + */ +int EC_KEY_print_fp(FILE *fp, const EC_KEY *key, int off); + +# endif + +const EC_KEY_METHOD *EC_KEY_OpenSSL(void); +const EC_KEY_METHOD *EC_KEY_get_default_method(void); +void EC_KEY_set_default_method(const EC_KEY_METHOD *meth); +const EC_KEY_METHOD *EC_KEY_get_method(const EC_KEY *key); +int EC_KEY_set_method(EC_KEY *key, const EC_KEY_METHOD *meth); +EC_KEY *EC_KEY_new_method(ENGINE *engine); + +int ECDH_KDF_X9_62(unsigned char *out, size_t outlen, + const unsigned char *Z, size_t Zlen, + const unsigned char *sinfo, size_t sinfolen, + const EVP_MD *md); + +int ECDH_compute_key(void *out, size_t outlen, const EC_POINT *pub_key, + const EC_KEY *ecdh, + void *(*KDF) (const void *in, size_t inlen, + void *out, size_t *outlen)); + +typedef struct ECDSA_SIG_st ECDSA_SIG; + +/** Allocates and initialize a ECDSA_SIG structure + * \return pointer to a ECDSA_SIG structure or NULL if an error occurred + */ +ECDSA_SIG *ECDSA_SIG_new(void); + +/** frees a ECDSA_SIG structure + * \param sig pointer to the ECDSA_SIG structure + */ +void ECDSA_SIG_free(ECDSA_SIG *sig); + +/** DER encode content of ECDSA_SIG object (note: this function modifies *pp + * (*pp += length of the DER encoded signature)). + * \param sig pointer to the ECDSA_SIG object + * \param pp pointer to a unsigned char pointer for the output or NULL + * \return the length of the DER encoded ECDSA_SIG object or 0 + */ +int i2d_ECDSA_SIG(const ECDSA_SIG *sig, unsigned char **pp); + +/** Decodes a DER encoded ECDSA signature (note: this function changes *pp + * (*pp += len)). + * \param sig pointer to ECDSA_SIG pointer (may be NULL) + * \param pp memory buffer with the DER encoded signature + * \param len length of the buffer + * \return pointer to the decoded ECDSA_SIG structure (or NULL) + */ +ECDSA_SIG *d2i_ECDSA_SIG(ECDSA_SIG **sig, const unsigned char **pp, long len); + +/** Accessor for r and s fields of ECDSA_SIG + * \param sig pointer to ECDSA_SIG structure + * \param pr pointer to BIGNUM pointer for r (may be NULL) + * \param ps pointer to BIGNUM pointer for s (may be NULL) + */ +void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps); + +/** Accessor for r field of ECDSA_SIG + * \param sig pointer to ECDSA_SIG structure + */ +const BIGNUM *ECDSA_SIG_get0_r(const ECDSA_SIG *sig); + +/** Accessor for s field of ECDSA_SIG + * \param sig pointer to ECDSA_SIG structure + */ +const BIGNUM *ECDSA_SIG_get0_s(const ECDSA_SIG *sig); + +/** Setter for r and s fields of ECDSA_SIG + * \param sig pointer to ECDSA_SIG structure + * \param r pointer to BIGNUM for r (may be NULL) + * \param s pointer to BIGNUM for s (may be NULL) + */ +int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s); + +/** Computes the ECDSA signature of the given hash value using + * the supplied private key and returns the created signature. + * \param dgst pointer to the hash value + * \param dgst_len length of the hash value + * \param eckey EC_KEY object containing a private EC key + * \return pointer to a ECDSA_SIG structure or NULL if an error occurred + */ +ECDSA_SIG *ECDSA_do_sign(const unsigned char *dgst, int dgst_len, + EC_KEY *eckey); + +/** Computes ECDSA signature of a given hash value using the supplied + * private key (note: sig must point to ECDSA_size(eckey) bytes of memory). + * \param dgst pointer to the hash value to sign + * \param dgstlen length of the hash value + * \param kinv BIGNUM with a pre-computed inverse k (optional) + * \param rp BIGNUM with a pre-computed rp value (optional), + * see ECDSA_sign_setup + * \param eckey EC_KEY object containing a private EC key + * \return pointer to a ECDSA_SIG structure or NULL if an error occurred + */ +ECDSA_SIG *ECDSA_do_sign_ex(const unsigned char *dgst, int dgstlen, + const BIGNUM *kinv, const BIGNUM *rp, + EC_KEY *eckey); + +/** Verifies that the supplied signature is a valid ECDSA + * signature of the supplied hash value using the supplied public key. + * \param dgst pointer to the hash value + * \param dgst_len length of the hash value + * \param sig ECDSA_SIG structure + * \param eckey EC_KEY object containing a public EC key + * \return 1 if the signature is valid, 0 if the signature is invalid + * and -1 on error + */ +int ECDSA_do_verify(const unsigned char *dgst, int dgst_len, + const ECDSA_SIG *sig, EC_KEY *eckey); + +/** Precompute parts of the signing operation + * \param eckey EC_KEY object containing a private EC key + * \param ctx BN_CTX object (optional) + * \param kinv BIGNUM pointer for the inverse of k + * \param rp BIGNUM pointer for x coordinate of k * generator + * \return 1 on success and 0 otherwise + */ +int ECDSA_sign_setup(EC_KEY *eckey, BN_CTX *ctx, BIGNUM **kinv, BIGNUM **rp); + +/** Computes ECDSA signature of a given hash value using the supplied + * private key (note: sig must point to ECDSA_size(eckey) bytes of memory). + * \param type this parameter is ignored + * \param dgst pointer to the hash value to sign + * \param dgstlen length of the hash value + * \param sig memory for the DER encoded created signature + * \param siglen pointer to the length of the returned signature + * \param eckey EC_KEY object containing a private EC key + * \return 1 on success and 0 otherwise + */ +int ECDSA_sign(int type, const unsigned char *dgst, int dgstlen, + unsigned char *sig, unsigned int *siglen, EC_KEY *eckey); + +/** Computes ECDSA signature of a given hash value using the supplied + * private key (note: sig must point to ECDSA_size(eckey) bytes of memory). + * \param type this parameter is ignored + * \param dgst pointer to the hash value to sign + * \param dgstlen length of the hash value + * \param sig buffer to hold the DER encoded signature + * \param siglen pointer to the length of the returned signature + * \param kinv BIGNUM with a pre-computed inverse k (optional) + * \param rp BIGNUM with a pre-computed rp value (optional), + * see ECDSA_sign_setup + * \param eckey EC_KEY object containing a private EC key + * \return 1 on success and 0 otherwise + */ +int ECDSA_sign_ex(int type, const unsigned char *dgst, int dgstlen, + unsigned char *sig, unsigned int *siglen, + const BIGNUM *kinv, const BIGNUM *rp, EC_KEY *eckey); + +/** Verifies that the given signature is valid ECDSA signature + * of the supplied hash value using the specified public key. + * \param type this parameter is ignored + * \param dgst pointer to the hash value + * \param dgstlen length of the hash value + * \param sig pointer to the DER encoded signature + * \param siglen length of the DER encoded signature + * \param eckey EC_KEY object containing a public EC key + * \return 1 if the signature is valid, 0 if the signature is invalid + * and -1 on error + */ +int ECDSA_verify(int type, const unsigned char *dgst, int dgstlen, + const unsigned char *sig, int siglen, EC_KEY *eckey); + +/** Returns the maximum length of the DER encoded signature + * \param eckey EC_KEY object + * \return numbers of bytes required for the DER encoded signature + */ +int ECDSA_size(const EC_KEY *eckey); + +/********************************************************************/ +/* EC_KEY_METHOD constructors, destructors, writers and accessors */ +/********************************************************************/ + +EC_KEY_METHOD *EC_KEY_METHOD_new(const EC_KEY_METHOD *meth); +void EC_KEY_METHOD_free(EC_KEY_METHOD *meth); +void EC_KEY_METHOD_set_init(EC_KEY_METHOD *meth, + int (*init)(EC_KEY *key), + void (*finish)(EC_KEY *key), + int (*copy)(EC_KEY *dest, const EC_KEY *src), + int (*set_group)(EC_KEY *key, const EC_GROUP *grp), + int (*set_private)(EC_KEY *key, + const BIGNUM *priv_key), + int (*set_public)(EC_KEY *key, + const EC_POINT *pub_key)); + +void EC_KEY_METHOD_set_keygen(EC_KEY_METHOD *meth, + int (*keygen)(EC_KEY *key)); + +void EC_KEY_METHOD_set_compute_key(EC_KEY_METHOD *meth, + int (*ckey)(unsigned char **psec, + size_t *pseclen, + const EC_POINT *pub_key, + const EC_KEY *ecdh)); + +void EC_KEY_METHOD_set_sign(EC_KEY_METHOD *meth, + int (*sign)(int type, const unsigned char *dgst, + int dlen, unsigned char *sig, + unsigned int *siglen, + const BIGNUM *kinv, const BIGNUM *r, + EC_KEY *eckey), + int (*sign_setup)(EC_KEY *eckey, BN_CTX *ctx_in, + BIGNUM **kinvp, BIGNUM **rp), + ECDSA_SIG *(*sign_sig)(const unsigned char *dgst, + int dgst_len, + const BIGNUM *in_kinv, + const BIGNUM *in_r, + EC_KEY *eckey)); + +void EC_KEY_METHOD_set_verify(EC_KEY_METHOD *meth, + int (*verify)(int type, const unsigned + char *dgst, int dgst_len, + const unsigned char *sigbuf, + int sig_len, EC_KEY *eckey), + int (*verify_sig)(const unsigned char *dgst, + int dgst_len, + const ECDSA_SIG *sig, + EC_KEY *eckey)); + +void EC_KEY_METHOD_get_init(const EC_KEY_METHOD *meth, + int (**pinit)(EC_KEY *key), + void (**pfinish)(EC_KEY *key), + int (**pcopy)(EC_KEY *dest, const EC_KEY *src), + int (**pset_group)(EC_KEY *key, + const EC_GROUP *grp), + int (**pset_private)(EC_KEY *key, + const BIGNUM *priv_key), + int (**pset_public)(EC_KEY *key, + const EC_POINT *pub_key)); + +void EC_KEY_METHOD_get_keygen(const EC_KEY_METHOD *meth, + int (**pkeygen)(EC_KEY *key)); + +void EC_KEY_METHOD_get_compute_key(const EC_KEY_METHOD *meth, + int (**pck)(unsigned char **psec, + size_t *pseclen, + const EC_POINT *pub_key, + const EC_KEY *ecdh)); + +void EC_KEY_METHOD_get_sign(const EC_KEY_METHOD *meth, + int (**psign)(int type, const unsigned char *dgst, + int dlen, unsigned char *sig, + unsigned int *siglen, + const BIGNUM *kinv, const BIGNUM *r, + EC_KEY *eckey), + int (**psign_setup)(EC_KEY *eckey, BN_CTX *ctx_in, + BIGNUM **kinvp, BIGNUM **rp), + ECDSA_SIG *(**psign_sig)(const unsigned char *dgst, + int dgst_len, + const BIGNUM *in_kinv, + const BIGNUM *in_r, + EC_KEY *eckey)); + +void EC_KEY_METHOD_get_verify(const EC_KEY_METHOD *meth, + int (**pverify)(int type, const unsigned + char *dgst, int dgst_len, + const unsigned char *sigbuf, + int sig_len, EC_KEY *eckey), + int (**pverify_sig)(const unsigned char *dgst, + int dgst_len, + const ECDSA_SIG *sig, + EC_KEY *eckey)); + +# define ECParameters_dup(x) ASN1_dup_of(EC_KEY,i2d_ECParameters,d2i_ECParameters,x) + +# ifndef __cplusplus +# if defined(__SUNPRO_C) +# if __SUNPRO_C >= 0x520 +# pragma error_messages (default,E_ARRAY_OF_INCOMPLETE_NONAME,E_ARRAY_OF_INCOMPLETE) +# endif +# endif +# endif + +# define EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_PARAMGEN|EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, nid, NULL) + +# define EVP_PKEY_CTX_set_ec_param_enc(ctx, flag) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_PARAMGEN|EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_EC_PARAM_ENC, flag, NULL) + +# define EVP_PKEY_CTX_set_ecdh_cofactor_mode(ctx, flag) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_EC_ECDH_COFACTOR, flag, NULL) + +# define EVP_PKEY_CTX_get_ecdh_cofactor_mode(ctx) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_EC_ECDH_COFACTOR, -2, NULL) + +# define EVP_PKEY_CTX_set_ecdh_kdf_type(ctx, kdf) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_EC_KDF_TYPE, kdf, NULL) + +# define EVP_PKEY_CTX_get_ecdh_kdf_type(ctx) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_EC_KDF_TYPE, -2, NULL) + +# define EVP_PKEY_CTX_set_ecdh_kdf_md(ctx, md) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_EC_KDF_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_get_ecdh_kdf_md(ctx, pmd) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_GET_EC_KDF_MD, 0, (void *)(pmd)) + +# define EVP_PKEY_CTX_set_ecdh_kdf_outlen(ctx, len) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_EC_KDF_OUTLEN, len, NULL) + +# define EVP_PKEY_CTX_get_ecdh_kdf_outlen(ctx, plen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN, 0, \ + (void *)(plen)) + +# define EVP_PKEY_CTX_set0_ecdh_kdf_ukm(ctx, p, plen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_EC_KDF_UKM, plen, (void *)(p)) + +# define EVP_PKEY_CTX_get0_ecdh_kdf_ukm(ctx, p) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_EC, \ + EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_GET_EC_KDF_UKM, 0, (void *)(p)) + +/* SM2 will skip the operation check so no need to pass operation here */ +# define EVP_PKEY_CTX_set1_id(ctx, id, id_len) \ + EVP_PKEY_CTX_ctrl(ctx, -1, -1, \ + EVP_PKEY_CTRL_SET1_ID, (int)id_len, (void*)(id)) + +# define EVP_PKEY_CTX_get1_id(ctx, id) \ + EVP_PKEY_CTX_ctrl(ctx, -1, -1, \ + EVP_PKEY_CTRL_GET1_ID, 0, (void*)(id)) + +# define EVP_PKEY_CTX_get1_id_len(ctx, id_len) \ + EVP_PKEY_CTX_ctrl(ctx, -1, -1, \ + EVP_PKEY_CTRL_GET1_ID_LEN, 0, (void*)(id_len)) + +# define EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID (EVP_PKEY_ALG_CTRL + 1) +# define EVP_PKEY_CTRL_EC_PARAM_ENC (EVP_PKEY_ALG_CTRL + 2) +# define EVP_PKEY_CTRL_EC_ECDH_COFACTOR (EVP_PKEY_ALG_CTRL + 3) +# define EVP_PKEY_CTRL_EC_KDF_TYPE (EVP_PKEY_ALG_CTRL + 4) +# define EVP_PKEY_CTRL_EC_KDF_MD (EVP_PKEY_ALG_CTRL + 5) +# define EVP_PKEY_CTRL_GET_EC_KDF_MD (EVP_PKEY_ALG_CTRL + 6) +# define EVP_PKEY_CTRL_EC_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 7) +# define EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 8) +# define EVP_PKEY_CTRL_EC_KDF_UKM (EVP_PKEY_ALG_CTRL + 9) +# define EVP_PKEY_CTRL_GET_EC_KDF_UKM (EVP_PKEY_ALG_CTRL + 10) +# define EVP_PKEY_CTRL_SET1_ID (EVP_PKEY_ALG_CTRL + 11) +# define EVP_PKEY_CTRL_GET1_ID (EVP_PKEY_ALG_CTRL + 12) +# define EVP_PKEY_CTRL_GET1_ID_LEN (EVP_PKEY_ALG_CTRL + 13) +/* KDF types */ +# define EVP_PKEY_ECDH_KDF_NONE 1 +# define EVP_PKEY_ECDH_KDF_X9_62 2 + + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/ecdh.h b/include/openssl/ecdh.h new file mode 100644 index 0000000..61b5bd3 --- /dev/null +++ b/include/openssl/ecdh.h @@ -0,0 +1,10 @@ +/* + * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include diff --git a/include/openssl/ecdsa.h b/include/openssl/ecdsa.h new file mode 100644 index 0000000..61b5bd3 --- /dev/null +++ b/include/openssl/ecdsa.h @@ -0,0 +1,10 @@ +/* + * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include diff --git a/include/openssl/ecerr.h b/include/openssl/ecerr.h new file mode 100644 index 0000000..de4275a --- /dev/null +++ b/include/openssl/ecerr.h @@ -0,0 +1,267 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ECERR_H +# define HEADER_ECERR_H + +# include + +# ifndef OPENSSL_NO_EC + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_EC_strings(void); + +/* + * EC function codes. + */ +# define EC_F_BN_TO_FELEM 224 +# define EC_F_D2I_ECPARAMETERS 144 +# define EC_F_D2I_ECPKPARAMETERS 145 +# define EC_F_D2I_ECPRIVATEKEY 146 +# define EC_F_DO_EC_KEY_PRINT 221 +# define EC_F_ECDH_CMS_DECRYPT 238 +# define EC_F_ECDH_CMS_SET_SHARED_INFO 239 +# define EC_F_ECDH_COMPUTE_KEY 246 +# define EC_F_ECDH_SIMPLE_COMPUTE_KEY 257 +# define EC_F_ECDSA_DO_SIGN_EX 251 +# define EC_F_ECDSA_DO_VERIFY 252 +# define EC_F_ECDSA_SIGN_EX 254 +# define EC_F_ECDSA_SIGN_SETUP 248 +# define EC_F_ECDSA_SIG_NEW 265 +# define EC_F_ECDSA_VERIFY 253 +# define EC_F_ECD_ITEM_VERIFY 270 +# define EC_F_ECKEY_PARAM2TYPE 223 +# define EC_F_ECKEY_PARAM_DECODE 212 +# define EC_F_ECKEY_PRIV_DECODE 213 +# define EC_F_ECKEY_PRIV_ENCODE 214 +# define EC_F_ECKEY_PUB_DECODE 215 +# define EC_F_ECKEY_PUB_ENCODE 216 +# define EC_F_ECKEY_TYPE2PARAM 220 +# define EC_F_ECPARAMETERS_PRINT 147 +# define EC_F_ECPARAMETERS_PRINT_FP 148 +# define EC_F_ECPKPARAMETERS_PRINT 149 +# define EC_F_ECPKPARAMETERS_PRINT_FP 150 +# define EC_F_ECP_NISTZ256_GET_AFFINE 240 +# define EC_F_ECP_NISTZ256_INV_MOD_ORD 275 +# define EC_F_ECP_NISTZ256_MULT_PRECOMPUTE 243 +# define EC_F_ECP_NISTZ256_POINTS_MUL 241 +# define EC_F_ECP_NISTZ256_PRE_COMP_NEW 244 +# define EC_F_ECP_NISTZ256_WINDOWED_MUL 242 +# define EC_F_ECX_KEY_OP 266 +# define EC_F_ECX_PRIV_ENCODE 267 +# define EC_F_ECX_PUB_ENCODE 268 +# define EC_F_EC_ASN1_GROUP2CURVE 153 +# define EC_F_EC_ASN1_GROUP2FIELDID 154 +# define EC_F_EC_GF2M_MONTGOMERY_POINT_MULTIPLY 208 +# define EC_F_EC_GF2M_SIMPLE_GROUP_CHECK_DISCRIMINANT 159 +# define EC_F_EC_GF2M_SIMPLE_GROUP_SET_CURVE 195 +# define EC_F_EC_GF2M_SIMPLE_LADDER_POST 285 +# define EC_F_EC_GF2M_SIMPLE_LADDER_PRE 288 +# define EC_F_EC_GF2M_SIMPLE_OCT2POINT 160 +# define EC_F_EC_GF2M_SIMPLE_POINT2OCT 161 +# define EC_F_EC_GF2M_SIMPLE_POINTS_MUL 289 +# define EC_F_EC_GF2M_SIMPLE_POINT_GET_AFFINE_COORDINATES 162 +# define EC_F_EC_GF2M_SIMPLE_POINT_SET_AFFINE_COORDINATES 163 +# define EC_F_EC_GF2M_SIMPLE_SET_COMPRESSED_COORDINATES 164 +# define EC_F_EC_GFP_MONT_FIELD_DECODE 133 +# define EC_F_EC_GFP_MONT_FIELD_ENCODE 134 +# define EC_F_EC_GFP_MONT_FIELD_MUL 131 +# define EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE 209 +# define EC_F_EC_GFP_MONT_FIELD_SQR 132 +# define EC_F_EC_GFP_MONT_GROUP_SET_CURVE 189 +# define EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE 225 +# define EC_F_EC_GFP_NISTP224_POINTS_MUL 228 +# define EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES 226 +# define EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE 230 +# define EC_F_EC_GFP_NISTP256_POINTS_MUL 231 +# define EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES 232 +# define EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE 233 +# define EC_F_EC_GFP_NISTP521_POINTS_MUL 234 +# define EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES 235 +# define EC_F_EC_GFP_NIST_FIELD_MUL 200 +# define EC_F_EC_GFP_NIST_FIELD_SQR 201 +# define EC_F_EC_GFP_NIST_GROUP_SET_CURVE 202 +# define EC_F_EC_GFP_SIMPLE_BLIND_COORDINATES 287 +# define EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT 165 +# define EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE 166 +# define EC_F_EC_GFP_SIMPLE_MAKE_AFFINE 102 +# define EC_F_EC_GFP_SIMPLE_OCT2POINT 103 +# define EC_F_EC_GFP_SIMPLE_POINT2OCT 104 +# define EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE 137 +# define EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES 167 +# define EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES 168 +# define EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES 169 +# define EC_F_EC_GROUP_CHECK 170 +# define EC_F_EC_GROUP_CHECK_DISCRIMINANT 171 +# define EC_F_EC_GROUP_COPY 106 +# define EC_F_EC_GROUP_GET_CURVE 291 +# define EC_F_EC_GROUP_GET_CURVE_GF2M 172 +# define EC_F_EC_GROUP_GET_CURVE_GFP 130 +# define EC_F_EC_GROUP_GET_DEGREE 173 +# define EC_F_EC_GROUP_GET_ECPARAMETERS 261 +# define EC_F_EC_GROUP_GET_ECPKPARAMETERS 262 +# define EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS 193 +# define EC_F_EC_GROUP_GET_TRINOMIAL_BASIS 194 +# define EC_F_EC_GROUP_NEW 108 +# define EC_F_EC_GROUP_NEW_BY_CURVE_NAME 174 +# define EC_F_EC_GROUP_NEW_FROM_DATA 175 +# define EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS 263 +# define EC_F_EC_GROUP_NEW_FROM_ECPKPARAMETERS 264 +# define EC_F_EC_GROUP_SET_CURVE 292 +# define EC_F_EC_GROUP_SET_CURVE_GF2M 176 +# define EC_F_EC_GROUP_SET_CURVE_GFP 109 +# define EC_F_EC_GROUP_SET_GENERATOR 111 +# define EC_F_EC_GROUP_SET_SEED 286 +# define EC_F_EC_KEY_CHECK_KEY 177 +# define EC_F_EC_KEY_COPY 178 +# define EC_F_EC_KEY_GENERATE_KEY 179 +# define EC_F_EC_KEY_NEW 182 +# define EC_F_EC_KEY_NEW_METHOD 245 +# define EC_F_EC_KEY_OCT2PRIV 255 +# define EC_F_EC_KEY_PRINT 180 +# define EC_F_EC_KEY_PRINT_FP 181 +# define EC_F_EC_KEY_PRIV2BUF 279 +# define EC_F_EC_KEY_PRIV2OCT 256 +# define EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES 229 +# define EC_F_EC_KEY_SIMPLE_CHECK_KEY 258 +# define EC_F_EC_KEY_SIMPLE_OCT2PRIV 259 +# define EC_F_EC_KEY_SIMPLE_PRIV2OCT 260 +# define EC_F_EC_PKEY_CHECK 273 +# define EC_F_EC_PKEY_PARAM_CHECK 274 +# define EC_F_EC_POINTS_MAKE_AFFINE 136 +# define EC_F_EC_POINTS_MUL 290 +# define EC_F_EC_POINT_ADD 112 +# define EC_F_EC_POINT_BN2POINT 280 +# define EC_F_EC_POINT_CMP 113 +# define EC_F_EC_POINT_COPY 114 +# define EC_F_EC_POINT_DBL 115 +# define EC_F_EC_POINT_GET_AFFINE_COORDINATES 293 +# define EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M 183 +# define EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP 116 +# define EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP 117 +# define EC_F_EC_POINT_INVERT 210 +# define EC_F_EC_POINT_IS_AT_INFINITY 118 +# define EC_F_EC_POINT_IS_ON_CURVE 119 +# define EC_F_EC_POINT_MAKE_AFFINE 120 +# define EC_F_EC_POINT_NEW 121 +# define EC_F_EC_POINT_OCT2POINT 122 +# define EC_F_EC_POINT_POINT2BUF 281 +# define EC_F_EC_POINT_POINT2OCT 123 +# define EC_F_EC_POINT_SET_AFFINE_COORDINATES 294 +# define EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M 185 +# define EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP 124 +# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES 295 +# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GF2M 186 +# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GFP 125 +# define EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP 126 +# define EC_F_EC_POINT_SET_TO_INFINITY 127 +# define EC_F_EC_PRE_COMP_NEW 196 +# define EC_F_EC_SCALAR_MUL_LADDER 284 +# define EC_F_EC_WNAF_MUL 187 +# define EC_F_EC_WNAF_PRECOMPUTE_MULT 188 +# define EC_F_I2D_ECPARAMETERS 190 +# define EC_F_I2D_ECPKPARAMETERS 191 +# define EC_F_I2D_ECPRIVATEKEY 192 +# define EC_F_I2O_ECPUBLICKEY 151 +# define EC_F_NISTP224_PRE_COMP_NEW 227 +# define EC_F_NISTP256_PRE_COMP_NEW 236 +# define EC_F_NISTP521_PRE_COMP_NEW 237 +# define EC_F_O2I_ECPUBLICKEY 152 +# define EC_F_OLD_EC_PRIV_DECODE 222 +# define EC_F_OSSL_ECDH_COMPUTE_KEY 247 +# define EC_F_OSSL_ECDSA_SIGN_SIG 249 +# define EC_F_OSSL_ECDSA_VERIFY_SIG 250 +# define EC_F_PKEY_ECD_CTRL 271 +# define EC_F_PKEY_ECD_DIGESTSIGN 272 +# define EC_F_PKEY_ECD_DIGESTSIGN25519 276 +# define EC_F_PKEY_ECD_DIGESTSIGN448 277 +# define EC_F_PKEY_ECX_DERIVE 269 +# define EC_F_PKEY_EC_CTRL 197 +# define EC_F_PKEY_EC_CTRL_STR 198 +# define EC_F_PKEY_EC_DERIVE 217 +# define EC_F_PKEY_EC_INIT 282 +# define EC_F_PKEY_EC_KDF_DERIVE 283 +# define EC_F_PKEY_EC_KEYGEN 199 +# define EC_F_PKEY_EC_PARAMGEN 219 +# define EC_F_PKEY_EC_SIGN 218 +# define EC_F_VALIDATE_ECX_DERIVE 278 + +/* + * EC reason codes. + */ +# define EC_R_ASN1_ERROR 115 +# define EC_R_BAD_SIGNATURE 156 +# define EC_R_BIGNUM_OUT_OF_RANGE 144 +# define EC_R_BUFFER_TOO_SMALL 100 +# define EC_R_COORDINATES_OUT_OF_RANGE 146 +# define EC_R_CURVE_DOES_NOT_SUPPORT_ECDH 160 +# define EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING 159 +# define EC_R_D2I_ECPKPARAMETERS_FAILURE 117 +# define EC_R_DECODE_ERROR 142 +# define EC_R_DISCRIMINANT_IS_ZERO 118 +# define EC_R_EC_GROUP_NEW_BY_NAME_FAILURE 119 +# define EC_R_FIELD_TOO_LARGE 143 +# define EC_R_GF2M_NOT_SUPPORTED 147 +# define EC_R_GROUP2PKPARAMETERS_FAILURE 120 +# define EC_R_I2D_ECPKPARAMETERS_FAILURE 121 +# define EC_R_INCOMPATIBLE_OBJECTS 101 +# define EC_R_INVALID_ARGUMENT 112 +# define EC_R_INVALID_COMPRESSED_POINT 110 +# define EC_R_INVALID_COMPRESSION_BIT 109 +# define EC_R_INVALID_CURVE 141 +# define EC_R_INVALID_DIGEST 151 +# define EC_R_INVALID_DIGEST_TYPE 138 +# define EC_R_INVALID_ENCODING 102 +# define EC_R_INVALID_FIELD 103 +# define EC_R_INVALID_FORM 104 +# define EC_R_INVALID_GROUP_ORDER 122 +# define EC_R_INVALID_KEY 116 +# define EC_R_INVALID_OUTPUT_LENGTH 161 +# define EC_R_INVALID_PEER_KEY 133 +# define EC_R_INVALID_PENTANOMIAL_BASIS 132 +# define EC_R_INVALID_PRIVATE_KEY 123 +# define EC_R_INVALID_TRINOMIAL_BASIS 137 +# define EC_R_KDF_PARAMETER_ERROR 148 +# define EC_R_KEYS_NOT_SET 140 +# define EC_R_LADDER_POST_FAILURE 136 +# define EC_R_LADDER_PRE_FAILURE 153 +# define EC_R_LADDER_STEP_FAILURE 162 +# define EC_R_MISSING_PARAMETERS 124 +# define EC_R_MISSING_PRIVATE_KEY 125 +# define EC_R_NEED_NEW_SETUP_VALUES 157 +# define EC_R_NOT_A_NIST_PRIME 135 +# define EC_R_NOT_IMPLEMENTED 126 +# define EC_R_NOT_INITIALIZED 111 +# define EC_R_NO_PARAMETERS_SET 139 +# define EC_R_NO_PRIVATE_VALUE 154 +# define EC_R_OPERATION_NOT_SUPPORTED 152 +# define EC_R_PASSED_NULL_PARAMETER 134 +# define EC_R_PEER_KEY_ERROR 149 +# define EC_R_PKPARAMETERS2GROUP_FAILURE 127 +# define EC_R_POINT_ARITHMETIC_FAILURE 155 +# define EC_R_POINT_AT_INFINITY 106 +# define EC_R_POINT_COORDINATES_BLIND_FAILURE 163 +# define EC_R_POINT_IS_NOT_ON_CURVE 107 +# define EC_R_RANDOM_NUMBER_GENERATION_FAILED 158 +# define EC_R_SHARED_INFO_ERROR 150 +# define EC_R_SLOT_FULL 108 +# define EC_R_UNDEFINED_GENERATOR 113 +# define EC_R_UNDEFINED_ORDER 128 +# define EC_R_UNKNOWN_COFACTOR 164 +# define EC_R_UNKNOWN_GROUP 129 +# define EC_R_UNKNOWN_ORDER 114 +# define EC_R_UNSUPPORTED_FIELD 131 +# define EC_R_WRONG_CURVE_PARAMETERS 145 +# define EC_R_WRONG_ORDER 130 + +# endif +#endif diff --git a/include/openssl/engine.h b/include/openssl/engine.h new file mode 100644 index 0000000..baa1578 --- /dev/null +++ b/include/openssl/engine.h @@ -0,0 +1,751 @@ +/* + * Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ENGINE_H +# define HEADER_ENGINE_H + +# include + +# ifndef OPENSSL_NO_ENGINE +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# include +# include +# include +# include +# include +# include +# include +# endif +# include +# include +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +/* + * These flags are used to control combinations of algorithm (methods) by + * bitwise "OR"ing. + */ +# define ENGINE_METHOD_RSA (unsigned int)0x0001 +# define ENGINE_METHOD_DSA (unsigned int)0x0002 +# define ENGINE_METHOD_DH (unsigned int)0x0004 +# define ENGINE_METHOD_RAND (unsigned int)0x0008 +# define ENGINE_METHOD_CIPHERS (unsigned int)0x0040 +# define ENGINE_METHOD_DIGESTS (unsigned int)0x0080 +# define ENGINE_METHOD_PKEY_METHS (unsigned int)0x0200 +# define ENGINE_METHOD_PKEY_ASN1_METHS (unsigned int)0x0400 +# define ENGINE_METHOD_EC (unsigned int)0x0800 +/* Obvious all-or-nothing cases. */ +# define ENGINE_METHOD_ALL (unsigned int)0xFFFF +# define ENGINE_METHOD_NONE (unsigned int)0x0000 + +/* + * This(ese) flag(s) controls behaviour of the ENGINE_TABLE mechanism used + * internally to control registration of ENGINE implementations, and can be + * set by ENGINE_set_table_flags(). The "NOINIT" flag prevents attempts to + * initialise registered ENGINEs if they are not already initialised. + */ +# define ENGINE_TABLE_FLAG_NOINIT (unsigned int)0x0001 + +/* ENGINE flags that can be set by ENGINE_set_flags(). */ +/* Not used */ +/* #define ENGINE_FLAGS_MALLOCED 0x0001 */ + +/* + * This flag is for ENGINEs that wish to handle the various 'CMD'-related + * control commands on their own. Without this flag, ENGINE_ctrl() handles + * these control commands on behalf of the ENGINE using their "cmd_defns" + * data. + */ +# define ENGINE_FLAGS_MANUAL_CMD_CTRL (int)0x0002 + +/* + * This flag is for ENGINEs who return new duplicate structures when found + * via "ENGINE_by_id()". When an ENGINE must store state (eg. if + * ENGINE_ctrl() commands are called in sequence as part of some stateful + * process like key-generation setup and execution), it can set this flag - + * then each attempt to obtain the ENGINE will result in it being copied into + * a new structure. Normally, ENGINEs don't declare this flag so + * ENGINE_by_id() just increments the existing ENGINE's structural reference + * count. + */ +# define ENGINE_FLAGS_BY_ID_COPY (int)0x0004 + +/* + * This flag if for an ENGINE that does not want its methods registered as + * part of ENGINE_register_all_complete() for example if the methods are not + * usable as default methods. + */ + +# define ENGINE_FLAGS_NO_REGISTER_ALL (int)0x0008 + +/* + * ENGINEs can support their own command types, and these flags are used in + * ENGINE_CTRL_GET_CMD_FLAGS to indicate to the caller what kind of input + * each command expects. Currently only numeric and string input is + * supported. If a control command supports none of the _NUMERIC, _STRING, or + * _NO_INPUT options, then it is regarded as an "internal" control command - + * and not for use in config setting situations. As such, they're not + * available to the ENGINE_ctrl_cmd_string() function, only raw ENGINE_ctrl() + * access. Changes to this list of 'command types' should be reflected + * carefully in ENGINE_cmd_is_executable() and ENGINE_ctrl_cmd_string(). + */ + +/* accepts a 'long' input value (3rd parameter to ENGINE_ctrl) */ +# define ENGINE_CMD_FLAG_NUMERIC (unsigned int)0x0001 +/* + * accepts string input (cast from 'void*' to 'const char *', 4th parameter + * to ENGINE_ctrl) + */ +# define ENGINE_CMD_FLAG_STRING (unsigned int)0x0002 +/* + * Indicates that the control command takes *no* input. Ie. the control + * command is unparameterised. + */ +# define ENGINE_CMD_FLAG_NO_INPUT (unsigned int)0x0004 +/* + * Indicates that the control command is internal. This control command won't + * be shown in any output, and is only usable through the ENGINE_ctrl_cmd() + * function. + */ +# define ENGINE_CMD_FLAG_INTERNAL (unsigned int)0x0008 + +/* + * NB: These 3 control commands are deprecated and should not be used. + * ENGINEs relying on these commands should compile conditional support for + * compatibility (eg. if these symbols are defined) but should also migrate + * the same functionality to their own ENGINE-specific control functions that + * can be "discovered" by calling applications. The fact these control + * commands wouldn't be "executable" (ie. usable by text-based config) + * doesn't change the fact that application code can find and use them + * without requiring per-ENGINE hacking. + */ + +/* + * These flags are used to tell the ctrl function what should be done. All + * command numbers are shared between all engines, even if some don't make + * sense to some engines. In such a case, they do nothing but return the + * error ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED. + */ +# define ENGINE_CTRL_SET_LOGSTREAM 1 +# define ENGINE_CTRL_SET_PASSWORD_CALLBACK 2 +# define ENGINE_CTRL_HUP 3/* Close and reinitialise + * any handles/connections + * etc. */ +# define ENGINE_CTRL_SET_USER_INTERFACE 4/* Alternative to callback */ +# define ENGINE_CTRL_SET_CALLBACK_DATA 5/* User-specific data, used + * when calling the password + * callback and the user + * interface */ +# define ENGINE_CTRL_LOAD_CONFIGURATION 6/* Load a configuration, + * given a string that + * represents a file name + * or so */ +# define ENGINE_CTRL_LOAD_SECTION 7/* Load data from a given + * section in the already + * loaded configuration */ + +/* + * These control commands allow an application to deal with an arbitrary + * engine in a dynamic way. Warn: Negative return values indicate errors FOR + * THESE COMMANDS because zero is used to indicate 'end-of-list'. Other + * commands, including ENGINE-specific command types, return zero for an + * error. An ENGINE can choose to implement these ctrl functions, and can + * internally manage things however it chooses - it does so by setting the + * ENGINE_FLAGS_MANUAL_CMD_CTRL flag (using ENGINE_set_flags()). Otherwise + * the ENGINE_ctrl() code handles this on the ENGINE's behalf using the + * cmd_defns data (set using ENGINE_set_cmd_defns()). This means an ENGINE's + * ctrl() handler need only implement its own commands - the above "meta" + * commands will be taken care of. + */ + +/* + * Returns non-zero if the supplied ENGINE has a ctrl() handler. If "not", + * then all the remaining control commands will return failure, so it is + * worth checking this first if the caller is trying to "discover" the + * engine's capabilities and doesn't want errors generated unnecessarily. + */ +# define ENGINE_CTRL_HAS_CTRL_FUNCTION 10 +/* + * Returns a positive command number for the first command supported by the + * engine. Returns zero if no ctrl commands are supported. + */ +# define ENGINE_CTRL_GET_FIRST_CMD_TYPE 11 +/* + * The 'long' argument specifies a command implemented by the engine, and the + * return value is the next command supported, or zero if there are no more. + */ +# define ENGINE_CTRL_GET_NEXT_CMD_TYPE 12 +/* + * The 'void*' argument is a command name (cast from 'const char *'), and the + * return value is the command that corresponds to it. + */ +# define ENGINE_CTRL_GET_CMD_FROM_NAME 13 +/* + * The next two allow a command to be converted into its corresponding string + * form. In each case, the 'long' argument supplies the command. In the + * NAME_LEN case, the return value is the length of the command name (not + * counting a trailing EOL). In the NAME case, the 'void*' argument must be a + * string buffer large enough, and it will be populated with the name of the + * command (WITH a trailing EOL). + */ +# define ENGINE_CTRL_GET_NAME_LEN_FROM_CMD 14 +# define ENGINE_CTRL_GET_NAME_FROM_CMD 15 +/* The next two are similar but give a "short description" of a command. */ +# define ENGINE_CTRL_GET_DESC_LEN_FROM_CMD 16 +# define ENGINE_CTRL_GET_DESC_FROM_CMD 17 +/* + * With this command, the return value is the OR'd combination of + * ENGINE_CMD_FLAG_*** values that indicate what kind of input a given + * engine-specific ctrl command expects. + */ +# define ENGINE_CTRL_GET_CMD_FLAGS 18 + +/* + * ENGINE implementations should start the numbering of their own control + * commands from this value. (ie. ENGINE_CMD_BASE, ENGINE_CMD_BASE + 1, etc). + */ +# define ENGINE_CMD_BASE 200 + +/* + * NB: These 2 nCipher "chil" control commands are deprecated, and their + * functionality is now available through ENGINE-specific control commands + * (exposed through the above-mentioned 'CMD'-handling). Code using these 2 + * commands should be migrated to the more general command handling before + * these are removed. + */ + +/* Flags specific to the nCipher "chil" engine */ +# define ENGINE_CTRL_CHIL_SET_FORKCHECK 100 + /* + * Depending on the value of the (long)i argument, this sets or + * unsets the SimpleForkCheck flag in the CHIL API to enable or + * disable checking and workarounds for applications that fork(). + */ +# define ENGINE_CTRL_CHIL_NO_LOCKING 101 + /* + * This prevents the initialisation function from providing mutex + * callbacks to the nCipher library. + */ + +/* + * If an ENGINE supports its own specific control commands and wishes the + * framework to handle the above 'ENGINE_CMD_***'-manipulation commands on + * its behalf, it should supply a null-terminated array of ENGINE_CMD_DEFN + * entries to ENGINE_set_cmd_defns(). It should also implement a ctrl() + * handler that supports the stated commands (ie. the "cmd_num" entries as + * described by the array). NB: The array must be ordered in increasing order + * of cmd_num. "null-terminated" means that the last ENGINE_CMD_DEFN element + * has cmd_num set to zero and/or cmd_name set to NULL. + */ +typedef struct ENGINE_CMD_DEFN_st { + unsigned int cmd_num; /* The command number */ + const char *cmd_name; /* The command name itself */ + const char *cmd_desc; /* A short description of the command */ + unsigned int cmd_flags; /* The input the command expects */ +} ENGINE_CMD_DEFN; + +/* Generic function pointer */ +typedef int (*ENGINE_GEN_FUNC_PTR) (void); +/* Generic function pointer taking no arguments */ +typedef int (*ENGINE_GEN_INT_FUNC_PTR) (ENGINE *); +/* Specific control function pointer */ +typedef int (*ENGINE_CTRL_FUNC_PTR) (ENGINE *, int, long, void *, + void (*f) (void)); +/* Generic load_key function pointer */ +typedef EVP_PKEY *(*ENGINE_LOAD_KEY_PTR)(ENGINE *, const char *, + UI_METHOD *ui_method, + void *callback_data); +typedef int (*ENGINE_SSL_CLIENT_CERT_PTR) (ENGINE *, SSL *ssl, + STACK_OF(X509_NAME) *ca_dn, + X509 **pcert, EVP_PKEY **pkey, + STACK_OF(X509) **pother, + UI_METHOD *ui_method, + void *callback_data); +/*- + * These callback types are for an ENGINE's handler for cipher and digest logic. + * These handlers have these prototypes; + * int foo(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid); + * int foo(ENGINE *e, const EVP_MD **digest, const int **nids, int nid); + * Looking at how to implement these handlers in the case of cipher support, if + * the framework wants the EVP_CIPHER for 'nid', it will call; + * foo(e, &p_evp_cipher, NULL, nid); (return zero for failure) + * If the framework wants a list of supported 'nid's, it will call; + * foo(e, NULL, &p_nids, 0); (returns number of 'nids' or -1 for error) + */ +/* + * Returns to a pointer to the array of supported cipher 'nid's. If the + * second parameter is non-NULL it is set to the size of the returned array. + */ +typedef int (*ENGINE_CIPHERS_PTR) (ENGINE *, const EVP_CIPHER **, + const int **, int); +typedef int (*ENGINE_DIGESTS_PTR) (ENGINE *, const EVP_MD **, const int **, + int); +typedef int (*ENGINE_PKEY_METHS_PTR) (ENGINE *, EVP_PKEY_METHOD **, + const int **, int); +typedef int (*ENGINE_PKEY_ASN1_METHS_PTR) (ENGINE *, EVP_PKEY_ASN1_METHOD **, + const int **, int); +/* + * STRUCTURE functions ... all of these functions deal with pointers to + * ENGINE structures where the pointers have a "structural reference". This + * means that their reference is to allowed access to the structure but it + * does not imply that the structure is functional. To simply increment or + * decrement the structural reference count, use ENGINE_by_id and + * ENGINE_free. NB: This is not required when iterating using ENGINE_get_next + * as it will automatically decrement the structural reference count of the + * "current" ENGINE and increment the structural reference count of the + * ENGINE it returns (unless it is NULL). + */ + +/* Get the first/last "ENGINE" type available. */ +ENGINE *ENGINE_get_first(void); +ENGINE *ENGINE_get_last(void); +/* Iterate to the next/previous "ENGINE" type (NULL = end of the list). */ +ENGINE *ENGINE_get_next(ENGINE *e); +ENGINE *ENGINE_get_prev(ENGINE *e); +/* Add another "ENGINE" type into the array. */ +int ENGINE_add(ENGINE *e); +/* Remove an existing "ENGINE" type from the array. */ +int ENGINE_remove(ENGINE *e); +/* Retrieve an engine from the list by its unique "id" value. */ +ENGINE *ENGINE_by_id(const char *id); + +#if OPENSSL_API_COMPAT < 0x10100000L +# define ENGINE_load_openssl() \ + OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_OPENSSL, NULL) +# define ENGINE_load_dynamic() \ + OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_DYNAMIC, NULL) +# ifndef OPENSSL_NO_STATIC_ENGINE +# define ENGINE_load_padlock() \ + OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_PADLOCK, NULL) +# define ENGINE_load_capi() \ + OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_CAPI, NULL) +# define ENGINE_load_afalg() \ + OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_AFALG, NULL) +# endif +# define ENGINE_load_cryptodev() \ + OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_CRYPTODEV, NULL) +# define ENGINE_load_rdrand() \ + OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_RDRAND, NULL) +#endif +void ENGINE_load_builtin_engines(void); + +/* + * Get and set global flags (ENGINE_TABLE_FLAG_***) for the implementation + * "registry" handling. + */ +unsigned int ENGINE_get_table_flags(void); +void ENGINE_set_table_flags(unsigned int flags); + +/*- Manage registration of ENGINEs per "table". For each type, there are 3 + * functions; + * ENGINE_register_***(e) - registers the implementation from 'e' (if it has one) + * ENGINE_unregister_***(e) - unregister the implementation from 'e' + * ENGINE_register_all_***() - call ENGINE_register_***() for each 'e' in the list + * Cleanup is automatically registered from each table when required. + */ + +int ENGINE_register_RSA(ENGINE *e); +void ENGINE_unregister_RSA(ENGINE *e); +void ENGINE_register_all_RSA(void); + +int ENGINE_register_DSA(ENGINE *e); +void ENGINE_unregister_DSA(ENGINE *e); +void ENGINE_register_all_DSA(void); + +int ENGINE_register_EC(ENGINE *e); +void ENGINE_unregister_EC(ENGINE *e); +void ENGINE_register_all_EC(void); + +int ENGINE_register_DH(ENGINE *e); +void ENGINE_unregister_DH(ENGINE *e); +void ENGINE_register_all_DH(void); + +int ENGINE_register_RAND(ENGINE *e); +void ENGINE_unregister_RAND(ENGINE *e); +void ENGINE_register_all_RAND(void); + +int ENGINE_register_ciphers(ENGINE *e); +void ENGINE_unregister_ciphers(ENGINE *e); +void ENGINE_register_all_ciphers(void); + +int ENGINE_register_digests(ENGINE *e); +void ENGINE_unregister_digests(ENGINE *e); +void ENGINE_register_all_digests(void); + +int ENGINE_register_pkey_meths(ENGINE *e); +void ENGINE_unregister_pkey_meths(ENGINE *e); +void ENGINE_register_all_pkey_meths(void); + +int ENGINE_register_pkey_asn1_meths(ENGINE *e); +void ENGINE_unregister_pkey_asn1_meths(ENGINE *e); +void ENGINE_register_all_pkey_asn1_meths(void); + +/* + * These functions register all support from the above categories. Note, use + * of these functions can result in static linkage of code your application + * may not need. If you only need a subset of functionality, consider using + * more selective initialisation. + */ +int ENGINE_register_complete(ENGINE *e); +int ENGINE_register_all_complete(void); + +/* + * Send parameterised control commands to the engine. The possibilities to + * send down an integer, a pointer to data or a function pointer are + * provided. Any of the parameters may or may not be NULL, depending on the + * command number. In actuality, this function only requires a structural + * (rather than functional) reference to an engine, but many control commands + * may require the engine be functional. The caller should be aware of trying + * commands that require an operational ENGINE, and only use functional + * references in such situations. + */ +int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f) (void)); + +/* + * This function tests if an ENGINE-specific command is usable as a + * "setting". Eg. in an application's config file that gets processed through + * ENGINE_ctrl_cmd_string(). If this returns zero, it is not available to + * ENGINE_ctrl_cmd_string(), only ENGINE_ctrl(). + */ +int ENGINE_cmd_is_executable(ENGINE *e, int cmd); + +/* + * This function works like ENGINE_ctrl() with the exception of taking a + * command name instead of a command number, and can handle optional + * commands. See the comment on ENGINE_ctrl_cmd_string() for an explanation + * on how to use the cmd_name and cmd_optional. + */ +int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name, + long i, void *p, void (*f) (void), int cmd_optional); + +/* + * This function passes a command-name and argument to an ENGINE. The + * cmd_name is converted to a command number and the control command is + * called using 'arg' as an argument (unless the ENGINE doesn't support such + * a command, in which case no control command is called). The command is + * checked for input flags, and if necessary the argument will be converted + * to a numeric value. If cmd_optional is non-zero, then if the ENGINE + * doesn't support the given cmd_name the return value will be success + * anyway. This function is intended for applications to use so that users + * (or config files) can supply engine-specific config data to the ENGINE at + * run-time to control behaviour of specific engines. As such, it shouldn't + * be used for calling ENGINE_ctrl() functions that return data, deal with + * binary data, or that are otherwise supposed to be used directly through + * ENGINE_ctrl() in application code. Any "return" data from an ENGINE_ctrl() + * operation in this function will be lost - the return value is interpreted + * as failure if the return value is zero, success otherwise, and this + * function returns a boolean value as a result. In other words, vendors of + * 'ENGINE'-enabled devices should write ENGINE implementations with + * parameterisations that work in this scheme, so that compliant ENGINE-based + * applications can work consistently with the same configuration for the + * same ENGINE-enabled devices, across applications. + */ +int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg, + int cmd_optional); + +/* + * These functions are useful for manufacturing new ENGINE structures. They + * don't address reference counting at all - one uses them to populate an + * ENGINE structure with personalised implementations of things prior to + * using it directly or adding it to the builtin ENGINE list in OpenSSL. + * These are also here so that the ENGINE structure doesn't have to be + * exposed and break binary compatibility! + */ +ENGINE *ENGINE_new(void); +int ENGINE_free(ENGINE *e); +int ENGINE_up_ref(ENGINE *e); +int ENGINE_set_id(ENGINE *e, const char *id); +int ENGINE_set_name(ENGINE *e, const char *name); +int ENGINE_set_RSA(ENGINE *e, const RSA_METHOD *rsa_meth); +int ENGINE_set_DSA(ENGINE *e, const DSA_METHOD *dsa_meth); +int ENGINE_set_EC(ENGINE *e, const EC_KEY_METHOD *ecdsa_meth); +int ENGINE_set_DH(ENGINE *e, const DH_METHOD *dh_meth); +int ENGINE_set_RAND(ENGINE *e, const RAND_METHOD *rand_meth); +int ENGINE_set_destroy_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR destroy_f); +int ENGINE_set_init_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR init_f); +int ENGINE_set_finish_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR finish_f); +int ENGINE_set_ctrl_function(ENGINE *e, ENGINE_CTRL_FUNC_PTR ctrl_f); +int ENGINE_set_load_privkey_function(ENGINE *e, + ENGINE_LOAD_KEY_PTR loadpriv_f); +int ENGINE_set_load_pubkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpub_f); +int ENGINE_set_load_ssl_client_cert_function(ENGINE *e, + ENGINE_SSL_CLIENT_CERT_PTR + loadssl_f); +int ENGINE_set_ciphers(ENGINE *e, ENGINE_CIPHERS_PTR f); +int ENGINE_set_digests(ENGINE *e, ENGINE_DIGESTS_PTR f); +int ENGINE_set_pkey_meths(ENGINE *e, ENGINE_PKEY_METHS_PTR f); +int ENGINE_set_pkey_asn1_meths(ENGINE *e, ENGINE_PKEY_ASN1_METHS_PTR f); +int ENGINE_set_flags(ENGINE *e, int flags); +int ENGINE_set_cmd_defns(ENGINE *e, const ENGINE_CMD_DEFN *defns); +/* These functions allow control over any per-structure ENGINE data. */ +#define ENGINE_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_ENGINE, l, p, newf, dupf, freef) +int ENGINE_set_ex_data(ENGINE *e, int idx, void *arg); +void *ENGINE_get_ex_data(const ENGINE *e, int idx); + +#if OPENSSL_API_COMPAT < 0x10100000L +/* + * This function previously cleaned up anything that needs it. Auto-deinit will + * now take care of it so it is no longer required to call this function. + */ +# define ENGINE_cleanup() while(0) continue +#endif + +/* + * These return values from within the ENGINE structure. These can be useful + * with functional references as well as structural references - it depends + * which you obtained. Using the result for functional purposes if you only + * obtained a structural reference may be problematic! + */ +const char *ENGINE_get_id(const ENGINE *e); +const char *ENGINE_get_name(const ENGINE *e); +const RSA_METHOD *ENGINE_get_RSA(const ENGINE *e); +const DSA_METHOD *ENGINE_get_DSA(const ENGINE *e); +const EC_KEY_METHOD *ENGINE_get_EC(const ENGINE *e); +const DH_METHOD *ENGINE_get_DH(const ENGINE *e); +const RAND_METHOD *ENGINE_get_RAND(const ENGINE *e); +ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e); +ENGINE_GEN_INT_FUNC_PTR ENGINE_get_init_function(const ENGINE *e); +ENGINE_GEN_INT_FUNC_PTR ENGINE_get_finish_function(const ENGINE *e); +ENGINE_CTRL_FUNC_PTR ENGINE_get_ctrl_function(const ENGINE *e); +ENGINE_LOAD_KEY_PTR ENGINE_get_load_privkey_function(const ENGINE *e); +ENGINE_LOAD_KEY_PTR ENGINE_get_load_pubkey_function(const ENGINE *e); +ENGINE_SSL_CLIENT_CERT_PTR ENGINE_get_ssl_client_cert_function(const ENGINE + *e); +ENGINE_CIPHERS_PTR ENGINE_get_ciphers(const ENGINE *e); +ENGINE_DIGESTS_PTR ENGINE_get_digests(const ENGINE *e); +ENGINE_PKEY_METHS_PTR ENGINE_get_pkey_meths(const ENGINE *e); +ENGINE_PKEY_ASN1_METHS_PTR ENGINE_get_pkey_asn1_meths(const ENGINE *e); +const EVP_CIPHER *ENGINE_get_cipher(ENGINE *e, int nid); +const EVP_MD *ENGINE_get_digest(ENGINE *e, int nid); +const EVP_PKEY_METHOD *ENGINE_get_pkey_meth(ENGINE *e, int nid); +const EVP_PKEY_ASN1_METHOD *ENGINE_get_pkey_asn1_meth(ENGINE *e, int nid); +const EVP_PKEY_ASN1_METHOD *ENGINE_get_pkey_asn1_meth_str(ENGINE *e, + const char *str, + int len); +const EVP_PKEY_ASN1_METHOD *ENGINE_pkey_asn1_find_str(ENGINE **pe, + const char *str, + int len); +const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e); +int ENGINE_get_flags(const ENGINE *e); + +/* + * FUNCTIONAL functions. These functions deal with ENGINE structures that + * have (or will) be initialised for use. Broadly speaking, the structural + * functions are useful for iterating the list of available engine types, + * creating new engine types, and other "list" operations. These functions + * actually deal with ENGINEs that are to be used. As such these functions + * can fail (if applicable) when particular engines are unavailable - eg. if + * a hardware accelerator is not attached or not functioning correctly. Each + * ENGINE has 2 reference counts; structural and functional. Every time a + * functional reference is obtained or released, a corresponding structural + * reference is automatically obtained or released too. + */ + +/* + * Initialise a engine type for use (or up its reference count if it's + * already in use). This will fail if the engine is not currently operational + * and cannot initialise. + */ +int ENGINE_init(ENGINE *e); +/* + * Free a functional reference to a engine type. This does not require a + * corresponding call to ENGINE_free as it also releases a structural + * reference. + */ +int ENGINE_finish(ENGINE *e); + +/* + * The following functions handle keys that are stored in some secondary + * location, handled by the engine. The storage may be on a card or + * whatever. + */ +EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id, + UI_METHOD *ui_method, void *callback_data); +EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id, + UI_METHOD *ui_method, void *callback_data); +int ENGINE_load_ssl_client_cert(ENGINE *e, SSL *s, + STACK_OF(X509_NAME) *ca_dn, X509 **pcert, + EVP_PKEY **ppkey, STACK_OF(X509) **pother, + UI_METHOD *ui_method, void *callback_data); + +/* + * This returns a pointer for the current ENGINE structure that is (by + * default) performing any RSA operations. The value returned is an + * incremented reference, so it should be free'd (ENGINE_finish) before it is + * discarded. + */ +ENGINE *ENGINE_get_default_RSA(void); +/* Same for the other "methods" */ +ENGINE *ENGINE_get_default_DSA(void); +ENGINE *ENGINE_get_default_EC(void); +ENGINE *ENGINE_get_default_DH(void); +ENGINE *ENGINE_get_default_RAND(void); +/* + * These functions can be used to get a functional reference to perform + * ciphering or digesting corresponding to "nid". + */ +ENGINE *ENGINE_get_cipher_engine(int nid); +ENGINE *ENGINE_get_digest_engine(int nid); +ENGINE *ENGINE_get_pkey_meth_engine(int nid); +ENGINE *ENGINE_get_pkey_asn1_meth_engine(int nid); + +/* + * This sets a new default ENGINE structure for performing RSA operations. If + * the result is non-zero (success) then the ENGINE structure will have had + * its reference count up'd so the caller should still free their own + * reference 'e'. + */ +int ENGINE_set_default_RSA(ENGINE *e); +int ENGINE_set_default_string(ENGINE *e, const char *def_list); +/* Same for the other "methods" */ +int ENGINE_set_default_DSA(ENGINE *e); +int ENGINE_set_default_EC(ENGINE *e); +int ENGINE_set_default_DH(ENGINE *e); +int ENGINE_set_default_RAND(ENGINE *e); +int ENGINE_set_default_ciphers(ENGINE *e); +int ENGINE_set_default_digests(ENGINE *e); +int ENGINE_set_default_pkey_meths(ENGINE *e); +int ENGINE_set_default_pkey_asn1_meths(ENGINE *e); + +/* + * The combination "set" - the flags are bitwise "OR"d from the + * ENGINE_METHOD_*** defines above. As with the "ENGINE_register_complete()" + * function, this function can result in unnecessary static linkage. If your + * application requires only specific functionality, consider using more + * selective functions. + */ +int ENGINE_set_default(ENGINE *e, unsigned int flags); + +void ENGINE_add_conf_module(void); + +/* Deprecated functions ... */ +/* int ENGINE_clear_defaults(void); */ + +/**************************/ +/* DYNAMIC ENGINE SUPPORT */ +/**************************/ + +/* Binary/behaviour compatibility levels */ +# define OSSL_DYNAMIC_VERSION (unsigned long)0x00030000 +/* + * Binary versions older than this are too old for us (whether we're a loader + * or a loadee) + */ +# define OSSL_DYNAMIC_OLDEST (unsigned long)0x00030000 + +/* + * When compiling an ENGINE entirely as an external shared library, loadable + * by the "dynamic" ENGINE, these types are needed. The 'dynamic_fns' + * structure type provides the calling application's (or library's) error + * functionality and memory management function pointers to the loaded + * library. These should be used/set in the loaded library code so that the + * loading application's 'state' will be used/changed in all operations. The + * 'static_state' pointer allows the loaded library to know if it shares the + * same static data as the calling application (or library), and thus whether + * these callbacks need to be set or not. + */ +typedef void *(*dyn_MEM_malloc_fn) (size_t, const char *, int); +typedef void *(*dyn_MEM_realloc_fn) (void *, size_t, const char *, int); +typedef void (*dyn_MEM_free_fn) (void *, const char *, int); +typedef struct st_dynamic_MEM_fns { + dyn_MEM_malloc_fn malloc_fn; + dyn_MEM_realloc_fn realloc_fn; + dyn_MEM_free_fn free_fn; +} dynamic_MEM_fns; +/* + * FIXME: Perhaps the memory and locking code (crypto.h) should declare and + * use these types so we (and any other dependent code) can simplify a bit?? + */ +/* The top-level structure */ +typedef struct st_dynamic_fns { + void *static_state; + dynamic_MEM_fns mem_fns; +} dynamic_fns; + +/* + * The version checking function should be of this prototype. NB: The + * ossl_version value passed in is the OSSL_DYNAMIC_VERSION of the loading + * code. If this function returns zero, it indicates a (potential) version + * incompatibility and the loaded library doesn't believe it can proceed. + * Otherwise, the returned value is the (latest) version supported by the + * loading library. The loader may still decide that the loaded code's + * version is unsatisfactory and could veto the load. The function is + * expected to be implemented with the symbol name "v_check", and a default + * implementation can be fully instantiated with + * IMPLEMENT_DYNAMIC_CHECK_FN(). + */ +typedef unsigned long (*dynamic_v_check_fn) (unsigned long ossl_version); +# define IMPLEMENT_DYNAMIC_CHECK_FN() \ + OPENSSL_EXPORT unsigned long v_check(unsigned long v); \ + OPENSSL_EXPORT unsigned long v_check(unsigned long v) { \ + if (v >= OSSL_DYNAMIC_OLDEST) return OSSL_DYNAMIC_VERSION; \ + return 0; } + +/* + * This function is passed the ENGINE structure to initialise with its own + * function and command settings. It should not adjust the structural or + * functional reference counts. If this function returns zero, (a) the load + * will be aborted, (b) the previous ENGINE state will be memcpy'd back onto + * the structure, and (c) the shared library will be unloaded. So + * implementations should do their own internal cleanup in failure + * circumstances otherwise they could leak. The 'id' parameter, if non-NULL, + * represents the ENGINE id that the loader is looking for. If this is NULL, + * the shared library can choose to return failure or to initialise a + * 'default' ENGINE. If non-NULL, the shared library must initialise only an + * ENGINE matching the passed 'id'. The function is expected to be + * implemented with the symbol name "bind_engine". A standard implementation + * can be instantiated with IMPLEMENT_DYNAMIC_BIND_FN(fn) where the parameter + * 'fn' is a callback function that populates the ENGINE structure and + * returns an int value (zero for failure). 'fn' should have prototype; + * [static] int fn(ENGINE *e, const char *id); + */ +typedef int (*dynamic_bind_engine) (ENGINE *e, const char *id, + const dynamic_fns *fns); +# define IMPLEMENT_DYNAMIC_BIND_FN(fn) \ + OPENSSL_EXPORT \ + int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns); \ + OPENSSL_EXPORT \ + int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { \ + if (ENGINE_get_static_state() == fns->static_state) goto skip_cbs; \ + CRYPTO_set_mem_functions(fns->mem_fns.malloc_fn, \ + fns->mem_fns.realloc_fn, \ + fns->mem_fns.free_fn); \ + skip_cbs: \ + if (!fn(e, id)) return 0; \ + return 1; } + +/* + * If the loading application (or library) and the loaded ENGINE library + * share the same static data (eg. they're both dynamically linked to the + * same libcrypto.so) we need a way to avoid trying to set system callbacks - + * this would fail, and for the same reason that it's unnecessary to try. If + * the loaded ENGINE has (or gets from through the loader) its own copy of + * the libcrypto static data, we will need to set the callbacks. The easiest + * way to detect this is to have a function that returns a pointer to some + * static data and let the loading application and loaded ENGINE compare + * their respective values. + */ +void *ENGINE_get_static_state(void); + +# if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) +DEPRECATEDIN_1_1_0(void ENGINE_setup_bsd_cryptodev(void)) +# endif + + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/engineerr.h b/include/openssl/engineerr.h new file mode 100644 index 0000000..f14ed9d --- /dev/null +++ b/include/openssl/engineerr.h @@ -0,0 +1,107 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ENGINEERR_H +# define HEADER_ENGINEERR_H + +# include + +# ifndef OPENSSL_NO_ENGINE + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_ENGINE_strings(void); + +/* + * ENGINE function codes. + */ +# define ENGINE_F_DIGEST_UPDATE 198 +# define ENGINE_F_DYNAMIC_CTRL 180 +# define ENGINE_F_DYNAMIC_GET_DATA_CTX 181 +# define ENGINE_F_DYNAMIC_LOAD 182 +# define ENGINE_F_DYNAMIC_SET_DATA_CTX 183 +# define ENGINE_F_ENGINE_ADD 105 +# define ENGINE_F_ENGINE_BY_ID 106 +# define ENGINE_F_ENGINE_CMD_IS_EXECUTABLE 170 +# define ENGINE_F_ENGINE_CTRL 142 +# define ENGINE_F_ENGINE_CTRL_CMD 178 +# define ENGINE_F_ENGINE_CTRL_CMD_STRING 171 +# define ENGINE_F_ENGINE_FINISH 107 +# define ENGINE_F_ENGINE_GET_CIPHER 185 +# define ENGINE_F_ENGINE_GET_DIGEST 186 +# define ENGINE_F_ENGINE_GET_FIRST 195 +# define ENGINE_F_ENGINE_GET_LAST 196 +# define ENGINE_F_ENGINE_GET_NEXT 115 +# define ENGINE_F_ENGINE_GET_PKEY_ASN1_METH 193 +# define ENGINE_F_ENGINE_GET_PKEY_METH 192 +# define ENGINE_F_ENGINE_GET_PREV 116 +# define ENGINE_F_ENGINE_INIT 119 +# define ENGINE_F_ENGINE_LIST_ADD 120 +# define ENGINE_F_ENGINE_LIST_REMOVE 121 +# define ENGINE_F_ENGINE_LOAD_PRIVATE_KEY 150 +# define ENGINE_F_ENGINE_LOAD_PUBLIC_KEY 151 +# define ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT 194 +# define ENGINE_F_ENGINE_NEW 122 +# define ENGINE_F_ENGINE_PKEY_ASN1_FIND_STR 197 +# define ENGINE_F_ENGINE_REMOVE 123 +# define ENGINE_F_ENGINE_SET_DEFAULT_STRING 189 +# define ENGINE_F_ENGINE_SET_ID 129 +# define ENGINE_F_ENGINE_SET_NAME 130 +# define ENGINE_F_ENGINE_TABLE_REGISTER 184 +# define ENGINE_F_ENGINE_UNLOCKED_FINISH 191 +# define ENGINE_F_ENGINE_UP_REF 190 +# define ENGINE_F_INT_CLEANUP_ITEM 199 +# define ENGINE_F_INT_CTRL_HELPER 172 +# define ENGINE_F_INT_ENGINE_CONFIGURE 188 +# define ENGINE_F_INT_ENGINE_MODULE_INIT 187 +# define ENGINE_F_OSSL_HMAC_INIT 200 + +/* + * ENGINE reason codes. + */ +# define ENGINE_R_ALREADY_LOADED 100 +# define ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER 133 +# define ENGINE_R_CMD_NOT_EXECUTABLE 134 +# define ENGINE_R_COMMAND_TAKES_INPUT 135 +# define ENGINE_R_COMMAND_TAKES_NO_INPUT 136 +# define ENGINE_R_CONFLICTING_ENGINE_ID 103 +# define ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED 119 +# define ENGINE_R_DSO_FAILURE 104 +# define ENGINE_R_DSO_NOT_FOUND 132 +# define ENGINE_R_ENGINES_SECTION_ERROR 148 +# define ENGINE_R_ENGINE_CONFIGURATION_ERROR 102 +# define ENGINE_R_ENGINE_IS_NOT_IN_LIST 105 +# define ENGINE_R_ENGINE_SECTION_ERROR 149 +# define ENGINE_R_FAILED_LOADING_PRIVATE_KEY 128 +# define ENGINE_R_FAILED_LOADING_PUBLIC_KEY 129 +# define ENGINE_R_FINISH_FAILED 106 +# define ENGINE_R_ID_OR_NAME_MISSING 108 +# define ENGINE_R_INIT_FAILED 109 +# define ENGINE_R_INTERNAL_LIST_ERROR 110 +# define ENGINE_R_INVALID_ARGUMENT 143 +# define ENGINE_R_INVALID_CMD_NAME 137 +# define ENGINE_R_INVALID_CMD_NUMBER 138 +# define ENGINE_R_INVALID_INIT_VALUE 151 +# define ENGINE_R_INVALID_STRING 150 +# define ENGINE_R_NOT_INITIALISED 117 +# define ENGINE_R_NOT_LOADED 112 +# define ENGINE_R_NO_CONTROL_FUNCTION 120 +# define ENGINE_R_NO_INDEX 144 +# define ENGINE_R_NO_LOAD_FUNCTION 125 +# define ENGINE_R_NO_REFERENCE 130 +# define ENGINE_R_NO_SUCH_ENGINE 116 +# define ENGINE_R_UNIMPLEMENTED_CIPHER 146 +# define ENGINE_R_UNIMPLEMENTED_DIGEST 147 +# define ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD 101 +# define ENGINE_R_VERSION_INCOMPATIBILITY 145 + +# endif +#endif diff --git a/include/openssl/err.h b/include/openssl/err.h new file mode 100644 index 0000000..63bf72b --- /dev/null +++ b/include/openssl/err.h @@ -0,0 +1,273 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ERR_H +# define HEADER_ERR_H + +# include + +# ifndef OPENSSL_NO_STDIO +# include +# include +# endif + +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +# ifndef OPENSSL_NO_ERR +# define ERR_PUT_error(a,b,c,d,e) ERR_put_error(a,b,c,d,e) +# else +# define ERR_PUT_error(a,b,c,d,e) ERR_put_error(a,b,c,NULL,0) +# endif + +# include + +# define ERR_TXT_MALLOCED 0x01 +# define ERR_TXT_STRING 0x02 + +# define ERR_FLAG_MARK 0x01 + +# define ERR_NUM_ERRORS 16 +typedef struct err_state_st { + int err_flags[ERR_NUM_ERRORS]; + unsigned long err_buffer[ERR_NUM_ERRORS]; + char *err_data[ERR_NUM_ERRORS]; + int err_data_flags[ERR_NUM_ERRORS]; + const char *err_file[ERR_NUM_ERRORS]; + int err_line[ERR_NUM_ERRORS]; + int top, bottom; +} ERR_STATE; + +/* library */ +# define ERR_LIB_NONE 1 +# define ERR_LIB_SYS 2 +# define ERR_LIB_BN 3 +# define ERR_LIB_RSA 4 +# define ERR_LIB_DH 5 +# define ERR_LIB_EVP 6 +# define ERR_LIB_BUF 7 +# define ERR_LIB_OBJ 8 +# define ERR_LIB_PEM 9 +# define ERR_LIB_DSA 10 +# define ERR_LIB_X509 11 +/* #define ERR_LIB_METH 12 */ +# define ERR_LIB_ASN1 13 +# define ERR_LIB_CONF 14 +# define ERR_LIB_CRYPTO 15 +# define ERR_LIB_EC 16 +# define ERR_LIB_SSL 20 +/* #define ERR_LIB_SSL23 21 */ +/* #define ERR_LIB_SSL2 22 */ +/* #define ERR_LIB_SSL3 23 */ +/* #define ERR_LIB_RSAREF 30 */ +/* #define ERR_LIB_PROXY 31 */ +# define ERR_LIB_BIO 32 +# define ERR_LIB_PKCS7 33 +# define ERR_LIB_X509V3 34 +# define ERR_LIB_PKCS12 35 +# define ERR_LIB_RAND 36 +# define ERR_LIB_DSO 37 +# define ERR_LIB_ENGINE 38 +# define ERR_LIB_OCSP 39 +# define ERR_LIB_UI 40 +# define ERR_LIB_COMP 41 +# define ERR_LIB_ECDSA 42 +# define ERR_LIB_ECDH 43 +# define ERR_LIB_OSSL_STORE 44 +# define ERR_LIB_FIPS 45 +# define ERR_LIB_CMS 46 +# define ERR_LIB_TS 47 +# define ERR_LIB_HMAC 48 +/* # define ERR_LIB_JPAKE 49 */ +# define ERR_LIB_CT 50 +# define ERR_LIB_ASYNC 51 +# define ERR_LIB_KDF 52 +# define ERR_LIB_SM2 53 + +# define ERR_LIB_USER 128 + +# define SYSerr(f,r) ERR_PUT_error(ERR_LIB_SYS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define BNerr(f,r) ERR_PUT_error(ERR_LIB_BN,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define RSAerr(f,r) ERR_PUT_error(ERR_LIB_RSA,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define DHerr(f,r) ERR_PUT_error(ERR_LIB_DH,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define EVPerr(f,r) ERR_PUT_error(ERR_LIB_EVP,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define BUFerr(f,r) ERR_PUT_error(ERR_LIB_BUF,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define OBJerr(f,r) ERR_PUT_error(ERR_LIB_OBJ,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define PEMerr(f,r) ERR_PUT_error(ERR_LIB_PEM,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define DSAerr(f,r) ERR_PUT_error(ERR_LIB_DSA,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define X509err(f,r) ERR_PUT_error(ERR_LIB_X509,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define ASN1err(f,r) ERR_PUT_error(ERR_LIB_ASN1,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define CONFerr(f,r) ERR_PUT_error(ERR_LIB_CONF,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define CRYPTOerr(f,r) ERR_PUT_error(ERR_LIB_CRYPTO,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define ECerr(f,r) ERR_PUT_error(ERR_LIB_EC,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define SSLerr(f,r) ERR_PUT_error(ERR_LIB_SSL,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define BIOerr(f,r) ERR_PUT_error(ERR_LIB_BIO,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define PKCS7err(f,r) ERR_PUT_error(ERR_LIB_PKCS7,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define X509V3err(f,r) ERR_PUT_error(ERR_LIB_X509V3,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define PKCS12err(f,r) ERR_PUT_error(ERR_LIB_PKCS12,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define RANDerr(f,r) ERR_PUT_error(ERR_LIB_RAND,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define DSOerr(f,r) ERR_PUT_error(ERR_LIB_DSO,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define ENGINEerr(f,r) ERR_PUT_error(ERR_LIB_ENGINE,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define OCSPerr(f,r) ERR_PUT_error(ERR_LIB_OCSP,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define UIerr(f,r) ERR_PUT_error(ERR_LIB_UI,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define COMPerr(f,r) ERR_PUT_error(ERR_LIB_COMP,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define ECDSAerr(f,r) ERR_PUT_error(ERR_LIB_ECDSA,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define OSSL_STOREerr(f,r) ERR_PUT_error(ERR_LIB_OSSL_STORE,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define CTerr(f,r) ERR_PUT_error(ERR_LIB_CT,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define ASYNCerr(f,r) ERR_PUT_error(ERR_LIB_ASYNC,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define KDFerr(f,r) ERR_PUT_error(ERR_LIB_KDF,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define SM2err(f,r) ERR_PUT_error(ERR_LIB_SM2,(f),(r),OPENSSL_FILE,OPENSSL_LINE) + +# define ERR_PACK(l,f,r) ( \ + (((unsigned int)(l) & 0x0FF) << 24L) | \ + (((unsigned int)(f) & 0xFFF) << 12L) | \ + (((unsigned int)(r) & 0xFFF) ) ) +# define ERR_GET_LIB(l) (int)(((l) >> 24L) & 0x0FFL) +# define ERR_GET_FUNC(l) (int)(((l) >> 12L) & 0xFFFL) +# define ERR_GET_REASON(l) (int)( (l) & 0xFFFL) +# define ERR_FATAL_ERROR(l) (int)( (l) & ERR_R_FATAL) + +/* OS functions */ +# define SYS_F_FOPEN 1 +# define SYS_F_CONNECT 2 +# define SYS_F_GETSERVBYNAME 3 +# define SYS_F_SOCKET 4 +# define SYS_F_IOCTLSOCKET 5 +# define SYS_F_BIND 6 +# define SYS_F_LISTEN 7 +# define SYS_F_ACCEPT 8 +# define SYS_F_WSASTARTUP 9/* Winsock stuff */ +# define SYS_F_OPENDIR 10 +# define SYS_F_FREAD 11 +# define SYS_F_GETADDRINFO 12 +# define SYS_F_GETNAMEINFO 13 +# define SYS_F_SETSOCKOPT 14 +# define SYS_F_GETSOCKOPT 15 +# define SYS_F_GETSOCKNAME 16 +# define SYS_F_GETHOSTBYNAME 17 +# define SYS_F_FFLUSH 18 +# define SYS_F_OPEN 19 +# define SYS_F_CLOSE 20 +# define SYS_F_IOCTL 21 +# define SYS_F_STAT 22 +# define SYS_F_FCNTL 23 +# define SYS_F_FSTAT 24 + +/* reasons */ +# define ERR_R_SYS_LIB ERR_LIB_SYS/* 2 */ +# define ERR_R_BN_LIB ERR_LIB_BN/* 3 */ +# define ERR_R_RSA_LIB ERR_LIB_RSA/* 4 */ +# define ERR_R_DH_LIB ERR_LIB_DH/* 5 */ +# define ERR_R_EVP_LIB ERR_LIB_EVP/* 6 */ +# define ERR_R_BUF_LIB ERR_LIB_BUF/* 7 */ +# define ERR_R_OBJ_LIB ERR_LIB_OBJ/* 8 */ +# define ERR_R_PEM_LIB ERR_LIB_PEM/* 9 */ +# define ERR_R_DSA_LIB ERR_LIB_DSA/* 10 */ +# define ERR_R_X509_LIB ERR_LIB_X509/* 11 */ +# define ERR_R_ASN1_LIB ERR_LIB_ASN1/* 13 */ +# define ERR_R_EC_LIB ERR_LIB_EC/* 16 */ +# define ERR_R_BIO_LIB ERR_LIB_BIO/* 32 */ +# define ERR_R_PKCS7_LIB ERR_LIB_PKCS7/* 33 */ +# define ERR_R_X509V3_LIB ERR_LIB_X509V3/* 34 */ +# define ERR_R_ENGINE_LIB ERR_LIB_ENGINE/* 38 */ +# define ERR_R_UI_LIB ERR_LIB_UI/* 40 */ +# define ERR_R_ECDSA_LIB ERR_LIB_ECDSA/* 42 */ +# define ERR_R_OSSL_STORE_LIB ERR_LIB_OSSL_STORE/* 44 */ + +# define ERR_R_NESTED_ASN1_ERROR 58 +# define ERR_R_MISSING_ASN1_EOS 63 + +/* fatal error */ +# define ERR_R_FATAL 64 +# define ERR_R_MALLOC_FAILURE (1|ERR_R_FATAL) +# define ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED (2|ERR_R_FATAL) +# define ERR_R_PASSED_NULL_PARAMETER (3|ERR_R_FATAL) +# define ERR_R_INTERNAL_ERROR (4|ERR_R_FATAL) +# define ERR_R_DISABLED (5|ERR_R_FATAL) +# define ERR_R_INIT_FAIL (6|ERR_R_FATAL) +# define ERR_R_PASSED_INVALID_ARGUMENT (7) +# define ERR_R_OPERATION_FAIL (8|ERR_R_FATAL) + +/* + * 99 is the maximum possible ERR_R_... code, higher values are reserved for + * the individual libraries + */ + +typedef struct ERR_string_data_st { + unsigned long error; + const char *string; +} ERR_STRING_DATA; + +DEFINE_LHASH_OF(ERR_STRING_DATA); + +void ERR_put_error(int lib, int func, int reason, const char *file, int line); +void ERR_set_error_data(char *data, int flags); + +unsigned long ERR_get_error(void); +unsigned long ERR_get_error_line(const char **file, int *line); +unsigned long ERR_get_error_line_data(const char **file, int *line, + const char **data, int *flags); +unsigned long ERR_peek_error(void); +unsigned long ERR_peek_error_line(const char **file, int *line); +unsigned long ERR_peek_error_line_data(const char **file, int *line, + const char **data, int *flags); +unsigned long ERR_peek_last_error(void); +unsigned long ERR_peek_last_error_line(const char **file, int *line); +unsigned long ERR_peek_last_error_line_data(const char **file, int *line, + const char **data, int *flags); +void ERR_clear_error(void); +char *ERR_error_string(unsigned long e, char *buf); +void ERR_error_string_n(unsigned long e, char *buf, size_t len); +const char *ERR_lib_error_string(unsigned long e); +const char *ERR_func_error_string(unsigned long e); +const char *ERR_reason_error_string(unsigned long e); +void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u), + void *u); +# ifndef OPENSSL_NO_STDIO +void ERR_print_errors_fp(FILE *fp); +# endif +void ERR_print_errors(BIO *bp); +void ERR_add_error_data(int num, ...); +void ERR_add_error_vdata(int num, va_list args); +int ERR_load_strings(int lib, ERR_STRING_DATA *str); +int ERR_load_strings_const(const ERR_STRING_DATA *str); +int ERR_unload_strings(int lib, ERR_STRING_DATA *str); +int ERR_load_ERR_strings(void); + +#if OPENSSL_API_COMPAT < 0x10100000L +# define ERR_load_crypto_strings() \ + OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL) +# define ERR_free_strings() while(0) continue +#endif + +DEPRECATEDIN_1_1_0(void ERR_remove_thread_state(void *)) +DEPRECATEDIN_1_0_0(void ERR_remove_state(unsigned long pid)) +ERR_STATE *ERR_get_state(void); + +int ERR_get_next_error_library(void); + +int ERR_set_mark(void); +int ERR_pop_to_mark(void); +int ERR_clear_last_mark(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/evp.h b/include/openssl/evp.h new file mode 100644 index 0000000..0d7a0ec --- /dev/null +++ b/include/openssl/evp.h @@ -0,0 +1,1638 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_ENVELOPE_H +# define HEADER_ENVELOPE_H + +# include +# include +# include +# include +# include + +# define EVP_MAX_MD_SIZE 64/* longest known is SHA512 */ +# define EVP_MAX_KEY_LENGTH 64 +# define EVP_MAX_IV_LENGTH 16 +# define EVP_MAX_BLOCK_LENGTH 32 + +# define PKCS5_SALT_LEN 8 +/* Default PKCS#5 iteration count */ +# define PKCS5_DEFAULT_ITER 2048 + +# include + +# define EVP_PK_RSA 0x0001 +# define EVP_PK_DSA 0x0002 +# define EVP_PK_DH 0x0004 +# define EVP_PK_EC 0x0008 +# define EVP_PKT_SIGN 0x0010 +# define EVP_PKT_ENC 0x0020 +# define EVP_PKT_EXCH 0x0040 +# define EVP_PKS_RSA 0x0100 +# define EVP_PKS_DSA 0x0200 +# define EVP_PKS_EC 0x0400 + +# define EVP_PKEY_NONE NID_undef +# define EVP_PKEY_RSA NID_rsaEncryption +# define EVP_PKEY_RSA2 NID_rsa +# define EVP_PKEY_RSA_PSS NID_rsassaPss +# define EVP_PKEY_DSA NID_dsa +# define EVP_PKEY_DSA1 NID_dsa_2 +# define EVP_PKEY_DSA2 NID_dsaWithSHA +# define EVP_PKEY_DSA3 NID_dsaWithSHA1 +# define EVP_PKEY_DSA4 NID_dsaWithSHA1_2 +# define EVP_PKEY_DH NID_dhKeyAgreement +# define EVP_PKEY_DHX NID_dhpublicnumber +# define EVP_PKEY_EC NID_X9_62_id_ecPublicKey +# define EVP_PKEY_SM2 NID_sm2 +# define EVP_PKEY_HMAC NID_hmac +# define EVP_PKEY_CMAC NID_cmac +# define EVP_PKEY_SCRYPT NID_id_scrypt +# define EVP_PKEY_TLS1_PRF NID_tls1_prf +# define EVP_PKEY_HKDF NID_hkdf +# define EVP_PKEY_POLY1305 NID_poly1305 +# define EVP_PKEY_SIPHASH NID_siphash +# define EVP_PKEY_X25519 NID_X25519 +# define EVP_PKEY_ED25519 NID_ED25519 +# define EVP_PKEY_X448 NID_X448 +# define EVP_PKEY_ED448 NID_ED448 + +#ifdef __cplusplus +extern "C" { +#endif + +# define EVP_PKEY_MO_SIGN 0x0001 +# define EVP_PKEY_MO_VERIFY 0x0002 +# define EVP_PKEY_MO_ENCRYPT 0x0004 +# define EVP_PKEY_MO_DECRYPT 0x0008 + +# ifndef EVP_MD +EVP_MD *EVP_MD_meth_new(int md_type, int pkey_type); +EVP_MD *EVP_MD_meth_dup(const EVP_MD *md); +void EVP_MD_meth_free(EVP_MD *md); + +int EVP_MD_meth_set_input_blocksize(EVP_MD *md, int blocksize); +int EVP_MD_meth_set_result_size(EVP_MD *md, int resultsize); +int EVP_MD_meth_set_app_datasize(EVP_MD *md, int datasize); +int EVP_MD_meth_set_flags(EVP_MD *md, unsigned long flags); +int EVP_MD_meth_set_init(EVP_MD *md, int (*init)(EVP_MD_CTX *ctx)); +int EVP_MD_meth_set_update(EVP_MD *md, int (*update)(EVP_MD_CTX *ctx, + const void *data, + size_t count)); +int EVP_MD_meth_set_final(EVP_MD *md, int (*final)(EVP_MD_CTX *ctx, + unsigned char *md)); +int EVP_MD_meth_set_copy(EVP_MD *md, int (*copy)(EVP_MD_CTX *to, + const EVP_MD_CTX *from)); +int EVP_MD_meth_set_cleanup(EVP_MD *md, int (*cleanup)(EVP_MD_CTX *ctx)); +int EVP_MD_meth_set_ctrl(EVP_MD *md, int (*ctrl)(EVP_MD_CTX *ctx, int cmd, + int p1, void *p2)); + +int EVP_MD_meth_get_input_blocksize(const EVP_MD *md); +int EVP_MD_meth_get_result_size(const EVP_MD *md); +int EVP_MD_meth_get_app_datasize(const EVP_MD *md); +unsigned long EVP_MD_meth_get_flags(const EVP_MD *md); +int (*EVP_MD_meth_get_init(const EVP_MD *md))(EVP_MD_CTX *ctx); +int (*EVP_MD_meth_get_update(const EVP_MD *md))(EVP_MD_CTX *ctx, + const void *data, + size_t count); +int (*EVP_MD_meth_get_final(const EVP_MD *md))(EVP_MD_CTX *ctx, + unsigned char *md); +int (*EVP_MD_meth_get_copy(const EVP_MD *md))(EVP_MD_CTX *to, + const EVP_MD_CTX *from); +int (*EVP_MD_meth_get_cleanup(const EVP_MD *md))(EVP_MD_CTX *ctx); +int (*EVP_MD_meth_get_ctrl(const EVP_MD *md))(EVP_MD_CTX *ctx, int cmd, + int p1, void *p2); + +/* digest can only handle a single block */ +# define EVP_MD_FLAG_ONESHOT 0x0001 + +/* digest is extensible-output function, XOF */ +# define EVP_MD_FLAG_XOF 0x0002 + +/* DigestAlgorithmIdentifier flags... */ + +# define EVP_MD_FLAG_DIGALGID_MASK 0x0018 + +/* NULL or absent parameter accepted. Use NULL */ + +# define EVP_MD_FLAG_DIGALGID_NULL 0x0000 + +/* NULL or absent parameter accepted. Use NULL for PKCS#1 otherwise absent */ + +# define EVP_MD_FLAG_DIGALGID_ABSENT 0x0008 + +/* Custom handling via ctrl */ + +# define EVP_MD_FLAG_DIGALGID_CUSTOM 0x0018 + +/* Note if suitable for use in FIPS mode */ +# define EVP_MD_FLAG_FIPS 0x0400 + +/* Digest ctrls */ + +# define EVP_MD_CTRL_DIGALGID 0x1 +# define EVP_MD_CTRL_MICALG 0x2 +# define EVP_MD_CTRL_XOF_LEN 0x3 + +/* Minimum Algorithm specific ctrl value */ + +# define EVP_MD_CTRL_ALG_CTRL 0x1000 + +# endif /* !EVP_MD */ + +/* values for EVP_MD_CTX flags */ + +# define EVP_MD_CTX_FLAG_ONESHOT 0x0001/* digest update will be + * called once only */ +# define EVP_MD_CTX_FLAG_CLEANED 0x0002/* context has already been + * cleaned */ +# define EVP_MD_CTX_FLAG_REUSE 0x0004/* Don't free up ctx->md_data + * in EVP_MD_CTX_reset */ +/* + * FIPS and pad options are ignored in 1.0.0, definitions are here so we + * don't accidentally reuse the values for other purposes. + */ + +# define EVP_MD_CTX_FLAG_NON_FIPS_ALLOW 0x0008/* Allow use of non FIPS + * digest in FIPS mode */ + +/* + * The following PAD options are also currently ignored in 1.0.0, digest + * parameters are handled through EVP_DigestSign*() and EVP_DigestVerify*() + * instead. + */ +# define EVP_MD_CTX_FLAG_PAD_MASK 0xF0/* RSA mode to use */ +# define EVP_MD_CTX_FLAG_PAD_PKCS1 0x00/* PKCS#1 v1.5 mode */ +# define EVP_MD_CTX_FLAG_PAD_X931 0x10/* X9.31 mode */ +# define EVP_MD_CTX_FLAG_PAD_PSS 0x20/* PSS mode */ + +# define EVP_MD_CTX_FLAG_NO_INIT 0x0100/* Don't initialize md_data */ +/* + * Some functions such as EVP_DigestSign only finalise copies of internal + * contexts so additional data can be included after the finalisation call. + * This is inefficient if this functionality is not required: it is disabled + * if the following flag is set. + */ +# define EVP_MD_CTX_FLAG_FINALISE 0x0200 +/* NOTE: 0x0400 is reserved for internal usage in evp_int.h */ + +EVP_CIPHER *EVP_CIPHER_meth_new(int cipher_type, int block_size, int key_len); +EVP_CIPHER *EVP_CIPHER_meth_dup(const EVP_CIPHER *cipher); +void EVP_CIPHER_meth_free(EVP_CIPHER *cipher); + +int EVP_CIPHER_meth_set_iv_length(EVP_CIPHER *cipher, int iv_len); +int EVP_CIPHER_meth_set_flags(EVP_CIPHER *cipher, unsigned long flags); +int EVP_CIPHER_meth_set_impl_ctx_size(EVP_CIPHER *cipher, int ctx_size); +int EVP_CIPHER_meth_set_init(EVP_CIPHER *cipher, + int (*init) (EVP_CIPHER_CTX *ctx, + const unsigned char *key, + const unsigned char *iv, + int enc)); +int EVP_CIPHER_meth_set_do_cipher(EVP_CIPHER *cipher, + int (*do_cipher) (EVP_CIPHER_CTX *ctx, + unsigned char *out, + const unsigned char *in, + size_t inl)); +int EVP_CIPHER_meth_set_cleanup(EVP_CIPHER *cipher, + int (*cleanup) (EVP_CIPHER_CTX *)); +int EVP_CIPHER_meth_set_set_asn1_params(EVP_CIPHER *cipher, + int (*set_asn1_parameters) (EVP_CIPHER_CTX *, + ASN1_TYPE *)); +int EVP_CIPHER_meth_set_get_asn1_params(EVP_CIPHER *cipher, + int (*get_asn1_parameters) (EVP_CIPHER_CTX *, + ASN1_TYPE *)); +int EVP_CIPHER_meth_set_ctrl(EVP_CIPHER *cipher, + int (*ctrl) (EVP_CIPHER_CTX *, int type, + int arg, void *ptr)); + +int (*EVP_CIPHER_meth_get_init(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx, + const unsigned char *key, + const unsigned char *iv, + int enc); +int (*EVP_CIPHER_meth_get_do_cipher(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx, + unsigned char *out, + const unsigned char *in, + size_t inl); +int (*EVP_CIPHER_meth_get_cleanup(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *); +int (*EVP_CIPHER_meth_get_set_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, + ASN1_TYPE *); +int (*EVP_CIPHER_meth_get_get_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, + ASN1_TYPE *); +int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, + int type, int arg, + void *ptr); + +/* Values for cipher flags */ + +/* Modes for ciphers */ + +# define EVP_CIPH_STREAM_CIPHER 0x0 +# define EVP_CIPH_ECB_MODE 0x1 +# define EVP_CIPH_CBC_MODE 0x2 +# define EVP_CIPH_CFB_MODE 0x3 +# define EVP_CIPH_OFB_MODE 0x4 +# define EVP_CIPH_CTR_MODE 0x5 +# define EVP_CIPH_GCM_MODE 0x6 +# define EVP_CIPH_CCM_MODE 0x7 +# define EVP_CIPH_XTS_MODE 0x10001 +# define EVP_CIPH_WRAP_MODE 0x10002 +# define EVP_CIPH_OCB_MODE 0x10003 +# define EVP_CIPH_MODE 0xF0007 +/* Set if variable length cipher */ +# define EVP_CIPH_VARIABLE_LENGTH 0x8 +/* Set if the iv handling should be done by the cipher itself */ +# define EVP_CIPH_CUSTOM_IV 0x10 +/* Set if the cipher's init() function should be called if key is NULL */ +# define EVP_CIPH_ALWAYS_CALL_INIT 0x20 +/* Call ctrl() to init cipher parameters */ +# define EVP_CIPH_CTRL_INIT 0x40 +/* Don't use standard key length function */ +# define EVP_CIPH_CUSTOM_KEY_LENGTH 0x80 +/* Don't use standard block padding */ +# define EVP_CIPH_NO_PADDING 0x100 +/* cipher handles random key generation */ +# define EVP_CIPH_RAND_KEY 0x200 +/* cipher has its own additional copying logic */ +# define EVP_CIPH_CUSTOM_COPY 0x400 +/* Allow use default ASN1 get/set iv */ +# define EVP_CIPH_FLAG_DEFAULT_ASN1 0x1000 +/* Buffer length in bits not bytes: CFB1 mode only */ +# define EVP_CIPH_FLAG_LENGTH_BITS 0x2000 +/* Note if suitable for use in FIPS mode */ +# define EVP_CIPH_FLAG_FIPS 0x4000 +/* Allow non FIPS cipher in FIPS mode */ +# define EVP_CIPH_FLAG_NON_FIPS_ALLOW 0x8000 +/* + * Cipher handles any and all padding logic as well as finalisation. + */ +# define EVP_CIPH_FLAG_CUSTOM_CIPHER 0x100000 +# define EVP_CIPH_FLAG_AEAD_CIPHER 0x200000 +# define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0x400000 +/* Cipher can handle pipeline operations */ +# define EVP_CIPH_FLAG_PIPELINE 0X800000 + +/* + * Cipher context flag to indicate we can handle wrap mode: if allowed in + * older applications it could overflow buffers. + */ + +# define EVP_CIPHER_CTX_FLAG_WRAP_ALLOW 0x1 + +/* ctrl() values */ + +# define EVP_CTRL_INIT 0x0 +# define EVP_CTRL_SET_KEY_LENGTH 0x1 +# define EVP_CTRL_GET_RC2_KEY_BITS 0x2 +# define EVP_CTRL_SET_RC2_KEY_BITS 0x3 +# define EVP_CTRL_GET_RC5_ROUNDS 0x4 +# define EVP_CTRL_SET_RC5_ROUNDS 0x5 +# define EVP_CTRL_RAND_KEY 0x6 +# define EVP_CTRL_PBE_PRF_NID 0x7 +# define EVP_CTRL_COPY 0x8 +# define EVP_CTRL_AEAD_SET_IVLEN 0x9 +# define EVP_CTRL_AEAD_GET_TAG 0x10 +# define EVP_CTRL_AEAD_SET_TAG 0x11 +# define EVP_CTRL_AEAD_SET_IV_FIXED 0x12 +# define EVP_CTRL_GCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN +# define EVP_CTRL_GCM_GET_TAG EVP_CTRL_AEAD_GET_TAG +# define EVP_CTRL_GCM_SET_TAG EVP_CTRL_AEAD_SET_TAG +# define EVP_CTRL_GCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED +# define EVP_CTRL_GCM_IV_GEN 0x13 +# define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN +# define EVP_CTRL_CCM_GET_TAG EVP_CTRL_AEAD_GET_TAG +# define EVP_CTRL_CCM_SET_TAG EVP_CTRL_AEAD_SET_TAG +# define EVP_CTRL_CCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED +# define EVP_CTRL_CCM_SET_L 0x14 +# define EVP_CTRL_CCM_SET_MSGLEN 0x15 +/* + * AEAD cipher deduces payload length and returns number of bytes required to + * store MAC and eventual padding. Subsequent call to EVP_Cipher even + * appends/verifies MAC. + */ +# define EVP_CTRL_AEAD_TLS1_AAD 0x16 +/* Used by composite AEAD ciphers, no-op in GCM, CCM... */ +# define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 +/* Set the GCM invocation field, decrypt only */ +# define EVP_CTRL_GCM_SET_IV_INV 0x18 + +# define EVP_CTRL_TLS1_1_MULTIBLOCK_AAD 0x19 +# define EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT 0x1a +# define EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT 0x1b +# define EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE 0x1c + +# define EVP_CTRL_SSL3_MASTER_SECRET 0x1d + +/* EVP_CTRL_SET_SBOX takes the char * specifying S-boxes */ +# define EVP_CTRL_SET_SBOX 0x1e +/* + * EVP_CTRL_SBOX_USED takes a 'size_t' and 'char *', pointing at a + * pre-allocated buffer with specified size + */ +# define EVP_CTRL_SBOX_USED 0x1f +/* EVP_CTRL_KEY_MESH takes 'size_t' number of bytes to mesh the key after, + * 0 switches meshing off + */ +# define EVP_CTRL_KEY_MESH 0x20 +/* EVP_CTRL_BLOCK_PADDING_MODE takes the padding mode */ +# define EVP_CTRL_BLOCK_PADDING_MODE 0x21 + +/* Set the output buffers to use for a pipelined operation */ +# define EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS 0x22 +/* Set the input buffers to use for a pipelined operation */ +# define EVP_CTRL_SET_PIPELINE_INPUT_BUFS 0x23 +/* Set the input buffer lengths to use for a pipelined operation */ +# define EVP_CTRL_SET_PIPELINE_INPUT_LENS 0x24 + +/* Padding modes */ +#define EVP_PADDING_PKCS7 1 +#define EVP_PADDING_ISO7816_4 2 +#define EVP_PADDING_ANSI923 3 +#define EVP_PADDING_ISO10126 4 +#define EVP_PADDING_ZERO 5 + +/* RFC 5246 defines additional data to be 13 bytes in length */ +# define EVP_AEAD_TLS1_AAD_LEN 13 + +typedef struct { + unsigned char *out; + const unsigned char *inp; + size_t len; + unsigned int interleave; +} EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM; + +/* GCM TLS constants */ +/* Length of fixed part of IV derived from PRF */ +# define EVP_GCM_TLS_FIXED_IV_LEN 4 +/* Length of explicit part of IV part of TLS records */ +# define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 +/* Length of tag for TLS */ +# define EVP_GCM_TLS_TAG_LEN 16 + +/* CCM TLS constants */ +/* Length of fixed part of IV derived from PRF */ +# define EVP_CCM_TLS_FIXED_IV_LEN 4 +/* Length of explicit part of IV part of TLS records */ +# define EVP_CCM_TLS_EXPLICIT_IV_LEN 8 +/* Total length of CCM IV length for TLS */ +# define EVP_CCM_TLS_IV_LEN 12 +/* Length of tag for TLS */ +# define EVP_CCM_TLS_TAG_LEN 16 +/* Length of CCM8 tag for TLS */ +# define EVP_CCM8_TLS_TAG_LEN 8 + +/* Length of tag for TLS */ +# define EVP_CHACHAPOLY_TLS_TAG_LEN 16 + +typedef struct evp_cipher_info_st { + const EVP_CIPHER *cipher; + unsigned char iv[EVP_MAX_IV_LENGTH]; +} EVP_CIPHER_INFO; + + +/* Password based encryption function */ +typedef int (EVP_PBE_KEYGEN) (EVP_CIPHER_CTX *ctx, const char *pass, + int passlen, ASN1_TYPE *param, + const EVP_CIPHER *cipher, const EVP_MD *md, + int en_de); + +# ifndef OPENSSL_NO_RSA +# define EVP_PKEY_assign_RSA(pkey,rsa) EVP_PKEY_assign((pkey),EVP_PKEY_RSA,\ + (char *)(rsa)) +# endif + +# ifndef OPENSSL_NO_DSA +# define EVP_PKEY_assign_DSA(pkey,dsa) EVP_PKEY_assign((pkey),EVP_PKEY_DSA,\ + (char *)(dsa)) +# endif + +# ifndef OPENSSL_NO_DH +# define EVP_PKEY_assign_DH(pkey,dh) EVP_PKEY_assign((pkey),EVP_PKEY_DH,\ + (char *)(dh)) +# endif + +# ifndef OPENSSL_NO_EC +# define EVP_PKEY_assign_EC_KEY(pkey,eckey) EVP_PKEY_assign((pkey),EVP_PKEY_EC,\ + (char *)(eckey)) +# endif +# ifndef OPENSSL_NO_SIPHASH +# define EVP_PKEY_assign_SIPHASH(pkey,shkey) EVP_PKEY_assign((pkey),EVP_PKEY_SIPHASH,\ + (char *)(shkey)) +# endif + +# ifndef OPENSSL_NO_POLY1305 +# define EVP_PKEY_assign_POLY1305(pkey,polykey) EVP_PKEY_assign((pkey),EVP_PKEY_POLY1305,\ + (char *)(polykey)) +# endif + +/* Add some extra combinations */ +# define EVP_get_digestbynid(a) EVP_get_digestbyname(OBJ_nid2sn(a)) +# define EVP_get_digestbyobj(a) EVP_get_digestbynid(OBJ_obj2nid(a)) +# define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a)) +# define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a)) + +int EVP_MD_type(const EVP_MD *md); +# define EVP_MD_nid(e) EVP_MD_type(e) +# define EVP_MD_name(e) OBJ_nid2sn(EVP_MD_nid(e)) +int EVP_MD_pkey_type(const EVP_MD *md); +int EVP_MD_size(const EVP_MD *md); +int EVP_MD_block_size(const EVP_MD *md); +unsigned long EVP_MD_flags(const EVP_MD *md); + +const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx); +int (*EVP_MD_CTX_update_fn(EVP_MD_CTX *ctx))(EVP_MD_CTX *ctx, + const void *data, size_t count); +void EVP_MD_CTX_set_update_fn(EVP_MD_CTX *ctx, + int (*update) (EVP_MD_CTX *ctx, + const void *data, size_t count)); +# define EVP_MD_CTX_size(e) EVP_MD_size(EVP_MD_CTX_md(e)) +# define EVP_MD_CTX_block_size(e) EVP_MD_block_size(EVP_MD_CTX_md(e)) +# define EVP_MD_CTX_type(e) EVP_MD_type(EVP_MD_CTX_md(e)) +EVP_PKEY_CTX *EVP_MD_CTX_pkey_ctx(const EVP_MD_CTX *ctx); +void EVP_MD_CTX_set_pkey_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pctx); +void *EVP_MD_CTX_md_data(const EVP_MD_CTX *ctx); + +int EVP_CIPHER_nid(const EVP_CIPHER *cipher); +# define EVP_CIPHER_name(e) OBJ_nid2sn(EVP_CIPHER_nid(e)) +int EVP_CIPHER_block_size(const EVP_CIPHER *cipher); +int EVP_CIPHER_impl_ctx_size(const EVP_CIPHER *cipher); +int EVP_CIPHER_key_length(const EVP_CIPHER *cipher); +int EVP_CIPHER_iv_length(const EVP_CIPHER *cipher); +unsigned long EVP_CIPHER_flags(const EVP_CIPHER *cipher); +# define EVP_CIPHER_mode(e) (EVP_CIPHER_flags(e) & EVP_CIPH_MODE) + +const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx); +int EVP_CIPHER_CTX_encrypting(const EVP_CIPHER_CTX *ctx); +int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx); +int EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx); +int EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx); +int EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx); +const unsigned char *EVP_CIPHER_CTX_iv(const EVP_CIPHER_CTX *ctx); +const unsigned char *EVP_CIPHER_CTX_original_iv(const EVP_CIPHER_CTX *ctx); +unsigned char *EVP_CIPHER_CTX_iv_noconst(EVP_CIPHER_CTX *ctx); +unsigned char *EVP_CIPHER_CTX_buf_noconst(EVP_CIPHER_CTX *ctx); +int EVP_CIPHER_CTX_num(const EVP_CIPHER_CTX *ctx); +void EVP_CIPHER_CTX_set_num(EVP_CIPHER_CTX *ctx, int num); +int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in); +void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx); +void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data); +void *EVP_CIPHER_CTX_get_cipher_data(const EVP_CIPHER_CTX *ctx); +void *EVP_CIPHER_CTX_set_cipher_data(EVP_CIPHER_CTX *ctx, void *cipher_data); +# define EVP_CIPHER_CTX_type(c) EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c)) +# if OPENSSL_API_COMPAT < 0x10100000L +# define EVP_CIPHER_CTX_flags(c) EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(c)) +# endif +# define EVP_CIPHER_CTX_mode(c) EVP_CIPHER_mode(EVP_CIPHER_CTX_cipher(c)) + +# define EVP_ENCODE_LENGTH(l) ((((l)+2)/3*4)+((l)/48+1)*2+80) +# define EVP_DECODE_LENGTH(l) (((l)+3)/4*3+80) + +# define EVP_SignInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c) +# define EVP_SignInit(a,b) EVP_DigestInit(a,b) +# define EVP_SignUpdate(a,b,c) EVP_DigestUpdate(a,b,c) +# define EVP_VerifyInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c) +# define EVP_VerifyInit(a,b) EVP_DigestInit(a,b) +# define EVP_VerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c) +# define EVP_OpenUpdate(a,b,c,d,e) EVP_DecryptUpdate(a,b,c,d,e) +# define EVP_SealUpdate(a,b,c,d,e) EVP_EncryptUpdate(a,b,c,d,e) +# define EVP_DigestSignUpdate(a,b,c) EVP_DigestUpdate(a,b,c) +# define EVP_DigestVerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c) + +# ifdef CONST_STRICT +void BIO_set_md(BIO *, const EVP_MD *md); +# else +# define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,0,(char *)(md)) +# endif +# define BIO_get_md(b,mdp) BIO_ctrl(b,BIO_C_GET_MD,0,(char *)(mdp)) +# define BIO_get_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_GET_MD_CTX,0, \ + (char *)(mdcp)) +# define BIO_set_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_SET_MD_CTX,0, \ + (char *)(mdcp)) +# define BIO_get_cipher_status(b) BIO_ctrl(b,BIO_C_GET_CIPHER_STATUS,0,NULL) +# define BIO_get_cipher_ctx(b,c_pp) BIO_ctrl(b,BIO_C_GET_CIPHER_CTX,0, \ + (char *)(c_pp)) + +/*__owur*/ int EVP_Cipher(EVP_CIPHER_CTX *c, + unsigned char *out, + const unsigned char *in, unsigned int inl); + +# define EVP_add_cipher_alias(n,alias) \ + OBJ_NAME_add((alias),OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS,(n)) +# define EVP_add_digest_alias(n,alias) \ + OBJ_NAME_add((alias),OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS,(n)) +# define EVP_delete_cipher_alias(alias) \ + OBJ_NAME_remove(alias,OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS); +# define EVP_delete_digest_alias(alias) \ + OBJ_NAME_remove(alias,OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS); + +int EVP_MD_CTX_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void *p2); +EVP_MD_CTX *EVP_MD_CTX_new(void); +int EVP_MD_CTX_reset(EVP_MD_CTX *ctx); +void EVP_MD_CTX_free(EVP_MD_CTX *ctx); +# define EVP_MD_CTX_create() EVP_MD_CTX_new() +# define EVP_MD_CTX_init(ctx) EVP_MD_CTX_reset((ctx)) +# define EVP_MD_CTX_destroy(ctx) EVP_MD_CTX_free((ctx)) +__owur int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in); +void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags); +void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags); +int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx, int flags); +__owur int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, + ENGINE *impl); +__owur int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, + size_t cnt); +__owur int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, + unsigned int *s); +__owur int EVP_Digest(const void *data, size_t count, + unsigned char *md, unsigned int *size, + const EVP_MD *type, ENGINE *impl); + +__owur int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in); +__owur int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); +__owur int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, + unsigned int *s); +__owur int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md, + size_t len); + +int EVP_read_pw_string(char *buf, int length, const char *prompt, int verify); +int EVP_read_pw_string_min(char *buf, int minlen, int maxlen, + const char *prompt, int verify); +void EVP_set_pw_prompt(const char *prompt); +char *EVP_get_pw_prompt(void); + +__owur int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, + const unsigned char *salt, + const unsigned char *data, int datal, int count, + unsigned char *key, unsigned char *iv); + +void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags); +void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags); +int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx, int flags); + +__owur int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, + const unsigned char *key, const unsigned char *iv); +/*__owur*/ int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, + const EVP_CIPHER *cipher, ENGINE *impl, + const unsigned char *key, + const unsigned char *iv); +/*__owur*/ int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, + int *outl, const unsigned char *in, int inl); +/*__owur*/ int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, + int *outl); +/*__owur*/ int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, + int *outl); + +__owur int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, + const unsigned char *key, const unsigned char *iv); +/*__owur*/ int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, + const EVP_CIPHER *cipher, ENGINE *impl, + const unsigned char *key, + const unsigned char *iv); +/*__owur*/ int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, + int *outl, const unsigned char *in, int inl); +__owur int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, + int *outl); +/*__owur*/ int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, + int *outl); + +__owur int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, + const unsigned char *key, const unsigned char *iv, + int enc); +/*__owur*/ int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, + const EVP_CIPHER *cipher, ENGINE *impl, + const unsigned char *key, + const unsigned char *iv, int enc); +__owur int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, + int *outl, const unsigned char *in, int inl); +__owur int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, + int *outl); +__owur int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, + int *outl); + +__owur int EVP_SignFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s, + EVP_PKEY *pkey); + +__owur int EVP_DigestSign(EVP_MD_CTX *ctx, unsigned char *sigret, + size_t *siglen, const unsigned char *tbs, + size_t tbslen); + +__owur int EVP_VerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sigbuf, + unsigned int siglen, EVP_PKEY *pkey); + +__owur int EVP_DigestVerify(EVP_MD_CTX *ctx, const unsigned char *sigret, + size_t siglen, const unsigned char *tbs, + size_t tbslen); + +/*__owur*/ int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, + const EVP_MD *type, ENGINE *e, + EVP_PKEY *pkey); +__owur int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, + size_t *siglen); + +__owur int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, + const EVP_MD *type, ENGINE *e, + EVP_PKEY *pkey); +__owur int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, + size_t siglen); + +# ifndef OPENSSL_NO_RSA +__owur int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, + const unsigned char *ek, int ekl, + const unsigned char *iv, EVP_PKEY *priv); +__owur int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); + +__owur int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, + unsigned char **ek, int *ekl, unsigned char *iv, + EVP_PKEY **pubk, int npubk); +__owur int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); +# endif + +EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void); +void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx); +int EVP_ENCODE_CTX_copy(EVP_ENCODE_CTX *dctx, EVP_ENCODE_CTX *sctx); +int EVP_ENCODE_CTX_num(EVP_ENCODE_CTX *ctx); +void EVP_EncodeInit(EVP_ENCODE_CTX *ctx); +int EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, + const unsigned char *in, int inl); +void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl); +int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int n); + +void EVP_DecodeInit(EVP_ENCODE_CTX *ctx); +int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, + const unsigned char *in, int inl); +int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned + char *out, int *outl); +int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define EVP_CIPHER_CTX_init(c) EVP_CIPHER_CTX_reset(c) +# define EVP_CIPHER_CTX_cleanup(c) EVP_CIPHER_CTX_reset(c) +# endif +EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); +int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *c); +void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *c); +int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen); +int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad); +int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr); +int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key); + +const BIO_METHOD *BIO_f_md(void); +const BIO_METHOD *BIO_f_base64(void); +const BIO_METHOD *BIO_f_cipher(void); +const BIO_METHOD *BIO_f_reliable(void); +__owur int BIO_set_cipher(BIO *b, const EVP_CIPHER *c, const unsigned char *k, + const unsigned char *i, int enc); + +const EVP_MD *EVP_md_null(void); +# ifndef OPENSSL_NO_MD2 +const EVP_MD *EVP_md2(void); +# endif +# ifndef OPENSSL_NO_MD4 +const EVP_MD *EVP_md4(void); +# endif +# ifndef OPENSSL_NO_MD5 +const EVP_MD *EVP_md5(void); +const EVP_MD *EVP_md5_sha1(void); +# endif +# ifndef OPENSSL_NO_BLAKE2 +const EVP_MD *EVP_blake2b512(void); +const EVP_MD *EVP_blake2s256(void); +# endif +const EVP_MD *EVP_sha1(void); +const EVP_MD *EVP_sha224(void); +const EVP_MD *EVP_sha256(void); +const EVP_MD *EVP_sha384(void); +const EVP_MD *EVP_sha512(void); +const EVP_MD *EVP_sha512_224(void); +const EVP_MD *EVP_sha512_256(void); +const EVP_MD *EVP_sha3_224(void); +const EVP_MD *EVP_sha3_256(void); +const EVP_MD *EVP_sha3_384(void); +const EVP_MD *EVP_sha3_512(void); +const EVP_MD *EVP_shake128(void); +const EVP_MD *EVP_shake256(void); +# ifndef OPENSSL_NO_MDC2 +const EVP_MD *EVP_mdc2(void); +# endif +# ifndef OPENSSL_NO_RMD160 +const EVP_MD *EVP_ripemd160(void); +# endif +# ifndef OPENSSL_NO_WHIRLPOOL +const EVP_MD *EVP_whirlpool(void); +# endif +# ifndef OPENSSL_NO_SM3 +const EVP_MD *EVP_sm3(void); +# endif +const EVP_CIPHER *EVP_enc_null(void); /* does nothing :-) */ +# ifndef OPENSSL_NO_DES +const EVP_CIPHER *EVP_des_ecb(void); +const EVP_CIPHER *EVP_des_ede(void); +const EVP_CIPHER *EVP_des_ede3(void); +const EVP_CIPHER *EVP_des_ede_ecb(void); +const EVP_CIPHER *EVP_des_ede3_ecb(void); +const EVP_CIPHER *EVP_des_cfb64(void); +# define EVP_des_cfb EVP_des_cfb64 +const EVP_CIPHER *EVP_des_cfb1(void); +const EVP_CIPHER *EVP_des_cfb8(void); +const EVP_CIPHER *EVP_des_ede_cfb64(void); +# define EVP_des_ede_cfb EVP_des_ede_cfb64 +const EVP_CIPHER *EVP_des_ede3_cfb64(void); +# define EVP_des_ede3_cfb EVP_des_ede3_cfb64 +const EVP_CIPHER *EVP_des_ede3_cfb1(void); +const EVP_CIPHER *EVP_des_ede3_cfb8(void); +const EVP_CIPHER *EVP_des_ofb(void); +const EVP_CIPHER *EVP_des_ede_ofb(void); +const EVP_CIPHER *EVP_des_ede3_ofb(void); +const EVP_CIPHER *EVP_des_cbc(void); +const EVP_CIPHER *EVP_des_ede_cbc(void); +const EVP_CIPHER *EVP_des_ede3_cbc(void); +const EVP_CIPHER *EVP_desx_cbc(void); +const EVP_CIPHER *EVP_des_ede3_wrap(void); +/* + * This should now be supported through the dev_crypto ENGINE. But also, why + * are rc4 and md5 declarations made here inside a "NO_DES" precompiler + * branch? + */ +# endif +# ifndef OPENSSL_NO_RC4 +const EVP_CIPHER *EVP_rc4(void); +const EVP_CIPHER *EVP_rc4_40(void); +# ifndef OPENSSL_NO_MD5 +const EVP_CIPHER *EVP_rc4_hmac_md5(void); +# endif +# endif +# ifndef OPENSSL_NO_IDEA +const EVP_CIPHER *EVP_idea_ecb(void); +const EVP_CIPHER *EVP_idea_cfb64(void); +# define EVP_idea_cfb EVP_idea_cfb64 +const EVP_CIPHER *EVP_idea_ofb(void); +const EVP_CIPHER *EVP_idea_cbc(void); +# endif +# ifndef OPENSSL_NO_RC2 +const EVP_CIPHER *EVP_rc2_ecb(void); +const EVP_CIPHER *EVP_rc2_cbc(void); +const EVP_CIPHER *EVP_rc2_40_cbc(void); +const EVP_CIPHER *EVP_rc2_64_cbc(void); +const EVP_CIPHER *EVP_rc2_cfb64(void); +# define EVP_rc2_cfb EVP_rc2_cfb64 +const EVP_CIPHER *EVP_rc2_ofb(void); +# endif +# ifndef OPENSSL_NO_BF +const EVP_CIPHER *EVP_bf_ecb(void); +const EVP_CIPHER *EVP_bf_cbc(void); +const EVP_CIPHER *EVP_bf_cfb64(void); +# define EVP_bf_cfb EVP_bf_cfb64 +const EVP_CIPHER *EVP_bf_ofb(void); +# endif +# ifndef OPENSSL_NO_CAST +const EVP_CIPHER *EVP_cast5_ecb(void); +const EVP_CIPHER *EVP_cast5_cbc(void); +const EVP_CIPHER *EVP_cast5_cfb64(void); +# define EVP_cast5_cfb EVP_cast5_cfb64 +const EVP_CIPHER *EVP_cast5_ofb(void); +# endif +# ifndef OPENSSL_NO_RC5 +const EVP_CIPHER *EVP_rc5_32_12_16_cbc(void); +const EVP_CIPHER *EVP_rc5_32_12_16_ecb(void); +const EVP_CIPHER *EVP_rc5_32_12_16_cfb64(void); +# define EVP_rc5_32_12_16_cfb EVP_rc5_32_12_16_cfb64 +const EVP_CIPHER *EVP_rc5_32_12_16_ofb(void); +# endif +const EVP_CIPHER *EVP_aes_128_ecb(void); +const EVP_CIPHER *EVP_aes_128_cbc(void); +const EVP_CIPHER *EVP_aes_128_cfb1(void); +const EVP_CIPHER *EVP_aes_128_cfb8(void); +const EVP_CIPHER *EVP_aes_128_cfb128(void); +# define EVP_aes_128_cfb EVP_aes_128_cfb128 +const EVP_CIPHER *EVP_aes_128_ofb(void); +const EVP_CIPHER *EVP_aes_128_ctr(void); +const EVP_CIPHER *EVP_aes_128_ccm(void); +const EVP_CIPHER *EVP_aes_128_gcm(void); +const EVP_CIPHER *EVP_aes_128_xts(void); +const EVP_CIPHER *EVP_aes_128_wrap(void); +const EVP_CIPHER *EVP_aes_128_wrap_pad(void); +# ifndef OPENSSL_NO_OCB +const EVP_CIPHER *EVP_aes_128_ocb(void); +# endif +const EVP_CIPHER *EVP_aes_192_ecb(void); +const EVP_CIPHER *EVP_aes_192_cbc(void); +const EVP_CIPHER *EVP_aes_192_cfb1(void); +const EVP_CIPHER *EVP_aes_192_cfb8(void); +const EVP_CIPHER *EVP_aes_192_cfb128(void); +# define EVP_aes_192_cfb EVP_aes_192_cfb128 +const EVP_CIPHER *EVP_aes_192_ofb(void); +const EVP_CIPHER *EVP_aes_192_ctr(void); +const EVP_CIPHER *EVP_aes_192_ccm(void); +const EVP_CIPHER *EVP_aes_192_gcm(void); +const EVP_CIPHER *EVP_aes_192_wrap(void); +const EVP_CIPHER *EVP_aes_192_wrap_pad(void); +# ifndef OPENSSL_NO_OCB +const EVP_CIPHER *EVP_aes_192_ocb(void); +# endif +const EVP_CIPHER *EVP_aes_256_ecb(void); +const EVP_CIPHER *EVP_aes_256_cbc(void); +const EVP_CIPHER *EVP_aes_256_cfb1(void); +const EVP_CIPHER *EVP_aes_256_cfb8(void); +const EVP_CIPHER *EVP_aes_256_cfb128(void); +# define EVP_aes_256_cfb EVP_aes_256_cfb128 +const EVP_CIPHER *EVP_aes_256_ofb(void); +const EVP_CIPHER *EVP_aes_256_ctr(void); +const EVP_CIPHER *EVP_aes_256_ccm(void); +const EVP_CIPHER *EVP_aes_256_gcm(void); +const EVP_CIPHER *EVP_aes_256_xts(void); +const EVP_CIPHER *EVP_aes_256_wrap(void); +const EVP_CIPHER *EVP_aes_256_wrap_pad(void); +# ifndef OPENSSL_NO_OCB +const EVP_CIPHER *EVP_aes_256_ocb(void); +# endif +const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void); +const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void); +const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void); +const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void); +# ifndef OPENSSL_NO_ARIA +const EVP_CIPHER *EVP_aria_128_ecb(void); +const EVP_CIPHER *EVP_aria_128_cbc(void); +const EVP_CIPHER *EVP_aria_128_cfb1(void); +const EVP_CIPHER *EVP_aria_128_cfb8(void); +const EVP_CIPHER *EVP_aria_128_cfb128(void); +# define EVP_aria_128_cfb EVP_aria_128_cfb128 +const EVP_CIPHER *EVP_aria_128_ctr(void); +const EVP_CIPHER *EVP_aria_128_ofb(void); +const EVP_CIPHER *EVP_aria_128_gcm(void); +const EVP_CIPHER *EVP_aria_128_ccm(void); +const EVP_CIPHER *EVP_aria_192_ecb(void); +const EVP_CIPHER *EVP_aria_192_cbc(void); +const EVP_CIPHER *EVP_aria_192_cfb1(void); +const EVP_CIPHER *EVP_aria_192_cfb8(void); +const EVP_CIPHER *EVP_aria_192_cfb128(void); +# define EVP_aria_192_cfb EVP_aria_192_cfb128 +const EVP_CIPHER *EVP_aria_192_ctr(void); +const EVP_CIPHER *EVP_aria_192_ofb(void); +const EVP_CIPHER *EVP_aria_192_gcm(void); +const EVP_CIPHER *EVP_aria_192_ccm(void); +const EVP_CIPHER *EVP_aria_256_ecb(void); +const EVP_CIPHER *EVP_aria_256_cbc(void); +const EVP_CIPHER *EVP_aria_256_cfb1(void); +const EVP_CIPHER *EVP_aria_256_cfb8(void); +const EVP_CIPHER *EVP_aria_256_cfb128(void); +# define EVP_aria_256_cfb EVP_aria_256_cfb128 +const EVP_CIPHER *EVP_aria_256_ctr(void); +const EVP_CIPHER *EVP_aria_256_ofb(void); +const EVP_CIPHER *EVP_aria_256_gcm(void); +const EVP_CIPHER *EVP_aria_256_ccm(void); +# endif +# ifndef OPENSSL_NO_CAMELLIA +const EVP_CIPHER *EVP_camellia_128_ecb(void); +const EVP_CIPHER *EVP_camellia_128_cbc(void); +const EVP_CIPHER *EVP_camellia_128_cfb1(void); +const EVP_CIPHER *EVP_camellia_128_cfb8(void); +const EVP_CIPHER *EVP_camellia_128_cfb128(void); +# define EVP_camellia_128_cfb EVP_camellia_128_cfb128 +const EVP_CIPHER *EVP_camellia_128_ofb(void); +const EVP_CIPHER *EVP_camellia_128_ctr(void); +const EVP_CIPHER *EVP_camellia_192_ecb(void); +const EVP_CIPHER *EVP_camellia_192_cbc(void); +const EVP_CIPHER *EVP_camellia_192_cfb1(void); +const EVP_CIPHER *EVP_camellia_192_cfb8(void); +const EVP_CIPHER *EVP_camellia_192_cfb128(void); +# define EVP_camellia_192_cfb EVP_camellia_192_cfb128 +const EVP_CIPHER *EVP_camellia_192_ofb(void); +const EVP_CIPHER *EVP_camellia_192_ctr(void); +const EVP_CIPHER *EVP_camellia_256_ecb(void); +const EVP_CIPHER *EVP_camellia_256_cbc(void); +const EVP_CIPHER *EVP_camellia_256_cfb1(void); +const EVP_CIPHER *EVP_camellia_256_cfb8(void); +const EVP_CIPHER *EVP_camellia_256_cfb128(void); +# define EVP_camellia_256_cfb EVP_camellia_256_cfb128 +const EVP_CIPHER *EVP_camellia_256_ofb(void); +const EVP_CIPHER *EVP_camellia_256_ctr(void); +# endif +# ifndef OPENSSL_NO_CHACHA +const EVP_CIPHER *EVP_chacha20(void); +# ifndef OPENSSL_NO_POLY1305 +const EVP_CIPHER *EVP_chacha20_poly1305(void); +# endif +# endif + +# ifndef OPENSSL_NO_SEED +const EVP_CIPHER *EVP_seed_ecb(void); +const EVP_CIPHER *EVP_seed_cbc(void); +const EVP_CIPHER *EVP_seed_cfb128(void); +# define EVP_seed_cfb EVP_seed_cfb128 +const EVP_CIPHER *EVP_seed_ofb(void); +# endif + +# ifndef OPENSSL_NO_SM4 +const EVP_CIPHER *EVP_sm4_ecb(void); +const EVP_CIPHER *EVP_sm4_cbc(void); +const EVP_CIPHER *EVP_sm4_cfb128(void); +# define EVP_sm4_cfb EVP_sm4_cfb128 +const EVP_CIPHER *EVP_sm4_ofb(void); +const EVP_CIPHER *EVP_sm4_ctr(void); +# endif + +# if OPENSSL_API_COMPAT < 0x10100000L +# define OPENSSL_add_all_algorithms_conf() \ + OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ + | OPENSSL_INIT_ADD_ALL_DIGESTS \ + | OPENSSL_INIT_LOAD_CONFIG, NULL) +# define OPENSSL_add_all_algorithms_noconf() \ + OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ + | OPENSSL_INIT_ADD_ALL_DIGESTS, NULL) + +# ifdef OPENSSL_LOAD_CONF +# define OpenSSL_add_all_algorithms() \ + OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ + | OPENSSL_INIT_ADD_ALL_DIGESTS \ + | OPENSSL_INIT_LOAD_CONFIG, NULL) +# else +# define OpenSSL_add_all_algorithms() \ + OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ + | OPENSSL_INIT_ADD_ALL_DIGESTS, NULL) +# endif + +# define OpenSSL_add_all_ciphers() \ + OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL) +# define OpenSSL_add_all_digests() \ + OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL) + +# define EVP_cleanup() while(0) continue +# endif + +int EVP_add_cipher(const EVP_CIPHER *cipher); +int EVP_add_digest(const EVP_MD *digest); + +const EVP_CIPHER *EVP_get_cipherbyname(const char *name); +const EVP_MD *EVP_get_digestbyname(const char *name); + +void EVP_CIPHER_do_all(void (*fn) (const EVP_CIPHER *ciph, + const char *from, const char *to, void *x), + void *arg); +void EVP_CIPHER_do_all_sorted(void (*fn) + (const EVP_CIPHER *ciph, const char *from, + const char *to, void *x), void *arg); + +void EVP_MD_do_all(void (*fn) (const EVP_MD *ciph, + const char *from, const char *to, void *x), + void *arg); +void EVP_MD_do_all_sorted(void (*fn) + (const EVP_MD *ciph, const char *from, + const char *to, void *x), void *arg); + +int EVP_PKEY_decrypt_old(unsigned char *dec_key, + const unsigned char *enc_key, int enc_key_len, + EVP_PKEY *private_key); +int EVP_PKEY_encrypt_old(unsigned char *enc_key, + const unsigned char *key, int key_len, + EVP_PKEY *pub_key); +int EVP_PKEY_type(int type); +int EVP_PKEY_id(const EVP_PKEY *pkey); +int EVP_PKEY_base_id(const EVP_PKEY *pkey); +int EVP_PKEY_bits(const EVP_PKEY *pkey); +int EVP_PKEY_security_bits(const EVP_PKEY *pkey); +int EVP_PKEY_size(EVP_PKEY *pkey); +int EVP_PKEY_set_type(EVP_PKEY *pkey, int type); +int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len); +int EVP_PKEY_set_alias_type(EVP_PKEY *pkey, int type); +# ifndef OPENSSL_NO_ENGINE +int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e); +# endif +int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key); +void *EVP_PKEY_get0(const EVP_PKEY *pkey); +const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len); +# ifndef OPENSSL_NO_POLY1305 +const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len); +# endif +# ifndef OPENSSL_NO_SIPHASH +const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len); +# endif + +# ifndef OPENSSL_NO_RSA +struct rsa_st; +int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, struct rsa_st *key); +struct rsa_st *EVP_PKEY_get0_RSA(EVP_PKEY *pkey); +struct rsa_st *EVP_PKEY_get1_RSA(EVP_PKEY *pkey); +# endif +# ifndef OPENSSL_NO_DSA +struct dsa_st; +int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, struct dsa_st *key); +struct dsa_st *EVP_PKEY_get0_DSA(EVP_PKEY *pkey); +struct dsa_st *EVP_PKEY_get1_DSA(EVP_PKEY *pkey); +# endif +# ifndef OPENSSL_NO_DH +struct dh_st; +int EVP_PKEY_set1_DH(EVP_PKEY *pkey, struct dh_st *key); +struct dh_st *EVP_PKEY_get0_DH(EVP_PKEY *pkey); +struct dh_st *EVP_PKEY_get1_DH(EVP_PKEY *pkey); +# endif +# ifndef OPENSSL_NO_EC +struct ec_key_st; +int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, struct ec_key_st *key); +struct ec_key_st *EVP_PKEY_get0_EC_KEY(EVP_PKEY *pkey); +struct ec_key_st *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey); +# endif + +EVP_PKEY *EVP_PKEY_new(void); +int EVP_PKEY_up_ref(EVP_PKEY *pkey); +void EVP_PKEY_free(EVP_PKEY *pkey); + +EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, const unsigned char **pp, + long length); +int i2d_PublicKey(EVP_PKEY *a, unsigned char **pp); + +EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **a, const unsigned char **pp, + long length); +EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **a, const unsigned char **pp, + long length); +int i2d_PrivateKey(EVP_PKEY *a, unsigned char **pp); + +int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from); +int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey); +int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode); +int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b); + +int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b); + +int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, + int indent, ASN1_PCTX *pctx); +int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, + int indent, ASN1_PCTX *pctx); +int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey, + int indent, ASN1_PCTX *pctx); + +int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid); + +int EVP_PKEY_set1_tls_encodedpoint(EVP_PKEY *pkey, + const unsigned char *pt, size_t ptlen); +size_t EVP_PKEY_get1_tls_encodedpoint(EVP_PKEY *pkey, unsigned char **ppt); + +int EVP_CIPHER_type(const EVP_CIPHER *ctx); + +/* calls methods */ +int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type); +int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type); + +/* These are used by EVP_CIPHER methods */ +int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type); +int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type); + +/* PKCS5 password based encryption */ +int PKCS5_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, + ASN1_TYPE *param, const EVP_CIPHER *cipher, + const EVP_MD *md, int en_de); +int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen, + const unsigned char *salt, int saltlen, int iter, + int keylen, unsigned char *out); +int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, + const unsigned char *salt, int saltlen, int iter, + const EVP_MD *digest, int keylen, unsigned char *out); +int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, + ASN1_TYPE *param, const EVP_CIPHER *cipher, + const EVP_MD *md, int en_de); + +#ifndef OPENSSL_NO_SCRYPT +int EVP_PBE_scrypt(const char *pass, size_t passlen, + const unsigned char *salt, size_t saltlen, + uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem, + unsigned char *key, size_t keylen); + +int PKCS5_v2_scrypt_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, + int passlen, ASN1_TYPE *param, + const EVP_CIPHER *c, const EVP_MD *md, int en_de); +#endif + +void PKCS5_PBE_add(void); + +int EVP_PBE_CipherInit(ASN1_OBJECT *pbe_obj, const char *pass, int passlen, + ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de); + +/* PBE type */ + +/* Can appear as the outermost AlgorithmIdentifier */ +# define EVP_PBE_TYPE_OUTER 0x0 +/* Is an PRF type OID */ +# define EVP_PBE_TYPE_PRF 0x1 +/* Is a PKCS#5 v2.0 KDF */ +# define EVP_PBE_TYPE_KDF 0x2 + +int EVP_PBE_alg_add_type(int pbe_type, int pbe_nid, int cipher_nid, + int md_nid, EVP_PBE_KEYGEN *keygen); +int EVP_PBE_alg_add(int nid, const EVP_CIPHER *cipher, const EVP_MD *md, + EVP_PBE_KEYGEN *keygen); +int EVP_PBE_find(int type, int pbe_nid, int *pcnid, int *pmnid, + EVP_PBE_KEYGEN **pkeygen); +void EVP_PBE_cleanup(void); +int EVP_PBE_get(int *ptype, int *ppbe_nid, size_t num); + +# define ASN1_PKEY_ALIAS 0x1 +# define ASN1_PKEY_DYNAMIC 0x2 +# define ASN1_PKEY_SIGPARAM_NULL 0x4 + +# define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 +# define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 +# define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 +# define ASN1_PKEY_CTRL_CMS_SIGN 0x5 +# define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 +# define ASN1_PKEY_CTRL_CMS_RI_TYPE 0x8 + +# define ASN1_PKEY_CTRL_SET1_TLS_ENCPT 0x9 +# define ASN1_PKEY_CTRL_GET1_TLS_ENCPT 0xa + +int EVP_PKEY_asn1_get_count(void); +const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); +const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find(ENGINE **pe, int type); +const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find_str(ENGINE **pe, + const char *str, int len); +int EVP_PKEY_asn1_add0(const EVP_PKEY_ASN1_METHOD *ameth); +int EVP_PKEY_asn1_add_alias(int to, int from); +int EVP_PKEY_asn1_get0_info(int *ppkey_id, int *pkey_base_id, + int *ppkey_flags, const char **pinfo, + const char **ppem_str, + const EVP_PKEY_ASN1_METHOD *ameth); + +const EVP_PKEY_ASN1_METHOD *EVP_PKEY_get0_asn1(const EVP_PKEY *pkey); +EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_new(int id, int flags, + const char *pem_str, + const char *info); +void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD *dst, + const EVP_PKEY_ASN1_METHOD *src); +void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD *ameth); +void EVP_PKEY_asn1_set_public(EVP_PKEY_ASN1_METHOD *ameth, + int (*pub_decode) (EVP_PKEY *pk, + X509_PUBKEY *pub), + int (*pub_encode) (X509_PUBKEY *pub, + const EVP_PKEY *pk), + int (*pub_cmp) (const EVP_PKEY *a, + const EVP_PKEY *b), + int (*pub_print) (BIO *out, + const EVP_PKEY *pkey, + int indent, ASN1_PCTX *pctx), + int (*pkey_size) (const EVP_PKEY *pk), + int (*pkey_bits) (const EVP_PKEY *pk)); +void EVP_PKEY_asn1_set_private(EVP_PKEY_ASN1_METHOD *ameth, + int (*priv_decode) (EVP_PKEY *pk, + const PKCS8_PRIV_KEY_INFO + *p8inf), + int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8, + const EVP_PKEY *pk), + int (*priv_print) (BIO *out, + const EVP_PKEY *pkey, + int indent, + ASN1_PCTX *pctx)); +void EVP_PKEY_asn1_set_param(EVP_PKEY_ASN1_METHOD *ameth, + int (*param_decode) (EVP_PKEY *pkey, + const unsigned char **pder, + int derlen), + int (*param_encode) (const EVP_PKEY *pkey, + unsigned char **pder), + int (*param_missing) (const EVP_PKEY *pk), + int (*param_copy) (EVP_PKEY *to, + const EVP_PKEY *from), + int (*param_cmp) (const EVP_PKEY *a, + const EVP_PKEY *b), + int (*param_print) (BIO *out, + const EVP_PKEY *pkey, + int indent, + ASN1_PCTX *pctx)); + +void EVP_PKEY_asn1_set_free(EVP_PKEY_ASN1_METHOD *ameth, + void (*pkey_free) (EVP_PKEY *pkey)); +void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_ctrl) (EVP_PKEY *pkey, int op, + long arg1, void *arg2)); +void EVP_PKEY_asn1_set_item(EVP_PKEY_ASN1_METHOD *ameth, + int (*item_verify) (EVP_MD_CTX *ctx, + const ASN1_ITEM *it, + void *asn, + X509_ALGOR *a, + ASN1_BIT_STRING *sig, + EVP_PKEY *pkey), + int (*item_sign) (EVP_MD_CTX *ctx, + const ASN1_ITEM *it, + void *asn, + X509_ALGOR *alg1, + X509_ALGOR *alg2, + ASN1_BIT_STRING *sig)); + +void EVP_PKEY_asn1_set_siginf(EVP_PKEY_ASN1_METHOD *ameth, + int (*siginf_set) (X509_SIG_INFO *siginf, + const X509_ALGOR *alg, + const ASN1_STRING *sig)); + +void EVP_PKEY_asn1_set_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_check) (const EVP_PKEY *pk)); + +void EVP_PKEY_asn1_set_public_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_pub_check) (const EVP_PKEY *pk)); + +void EVP_PKEY_asn1_set_param_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_param_check) (const EVP_PKEY *pk)); + +void EVP_PKEY_asn1_set_set_priv_key(EVP_PKEY_ASN1_METHOD *ameth, + int (*set_priv_key) (EVP_PKEY *pk, + const unsigned char + *priv, + size_t len)); +void EVP_PKEY_asn1_set_set_pub_key(EVP_PKEY_ASN1_METHOD *ameth, + int (*set_pub_key) (EVP_PKEY *pk, + const unsigned char *pub, + size_t len)); +void EVP_PKEY_asn1_set_get_priv_key(EVP_PKEY_ASN1_METHOD *ameth, + int (*get_priv_key) (const EVP_PKEY *pk, + unsigned char *priv, + size_t *len)); +void EVP_PKEY_asn1_set_get_pub_key(EVP_PKEY_ASN1_METHOD *ameth, + int (*get_pub_key) (const EVP_PKEY *pk, + unsigned char *pub, + size_t *len)); + +void EVP_PKEY_asn1_set_security_bits(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_security_bits) (const EVP_PKEY + *pk)); + +# define EVP_PKEY_OP_UNDEFINED 0 +# define EVP_PKEY_OP_PARAMGEN (1<<1) +# define EVP_PKEY_OP_KEYGEN (1<<2) +# define EVP_PKEY_OP_SIGN (1<<3) +# define EVP_PKEY_OP_VERIFY (1<<4) +# define EVP_PKEY_OP_VERIFYRECOVER (1<<5) +# define EVP_PKEY_OP_SIGNCTX (1<<6) +# define EVP_PKEY_OP_VERIFYCTX (1<<7) +# define EVP_PKEY_OP_ENCRYPT (1<<8) +# define EVP_PKEY_OP_DECRYPT (1<<9) +# define EVP_PKEY_OP_DERIVE (1<<10) + +# define EVP_PKEY_OP_TYPE_SIG \ + (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY | EVP_PKEY_OP_VERIFYRECOVER \ + | EVP_PKEY_OP_SIGNCTX | EVP_PKEY_OP_VERIFYCTX) + +# define EVP_PKEY_OP_TYPE_CRYPT \ + (EVP_PKEY_OP_ENCRYPT | EVP_PKEY_OP_DECRYPT) + +# define EVP_PKEY_OP_TYPE_NOGEN \ + (EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_DERIVE) + +# define EVP_PKEY_OP_TYPE_GEN \ + (EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN) + +# define EVP_PKEY_CTX_set_signature_md(ctx, md) \ + EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG, \ + EVP_PKEY_CTRL_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_get_signature_md(ctx, pmd) \ + EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_TYPE_SIG, \ + EVP_PKEY_CTRL_GET_MD, 0, (void *)(pmd)) + +# define EVP_PKEY_CTX_set_mac_key(ctx, key, len) \ + EVP_PKEY_CTX_ctrl(ctx, -1, EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_SET_MAC_KEY, len, (void *)(key)) + +# define EVP_PKEY_CTRL_MD 1 +# define EVP_PKEY_CTRL_PEER_KEY 2 + +# define EVP_PKEY_CTRL_PKCS7_ENCRYPT 3 +# define EVP_PKEY_CTRL_PKCS7_DECRYPT 4 + +# define EVP_PKEY_CTRL_PKCS7_SIGN 5 + +# define EVP_PKEY_CTRL_SET_MAC_KEY 6 + +# define EVP_PKEY_CTRL_DIGESTINIT 7 + +/* Used by GOST key encryption in TLS */ +# define EVP_PKEY_CTRL_SET_IV 8 + +# define EVP_PKEY_CTRL_CMS_ENCRYPT 9 +# define EVP_PKEY_CTRL_CMS_DECRYPT 10 +# define EVP_PKEY_CTRL_CMS_SIGN 11 + +# define EVP_PKEY_CTRL_CIPHER 12 + +# define EVP_PKEY_CTRL_GET_MD 13 + +# define EVP_PKEY_CTRL_SET_DIGEST_SIZE 14 + +# define EVP_PKEY_ALG_CTRL 0x1000 + +# define EVP_PKEY_FLAG_AUTOARGLEN 2 +/* + * Method handles all operations: don't assume any digest related defaults. + */ +# define EVP_PKEY_FLAG_SIGCTX_CUSTOM 4 + +const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type); +EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags); +void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags, + const EVP_PKEY_METHOD *meth); +void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src); +void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth); +int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth); +int EVP_PKEY_meth_remove(const EVP_PKEY_METHOD *pmeth); +size_t EVP_PKEY_meth_get_count(void); +const EVP_PKEY_METHOD *EVP_PKEY_meth_get0(size_t idx); + +EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e); +EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e); +EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *ctx); +void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx); + +int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, + int cmd, int p1, void *p2); +int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, + const char *value); +int EVP_PKEY_CTX_ctrl_uint64(EVP_PKEY_CTX *ctx, int keytype, int optype, + int cmd, uint64_t value); + +int EVP_PKEY_CTX_str2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *str); +int EVP_PKEY_CTX_hex2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *hex); + +int EVP_PKEY_CTX_md(EVP_PKEY_CTX *ctx, int optype, int cmd, const char *md); + +int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx); +void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX *ctx, int *dat, int datlen); + +EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *e, + const unsigned char *key, int keylen); +EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e, + const unsigned char *priv, + size_t len); +EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e, + const unsigned char *pub, + size_t len); +int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv, + size_t *len); +int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub, + size_t *len); + +EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv, + size_t len, const EVP_CIPHER *cipher); + +void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX *ctx, void *data); +void *EVP_PKEY_CTX_get_data(EVP_PKEY_CTX *ctx); +EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx); + +EVP_PKEY *EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX *ctx); + +void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data); +void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx); + +int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_sign(EVP_PKEY_CTX *ctx, + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen); +int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_verify(EVP_PKEY_CTX *ctx, + const unsigned char *sig, size_t siglen, + const unsigned char *tbs, size_t tbslen); +int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx, + unsigned char *rout, size_t *routlen, + const unsigned char *sig, size_t siglen); +int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, + unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); +int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, + unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); + +int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer); +int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen); + +typedef int EVP_PKEY_gen_cb(EVP_PKEY_CTX *ctx); + +int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); +int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx); +int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); +int EVP_PKEY_check(EVP_PKEY_CTX *ctx); +int EVP_PKEY_public_check(EVP_PKEY_CTX *ctx); +int EVP_PKEY_param_check(EVP_PKEY_CTX *ctx); + +void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX *ctx, EVP_PKEY_gen_cb *cb); +EVP_PKEY_gen_cb *EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX *ctx); + +int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx); + +void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth, + int (*init) (EVP_PKEY_CTX *ctx)); + +void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth, + int (*copy) (EVP_PKEY_CTX *dst, + EVP_PKEY_CTX *src)); + +void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth, + void (*cleanup) (EVP_PKEY_CTX *ctx)); + +void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD *pmeth, + int (*paramgen_init) (EVP_PKEY_CTX *ctx), + int (*paramgen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + +void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD *pmeth, + int (*keygen_init) (EVP_PKEY_CTX *ctx), + int (*keygen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + +void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD *pmeth, + int (*sign_init) (EVP_PKEY_CTX *ctx), + int (*sign) (EVP_PKEY_CTX *ctx, + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD *pmeth, + int (*verify_init) (EVP_PKEY_CTX *ctx), + int (*verify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + size_t siglen, + const unsigned char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD *pmeth, + int (*verify_recover_init) (EVP_PKEY_CTX + *ctx), + int (*verify_recover) (EVP_PKEY_CTX + *ctx, + unsigned char + *sig, + size_t *siglen, + const unsigned + char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD *pmeth, + int (*signctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (*signctx) (EVP_PKEY_CTX *ctx, + unsigned char *sig, + size_t *siglen, + EVP_MD_CTX *mctx)); + +void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD *pmeth, + int (*verifyctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (*verifyctx) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + int siglen, + EVP_MD_CTX *mctx)); + +void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD *pmeth, + int (*encrypt_init) (EVP_PKEY_CTX *ctx), + int (*encryptfn) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + +void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD *pmeth, + int (*decrypt_init) (EVP_PKEY_CTX *ctx), + int (*decrypt) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + +void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD *pmeth, + int (*derive_init) (EVP_PKEY_CTX *ctx), + int (*derive) (EVP_PKEY_CTX *ctx, + unsigned char *key, + size_t *keylen)); + +void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth, + int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1, + void *p2), + int (*ctrl_str) (EVP_PKEY_CTX *ctx, + const char *type, + const char *value)); + +void EVP_PKEY_meth_set_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)); + +void EVP_PKEY_meth_set_public_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)); + +void EVP_PKEY_meth_set_param_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)); + +void EVP_PKEY_meth_set_digest_custom(EVP_PKEY_METHOD *pmeth, + int (*digest_custom) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx)); + +void EVP_PKEY_meth_get_init(const EVP_PKEY_METHOD *pmeth, + int (**pinit) (EVP_PKEY_CTX *ctx)); + +void EVP_PKEY_meth_get_copy(const EVP_PKEY_METHOD *pmeth, + int (**pcopy) (EVP_PKEY_CTX *dst, + EVP_PKEY_CTX *src)); + +void EVP_PKEY_meth_get_cleanup(const EVP_PKEY_METHOD *pmeth, + void (**pcleanup) (EVP_PKEY_CTX *ctx)); + +void EVP_PKEY_meth_get_paramgen(const EVP_PKEY_METHOD *pmeth, + int (**pparamgen_init) (EVP_PKEY_CTX *ctx), + int (**pparamgen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + +void EVP_PKEY_meth_get_keygen(const EVP_PKEY_METHOD *pmeth, + int (**pkeygen_init) (EVP_PKEY_CTX *ctx), + int (**pkeygen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + +void EVP_PKEY_meth_get_sign(const EVP_PKEY_METHOD *pmeth, + int (**psign_init) (EVP_PKEY_CTX *ctx), + int (**psign) (EVP_PKEY_CTX *ctx, + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_get_verify(const EVP_PKEY_METHOD *pmeth, + int (**pverify_init) (EVP_PKEY_CTX *ctx), + int (**pverify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + size_t siglen, + const unsigned char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_get_verify_recover(const EVP_PKEY_METHOD *pmeth, + int (**pverify_recover_init) (EVP_PKEY_CTX + *ctx), + int (**pverify_recover) (EVP_PKEY_CTX + *ctx, + unsigned char + *sig, + size_t *siglen, + const unsigned + char *tbs, + size_t tbslen)); + +void EVP_PKEY_meth_get_signctx(const EVP_PKEY_METHOD *pmeth, + int (**psignctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**psignctx) (EVP_PKEY_CTX *ctx, + unsigned char *sig, + size_t *siglen, + EVP_MD_CTX *mctx)); + +void EVP_PKEY_meth_get_verifyctx(const EVP_PKEY_METHOD *pmeth, + int (**pverifyctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**pverifyctx) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + int siglen, + EVP_MD_CTX *mctx)); + +void EVP_PKEY_meth_get_encrypt(const EVP_PKEY_METHOD *pmeth, + int (**pencrypt_init) (EVP_PKEY_CTX *ctx), + int (**pencryptfn) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + +void EVP_PKEY_meth_get_decrypt(const EVP_PKEY_METHOD *pmeth, + int (**pdecrypt_init) (EVP_PKEY_CTX *ctx), + int (**pdecrypt) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + +void EVP_PKEY_meth_get_derive(const EVP_PKEY_METHOD *pmeth, + int (**pderive_init) (EVP_PKEY_CTX *ctx), + int (**pderive) (EVP_PKEY_CTX *ctx, + unsigned char *key, + size_t *keylen)); + +void EVP_PKEY_meth_get_ctrl(const EVP_PKEY_METHOD *pmeth, + int (**pctrl) (EVP_PKEY_CTX *ctx, int type, int p1, + void *p2), + int (**pctrl_str) (EVP_PKEY_CTX *ctx, + const char *type, + const char *value)); + +void EVP_PKEY_meth_get_check(const EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)); + +void EVP_PKEY_meth_get_public_check(const EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)); + +void EVP_PKEY_meth_get_param_check(const EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)); + +void EVP_PKEY_meth_get_digest_custom(EVP_PKEY_METHOD *pmeth, + int (**pdigest_custom) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx)); +void EVP_add_alg_module(void); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/evperr.h b/include/openssl/evperr.h new file mode 100644 index 0000000..3484fa8 --- /dev/null +++ b/include/openssl/evperr.h @@ -0,0 +1,193 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_EVPERR_H +# define HEADER_EVPERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_EVP_strings(void); + +/* + * EVP function codes. + */ +# define EVP_F_AESNI_INIT_KEY 165 +# define EVP_F_AES_GCM_CTRL 196 +# define EVP_F_AES_INIT_KEY 133 +# define EVP_F_AES_OCB_CIPHER 169 +# define EVP_F_AES_T4_INIT_KEY 178 +# define EVP_F_AES_WRAP_CIPHER 170 +# define EVP_F_ALG_MODULE_INIT 177 +# define EVP_F_ARIA_CCM_INIT_KEY 175 +# define EVP_F_ARIA_GCM_CTRL 197 +# define EVP_F_ARIA_GCM_INIT_KEY 176 +# define EVP_F_ARIA_INIT_KEY 185 +# define EVP_F_B64_NEW 198 +# define EVP_F_CAMELLIA_INIT_KEY 159 +# define EVP_F_CHACHA20_POLY1305_CTRL 182 +# define EVP_F_CMLL_T4_INIT_KEY 179 +# define EVP_F_DES_EDE3_WRAP_CIPHER 171 +# define EVP_F_DO_SIGVER_INIT 161 +# define EVP_F_ENC_NEW 199 +# define EVP_F_EVP_CIPHERINIT_EX 123 +# define EVP_F_EVP_CIPHER_ASN1_TO_PARAM 204 +# define EVP_F_EVP_CIPHER_CTX_COPY 163 +# define EVP_F_EVP_CIPHER_CTX_CTRL 124 +# define EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH 122 +# define EVP_F_EVP_CIPHER_PARAM_TO_ASN1 205 +# define EVP_F_EVP_DECRYPTFINAL_EX 101 +# define EVP_F_EVP_DECRYPTUPDATE 166 +# define EVP_F_EVP_DIGESTFINALXOF 174 +# define EVP_F_EVP_DIGESTINIT_EX 128 +# define EVP_F_EVP_ENCRYPTFINAL_EX 127 +# define EVP_F_EVP_ENCRYPTUPDATE 167 +# define EVP_F_EVP_MD_CTX_COPY_EX 110 +# define EVP_F_EVP_MD_SIZE 162 +# define EVP_F_EVP_OPENINIT 102 +# define EVP_F_EVP_PBE_ALG_ADD 115 +# define EVP_F_EVP_PBE_ALG_ADD_TYPE 160 +# define EVP_F_EVP_PBE_CIPHERINIT 116 +# define EVP_F_EVP_PBE_SCRYPT 181 +# define EVP_F_EVP_PKCS82PKEY 111 +# define EVP_F_EVP_PKEY2PKCS8 113 +# define EVP_F_EVP_PKEY_ASN1_ADD0 188 +# define EVP_F_EVP_PKEY_CHECK 186 +# define EVP_F_EVP_PKEY_COPY_PARAMETERS 103 +# define EVP_F_EVP_PKEY_CTX_CTRL 137 +# define EVP_F_EVP_PKEY_CTX_CTRL_STR 150 +# define EVP_F_EVP_PKEY_CTX_DUP 156 +# define EVP_F_EVP_PKEY_CTX_MD 168 +# define EVP_F_EVP_PKEY_DECRYPT 104 +# define EVP_F_EVP_PKEY_DECRYPT_INIT 138 +# define EVP_F_EVP_PKEY_DECRYPT_OLD 151 +# define EVP_F_EVP_PKEY_DERIVE 153 +# define EVP_F_EVP_PKEY_DERIVE_INIT 154 +# define EVP_F_EVP_PKEY_DERIVE_SET_PEER 155 +# define EVP_F_EVP_PKEY_ENCRYPT 105 +# define EVP_F_EVP_PKEY_ENCRYPT_INIT 139 +# define EVP_F_EVP_PKEY_ENCRYPT_OLD 152 +# define EVP_F_EVP_PKEY_GET0_DH 119 +# define EVP_F_EVP_PKEY_GET0_DSA 120 +# define EVP_F_EVP_PKEY_GET0_EC_KEY 131 +# define EVP_F_EVP_PKEY_GET0_HMAC 183 +# define EVP_F_EVP_PKEY_GET0_POLY1305 184 +# define EVP_F_EVP_PKEY_GET0_RSA 121 +# define EVP_F_EVP_PKEY_GET0_SIPHASH 172 +# define EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY 202 +# define EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY 203 +# define EVP_F_EVP_PKEY_KEYGEN 146 +# define EVP_F_EVP_PKEY_KEYGEN_INIT 147 +# define EVP_F_EVP_PKEY_METH_ADD0 194 +# define EVP_F_EVP_PKEY_METH_NEW 195 +# define EVP_F_EVP_PKEY_NEW 106 +# define EVP_F_EVP_PKEY_NEW_CMAC_KEY 193 +# define EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY 191 +# define EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY 192 +# define EVP_F_EVP_PKEY_PARAMGEN 148 +# define EVP_F_EVP_PKEY_PARAMGEN_INIT 149 +# define EVP_F_EVP_PKEY_PARAM_CHECK 189 +# define EVP_F_EVP_PKEY_PUBLIC_CHECK 190 +# define EVP_F_EVP_PKEY_SET1_ENGINE 187 +# define EVP_F_EVP_PKEY_SET_ALIAS_TYPE 206 +# define EVP_F_EVP_PKEY_SIGN 140 +# define EVP_F_EVP_PKEY_SIGN_INIT 141 +# define EVP_F_EVP_PKEY_VERIFY 142 +# define EVP_F_EVP_PKEY_VERIFY_INIT 143 +# define EVP_F_EVP_PKEY_VERIFY_RECOVER 144 +# define EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT 145 +# define EVP_F_EVP_SIGNFINAL 107 +# define EVP_F_EVP_VERIFYFINAL 108 +# define EVP_F_INT_CTX_NEW 157 +# define EVP_F_OK_NEW 200 +# define EVP_F_PKCS5_PBE_KEYIVGEN 117 +# define EVP_F_PKCS5_V2_PBE_KEYIVGEN 118 +# define EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN 164 +# define EVP_F_PKCS5_V2_SCRYPT_KEYIVGEN 180 +# define EVP_F_PKEY_SET_TYPE 158 +# define EVP_F_RC2_MAGIC_TO_METH 109 +# define EVP_F_RC5_CTRL 125 +# define EVP_F_S390X_AES_GCM_CTRL 201 +# define EVP_F_UPDATE 173 + +/* + * EVP reason codes. + */ +# define EVP_R_AES_KEY_SETUP_FAILED 143 +# define EVP_R_ARIA_KEY_SETUP_FAILED 176 +# define EVP_R_BAD_DECRYPT 100 +# define EVP_R_BUFFER_TOO_SMALL 155 +# define EVP_R_CAMELLIA_KEY_SETUP_FAILED 157 +# define EVP_R_CIPHER_PARAMETER_ERROR 122 +# define EVP_R_COMMAND_NOT_SUPPORTED 147 +# define EVP_R_COPY_ERROR 173 +# define EVP_R_CTRL_NOT_IMPLEMENTED 132 +# define EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED 133 +# define EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH 138 +# define EVP_R_DECODE_ERROR 114 +# define EVP_R_DIFFERENT_KEY_TYPES 101 +# define EVP_R_DIFFERENT_PARAMETERS 153 +# define EVP_R_ERROR_LOADING_SECTION 165 +# define EVP_R_ERROR_SETTING_FIPS_MODE 166 +# define EVP_R_EXPECTING_AN_HMAC_KEY 174 +# define EVP_R_EXPECTING_AN_RSA_KEY 127 +# define EVP_R_EXPECTING_A_DH_KEY 128 +# define EVP_R_EXPECTING_A_DSA_KEY 129 +# define EVP_R_EXPECTING_A_EC_KEY 142 +# define EVP_R_EXPECTING_A_POLY1305_KEY 164 +# define EVP_R_EXPECTING_A_SIPHASH_KEY 175 +# define EVP_R_FIPS_MODE_NOT_SUPPORTED 167 +# define EVP_R_GET_RAW_KEY_FAILED 182 +# define EVP_R_ILLEGAL_SCRYPT_PARAMETERS 171 +# define EVP_R_INITIALIZATION_ERROR 134 +# define EVP_R_INPUT_NOT_INITIALIZED 111 +# define EVP_R_INVALID_DIGEST 152 +# define EVP_R_INVALID_FIPS_MODE 168 +# define EVP_R_INVALID_KEY 163 +# define EVP_R_INVALID_KEY_LENGTH 130 +# define EVP_R_INVALID_OPERATION 148 +# define EVP_R_KEYGEN_FAILURE 120 +# define EVP_R_KEY_SETUP_FAILED 180 +# define EVP_R_MEMORY_LIMIT_EXCEEDED 172 +# define EVP_R_MESSAGE_DIGEST_IS_NULL 159 +# define EVP_R_METHOD_NOT_SUPPORTED 144 +# define EVP_R_MISSING_PARAMETERS 103 +# define EVP_R_NOT_XOF_OR_INVALID_LENGTH 178 +# define EVP_R_NO_CIPHER_SET 131 +# define EVP_R_NO_DEFAULT_DIGEST 158 +# define EVP_R_NO_DIGEST_SET 139 +# define EVP_R_NO_KEY_SET 154 +# define EVP_R_NO_OPERATION_SET 149 +# define EVP_R_ONLY_ONESHOT_SUPPORTED 177 +# define EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 150 +# define EVP_R_OPERATON_NOT_INITIALIZED 151 +# define EVP_R_PARTIALLY_OVERLAPPING 162 +# define EVP_R_PBKDF2_ERROR 181 +# define EVP_R_PKEY_APPLICATION_ASN1_METHOD_ALREADY_REGISTERED 179 +# define EVP_R_PRIVATE_KEY_DECODE_ERROR 145 +# define EVP_R_PRIVATE_KEY_ENCODE_ERROR 146 +# define EVP_R_PUBLIC_KEY_NOT_RSA 106 +# define EVP_R_UNKNOWN_CIPHER 160 +# define EVP_R_UNKNOWN_DIGEST 161 +# define EVP_R_UNKNOWN_OPTION 169 +# define EVP_R_UNKNOWN_PBE_ALGORITHM 121 +# define EVP_R_UNSUPPORTED_ALGORITHM 156 +# define EVP_R_UNSUPPORTED_CIPHER 107 +# define EVP_R_UNSUPPORTED_KEYLENGTH 123 +# define EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION 124 +# define EVP_R_UNSUPPORTED_KEY_SIZE 108 +# define EVP_R_UNSUPPORTED_NUMBER_OF_ROUNDS 135 +# define EVP_R_UNSUPPORTED_PRF 125 +# define EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM 118 +# define EVP_R_UNSUPPORTED_SALT_TYPE 126 +# define EVP_R_WRAP_MODE_NOT_ALLOWED 170 +# define EVP_R_WRONG_FINAL_BLOCK_LENGTH 109 + +#endif diff --git a/include/openssl/hmac.h b/include/openssl/hmac.h new file mode 100644 index 0000000..6a5df31 --- /dev/null +++ b/include/openssl/hmac.h @@ -0,0 +1,51 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_HMAC_H +# define HEADER_HMAC_H + +# include + +# include + +# if OPENSSL_API_COMPAT < 0x10200000L +# define HMAC_MAX_MD_CBLOCK 128 /* Deprecated */ +# endif + +#ifdef __cplusplus +extern "C" { +#endif + +size_t HMAC_size(const HMAC_CTX *e); +HMAC_CTX *HMAC_CTX_new(void); +int HMAC_CTX_reset(HMAC_CTX *ctx); +void HMAC_CTX_free(HMAC_CTX *ctx); + +DEPRECATEDIN_1_1_0(__owur int HMAC_Init(HMAC_CTX *ctx, const void *key, int len, + const EVP_MD *md)) + +/*__owur*/ int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len, + const EVP_MD *md, ENGINE *impl); +/*__owur*/ int HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, + size_t len); +/*__owur*/ int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, + unsigned int *len); +unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len, + const unsigned char *d, size_t n, unsigned char *md, + unsigned int *md_len); +__owur int HMAC_CTX_copy(HMAC_CTX *dctx, HMAC_CTX *sctx); + +void HMAC_CTX_set_flags(HMAC_CTX *ctx, unsigned long flags); +const EVP_MD *HMAC_CTX_get_md(const HMAC_CTX *ctx); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/idea.h b/include/openssl/idea.h new file mode 100644 index 0000000..2f58933 --- /dev/null +++ b/include/openssl/idea.h @@ -0,0 +1,64 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_IDEA_H +# define HEADER_IDEA_H + +# include + +# ifndef OPENSSL_NO_IDEA +# ifdef __cplusplus +extern "C" { +# endif + +typedef unsigned int IDEA_INT; + +# define IDEA_ENCRYPT 1 +# define IDEA_DECRYPT 0 + +# define IDEA_BLOCK 8 +# define IDEA_KEY_LENGTH 16 + +typedef struct idea_key_st { + IDEA_INT data[9][6]; +} IDEA_KEY_SCHEDULE; + +const char *IDEA_options(void); +void IDEA_ecb_encrypt(const unsigned char *in, unsigned char *out, + IDEA_KEY_SCHEDULE *ks); +void IDEA_set_encrypt_key(const unsigned char *key, IDEA_KEY_SCHEDULE *ks); +void IDEA_set_decrypt_key(IDEA_KEY_SCHEDULE *ek, IDEA_KEY_SCHEDULE *dk); +void IDEA_cbc_encrypt(const unsigned char *in, unsigned char *out, + long length, IDEA_KEY_SCHEDULE *ks, unsigned char *iv, + int enc); +void IDEA_cfb64_encrypt(const unsigned char *in, unsigned char *out, + long length, IDEA_KEY_SCHEDULE *ks, unsigned char *iv, + int *num, int enc); +void IDEA_ofb64_encrypt(const unsigned char *in, unsigned char *out, + long length, IDEA_KEY_SCHEDULE *ks, unsigned char *iv, + int *num); +void IDEA_encrypt(unsigned long *in, IDEA_KEY_SCHEDULE *ks); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define idea_options IDEA_options +# define idea_ecb_encrypt IDEA_ecb_encrypt +# define idea_set_encrypt_key IDEA_set_encrypt_key +# define idea_set_decrypt_key IDEA_set_decrypt_key +# define idea_cbc_encrypt IDEA_cbc_encrypt +# define idea_cfb64_encrypt IDEA_cfb64_encrypt +# define idea_ofb64_encrypt IDEA_ofb64_encrypt +# define idea_encrypt IDEA_encrypt +# endif + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/internal/__DECC_INCLUDE_EPILOGUE.H b/include/openssl/internal/__DECC_INCLUDE_EPILOGUE.H new file mode 100644 index 0000000..c350018 --- /dev/null +++ b/include/openssl/internal/__DECC_INCLUDE_EPILOGUE.H @@ -0,0 +1,16 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* restore state. Must correspond to the save in __decc_include_prologue.h */ +#pragma names restore diff --git a/include/openssl/internal/__DECC_INCLUDE_PROLOGUE.H b/include/openssl/internal/__DECC_INCLUDE_PROLOGUE.H new file mode 100644 index 0000000..9a9c777 --- /dev/null +++ b/include/openssl/internal/__DECC_INCLUDE_PROLOGUE.H @@ -0,0 +1,20 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* save state */ +#pragma names save +/* have the compiler shorten symbols larger than 31 chars to 23 chars + * followed by a 8 hex char CRC + */ +#pragma names as_is,shortened diff --git a/include/openssl/internal/bio.h b/include/openssl/internal/bio.h new file mode 100644 index 0000000..ac529f0 --- /dev/null +++ b/include/openssl/internal/bio.h @@ -0,0 +1,33 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +struct bio_method_st { + int type; + char *name; + int (*bwrite) (BIO *, const char *, size_t, size_t *); + int (*bwrite_old) (BIO *, const char *, int); + int (*bread) (BIO *, char *, size_t, size_t *); + int (*bread_old) (BIO *, char *, int); + int (*bputs) (BIO *, const char *); + int (*bgets) (BIO *, char *, int); + long (*ctrl) (BIO *, int, long, void *); + int (*create) (BIO *); + int (*destroy) (BIO *); + long (*callback_ctrl) (BIO *, int, BIO_info_cb *); +}; + +void bio_free_ex_data(BIO *bio); +void bio_cleanup(void); + + +/* Old style to new style BIO_METHOD conversion functions */ +int bwrite_conv(BIO *bio, const char *data, size_t datal, size_t *written); +int bread_conv(BIO *bio, char *data, size_t datal, size_t *read); diff --git a/include/openssl/internal/comp.h b/include/openssl/internal/comp.h new file mode 100644 index 0000000..890af11 --- /dev/null +++ b/include/openssl/internal/comp.h @@ -0,0 +1,12 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +void comp_zlib_cleanup_int(void); diff --git a/include/openssl/internal/conf.h b/include/openssl/internal/conf.h new file mode 100644 index 0000000..4cb9d30 --- /dev/null +++ b/include/openssl/internal/conf.h @@ -0,0 +1,23 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_INTERNAL_CONF_H +# define HEADER_INTERNAL_CONF_H + +#include + +struct ossl_init_settings_st { + char *appname; +}; + +void openssl_config_int(const char *appname); +void openssl_no_config_int(void); +void conf_modules_free_int(void); + +#endif diff --git a/include/openssl/internal/constant_time_locl.h b/include/openssl/internal/constant_time_locl.h new file mode 100644 index 0000000..5794969 --- /dev/null +++ b/include/openssl/internal/constant_time_locl.h @@ -0,0 +1,327 @@ +/* + * Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CONSTANT_TIME_LOCL_H +# define HEADER_CONSTANT_TIME_LOCL_H + +# include +# include +# include /* For 'ossl_inline' */ + +/*- + * The boolean methods return a bitmask of all ones (0xff...f) for true + * and 0 for false. This is useful for choosing a value based on the result + * of a conditional in constant time. For example, + * if (a < b) { + * c = a; + * } else { + * c = b; + * } + * can be written as + * unsigned int lt = constant_time_lt(a, b); + * c = constant_time_select(lt, a, b); + */ + +/* Returns the given value with the MSB copied to all the other bits. */ +static ossl_inline unsigned int constant_time_msb(unsigned int a); +/* Convenience method for uint32_t. */ +static ossl_inline uint32_t constant_time_msb_32(uint32_t a); +/* Convenience method for uint64_t. */ +static ossl_inline uint64_t constant_time_msb_64(uint64_t a); + +/* Returns 0xff..f if a < b and 0 otherwise. */ +static ossl_inline unsigned int constant_time_lt(unsigned int a, + unsigned int b); +/* Convenience method for getting an 8-bit mask. */ +static ossl_inline unsigned char constant_time_lt_8(unsigned int a, + unsigned int b); +/* Convenience method for uint64_t. */ +static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b); + +/* Returns 0xff..f if a >= b and 0 otherwise. */ +static ossl_inline unsigned int constant_time_ge(unsigned int a, + unsigned int b); +/* Convenience method for getting an 8-bit mask. */ +static ossl_inline unsigned char constant_time_ge_8(unsigned int a, + unsigned int b); + +/* Returns 0xff..f if a == 0 and 0 otherwise. */ +static ossl_inline unsigned int constant_time_is_zero(unsigned int a); +/* Convenience method for getting an 8-bit mask. */ +static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a); +/* Convenience method for getting a 32-bit mask. */ +static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a); + +/* Returns 0xff..f if a == b and 0 otherwise. */ +static ossl_inline unsigned int constant_time_eq(unsigned int a, + unsigned int b); +/* Convenience method for getting an 8-bit mask. */ +static ossl_inline unsigned char constant_time_eq_8(unsigned int a, + unsigned int b); +/* Signed integers. */ +static ossl_inline unsigned int constant_time_eq_int(int a, int b); +/* Convenience method for getting an 8-bit mask. */ +static ossl_inline unsigned char constant_time_eq_int_8(int a, int b); + +/*- + * Returns (mask & a) | (~mask & b). + * + * When |mask| is all 1s or all 0s (as returned by the methods above), + * the select methods return either |a| (if |mask| is nonzero) or |b| + * (if |mask| is zero). + */ +static ossl_inline unsigned int constant_time_select(unsigned int mask, + unsigned int a, + unsigned int b); +/* Convenience method for unsigned chars. */ +static ossl_inline unsigned char constant_time_select_8(unsigned char mask, + unsigned char a, + unsigned char b); + +/* Convenience method for uint32_t. */ +static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a, + uint32_t b); + +/* Convenience method for uint64_t. */ +static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a, + uint64_t b); +/* Convenience method for signed integers. */ +static ossl_inline int constant_time_select_int(unsigned int mask, int a, + int b); + + +static ossl_inline unsigned int constant_time_msb(unsigned int a) +{ + return 0 - (a >> (sizeof(a) * 8 - 1)); +} + + +static ossl_inline uint32_t constant_time_msb_32(uint32_t a) +{ + return 0 - (a >> 31); +} + +static ossl_inline uint64_t constant_time_msb_64(uint64_t a) +{ + return 0 - (a >> 63); +} + +static ossl_inline size_t constant_time_msb_s(size_t a) +{ + return 0 - (a >> (sizeof(a) * 8 - 1)); +} + +static ossl_inline unsigned int constant_time_lt(unsigned int a, + unsigned int b) +{ + return constant_time_msb(a ^ ((a ^ b) | ((a - b) ^ b))); +} + +static ossl_inline size_t constant_time_lt_s(size_t a, size_t b) +{ + return constant_time_msb_s(a ^ ((a ^ b) | ((a - b) ^ b))); +} + +static ossl_inline unsigned char constant_time_lt_8(unsigned int a, + unsigned int b) +{ + return (unsigned char)constant_time_lt(a, b); +} + +static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b) +{ + return constant_time_msb_64(a ^ ((a ^ b) | ((a - b) ^ b))); +} + +static ossl_inline unsigned int constant_time_ge(unsigned int a, + unsigned int b) +{ + return ~constant_time_lt(a, b); +} + +static ossl_inline size_t constant_time_ge_s(size_t a, size_t b) +{ + return ~constant_time_lt_s(a, b); +} + +static ossl_inline unsigned char constant_time_ge_8(unsigned int a, + unsigned int b) +{ + return (unsigned char)constant_time_ge(a, b); +} + +static ossl_inline unsigned char constant_time_ge_8_s(size_t a, size_t b) +{ + return (unsigned char)constant_time_ge_s(a, b); +} + +static ossl_inline unsigned int constant_time_is_zero(unsigned int a) +{ + return constant_time_msb(~a & (a - 1)); +} + +static ossl_inline size_t constant_time_is_zero_s(size_t a) +{ + return constant_time_msb_s(~a & (a - 1)); +} + +static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a) +{ + return (unsigned char)constant_time_is_zero(a); +} + +static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a) +{ + return constant_time_msb_32(~a & (a - 1)); +} + +static ossl_inline unsigned int constant_time_eq(unsigned int a, + unsigned int b) +{ + return constant_time_is_zero(a ^ b); +} + +static ossl_inline size_t constant_time_eq_s(size_t a, size_t b) +{ + return constant_time_is_zero_s(a ^ b); +} + +static ossl_inline unsigned char constant_time_eq_8(unsigned int a, + unsigned int b) +{ + return (unsigned char)constant_time_eq(a, b); +} + +static ossl_inline unsigned char constant_time_eq_8_s(size_t a, size_t b) +{ + return (unsigned char)constant_time_eq_s(a, b); +} + +static ossl_inline unsigned int constant_time_eq_int(int a, int b) +{ + return constant_time_eq((unsigned)(a), (unsigned)(b)); +} + +static ossl_inline unsigned char constant_time_eq_int_8(int a, int b) +{ + return constant_time_eq_8((unsigned)(a), (unsigned)(b)); +} + +static ossl_inline unsigned int constant_time_select(unsigned int mask, + unsigned int a, + unsigned int b) +{ + return (mask & a) | (~mask & b); +} + +static ossl_inline size_t constant_time_select_s(size_t mask, + size_t a, + size_t b) +{ + return (mask & a) | (~mask & b); +} + +static ossl_inline unsigned char constant_time_select_8(unsigned char mask, + unsigned char a, + unsigned char b) +{ + return (unsigned char)constant_time_select(mask, a, b); +} + +static ossl_inline int constant_time_select_int(unsigned int mask, int a, + int b) +{ + return (int)constant_time_select(mask, (unsigned)(a), (unsigned)(b)); +} + +static ossl_inline int constant_time_select_int_s(size_t mask, int a, int b) +{ + return (int)constant_time_select((unsigned)mask, (unsigned)(a), + (unsigned)(b)); +} + +static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a, + uint32_t b) +{ + return (mask & a) | (~mask & b); +} + +static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a, + uint64_t b) +{ + return (mask & a) | (~mask & b); +} + +/* + * mask must be 0xFFFFFFFF or 0x00000000. + * + * if (mask) { + * uint32_t tmp = *a; + * + * *a = *b; + * *b = tmp; + * } + */ +static ossl_inline void constant_time_cond_swap_32(uint32_t mask, uint32_t *a, + uint32_t *b) +{ + uint32_t xor = *a ^ *b; + + xor &= mask; + *a ^= xor; + *b ^= xor; +} + +/* + * mask must be 0xFFFFFFFF or 0x00000000. + * + * if (mask) { + * uint64_t tmp = *a; + * + * *a = *b; + * *b = tmp; + * } + */ +static ossl_inline void constant_time_cond_swap_64(uint64_t mask, uint64_t *a, + uint64_t *b) +{ + uint64_t xor = *a ^ *b; + + xor &= mask; + *a ^= xor; + *b ^= xor; +} + +/* + * table is a two dimensional array of bytes. Each row has rowsize elements. + * Copies row number idx into out. rowsize and numrows are not considered + * private. + */ +static ossl_inline void constant_time_lookup(void *out, + const void *table, + size_t rowsize, + size_t numrows, + size_t idx) +{ + size_t i, j; + const unsigned char *tablec = (const unsigned char *)table; + unsigned char *outc = (unsigned char *)out; + unsigned char mask; + + memset(out, 0, rowsize); + + /* Note idx may underflow - but that is well defined */ + for (i = 0; i < numrows; i++, idx--) { + mask = (unsigned char)constant_time_is_zero_s(idx); + for (j = 0; j < rowsize; j++) + *(outc + j) |= constant_time_select_8(mask, *(tablec++), 0); + } +} + +#endif /* HEADER_CONSTANT_TIME_LOCL_H */ diff --git a/include/openssl/internal/cryptlib.h b/include/openssl/internal/cryptlib.h new file mode 100644 index 0000000..87592a7 --- /dev/null +++ b/include/openssl/internal/cryptlib.h @@ -0,0 +1,94 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CRYPTLIB_H +# define HEADER_CRYPTLIB_H + +# include +# include + +# ifdef OPENSSL_USE_APPLINK +# undef BIO_FLAGS_UPLINK +# define BIO_FLAGS_UPLINK 0x8000 +# include "ms/uplink.h" +# endif + +# include +# include +# include +# include +# include "internal/nelem.h" + +#ifdef NDEBUG +# define ossl_assert(x) ((x) != 0) +#else +__owur static ossl_inline int ossl_assert_int(int expr, const char *exprstr, + const char *file, int line) +{ + if (!expr) + OPENSSL_die(exprstr, file, line); + + return expr; +} + +# define ossl_assert(x) ossl_assert_int((x) != 0, "Assertion failed: "#x, \ + __FILE__, __LINE__) + +#endif + +typedef struct ex_callback_st EX_CALLBACK; + +DEFINE_STACK_OF(EX_CALLBACK) + +typedef struct app_mem_info_st APP_INFO; + +typedef struct mem_st MEM; +DEFINE_LHASH_OF(MEM); + +# define OPENSSL_CONF "openssl.cnf" + +# ifndef OPENSSL_SYS_VMS +# define X509_CERT_AREA OPENSSLDIR +# define X509_CERT_DIR OPENSSLDIR "/certs" +# define X509_CERT_FILE OPENSSLDIR "/cert.pem" +# define X509_PRIVATE_DIR OPENSSLDIR "/private" +# define CTLOG_FILE OPENSSLDIR "/ct_log_list.cnf" +# else +# define X509_CERT_AREA "OSSL$DATAROOT:[000000]" +# define X509_CERT_DIR "OSSL$DATAROOT:[CERTS]" +# define X509_CERT_FILE "OSSL$DATAROOT:[000000]cert.pem" +# define X509_PRIVATE_DIR "OSSL$DATAROOT:[PRIVATE]" +# define CTLOG_FILE "OSSL$DATAROOT:[000000]ct_log_list.cnf" +# endif + +# define X509_CERT_DIR_EVP "SSL_CERT_DIR" +# define X509_CERT_FILE_EVP "SSL_CERT_FILE" +# define CTLOG_FILE_EVP "CTLOG_FILE" + +/* size of string representations */ +# define DECIMAL_SIZE(type) ((sizeof(type)*8+2)/3+1) +# define HEX_SIZE(type) (sizeof(type)*2) + +void OPENSSL_cpuid_setup(void); +extern unsigned int OPENSSL_ia32cap_P[]; +void OPENSSL_showfatal(const char *fmta, ...); +void crypto_cleanup_all_ex_data_int(void); +int openssl_init_fork_handlers(void); + +extern CRYPTO_RWLOCK *memdbg_lock; +int openssl_strerror_r(int errnum, char *buf, size_t buflen); +# if !defined(OPENSSL_NO_STDIO) +FILE *openssl_fopen(const char *filename, const char *mode); +# else +void *openssl_fopen(const char *filename, const char *mode); +# endif + +uint32_t OPENSSL_rdtsc(void); + +#endif diff --git a/include/openssl/internal/dane.h b/include/openssl/internal/dane.h new file mode 100644 index 0000000..c4a6b62 --- /dev/null +++ b/include/openssl/internal/dane.h @@ -0,0 +1,103 @@ +/* + * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_INTERNAL_DANE_H +#define HEADER_INTERNAL_DANE_H + +#include + +/*- + * Certificate usages: + * https://tools.ietf.org/html/rfc6698#section-2.1.1 + */ +#define DANETLS_USAGE_PKIX_TA 0 +#define DANETLS_USAGE_PKIX_EE 1 +#define DANETLS_USAGE_DANE_TA 2 +#define DANETLS_USAGE_DANE_EE 3 +#define DANETLS_USAGE_LAST DANETLS_USAGE_DANE_EE + +/*- + * Selectors: + * https://tools.ietf.org/html/rfc6698#section-2.1.2 + */ +#define DANETLS_SELECTOR_CERT 0 +#define DANETLS_SELECTOR_SPKI 1 +#define DANETLS_SELECTOR_LAST DANETLS_SELECTOR_SPKI + +/*- + * Matching types: + * https://tools.ietf.org/html/rfc6698#section-2.1.3 + */ +#define DANETLS_MATCHING_FULL 0 +#define DANETLS_MATCHING_2256 1 +#define DANETLS_MATCHING_2512 2 +#define DANETLS_MATCHING_LAST DANETLS_MATCHING_2512 + +typedef struct danetls_record_st { + uint8_t usage; + uint8_t selector; + uint8_t mtype; + unsigned char *data; + size_t dlen; + EVP_PKEY *spki; +} danetls_record; + +DEFINE_STACK_OF(danetls_record) + +/* + * Shared DANE context + */ +struct dane_ctx_st { + const EVP_MD **mdevp; /* mtype -> digest */ + uint8_t *mdord; /* mtype -> preference */ + uint8_t mdmax; /* highest supported mtype */ + unsigned long flags; /* feature bitmask */ +}; + +/* + * Per connection DANE state + */ +struct ssl_dane_st { + struct dane_ctx_st *dctx; + STACK_OF(danetls_record) *trecs; + STACK_OF(X509) *certs; /* DANE-TA(2) Cert(0) Full(0) certs */ + danetls_record *mtlsa; /* Matching TLSA record */ + X509 *mcert; /* DANE matched cert */ + uint32_t umask; /* Usages present */ + int mdpth; /* Depth of matched cert */ + int pdpth; /* Depth of PKIX trust */ + unsigned long flags; /* feature bitmask */ +}; + +#define DANETLS_ENABLED(dane) \ + ((dane) != NULL && sk_danetls_record_num((dane)->trecs) > 0) + +#define DANETLS_USAGE_BIT(u) (((uint32_t)1) << u) + +#define DANETLS_PKIX_TA_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_PKIX_TA)) +#define DANETLS_PKIX_EE_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_PKIX_EE)) +#define DANETLS_DANE_TA_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_DANE_TA)) +#define DANETLS_DANE_EE_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_DANE_EE)) + +#define DANETLS_PKIX_MASK (DANETLS_PKIX_TA_MASK | DANETLS_PKIX_EE_MASK) +#define DANETLS_DANE_MASK (DANETLS_DANE_TA_MASK | DANETLS_DANE_EE_MASK) +#define DANETLS_TA_MASK (DANETLS_PKIX_TA_MASK | DANETLS_DANE_TA_MASK) +#define DANETLS_EE_MASK (DANETLS_PKIX_EE_MASK | DANETLS_DANE_EE_MASK) + +#define DANETLS_HAS_PKIX(dane) ((dane) && ((dane)->umask & DANETLS_PKIX_MASK)) +#define DANETLS_HAS_DANE(dane) ((dane) && ((dane)->umask & DANETLS_DANE_MASK)) +#define DANETLS_HAS_TA(dane) ((dane) && ((dane)->umask & DANETLS_TA_MASK)) +#define DANETLS_HAS_EE(dane) ((dane) && ((dane)->umask & DANETLS_EE_MASK)) + +#define DANETLS_HAS_PKIX_TA(dane) ((dane)&&((dane)->umask & DANETLS_PKIX_TA_MASK)) +#define DANETLS_HAS_PKIX_EE(dane) ((dane)&&((dane)->umask & DANETLS_PKIX_EE_MASK)) +#define DANETLS_HAS_DANE_TA(dane) ((dane)&&((dane)->umask & DANETLS_DANE_TA_MASK)) +#define DANETLS_HAS_DANE_EE(dane) ((dane)&&((dane)->umask & DANETLS_DANE_EE_MASK)) + +#endif /* HEADER_INTERNAL_DANE_H */ diff --git a/include/openssl/internal/dso.h b/include/openssl/internal/dso.h new file mode 100644 index 0000000..861d9cb --- /dev/null +++ b/include/openssl/internal/dso.h @@ -0,0 +1,165 @@ +/* + * Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DSO_H +# define HEADER_DSO_H + +# include +# include "internal/dsoerr.h" + +/* These values are used as commands to DSO_ctrl() */ +# define DSO_CTRL_GET_FLAGS 1 +# define DSO_CTRL_SET_FLAGS 2 +# define DSO_CTRL_OR_FLAGS 3 + +/* + * By default, DSO_load() will translate the provided filename into a form + * typical for the platform using the dso_name_converter function of the + * method. Eg. win32 will transform "blah" into "blah.dll", and dlfcn will + * transform it into "libblah.so". This callback could even utilise the + * DSO_METHOD's converter too if it only wants to override behaviour for + * one or two possible DSO methods. However, the following flag can be + * set in a DSO to prevent *any* native name-translation at all - eg. if + * the caller has prompted the user for a path to a driver library so the + * filename should be interpreted as-is. + */ +# define DSO_FLAG_NO_NAME_TRANSLATION 0x01 +/* + * An extra flag to give if only the extension should be added as + * translation. This is obviously only of importance on Unix and other + * operating systems where the translation also may prefix the name with + * something, like 'lib', and ignored everywhere else. This flag is also + * ignored if DSO_FLAG_NO_NAME_TRANSLATION is used at the same time. + */ +# define DSO_FLAG_NAME_TRANSLATION_EXT_ONLY 0x02 + +/* + * Don't unload the DSO when we call DSO_free() + */ +# define DSO_FLAG_NO_UNLOAD_ON_FREE 0x04 + +/* + * This flag loads the library with public symbols. Meaning: The exported + * symbols of this library are public to all libraries loaded after this + * library. At the moment only implemented in unix. + */ +# define DSO_FLAG_GLOBAL_SYMBOLS 0x20 + +typedef void (*DSO_FUNC_TYPE) (void); + +typedef struct dso_st DSO; +typedef struct dso_meth_st DSO_METHOD; + +/* + * The function prototype used for method functions (or caller-provided + * callbacks) that transform filenames. They are passed a DSO structure + * pointer (or NULL if they are to be used independently of a DSO object) and + * a filename to transform. They should either return NULL (if there is an + * error condition) or a newly allocated string containing the transformed + * form that the caller will need to free with OPENSSL_free() when done. + */ +typedef char *(*DSO_NAME_CONVERTER_FUNC)(DSO *, const char *); +/* + * The function prototype used for method functions (or caller-provided + * callbacks) that merge two file specifications. They are passed a DSO + * structure pointer (or NULL if they are to be used independently of a DSO + * object) and two file specifications to merge. They should either return + * NULL (if there is an error condition) or a newly allocated string + * containing the result of merging that the caller will need to free with + * OPENSSL_free() when done. Here, merging means that bits and pieces are + * taken from each of the file specifications and added together in whatever + * fashion that is sensible for the DSO method in question. The only rule + * that really applies is that if the two specification contain pieces of the + * same type, the copy from the first string takes priority. One could see + * it as the first specification is the one given by the user and the second + * being a bunch of defaults to add on if they're missing in the first. + */ +typedef char *(*DSO_MERGER_FUNC)(DSO *, const char *, const char *); + +DSO *DSO_new(void); +int DSO_free(DSO *dso); +int DSO_flags(DSO *dso); +int DSO_up_ref(DSO *dso); +long DSO_ctrl(DSO *dso, int cmd, long larg, void *parg); + +/* + * These functions can be used to get/set the platform-independent filename + * used for a DSO. NB: set will fail if the DSO is already loaded. + */ +const char *DSO_get_filename(DSO *dso); +int DSO_set_filename(DSO *dso, const char *filename); +/* + * This function will invoke the DSO's name_converter callback to translate a + * filename, or if the callback isn't set it will instead use the DSO_METHOD's + * converter. If "filename" is NULL, the "filename" in the DSO itself will be + * used. If the DSO_FLAG_NO_NAME_TRANSLATION flag is set, then the filename is + * simply duplicated. NB: This function is usually called from within a + * DSO_METHOD during the processing of a DSO_load() call, and is exposed so + * that caller-created DSO_METHODs can do the same thing. A non-NULL return + * value will need to be OPENSSL_free()'d. + */ +char *DSO_convert_filename(DSO *dso, const char *filename); +/* + * This function will invoke the DSO's merger callback to merge two file + * specifications, or if the callback isn't set it will instead use the + * DSO_METHOD's merger. A non-NULL return value will need to be + * OPENSSL_free()'d. + */ +char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2); + +/* + * The all-singing all-dancing load function, you normally pass NULL for the + * first and third parameters. Use DSO_up_ref and DSO_free for subsequent + * reference count handling. Any flags passed in will be set in the + * constructed DSO after its init() function but before the load operation. + * If 'dso' is non-NULL, 'flags' is ignored. + */ +DSO *DSO_load(DSO *dso, const char *filename, DSO_METHOD *meth, int flags); + +/* This function binds to a function inside a shared library. */ +DSO_FUNC_TYPE DSO_bind_func(DSO *dso, const char *symname); + +/* + * This method is the default, but will beg, borrow, or steal whatever method + * should be the default on any particular platform (including + * DSO_METH_null() if necessary). + */ +DSO_METHOD *DSO_METHOD_openssl(void); + +/* + * This function writes null-terminated pathname of DSO module containing + * 'addr' into 'sz' large caller-provided 'path' and returns the number of + * characters [including trailing zero] written to it. If 'sz' is 0 or + * negative, 'path' is ignored and required amount of characters [including + * trailing zero] to accommodate pathname is returned. If 'addr' is NULL, then + * pathname of cryptolib itself is returned. Negative or zero return value + * denotes error. + */ +int DSO_pathbyaddr(void *addr, char *path, int sz); + +/* + * Like DSO_pathbyaddr() but instead returns a handle to the DSO for the symbol + * or NULL on error. + */ +DSO *DSO_dsobyaddr(void *addr, int flags); + +/* + * This function should be used with caution! It looks up symbols in *all* + * loaded modules and if module gets unloaded by somebody else attempt to + * dereference the pointer is doomed to have fatal consequences. Primary + * usage for this function is to probe *core* system functionality, e.g. + * check if getnameinfo(3) is available at run-time without bothering about + * OS-specific details such as libc.so.versioning or where does it actually + * reside: in libc itself or libsocket. + */ +void *DSO_global_lookup(const char *name); + +int ERR_load_DSO_strings(void); + +#endif diff --git a/include/openssl/internal/dsoerr.h b/include/openssl/internal/dsoerr.h new file mode 100644 index 0000000..4bef713 --- /dev/null +++ b/include/openssl/internal/dsoerr.h @@ -0,0 +1,83 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DSOERR_H +# define HEADER_DSOERR_H + +# include + +# ifndef OPENSSL_NO_DSO + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_DSO_strings(void); + +/* + * DSO function codes. + */ +# define DSO_F_DLFCN_BIND_FUNC 100 +# define DSO_F_DLFCN_LOAD 102 +# define DSO_F_DLFCN_MERGER 130 +# define DSO_F_DLFCN_NAME_CONVERTER 123 +# define DSO_F_DLFCN_UNLOAD 103 +# define DSO_F_DL_BIND_FUNC 104 +# define DSO_F_DL_LOAD 106 +# define DSO_F_DL_MERGER 131 +# define DSO_F_DL_NAME_CONVERTER 124 +# define DSO_F_DL_UNLOAD 107 +# define DSO_F_DSO_BIND_FUNC 108 +# define DSO_F_DSO_CONVERT_FILENAME 126 +# define DSO_F_DSO_CTRL 110 +# define DSO_F_DSO_FREE 111 +# define DSO_F_DSO_GET_FILENAME 127 +# define DSO_F_DSO_GLOBAL_LOOKUP 139 +# define DSO_F_DSO_LOAD 112 +# define DSO_F_DSO_MERGE 132 +# define DSO_F_DSO_NEW_METHOD 113 +# define DSO_F_DSO_PATHBYADDR 105 +# define DSO_F_DSO_SET_FILENAME 129 +# define DSO_F_DSO_UP_REF 114 +# define DSO_F_VMS_BIND_SYM 115 +# define DSO_F_VMS_LOAD 116 +# define DSO_F_VMS_MERGER 133 +# define DSO_F_VMS_UNLOAD 117 +# define DSO_F_WIN32_BIND_FUNC 101 +# define DSO_F_WIN32_GLOBALLOOKUP 142 +# define DSO_F_WIN32_JOINER 135 +# define DSO_F_WIN32_LOAD 120 +# define DSO_F_WIN32_MERGER 134 +# define DSO_F_WIN32_NAME_CONVERTER 125 +# define DSO_F_WIN32_PATHBYADDR 109 +# define DSO_F_WIN32_SPLITTER 136 +# define DSO_F_WIN32_UNLOAD 121 + +/* + * DSO reason codes. + */ +# define DSO_R_CTRL_FAILED 100 +# define DSO_R_DSO_ALREADY_LOADED 110 +# define DSO_R_EMPTY_FILE_STRUCTURE 113 +# define DSO_R_FAILURE 114 +# define DSO_R_FILENAME_TOO_BIG 101 +# define DSO_R_FINISH_FAILED 102 +# define DSO_R_INCORRECT_FILE_SYNTAX 115 +# define DSO_R_LOAD_FAILED 103 +# define DSO_R_NAME_TRANSLATION_FAILED 109 +# define DSO_R_NO_FILENAME 111 +# define DSO_R_NULL_HANDLE 104 +# define DSO_R_SET_FILENAME_FAILED 112 +# define DSO_R_STACK_ERROR 105 +# define DSO_R_SYM_FAILURE 106 +# define DSO_R_UNLOAD_FAILED 107 +# define DSO_R_UNSUPPORTED 108 + +# endif +#endif diff --git a/include/openssl/internal/err.h b/include/openssl/internal/err.h new file mode 100644 index 0000000..d46b8bd --- /dev/null +++ b/include/openssl/internal/err.h @@ -0,0 +1,15 @@ +/* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef INTERNAL_ERR_H +# define INTERNAL_ERR_H + +void err_free_strings_int(void); + +#endif diff --git a/include/openssl/internal/nelem.h b/include/openssl/internal/nelem.h new file mode 100644 index 0000000..d65a21a --- /dev/null +++ b/include/openssl/internal/nelem.h @@ -0,0 +1,14 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_NELEM_H +# define HEADER_NELEM_H + +# define OSSL_NELEM(x) (sizeof(x)/sizeof((x)[0])) +#endif diff --git a/include/openssl/internal/numbers.h b/include/openssl/internal/numbers.h new file mode 100644 index 0000000..31931df --- /dev/null +++ b/include/openssl/internal/numbers.h @@ -0,0 +1,68 @@ +/* + * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_NUMBERS_H +# define HEADER_NUMBERS_H + +# include + +# if (-1 & 3) == 0x03 /* Two's complement */ + +# define __MAXUINT__(T) ((T) -1) +# define __MAXINT__(T) ((T) ((((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)) ^ __MAXUINT__(T))) +# define __MININT__(T) (-__MAXINT__(T) - 1) + +# elif (-1 & 3) == 0x02 /* One's complement */ + +# define __MAXUINT__(T) (((T) -1) + 1) +# define __MAXINT__(T) ((T) ((((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)) ^ __MAXUINT__(T))) +# define __MININT__(T) (-__MAXINT__(T)) + +# elif (-1 & 3) == 0x01 /* Sign/magnitude */ + +# define __MAXINT__(T) ((T) (((((T) 1) << ((sizeof(T) * CHAR_BIT) - 2)) - 1) | (((T) 1) << ((sizeof(T) * CHAR_BIT) - 2)))) +# define __MAXUINT__(T) ((T) (__MAXINT__(T) | (((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)))) +# define __MININT__(T) (-__MAXINT__(T)) + +# else + +# error "do not know the integer encoding on this architecture" + +# endif + +# ifndef INT8_MAX +# define INT8_MIN __MININT__(int8_t) +# define INT8_MAX __MAXINT__(int8_t) +# define UINT8_MAX __MAXUINT__(uint8_t) +# endif + +# ifndef INT16_MAX +# define INT16_MIN __MININT__(int16_t) +# define INT16_MAX __MAXINT__(int16_t) +# define UINT16_MAX __MAXUINT__(uint16_t) +# endif + +# ifndef INT32_MAX +# define INT32_MIN __MININT__(int32_t) +# define INT32_MAX __MAXINT__(int32_t) +# define UINT32_MAX __MAXUINT__(uint32_t) +# endif + +# ifndef INT64_MAX +# define INT64_MIN __MININT__(int64_t) +# define INT64_MAX __MAXINT__(int64_t) +# define UINT64_MAX __MAXUINT__(uint64_t) +# endif + +# ifndef SIZE_MAX +# define SIZE_MAX __MAXUINT__(size_t) +# endif + +#endif + diff --git a/include/openssl/internal/o_dir.h b/include/openssl/internal/o_dir.h new file mode 100644 index 0000000..e7b55e0 --- /dev/null +++ b/include/openssl/internal/o_dir.h @@ -0,0 +1,52 @@ +/* + * Copyright 2004-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * This file is dual-licensed and is also available under the following + * terms: + * + * Copyright (c) 2004, Richard Levitte + * All rights reserved. + * + * 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifndef O_DIR_H +# define O_DIR_H + +typedef struct OPENSSL_dir_context_st OPENSSL_DIR_CTX; + +/* + * returns NULL on error or end-of-directory. If it is end-of-directory, + * errno will be zero + */ +const char *OPENSSL_DIR_read(OPENSSL_DIR_CTX **ctx, const char *directory); +/* returns 1 on success, 0 on error */ +int OPENSSL_DIR_end(OPENSSL_DIR_CTX **ctx); + +#endif /* LPDIR_H */ diff --git a/include/openssl/internal/o_str.h b/include/openssl/internal/o_str.h new file mode 100644 index 0000000..86403c9 --- /dev/null +++ b/include/openssl/internal/o_str.h @@ -0,0 +1,17 @@ +/* + * Copyright 2003-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_O_STR_H +# define HEADER_O_STR_H + +# include /* to get size_t */ + +int OPENSSL_memcmp(const void *p1, const void *p2, size_t n); + +#endif diff --git a/include/openssl/internal/refcount.h b/include/openssl/internal/refcount.h new file mode 100644 index 0000000..75d70a6 --- /dev/null +++ b/include/openssl/internal/refcount.h @@ -0,0 +1,140 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ +#ifndef HEADER_INTERNAL_REFCOUNT_H +# define HEADER_INTERNAL_REFCOUNT_H + +/* Used to checking reference counts, most while doing perl5 stuff :-) */ +# if defined(OPENSSL_NO_STDIO) +# if defined(REF_PRINT) +# error "REF_PRINT requires stdio" +# endif +# endif + +# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \ + && !defined(__STDC_NO_ATOMICS__) +# include +# define HAVE_C11_ATOMICS +# endif + +# if defined(HAVE_C11_ATOMICS) && defined(ATOMIC_INT_LOCK_FREE) \ + && ATOMIC_INT_LOCK_FREE > 0 + +# define HAVE_ATOMICS 1 + +typedef _Atomic int CRYPTO_REF_COUNT; + +static inline int CRYPTO_UP_REF(_Atomic int *val, int *ret, void *lock) +{ + *ret = atomic_fetch_add_explicit(val, 1, memory_order_relaxed) + 1; + return 1; +} + +/* + * Changes to shared structure other than reference counter have to be + * serialized. And any kind of serialization implies a release fence. This + * means that by the time reference counter is decremented all other + * changes are visible on all processors. Hence decrement itself can be + * relaxed. In case it hits zero, object will be destructed. Since it's + * last use of the object, destructor programmer might reason that access + * to mutable members doesn't have to be serialized anymore, which would + * otherwise imply an acquire fence. Hence conditional acquire fence... + */ +static inline int CRYPTO_DOWN_REF(_Atomic int *val, int *ret, void *lock) +{ + *ret = atomic_fetch_sub_explicit(val, 1, memory_order_relaxed) - 1; + if (*ret == 0) + atomic_thread_fence(memory_order_acquire); + return 1; +} + +# elif defined(__GNUC__) && defined(__ATOMIC_RELAXED) && __GCC_ATOMIC_INT_LOCK_FREE > 0 + +# define HAVE_ATOMICS 1 + +typedef int CRYPTO_REF_COUNT; + +static __inline__ int CRYPTO_UP_REF(int *val, int *ret, void *lock) +{ + *ret = __atomic_fetch_add(val, 1, __ATOMIC_RELAXED) + 1; + return 1; +} + +static __inline__ int CRYPTO_DOWN_REF(int *val, int *ret, void *lock) +{ + *ret = __atomic_fetch_sub(val, 1, __ATOMIC_RELAXED) - 1; + if (*ret == 0) + __atomic_thread_fence(__ATOMIC_ACQUIRE); + return 1; +} + +# elif defined(_MSC_VER) && _MSC_VER>=1200 + +# define HAVE_ATOMICS 1 + +typedef volatile int CRYPTO_REF_COUNT; + +# if (defined(_M_ARM) && _M_ARM>=7) || defined(_M_ARM64) +# include +# if defined(_M_ARM64) && !defined(_ARM_BARRIER_ISH) +# define _ARM_BARRIER_ISH _ARM64_BARRIER_ISH +# endif + +static __inline int CRYPTO_UP_REF(volatile int *val, int *ret, void *lock) +{ + *ret = _InterlockedExchangeAdd_nf(val, 1) + 1; + return 1; +} + +static __inline int CRYPTO_DOWN_REF(volatile int *val, int *ret, void *lock) +{ + *ret = _InterlockedExchangeAdd_nf(val, -1) - 1; + if (*ret == 0) + __dmb(_ARM_BARRIER_ISH); + return 1; +} +# else +# pragma intrinsic(_InterlockedExchangeAdd) + +static __inline int CRYPTO_UP_REF(volatile int *val, int *ret, void *lock) +{ + *ret = _InterlockedExchangeAdd(val, 1) + 1; + return 1; +} + +static __inline int CRYPTO_DOWN_REF(volatile int *val, int *ret, void *lock) +{ + *ret = _InterlockedExchangeAdd(val, -1) - 1; + return 1; +} +# endif + +# else + +typedef int CRYPTO_REF_COUNT; + +# define CRYPTO_UP_REF(val, ret, lock) CRYPTO_atomic_add(val, 1, ret, lock) +# define CRYPTO_DOWN_REF(val, ret, lock) CRYPTO_atomic_add(val, -1, ret, lock) + +# endif + +# if !defined(NDEBUG) && !defined(OPENSSL_NO_STDIO) +# define REF_ASSERT_ISNT(test) \ + (void)((test) ? (OPENSSL_die("refcount error", __FILE__, __LINE__), 1) : 0) +# else +# define REF_ASSERT_ISNT(i) +# endif + +# ifdef REF_PRINT +# define REF_PRINT_COUNT(a, b) \ + fprintf(stderr, "%p:%4d:%s\n", b, b->references, a) +# else +# define REF_PRINT_COUNT(a, b) +# endif + +#endif diff --git a/include/openssl/internal/sockets.h b/include/openssl/internal/sockets.h new file mode 100644 index 0000000..a6026da --- /dev/null +++ b/include/openssl/internal/sockets.h @@ -0,0 +1,159 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + + +#ifndef HEADER_INTERNAL_SOCKETS +# define HEADER_INTERNAL_SOCKETS + +# if defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI) +# define NO_SYS_PARAM_H +# endif +# ifdef WIN32 +# define NO_SYS_UN_H +# endif +# ifdef OPENSSL_SYS_VMS +# define NO_SYS_PARAM_H +# define NO_SYS_UN_H +# endif + +# ifdef OPENSSL_NO_SOCK + +# elif defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) +# if defined(__DJGPP__) +# include +# include +# include +# include +# elif defined(_WIN32_WCE) && _WIN32_WCE<410 +# define getservbyname _masked_declaration_getservbyname +# endif +# if !defined(IPPROTO_IP) + /* winsock[2].h was included already? */ +# include +# endif +# ifdef getservbyname + /* this is used to be wcecompat/include/winsock_extras.h */ +# undef getservbyname +struct servent *PASCAL getservbyname(const char *, const char *); +# endif + +# ifdef _WIN64 +/* + * Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because + * the value constitutes an index in per-process table of limited size + * and not a real pointer. And we also depend on fact that all processors + * Windows run on happen to be two's-complement, which allows to + * interchange INVALID_SOCKET and -1. + */ +# define socket(d,t,p) ((int)socket(d,t,p)) +# define accept(s,f,l) ((int)accept(s,f,l)) +# endif + +# else + +# ifndef NO_SYS_PARAM_H +# include +# endif +# ifdef OPENSSL_SYS_VXWORKS +# include +# endif + +# include +# if defined(OPENSSL_SYS_VMS_NODECC) +# include +# include +# include +# else +# include +# ifndef NO_SYS_UN_H +# ifdef OPENSSL_SYS_VXWORKS +# include +# else +# include +# endif +# ifndef UNIX_PATH_MAX +# define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)NULL)->sun_path) +# endif +# endif +# ifdef FILIO_H +# include /* FIONBIO in some SVR4, e.g. unixware, solaris */ +# endif +# include +# include +# include +# endif + +# ifdef OPENSSL_SYS_AIX +# include +# endif + +# ifndef VMS +# include +# else +# if !defined(TCPIP_TYPE_SOCKETSHR) && defined(__VMS_VER) && (__VMS_VER > 70000000) + /* ioctl is only in VMS > 7.0 and when socketshr is not used */ +# include +# endif +# include +# if defined(TCPIP_TYPE_SOCKETSHR) +# include +# endif +# endif + +# ifndef INVALID_SOCKET +# define INVALID_SOCKET (-1) +# endif +# endif + +/* + * Some IPv6 implementations are broken, you can disable them in known + * bad versions. + */ +# if !defined(OPENSSL_USE_IPV6) +# if defined(AF_INET6) +# define OPENSSL_USE_IPV6 1 +# else +# define OPENSSL_USE_IPV6 0 +# endif +# endif + +# define get_last_socket_error() errno +# define clear_socket_error() errno=0 + +# if defined(OPENSSL_SYS_WINDOWS) +# undef get_last_socket_error +# undef clear_socket_error +# define get_last_socket_error() WSAGetLastError() +# define clear_socket_error() WSASetLastError(0) +# define readsocket(s,b,n) recv((s),(b),(n),0) +# define writesocket(s,b,n) send((s),(b),(n),0) +# elif defined(__DJGPP__) +# define WATT32 +# define WATT32_NO_OLDIES +# define closesocket(s) close_s(s) +# define readsocket(s,b,n) read_s(s,b,n) +# define writesocket(s,b,n) send(s,b,n,0) +# elif defined(OPENSSL_SYS_VMS) +# define ioctlsocket(a,b,c) ioctl(a,b,c) +# define closesocket(s) close(s) +# define readsocket(s,b,n) recv((s),(b),(n),0) +# define writesocket(s,b,n) send((s),(b),(n),0) +# elif defined(OPENSSL_SYS_VXWORKS) +# define ioctlsocket(a,b,c) ioctl((a),(b),(int)(c)) +# define closesocket(s) close(s) +# define readsocket(s,b,n) read((s),(b),(n)) +# define writesocket(s,b,n) write((s),(char *)(b),(n)) +# else +# define ioctlsocket(a,b,c) ioctl(a,b,c) +# define closesocket(s) close(s) +# define readsocket(s,b,n) read((s),(b),(n)) +# define writesocket(s,b,n) write((s),(b),(n)) +# endif + +#endif diff --git a/include/openssl/internal/sslconf.h b/include/openssl/internal/sslconf.h new file mode 100644 index 0000000..d538f86 --- /dev/null +++ b/include/openssl/internal/sslconf.h @@ -0,0 +1,20 @@ +/* + * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SSLCONF_H +# define HEADER_SSLCONF_H + +typedef struct ssl_conf_cmd_st SSL_CONF_CMD; + +const SSL_CONF_CMD *conf_ssl_get(size_t idx, const char **name, size_t *cnt); +int conf_ssl_name_find(const char *name, size_t *idx); +void conf_ssl_get_cmd(const SSL_CONF_CMD *cmd, size_t idx, char **cmdstr, + char **arg); + +#endif diff --git a/include/openssl/internal/thread_once.h b/include/openssl/internal/thread_once.h new file mode 100644 index 0000000..a79628d --- /dev/null +++ b/include/openssl/internal/thread_once.h @@ -0,0 +1,45 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +#define DEFINE_RUN_ONCE(init) \ + static int init(void); \ + int init##_ossl_ret_ = 0; \ + void init##_ossl_(void) \ + { \ + init##_ossl_ret_ = init(); \ + } \ + static int init(void) +#define DECLARE_RUN_ONCE(init) \ + extern int init##_ossl_ret_; \ + void init##_ossl_(void); + +#define DEFINE_RUN_ONCE_STATIC(init) \ + static int init(void); \ + static int init##_ossl_ret_ = 0; \ + static void init##_ossl_(void) \ + { \ + init##_ossl_ret_ = init(); \ + } \ + static int init(void) + +/* + * RUN_ONCE - use CRYPTO_THREAD_run_once, and check if the init succeeded + * @once: pointer to static object of type CRYPTO_ONCE + * @init: function name that was previously given to DEFINE_RUN_ONCE, + * DEFINE_RUN_ONCE_STATIC or DECLARE_RUN_ONCE. This function + * must return 1 for success or 0 for failure. + * + * The return value is 1 on success (*) or 0 in case of error. + * + * (*) by convention, since the init function must return 1 on success. + */ +#define RUN_ONCE(once, init) \ + (CRYPTO_THREAD_run_once(once, init##_ossl_) ? init##_ossl_ret_ : 0) diff --git a/include/openssl/internal/tsan_assist.h b/include/openssl/internal/tsan_assist.h new file mode 100644 index 0000000..2c76383 --- /dev/null +++ b/include/openssl/internal/tsan_assist.h @@ -0,0 +1,138 @@ +/* + * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * Contemporary compilers implement lock-free atomic memory access + * primitives that facilitate writing "thread-opportunistic" or even real + * multi-threading low-overhead code. "Thread-opportunistic" is when + * exact result is not required, e.g. some statistics, or execution flow + * doesn't have to be unambiguous. Simplest example is lazy "constant" + * initialization when one can synchronize on variable itself, e.g. + * + * if (var == NOT_YET_INITIALIZED) + * var = function_returning_same_value(); + * + * This does work provided that loads and stores are single-instuction + * operations (and integer ones are on *all* supported platforms), but + * it upsets Thread Sanitizer. Suggested solution is + * + * if (tsan_load(&var) == NOT_YET_INITIALIZED) + * tsan_store(&var, function_returning_same_value()); + * + * Production machine code would be the same, so one can wonder why + * bother. Having Thread Sanitizer accept "thread-opportunistic" code + * allows to move on trouble-shooting real bugs. + * + * Resolving Thread Sanitizer nits was the initial purpose for this module, + * but it was later extended with more nuanced primitives that are useful + * even in "non-opportunistic" scenarios. Most notably verifying if a shared + * structure is fully initialized and bypassing the initialization lock. + * It's suggested to view macros defined in this module as "annotations" for + * thread-safe lock-free code, "Thread-Safe ANnotations"... + * + * It's assumed that ATOMIC_{LONG|INT}_LOCK_FREE are assigned same value as + * ATOMIC_POINTER_LOCK_FREE. And check for >= 2 ensures that corresponding + * code is inlined. It should be noted that statistics counters become + * accurate in such case. + * + * Special note about TSAN_QUALIFIER. It might be undesired to use it in + * a shared header. Because whether operation on specific variable or member + * is atomic or not might be irrelevant in other modules. In such case one + * can use TSAN_QUALIFIER in cast specifically when it has to count. + */ + +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \ + && !defined(__STDC_NO_ATOMICS__) +# include + +# if defined(ATOMIC_POINTER_LOCK_FREE) \ + && ATOMIC_POINTER_LOCK_FREE >= 2 +# define TSAN_QUALIFIER _Atomic +# define tsan_load(ptr) atomic_load_explicit((ptr), memory_order_relaxed) +# define tsan_store(ptr, val) atomic_store_explicit((ptr), (val), memory_order_relaxed) +# define tsan_counter(ptr) atomic_fetch_add_explicit((ptr), 1, memory_order_relaxed) +# define tsan_ld_acq(ptr) atomic_load_explicit((ptr), memory_order_acquire) +# define tsan_st_rel(ptr, val) atomic_store_explicit((ptr), (val), memory_order_release) +# endif + +#elif defined(__GNUC__) && defined(__ATOMIC_RELAXED) + +# if defined(__GCC_ATOMIC_POINTER_LOCK_FREE) \ + && __GCC_ATOMIC_POINTER_LOCK_FREE >= 2 +# define TSAN_QUALIFIER volatile +# define tsan_load(ptr) __atomic_load_n((ptr), __ATOMIC_RELAXED) +# define tsan_store(ptr, val) __atomic_store_n((ptr), (val), __ATOMIC_RELAXED) +# define tsan_counter(ptr) __atomic_fetch_add((ptr), 1, __ATOMIC_RELAXED) +# define tsan_ld_acq(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE) +# define tsan_st_rel(ptr, val) __atomic_store_n((ptr), (val), __ATOMIC_RELEASE) +# endif + +#elif defined(_MSC_VER) && _MSC_VER>=1200 \ + && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64) || \ + defined(_M_ARM64) || (defined(_M_ARM) && _M_ARM >= 7)) +/* + * There is subtle dependency on /volatile: command-line option. + * "ms" implies same semantic as memory_order_acquire for loads and + * memory_order_release for stores, while "iso" - memory_order_relaxed for + * either. Real complication is that defaults are different on x86 and ARM. + * There is explanation for that, "ms" is backward compatible with earlier + * compiler versions, while multi-processor ARM can be viewed as brand new + * platform to MSC and its users, and with non-relaxed semantic taking toll + * with additional instructions and penalties, it kind of makes sense to + * default to "iso"... + */ +# define TSAN_QUALIFIER volatile +# if defined(_M_ARM) || defined(_M_ARM64) +# define _InterlockedExchangeAdd _InterlockedExchangeAdd_nf +# pragma intrinsic(_InterlockedExchangeAdd_nf) +# pragma intrinsic(__iso_volatile_load32, __iso_volatile_store32) +# ifdef _WIN64 +# define _InterlockedExchangeAdd64 _InterlockedExchangeAdd64_nf +# pragma intrinsic(_InterlockedExchangeAdd64_nf) +# pragma intrinsic(__iso_volatile_load64, __iso_volatile_store64) +# define tsan_load(ptr) (sizeof(*(ptr)) == 8 ? __iso_volatile_load64(ptr) \ + : __iso_volatile_load32(ptr)) +# define tsan_store(ptr, val) (sizeof(*(ptr)) == 8 ? __iso_volatile_store64((ptr), (val)) \ + : __iso_volatile_store32((ptr), (val))) +# else +# define tsan_load(ptr) __iso_volatile_load32(ptr) +# define tsan_store(ptr, val) __iso_volatile_store32((ptr), (val)) +# endif +# else +# define tsan_load(ptr) (*(ptr)) +# define tsan_store(ptr, val) (*(ptr) = (val)) +# endif +# pragma intrinsic(_InterlockedExchangeAdd) +# ifdef _WIN64 +# pragma intrinsic(_InterlockedExchangeAdd64) +# define tsan_counter(ptr) (sizeof(*(ptr)) == 8 ? _InterlockedExchangeAdd64((ptr), 1) \ + : _InterlockedExchangeAdd((ptr), 1)) +# else +# define tsan_counter(ptr) _InterlockedExchangeAdd((ptr), 1) +# endif +# if !defined(_ISO_VOLATILE) +# define tsan_ld_acq(ptr) (*(ptr)) +# define tsan_st_rel(ptr, val) (*(ptr) = (val)) +# endif + +#endif + +#ifndef TSAN_QUALIFIER + +# define TSAN_QUALIFIER volatile +# define tsan_load(ptr) (*(ptr)) +# define tsan_store(ptr, val) (*(ptr) = (val)) +# define tsan_counter(ptr) ((*(ptr))++) +/* + * Lack of tsan_ld_acq and tsan_ld_rel means that compiler support is not + * sophisticated enough to support them. Code that relies on them should be + * protected with #ifdef tsan_ld_acq with locked fallback. + */ + +#endif diff --git a/include/openssl/kdf.h b/include/openssl/kdf.h new file mode 100644 index 0000000..d61dd81 --- /dev/null +++ b/include/openssl/kdf.h @@ -0,0 +1,97 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_KDF_H +# define HEADER_KDF_H + +# include +#ifdef __cplusplus +extern "C" { +#endif + +# define EVP_PKEY_CTRL_TLS_MD (EVP_PKEY_ALG_CTRL) +# define EVP_PKEY_CTRL_TLS_SECRET (EVP_PKEY_ALG_CTRL + 1) +# define EVP_PKEY_CTRL_TLS_SEED (EVP_PKEY_ALG_CTRL + 2) +# define EVP_PKEY_CTRL_HKDF_MD (EVP_PKEY_ALG_CTRL + 3) +# define EVP_PKEY_CTRL_HKDF_SALT (EVP_PKEY_ALG_CTRL + 4) +# define EVP_PKEY_CTRL_HKDF_KEY (EVP_PKEY_ALG_CTRL + 5) +# define EVP_PKEY_CTRL_HKDF_INFO (EVP_PKEY_ALG_CTRL + 6) +# define EVP_PKEY_CTRL_HKDF_MODE (EVP_PKEY_ALG_CTRL + 7) +# define EVP_PKEY_CTRL_PASS (EVP_PKEY_ALG_CTRL + 8) +# define EVP_PKEY_CTRL_SCRYPT_SALT (EVP_PKEY_ALG_CTRL + 9) +# define EVP_PKEY_CTRL_SCRYPT_N (EVP_PKEY_ALG_CTRL + 10) +# define EVP_PKEY_CTRL_SCRYPT_R (EVP_PKEY_ALG_CTRL + 11) +# define EVP_PKEY_CTRL_SCRYPT_P (EVP_PKEY_ALG_CTRL + 12) +# define EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES (EVP_PKEY_ALG_CTRL + 13) + +# define EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND 0 +# define EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY 1 +# define EVP_PKEY_HKDEF_MODE_EXPAND_ONLY 2 + +# define EVP_PKEY_CTX_set_tls1_prf_md(pctx, md) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_TLS_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, sec, seclen) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_TLS_SECRET, seclen, (void *)(sec)) + +# define EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed, seedlen) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_TLS_SEED, seedlen, (void *)(seed)) + +# define EVP_PKEY_CTX_set_hkdf_md(pctx, md) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_HKDF_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltlen) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_HKDF_SALT, saltlen, (void *)(salt)) + +# define EVP_PKEY_CTX_set1_hkdf_key(pctx, key, keylen) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_HKDF_KEY, keylen, (void *)(key)) + +# define EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infolen) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_HKDF_INFO, infolen, (void *)(info)) + +# define EVP_PKEY_CTX_hkdf_mode(pctx, mode) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_HKDF_MODE, mode, NULL) + +# define EVP_PKEY_CTX_set1_pbe_pass(pctx, pass, passlen) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_PASS, passlen, (void *)(pass)) + +# define EVP_PKEY_CTX_set1_scrypt_salt(pctx, salt, saltlen) \ + EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_SCRYPT_SALT, saltlen, (void *)(salt)) + +# define EVP_PKEY_CTX_set_scrypt_N(pctx, n) \ + EVP_PKEY_CTX_ctrl_uint64(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_SCRYPT_N, n) + +# define EVP_PKEY_CTX_set_scrypt_r(pctx, r) \ + EVP_PKEY_CTX_ctrl_uint64(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_SCRYPT_R, r) + +# define EVP_PKEY_CTX_set_scrypt_p(pctx, p) \ + EVP_PKEY_CTX_ctrl_uint64(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_SCRYPT_P, p) + +# define EVP_PKEY_CTX_set_scrypt_maxmem_bytes(pctx, maxmem_bytes) \ + EVP_PKEY_CTX_ctrl_uint64(pctx, -1, EVP_PKEY_OP_DERIVE, \ + EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES, maxmem_bytes) + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/kdferr.h b/include/openssl/kdferr.h new file mode 100644 index 0000000..6437c27 --- /dev/null +++ b/include/openssl/kdferr.h @@ -0,0 +1,51 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_KDFERR_H +# define HEADER_KDFERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_KDF_strings(void); + +/* + * KDF function codes. + */ +# define KDF_F_PKEY_HKDF_CTRL_STR 103 +# define KDF_F_PKEY_HKDF_DERIVE 102 +# define KDF_F_PKEY_HKDF_INIT 108 +# define KDF_F_PKEY_SCRYPT_CTRL_STR 104 +# define KDF_F_PKEY_SCRYPT_CTRL_UINT64 105 +# define KDF_F_PKEY_SCRYPT_DERIVE 109 +# define KDF_F_PKEY_SCRYPT_INIT 106 +# define KDF_F_PKEY_SCRYPT_SET_MEMBUF 107 +# define KDF_F_PKEY_TLS1_PRF_CTRL_STR 100 +# define KDF_F_PKEY_TLS1_PRF_DERIVE 101 +# define KDF_F_PKEY_TLS1_PRF_INIT 110 +# define KDF_F_TLS1_PRF_ALG 111 + +/* + * KDF reason codes. + */ +# define KDF_R_INVALID_DIGEST 100 +# define KDF_R_MISSING_ITERATION_COUNT 109 +# define KDF_R_MISSING_KEY 104 +# define KDF_R_MISSING_MESSAGE_DIGEST 105 +# define KDF_R_MISSING_PARAMETER 101 +# define KDF_R_MISSING_PASS 110 +# define KDF_R_MISSING_SALT 111 +# define KDF_R_MISSING_SECRET 107 +# define KDF_R_MISSING_SEED 106 +# define KDF_R_UNKNOWN_PARAMETER_TYPE 103 +# define KDF_R_VALUE_ERROR 108 +# define KDF_R_VALUE_MISSING 102 + +#endif diff --git a/include/openssl/lhash.h b/include/openssl/lhash.h new file mode 100644 index 0000000..7309801 --- /dev/null +++ b/include/openssl/lhash.h @@ -0,0 +1,217 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * Header for dynamic hash table routines Author - Eric Young + */ + +#ifndef HEADER_LHASH_H +# define HEADER_LHASH_H + +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct lhash_node_st OPENSSL_LH_NODE; +typedef int (*OPENSSL_LH_COMPFUNC) (const void *, const void *); +typedef unsigned long (*OPENSSL_LH_HASHFUNC) (const void *); +typedef void (*OPENSSL_LH_DOALL_FUNC) (void *); +typedef void (*OPENSSL_LH_DOALL_FUNCARG) (void *, void *); +typedef struct lhash_st OPENSSL_LHASH; + +/* + * Macros for declaring and implementing type-safe wrappers for LHASH + * callbacks. This way, callbacks can be provided to LHASH structures without + * function pointer casting and the macro-defined callbacks provide + * per-variable casting before deferring to the underlying type-specific + * callbacks. NB: It is possible to place a "static" in front of both the + * DECLARE and IMPLEMENT macros if the functions are strictly internal. + */ + +/* First: "hash" functions */ +# define DECLARE_LHASH_HASH_FN(name, o_type) \ + unsigned long name##_LHASH_HASH(const void *); +# define IMPLEMENT_LHASH_HASH_FN(name, o_type) \ + unsigned long name##_LHASH_HASH(const void *arg) { \ + const o_type *a = arg; \ + return name##_hash(a); } +# define LHASH_HASH_FN(name) name##_LHASH_HASH + +/* Second: "compare" functions */ +# define DECLARE_LHASH_COMP_FN(name, o_type) \ + int name##_LHASH_COMP(const void *, const void *); +# define IMPLEMENT_LHASH_COMP_FN(name, o_type) \ + int name##_LHASH_COMP(const void *arg1, const void *arg2) { \ + const o_type *a = arg1; \ + const o_type *b = arg2; \ + return name##_cmp(a,b); } +# define LHASH_COMP_FN(name) name##_LHASH_COMP + +/* Fourth: "doall_arg" functions */ +# define DECLARE_LHASH_DOALL_ARG_FN(name, o_type, a_type) \ + void name##_LHASH_DOALL_ARG(void *, void *); +# define IMPLEMENT_LHASH_DOALL_ARG_FN(name, o_type, a_type) \ + void name##_LHASH_DOALL_ARG(void *arg1, void *arg2) { \ + o_type *a = arg1; \ + a_type *b = arg2; \ + name##_doall_arg(a, b); } +# define LHASH_DOALL_ARG_FN(name) name##_LHASH_DOALL_ARG + + +# define LH_LOAD_MULT 256 + +int OPENSSL_LH_error(OPENSSL_LHASH *lh); +OPENSSL_LHASH *OPENSSL_LH_new(OPENSSL_LH_HASHFUNC h, OPENSSL_LH_COMPFUNC c); +void OPENSSL_LH_free(OPENSSL_LHASH *lh); +void *OPENSSL_LH_insert(OPENSSL_LHASH *lh, void *data); +void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data); +void *OPENSSL_LH_retrieve(OPENSSL_LHASH *lh, const void *data); +void OPENSSL_LH_doall(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNC func); +void OPENSSL_LH_doall_arg(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNCARG func, void *arg); +unsigned long OPENSSL_LH_strhash(const char *c); +unsigned long OPENSSL_LH_num_items(const OPENSSL_LHASH *lh); +unsigned long OPENSSL_LH_get_down_load(const OPENSSL_LHASH *lh); +void OPENSSL_LH_set_down_load(OPENSSL_LHASH *lh, unsigned long down_load); + +# ifndef OPENSSL_NO_STDIO +void OPENSSL_LH_stats(const OPENSSL_LHASH *lh, FILE *fp); +void OPENSSL_LH_node_stats(const OPENSSL_LHASH *lh, FILE *fp); +void OPENSSL_LH_node_usage_stats(const OPENSSL_LHASH *lh, FILE *fp); +# endif +void OPENSSL_LH_stats_bio(const OPENSSL_LHASH *lh, BIO *out); +void OPENSSL_LH_node_stats_bio(const OPENSSL_LHASH *lh, BIO *out); +void OPENSSL_LH_node_usage_stats_bio(const OPENSSL_LHASH *lh, BIO *out); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define _LHASH OPENSSL_LHASH +# define LHASH_NODE OPENSSL_LH_NODE +# define lh_error OPENSSL_LH_error +# define lh_new OPENSSL_LH_new +# define lh_free OPENSSL_LH_free +# define lh_insert OPENSSL_LH_insert +# define lh_delete OPENSSL_LH_delete +# define lh_retrieve OPENSSL_LH_retrieve +# define lh_doall OPENSSL_LH_doall +# define lh_doall_arg OPENSSL_LH_doall_arg +# define lh_strhash OPENSSL_LH_strhash +# define lh_num_items OPENSSL_LH_num_items +# ifndef OPENSSL_NO_STDIO +# define lh_stats OPENSSL_LH_stats +# define lh_node_stats OPENSSL_LH_node_stats +# define lh_node_usage_stats OPENSSL_LH_node_usage_stats +# endif +# define lh_stats_bio OPENSSL_LH_stats_bio +# define lh_node_stats_bio OPENSSL_LH_node_stats_bio +# define lh_node_usage_stats_bio OPENSSL_LH_node_usage_stats_bio +# endif + +/* Type checking... */ + +# define LHASH_OF(type) struct lhash_st_##type + +# define DEFINE_LHASH_OF(type) \ + LHASH_OF(type) { union lh_##type##_dummy { void* d1; unsigned long d2; int d3; } dummy; }; \ + static ossl_inline LHASH_OF(type) * \ + lh_##type##_new(unsigned long (*hfn)(const type *), \ + int (*cfn)(const type *, const type *)) \ + { \ + return (LHASH_OF(type) *) \ + OPENSSL_LH_new((OPENSSL_LH_HASHFUNC)hfn, (OPENSSL_LH_COMPFUNC)cfn); \ + } \ + static ossl_inline void lh_##type##_free(LHASH_OF(type) *lh) \ + { \ + OPENSSL_LH_free((OPENSSL_LHASH *)lh); \ + } \ + static ossl_inline type *lh_##type##_insert(LHASH_OF(type) *lh, type *d) \ + { \ + return (type *)OPENSSL_LH_insert((OPENSSL_LHASH *)lh, d); \ + } \ + static ossl_inline type *lh_##type##_delete(LHASH_OF(type) *lh, const type *d) \ + { \ + return (type *)OPENSSL_LH_delete((OPENSSL_LHASH *)lh, d); \ + } \ + static ossl_inline type *lh_##type##_retrieve(LHASH_OF(type) *lh, const type *d) \ + { \ + return (type *)OPENSSL_LH_retrieve((OPENSSL_LHASH *)lh, d); \ + } \ + static ossl_inline int lh_##type##_error(LHASH_OF(type) *lh) \ + { \ + return OPENSSL_LH_error((OPENSSL_LHASH *)lh); \ + } \ + static ossl_inline unsigned long lh_##type##_num_items(LHASH_OF(type) *lh) \ + { \ + return OPENSSL_LH_num_items((OPENSSL_LHASH *)lh); \ + } \ + static ossl_inline void lh_##type##_node_stats_bio(const LHASH_OF(type) *lh, BIO *out) \ + { \ + OPENSSL_LH_node_stats_bio((const OPENSSL_LHASH *)lh, out); \ + } \ + static ossl_inline void lh_##type##_node_usage_stats_bio(const LHASH_OF(type) *lh, BIO *out) \ + { \ + OPENSSL_LH_node_usage_stats_bio((const OPENSSL_LHASH *)lh, out); \ + } \ + static ossl_inline void lh_##type##_stats_bio(const LHASH_OF(type) *lh, BIO *out) \ + { \ + OPENSSL_LH_stats_bio((const OPENSSL_LHASH *)lh, out); \ + } \ + static ossl_inline unsigned long lh_##type##_get_down_load(LHASH_OF(type) *lh) \ + { \ + return OPENSSL_LH_get_down_load((OPENSSL_LHASH *)lh); \ + } \ + static ossl_inline void lh_##type##_set_down_load(LHASH_OF(type) *lh, unsigned long dl) \ + { \ + OPENSSL_LH_set_down_load((OPENSSL_LHASH *)lh, dl); \ + } \ + static ossl_inline void lh_##type##_doall(LHASH_OF(type) *lh, \ + void (*doall)(type *)) \ + { \ + OPENSSL_LH_doall((OPENSSL_LHASH *)lh, (OPENSSL_LH_DOALL_FUNC)doall); \ + } \ + LHASH_OF(type) + +#define IMPLEMENT_LHASH_DOALL_ARG_CONST(type, argtype) \ + int_implement_lhash_doall(type, argtype, const type) + +#define IMPLEMENT_LHASH_DOALL_ARG(type, argtype) \ + int_implement_lhash_doall(type, argtype, type) + +#define int_implement_lhash_doall(type, argtype, cbargtype) \ + static ossl_inline void \ + lh_##type##_doall_##argtype(LHASH_OF(type) *lh, \ + void (*fn)(cbargtype *, argtype *), \ + argtype *arg) \ + { \ + OPENSSL_LH_doall_arg((OPENSSL_LHASH *)lh, (OPENSSL_LH_DOALL_FUNCARG)fn, (void *)arg); \ + } \ + LHASH_OF(type) + +DEFINE_LHASH_OF(OPENSSL_STRING); +# ifdef _MSC_VER +/* + * push and pop this warning: + * warning C4090: 'function': different 'const' qualifiers + */ +# pragma warning (push) +# pragma warning (disable: 4090) +# endif + +DEFINE_LHASH_OF(OPENSSL_CSTRING); + +# ifdef _MSC_VER +# pragma warning (pop) +# endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/md2.h b/include/openssl/md2.h new file mode 100644 index 0000000..22ebacd --- /dev/null +++ b/include/openssl/md2.h @@ -0,0 +1,44 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_MD2_H +# define HEADER_MD2_H + +# include + +# ifndef OPENSSL_NO_MD2 +# include +# ifdef __cplusplus +extern "C" { +# endif + +typedef unsigned char MD2_INT; + +# define MD2_DIGEST_LENGTH 16 +# define MD2_BLOCK 16 + +typedef struct MD2state_st { + unsigned int num; + unsigned char data[MD2_BLOCK]; + MD2_INT cksm[MD2_BLOCK]; + MD2_INT state[MD2_BLOCK]; +} MD2_CTX; + +const char *MD2_options(void); +int MD2_Init(MD2_CTX *c); +int MD2_Update(MD2_CTX *c, const unsigned char *data, size_t len); +int MD2_Final(unsigned char *md, MD2_CTX *c); +unsigned char *MD2(const unsigned char *d, size_t n, unsigned char *md); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/md4.h b/include/openssl/md4.h new file mode 100644 index 0000000..0f4921d --- /dev/null +++ b/include/openssl/md4.h @@ -0,0 +1,51 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_MD4_H +# define HEADER_MD4_H + +# include + +# ifndef OPENSSL_NO_MD4 +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +/*- + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + * ! MD4_LONG has to be at least 32 bits wide. ! + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + */ +# define MD4_LONG unsigned int + +# define MD4_CBLOCK 64 +# define MD4_LBLOCK (MD4_CBLOCK/4) +# define MD4_DIGEST_LENGTH 16 + +typedef struct MD4state_st { + MD4_LONG A, B, C, D; + MD4_LONG Nl, Nh; + MD4_LONG data[MD4_LBLOCK]; + unsigned int num; +} MD4_CTX; + +int MD4_Init(MD4_CTX *c); +int MD4_Update(MD4_CTX *c, const void *data, size_t len); +int MD4_Final(unsigned char *md, MD4_CTX *c); +unsigned char *MD4(const unsigned char *d, size_t n, unsigned char *md); +void MD4_Transform(MD4_CTX *c, const unsigned char *b); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/md5.h b/include/openssl/md5.h new file mode 100644 index 0000000..2b924ad --- /dev/null +++ b/include/openssl/md5.h @@ -0,0 +1,50 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_MD5_H +# define HEADER_MD5_H + +# include + +# ifndef OPENSSL_NO_MD5 +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +/* + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + * ! MD5_LONG has to be at least 32 bits wide. ! + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + */ +# define MD5_LONG unsigned int + +# define MD5_CBLOCK 64 +# define MD5_LBLOCK (MD5_CBLOCK/4) +# define MD5_DIGEST_LENGTH 16 + +typedef struct MD5state_st { + MD5_LONG A, B, C, D; + MD5_LONG Nl, Nh; + MD5_LONG data[MD5_LBLOCK]; + unsigned int num; +} MD5_CTX; + +int MD5_Init(MD5_CTX *c); +int MD5_Update(MD5_CTX *c, const void *data, size_t len); +int MD5_Final(unsigned char *md, MD5_CTX *c); +unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md); +void MD5_Transform(MD5_CTX *c, const unsigned char *b); +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/mdc2.h b/include/openssl/mdc2.h new file mode 100644 index 0000000..f4632e6 --- /dev/null +++ b/include/openssl/mdc2.h @@ -0,0 +1,42 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_MDC2_H +# define HEADER_MDC2_H + +# include + +#ifndef OPENSSL_NO_MDC2 +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +# define MDC2_BLOCK 8 +# define MDC2_DIGEST_LENGTH 16 + +typedef struct mdc2_ctx_st { + unsigned int num; + unsigned char data[MDC2_BLOCK]; + DES_cblock h, hh; + int pad_type; /* either 1 or 2, default 1 */ +} MDC2_CTX; + +int MDC2_Init(MDC2_CTX *c); +int MDC2_Update(MDC2_CTX *c, const unsigned char *data, size_t len); +int MDC2_Final(unsigned char *md, MDC2_CTX *c); +unsigned char *MDC2(const unsigned char *d, size_t n, unsigned char *md); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/modes.h b/include/openssl/modes.h new file mode 100644 index 0000000..d544f98 --- /dev/null +++ b/include/openssl/modes.h @@ -0,0 +1,208 @@ +/* + * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_MODES_H +# define HEADER_MODES_H + +# include + +# ifdef __cplusplus +extern "C" { +# endif +typedef void (*block128_f) (const unsigned char in[16], + unsigned char out[16], const void *key); + +typedef void (*cbc128_f) (const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], int enc); + +typedef void (*ctr128_f) (const unsigned char *in, unsigned char *out, + size_t blocks, const void *key, + const unsigned char ivec[16]); + +typedef void (*ccm128_f) (const unsigned char *in, unsigned char *out, + size_t blocks, const void *key, + const unsigned char ivec[16], + unsigned char cmac[16]); + +void CRYPTO_cbc128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], block128_f block); +void CRYPTO_cbc128_decrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], block128_f block); + +void CRYPTO_ctr128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], + unsigned char ecount_buf[16], unsigned int *num, + block128_f block); + +void CRYPTO_ctr128_encrypt_ctr32(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], + unsigned char ecount_buf[16], + unsigned int *num, ctr128_f ctr); + +void CRYPTO_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], int *num, + block128_f block); + +void CRYPTO_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], int *num, + int enc, block128_f block); +void CRYPTO_cfb128_8_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const void *key, + unsigned char ivec[16], int *num, + int enc, block128_f block); +void CRYPTO_cfb128_1_encrypt(const unsigned char *in, unsigned char *out, + size_t bits, const void *key, + unsigned char ivec[16], int *num, + int enc, block128_f block); + +size_t CRYPTO_cts128_encrypt_block(const unsigned char *in, + unsigned char *out, size_t len, + const void *key, unsigned char ivec[16], + block128_f block); +size_t CRYPTO_cts128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], cbc128_f cbc); +size_t CRYPTO_cts128_decrypt_block(const unsigned char *in, + unsigned char *out, size_t len, + const void *key, unsigned char ivec[16], + block128_f block); +size_t CRYPTO_cts128_decrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], cbc128_f cbc); + +size_t CRYPTO_nistcts128_encrypt_block(const unsigned char *in, + unsigned char *out, size_t len, + const void *key, + unsigned char ivec[16], + block128_f block); +size_t CRYPTO_nistcts128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], cbc128_f cbc); +size_t CRYPTO_nistcts128_decrypt_block(const unsigned char *in, + unsigned char *out, size_t len, + const void *key, + unsigned char ivec[16], + block128_f block); +size_t CRYPTO_nistcts128_decrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], cbc128_f cbc); + +typedef struct gcm128_context GCM128_CONTEXT; + +GCM128_CONTEXT *CRYPTO_gcm128_new(void *key, block128_f block); +void CRYPTO_gcm128_init(GCM128_CONTEXT *ctx, void *key, block128_f block); +void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const unsigned char *iv, + size_t len); +int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const unsigned char *aad, + size_t len); +int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, + const unsigned char *in, unsigned char *out, + size_t len); +int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, + const unsigned char *in, unsigned char *out, + size_t len); +int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, + const unsigned char *in, unsigned char *out, + size_t len, ctr128_f stream); +int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, + const unsigned char *in, unsigned char *out, + size_t len, ctr128_f stream); +int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const unsigned char *tag, + size_t len); +void CRYPTO_gcm128_tag(GCM128_CONTEXT *ctx, unsigned char *tag, size_t len); +void CRYPTO_gcm128_release(GCM128_CONTEXT *ctx); + +typedef struct ccm128_context CCM128_CONTEXT; + +void CRYPTO_ccm128_init(CCM128_CONTEXT *ctx, + unsigned int M, unsigned int L, void *key, + block128_f block); +int CRYPTO_ccm128_setiv(CCM128_CONTEXT *ctx, const unsigned char *nonce, + size_t nlen, size_t mlen); +void CRYPTO_ccm128_aad(CCM128_CONTEXT *ctx, const unsigned char *aad, + size_t alen); +int CRYPTO_ccm128_encrypt(CCM128_CONTEXT *ctx, const unsigned char *inp, + unsigned char *out, size_t len); +int CRYPTO_ccm128_decrypt(CCM128_CONTEXT *ctx, const unsigned char *inp, + unsigned char *out, size_t len); +int CRYPTO_ccm128_encrypt_ccm64(CCM128_CONTEXT *ctx, const unsigned char *inp, + unsigned char *out, size_t len, + ccm128_f stream); +int CRYPTO_ccm128_decrypt_ccm64(CCM128_CONTEXT *ctx, const unsigned char *inp, + unsigned char *out, size_t len, + ccm128_f stream); +size_t CRYPTO_ccm128_tag(CCM128_CONTEXT *ctx, unsigned char *tag, size_t len); + +typedef struct xts128_context XTS128_CONTEXT; + +int CRYPTO_xts128_encrypt(const XTS128_CONTEXT *ctx, + const unsigned char iv[16], + const unsigned char *inp, unsigned char *out, + size_t len, int enc); + +size_t CRYPTO_128_wrap(void *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, size_t inlen, + block128_f block); + +size_t CRYPTO_128_unwrap(void *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, size_t inlen, + block128_f block); +size_t CRYPTO_128_wrap_pad(void *key, const unsigned char *icv, + unsigned char *out, const unsigned char *in, + size_t inlen, block128_f block); +size_t CRYPTO_128_unwrap_pad(void *key, const unsigned char *icv, + unsigned char *out, const unsigned char *in, + size_t inlen, block128_f block); + +# ifndef OPENSSL_NO_OCB +typedef struct ocb128_context OCB128_CONTEXT; + +typedef void (*ocb128_f) (const unsigned char *in, unsigned char *out, + size_t blocks, const void *key, + size_t start_block_num, + unsigned char offset_i[16], + const unsigned char L_[][16], + unsigned char checksum[16]); + +OCB128_CONTEXT *CRYPTO_ocb128_new(void *keyenc, void *keydec, + block128_f encrypt, block128_f decrypt, + ocb128_f stream); +int CRYPTO_ocb128_init(OCB128_CONTEXT *ctx, void *keyenc, void *keydec, + block128_f encrypt, block128_f decrypt, + ocb128_f stream); +int CRYPTO_ocb128_copy_ctx(OCB128_CONTEXT *dest, OCB128_CONTEXT *src, + void *keyenc, void *keydec); +int CRYPTO_ocb128_setiv(OCB128_CONTEXT *ctx, const unsigned char *iv, + size_t len, size_t taglen); +int CRYPTO_ocb128_aad(OCB128_CONTEXT *ctx, const unsigned char *aad, + size_t len); +int CRYPTO_ocb128_encrypt(OCB128_CONTEXT *ctx, const unsigned char *in, + unsigned char *out, size_t len); +int CRYPTO_ocb128_decrypt(OCB128_CONTEXT *ctx, const unsigned char *in, + unsigned char *out, size_t len); +int CRYPTO_ocb128_finish(OCB128_CONTEXT *ctx, const unsigned char *tag, + size_t len); +int CRYPTO_ocb128_tag(OCB128_CONTEXT *ctx, unsigned char *tag, size_t len); +void CRYPTO_ocb128_cleanup(OCB128_CONTEXT *ctx); +# endif /* OPENSSL_NO_OCB */ + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/include/openssl/obj_mac.h b/include/openssl/obj_mac.h new file mode 100644 index 0000000..80ff5a7 --- /dev/null +++ b/include/openssl/obj_mac.h @@ -0,0 +1,5198 @@ +/* + * WARNING: do not edit! + * Generated by crypto/objects/objects.pl + * + * Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#define SN_undef "UNDEF" +#define LN_undef "undefined" +#define NID_undef 0 +#define OBJ_undef 0L + +#define SN_itu_t "ITU-T" +#define LN_itu_t "itu-t" +#define NID_itu_t 645 +#define OBJ_itu_t 0L + +#define NID_ccitt 404 +#define OBJ_ccitt OBJ_itu_t + +#define SN_iso "ISO" +#define LN_iso "iso" +#define NID_iso 181 +#define OBJ_iso 1L + +#define SN_joint_iso_itu_t "JOINT-ISO-ITU-T" +#define LN_joint_iso_itu_t "joint-iso-itu-t" +#define NID_joint_iso_itu_t 646 +#define OBJ_joint_iso_itu_t 2L + +#define NID_joint_iso_ccitt 393 +#define OBJ_joint_iso_ccitt OBJ_joint_iso_itu_t + +#define SN_member_body "member-body" +#define LN_member_body "ISO Member Body" +#define NID_member_body 182 +#define OBJ_member_body OBJ_iso,2L + +#define SN_identified_organization "identified-organization" +#define NID_identified_organization 676 +#define OBJ_identified_organization OBJ_iso,3L + +#define SN_hmac_md5 "HMAC-MD5" +#define LN_hmac_md5 "hmac-md5" +#define NID_hmac_md5 780 +#define OBJ_hmac_md5 OBJ_identified_organization,6L,1L,5L,5L,8L,1L,1L + +#define SN_hmac_sha1 "HMAC-SHA1" +#define LN_hmac_sha1 "hmac-sha1" +#define NID_hmac_sha1 781 +#define OBJ_hmac_sha1 OBJ_identified_organization,6L,1L,5L,5L,8L,1L,2L + +#define SN_x509ExtAdmission "x509ExtAdmission" +#define LN_x509ExtAdmission "Professional Information or basis for Admission" +#define NID_x509ExtAdmission 1093 +#define OBJ_x509ExtAdmission OBJ_identified_organization,36L,8L,3L,3L + +#define SN_certicom_arc "certicom-arc" +#define NID_certicom_arc 677 +#define OBJ_certicom_arc OBJ_identified_organization,132L + +#define SN_ieee "ieee" +#define NID_ieee 1170 +#define OBJ_ieee OBJ_identified_organization,111L + +#define SN_ieee_siswg "ieee-siswg" +#define LN_ieee_siswg "IEEE Security in Storage Working Group" +#define NID_ieee_siswg 1171 +#define OBJ_ieee_siswg OBJ_ieee,2L,1619L + +#define SN_international_organizations "international-organizations" +#define LN_international_organizations "International Organizations" +#define NID_international_organizations 647 +#define OBJ_international_organizations OBJ_joint_iso_itu_t,23L + +#define SN_wap "wap" +#define NID_wap 678 +#define OBJ_wap OBJ_international_organizations,43L + +#define SN_wap_wsg "wap-wsg" +#define NID_wap_wsg 679 +#define OBJ_wap_wsg OBJ_wap,1L + +#define SN_selected_attribute_types "selected-attribute-types" +#define LN_selected_attribute_types "Selected Attribute Types" +#define NID_selected_attribute_types 394 +#define OBJ_selected_attribute_types OBJ_joint_iso_itu_t,5L,1L,5L + +#define SN_clearance "clearance" +#define NID_clearance 395 +#define OBJ_clearance OBJ_selected_attribute_types,55L + +#define SN_ISO_US "ISO-US" +#define LN_ISO_US "ISO US Member Body" +#define NID_ISO_US 183 +#define OBJ_ISO_US OBJ_member_body,840L + +#define SN_X9_57 "X9-57" +#define LN_X9_57 "X9.57" +#define NID_X9_57 184 +#define OBJ_X9_57 OBJ_ISO_US,10040L + +#define SN_X9cm "X9cm" +#define LN_X9cm "X9.57 CM ?" +#define NID_X9cm 185 +#define OBJ_X9cm OBJ_X9_57,4L + +#define SN_ISO_CN "ISO-CN" +#define LN_ISO_CN "ISO CN Member Body" +#define NID_ISO_CN 1140 +#define OBJ_ISO_CN OBJ_member_body,156L + +#define SN_oscca "oscca" +#define NID_oscca 1141 +#define OBJ_oscca OBJ_ISO_CN,10197L + +#define SN_sm_scheme "sm-scheme" +#define NID_sm_scheme 1142 +#define OBJ_sm_scheme OBJ_oscca,1L + +#define SN_dsa "DSA" +#define LN_dsa "dsaEncryption" +#define NID_dsa 116 +#define OBJ_dsa OBJ_X9cm,1L + +#define SN_dsaWithSHA1 "DSA-SHA1" +#define LN_dsaWithSHA1 "dsaWithSHA1" +#define NID_dsaWithSHA1 113 +#define OBJ_dsaWithSHA1 OBJ_X9cm,3L + +#define SN_ansi_X9_62 "ansi-X9-62" +#define LN_ansi_X9_62 "ANSI X9.62" +#define NID_ansi_X9_62 405 +#define OBJ_ansi_X9_62 OBJ_ISO_US,10045L + +#define OBJ_X9_62_id_fieldType OBJ_ansi_X9_62,1L + +#define SN_X9_62_prime_field "prime-field" +#define NID_X9_62_prime_field 406 +#define OBJ_X9_62_prime_field OBJ_X9_62_id_fieldType,1L + +#define SN_X9_62_characteristic_two_field "characteristic-two-field" +#define NID_X9_62_characteristic_two_field 407 +#define OBJ_X9_62_characteristic_two_field OBJ_X9_62_id_fieldType,2L + +#define SN_X9_62_id_characteristic_two_basis "id-characteristic-two-basis" +#define NID_X9_62_id_characteristic_two_basis 680 +#define OBJ_X9_62_id_characteristic_two_basis OBJ_X9_62_characteristic_two_field,3L + +#define SN_X9_62_onBasis "onBasis" +#define NID_X9_62_onBasis 681 +#define OBJ_X9_62_onBasis OBJ_X9_62_id_characteristic_two_basis,1L + +#define SN_X9_62_tpBasis "tpBasis" +#define NID_X9_62_tpBasis 682 +#define OBJ_X9_62_tpBasis OBJ_X9_62_id_characteristic_two_basis,2L + +#define SN_X9_62_ppBasis "ppBasis" +#define NID_X9_62_ppBasis 683 +#define OBJ_X9_62_ppBasis OBJ_X9_62_id_characteristic_two_basis,3L + +#define OBJ_X9_62_id_publicKeyType OBJ_ansi_X9_62,2L + +#define SN_X9_62_id_ecPublicKey "id-ecPublicKey" +#define NID_X9_62_id_ecPublicKey 408 +#define OBJ_X9_62_id_ecPublicKey OBJ_X9_62_id_publicKeyType,1L + +#define OBJ_X9_62_ellipticCurve OBJ_ansi_X9_62,3L + +#define OBJ_X9_62_c_TwoCurve OBJ_X9_62_ellipticCurve,0L + +#define SN_X9_62_c2pnb163v1 "c2pnb163v1" +#define NID_X9_62_c2pnb163v1 684 +#define OBJ_X9_62_c2pnb163v1 OBJ_X9_62_c_TwoCurve,1L + +#define SN_X9_62_c2pnb163v2 "c2pnb163v2" +#define NID_X9_62_c2pnb163v2 685 +#define OBJ_X9_62_c2pnb163v2 OBJ_X9_62_c_TwoCurve,2L + +#define SN_X9_62_c2pnb163v3 "c2pnb163v3" +#define NID_X9_62_c2pnb163v3 686 +#define OBJ_X9_62_c2pnb163v3 OBJ_X9_62_c_TwoCurve,3L + +#define SN_X9_62_c2pnb176v1 "c2pnb176v1" +#define NID_X9_62_c2pnb176v1 687 +#define OBJ_X9_62_c2pnb176v1 OBJ_X9_62_c_TwoCurve,4L + +#define SN_X9_62_c2tnb191v1 "c2tnb191v1" +#define NID_X9_62_c2tnb191v1 688 +#define OBJ_X9_62_c2tnb191v1 OBJ_X9_62_c_TwoCurve,5L + +#define SN_X9_62_c2tnb191v2 "c2tnb191v2" +#define NID_X9_62_c2tnb191v2 689 +#define OBJ_X9_62_c2tnb191v2 OBJ_X9_62_c_TwoCurve,6L + +#define SN_X9_62_c2tnb191v3 "c2tnb191v3" +#define NID_X9_62_c2tnb191v3 690 +#define OBJ_X9_62_c2tnb191v3 OBJ_X9_62_c_TwoCurve,7L + +#define SN_X9_62_c2onb191v4 "c2onb191v4" +#define NID_X9_62_c2onb191v4 691 +#define OBJ_X9_62_c2onb191v4 OBJ_X9_62_c_TwoCurve,8L + +#define SN_X9_62_c2onb191v5 "c2onb191v5" +#define NID_X9_62_c2onb191v5 692 +#define OBJ_X9_62_c2onb191v5 OBJ_X9_62_c_TwoCurve,9L + +#define SN_X9_62_c2pnb208w1 "c2pnb208w1" +#define NID_X9_62_c2pnb208w1 693 +#define OBJ_X9_62_c2pnb208w1 OBJ_X9_62_c_TwoCurve,10L + +#define SN_X9_62_c2tnb239v1 "c2tnb239v1" +#define NID_X9_62_c2tnb239v1 694 +#define OBJ_X9_62_c2tnb239v1 OBJ_X9_62_c_TwoCurve,11L + +#define SN_X9_62_c2tnb239v2 "c2tnb239v2" +#define NID_X9_62_c2tnb239v2 695 +#define OBJ_X9_62_c2tnb239v2 OBJ_X9_62_c_TwoCurve,12L + +#define SN_X9_62_c2tnb239v3 "c2tnb239v3" +#define NID_X9_62_c2tnb239v3 696 +#define OBJ_X9_62_c2tnb239v3 OBJ_X9_62_c_TwoCurve,13L + +#define SN_X9_62_c2onb239v4 "c2onb239v4" +#define NID_X9_62_c2onb239v4 697 +#define OBJ_X9_62_c2onb239v4 OBJ_X9_62_c_TwoCurve,14L + +#define SN_X9_62_c2onb239v5 "c2onb239v5" +#define NID_X9_62_c2onb239v5 698 +#define OBJ_X9_62_c2onb239v5 OBJ_X9_62_c_TwoCurve,15L + +#define SN_X9_62_c2pnb272w1 "c2pnb272w1" +#define NID_X9_62_c2pnb272w1 699 +#define OBJ_X9_62_c2pnb272w1 OBJ_X9_62_c_TwoCurve,16L + +#define SN_X9_62_c2pnb304w1 "c2pnb304w1" +#define NID_X9_62_c2pnb304w1 700 +#define OBJ_X9_62_c2pnb304w1 OBJ_X9_62_c_TwoCurve,17L + +#define SN_X9_62_c2tnb359v1 "c2tnb359v1" +#define NID_X9_62_c2tnb359v1 701 +#define OBJ_X9_62_c2tnb359v1 OBJ_X9_62_c_TwoCurve,18L + +#define SN_X9_62_c2pnb368w1 "c2pnb368w1" +#define NID_X9_62_c2pnb368w1 702 +#define OBJ_X9_62_c2pnb368w1 OBJ_X9_62_c_TwoCurve,19L + +#define SN_X9_62_c2tnb431r1 "c2tnb431r1" +#define NID_X9_62_c2tnb431r1 703 +#define OBJ_X9_62_c2tnb431r1 OBJ_X9_62_c_TwoCurve,20L + +#define OBJ_X9_62_primeCurve OBJ_X9_62_ellipticCurve,1L + +#define SN_X9_62_prime192v1 "prime192v1" +#define NID_X9_62_prime192v1 409 +#define OBJ_X9_62_prime192v1 OBJ_X9_62_primeCurve,1L + +#define SN_X9_62_prime192v2 "prime192v2" +#define NID_X9_62_prime192v2 410 +#define OBJ_X9_62_prime192v2 OBJ_X9_62_primeCurve,2L + +#define SN_X9_62_prime192v3 "prime192v3" +#define NID_X9_62_prime192v3 411 +#define OBJ_X9_62_prime192v3 OBJ_X9_62_primeCurve,3L + +#define SN_X9_62_prime239v1 "prime239v1" +#define NID_X9_62_prime239v1 412 +#define OBJ_X9_62_prime239v1 OBJ_X9_62_primeCurve,4L + +#define SN_X9_62_prime239v2 "prime239v2" +#define NID_X9_62_prime239v2 413 +#define OBJ_X9_62_prime239v2 OBJ_X9_62_primeCurve,5L + +#define SN_X9_62_prime239v3 "prime239v3" +#define NID_X9_62_prime239v3 414 +#define OBJ_X9_62_prime239v3 OBJ_X9_62_primeCurve,6L + +#define SN_X9_62_prime256v1 "prime256v1" +#define NID_X9_62_prime256v1 415 +#define OBJ_X9_62_prime256v1 OBJ_X9_62_primeCurve,7L + +#define OBJ_X9_62_id_ecSigType OBJ_ansi_X9_62,4L + +#define SN_ecdsa_with_SHA1 "ecdsa-with-SHA1" +#define NID_ecdsa_with_SHA1 416 +#define OBJ_ecdsa_with_SHA1 OBJ_X9_62_id_ecSigType,1L + +#define SN_ecdsa_with_Recommended "ecdsa-with-Recommended" +#define NID_ecdsa_with_Recommended 791 +#define OBJ_ecdsa_with_Recommended OBJ_X9_62_id_ecSigType,2L + +#define SN_ecdsa_with_Specified "ecdsa-with-Specified" +#define NID_ecdsa_with_Specified 792 +#define OBJ_ecdsa_with_Specified OBJ_X9_62_id_ecSigType,3L + +#define SN_ecdsa_with_SHA224 "ecdsa-with-SHA224" +#define NID_ecdsa_with_SHA224 793 +#define OBJ_ecdsa_with_SHA224 OBJ_ecdsa_with_Specified,1L + +#define SN_ecdsa_with_SHA256 "ecdsa-with-SHA256" +#define NID_ecdsa_with_SHA256 794 +#define OBJ_ecdsa_with_SHA256 OBJ_ecdsa_with_Specified,2L + +#define SN_ecdsa_with_SHA384 "ecdsa-with-SHA384" +#define NID_ecdsa_with_SHA384 795 +#define OBJ_ecdsa_with_SHA384 OBJ_ecdsa_with_Specified,3L + +#define SN_ecdsa_with_SHA512 "ecdsa-with-SHA512" +#define NID_ecdsa_with_SHA512 796 +#define OBJ_ecdsa_with_SHA512 OBJ_ecdsa_with_Specified,4L + +#define OBJ_secg_ellipticCurve OBJ_certicom_arc,0L + +#define SN_secp112r1 "secp112r1" +#define NID_secp112r1 704 +#define OBJ_secp112r1 OBJ_secg_ellipticCurve,6L + +#define SN_secp112r2 "secp112r2" +#define NID_secp112r2 705 +#define OBJ_secp112r2 OBJ_secg_ellipticCurve,7L + +#define SN_secp128r1 "secp128r1" +#define NID_secp128r1 706 +#define OBJ_secp128r1 OBJ_secg_ellipticCurve,28L + +#define SN_secp128r2 "secp128r2" +#define NID_secp128r2 707 +#define OBJ_secp128r2 OBJ_secg_ellipticCurve,29L + +#define SN_secp160k1 "secp160k1" +#define NID_secp160k1 708 +#define OBJ_secp160k1 OBJ_secg_ellipticCurve,9L + +#define SN_secp160r1 "secp160r1" +#define NID_secp160r1 709 +#define OBJ_secp160r1 OBJ_secg_ellipticCurve,8L + +#define SN_secp160r2 "secp160r2" +#define NID_secp160r2 710 +#define OBJ_secp160r2 OBJ_secg_ellipticCurve,30L + +#define SN_secp192k1 "secp192k1" +#define NID_secp192k1 711 +#define OBJ_secp192k1 OBJ_secg_ellipticCurve,31L + +#define SN_secp224k1 "secp224k1" +#define NID_secp224k1 712 +#define OBJ_secp224k1 OBJ_secg_ellipticCurve,32L + +#define SN_secp224r1 "secp224r1" +#define NID_secp224r1 713 +#define OBJ_secp224r1 OBJ_secg_ellipticCurve,33L + +#define SN_secp256k1 "secp256k1" +#define NID_secp256k1 714 +#define OBJ_secp256k1 OBJ_secg_ellipticCurve,10L + +#define SN_secp384r1 "secp384r1" +#define NID_secp384r1 715 +#define OBJ_secp384r1 OBJ_secg_ellipticCurve,34L + +#define SN_secp521r1 "secp521r1" +#define NID_secp521r1 716 +#define OBJ_secp521r1 OBJ_secg_ellipticCurve,35L + +#define SN_sect113r1 "sect113r1" +#define NID_sect113r1 717 +#define OBJ_sect113r1 OBJ_secg_ellipticCurve,4L + +#define SN_sect113r2 "sect113r2" +#define NID_sect113r2 718 +#define OBJ_sect113r2 OBJ_secg_ellipticCurve,5L + +#define SN_sect131r1 "sect131r1" +#define NID_sect131r1 719 +#define OBJ_sect131r1 OBJ_secg_ellipticCurve,22L + +#define SN_sect131r2 "sect131r2" +#define NID_sect131r2 720 +#define OBJ_sect131r2 OBJ_secg_ellipticCurve,23L + +#define SN_sect163k1 "sect163k1" +#define NID_sect163k1 721 +#define OBJ_sect163k1 OBJ_secg_ellipticCurve,1L + +#define SN_sect163r1 "sect163r1" +#define NID_sect163r1 722 +#define OBJ_sect163r1 OBJ_secg_ellipticCurve,2L + +#define SN_sect163r2 "sect163r2" +#define NID_sect163r2 723 +#define OBJ_sect163r2 OBJ_secg_ellipticCurve,15L + +#define SN_sect193r1 "sect193r1" +#define NID_sect193r1 724 +#define OBJ_sect193r1 OBJ_secg_ellipticCurve,24L + +#define SN_sect193r2 "sect193r2" +#define NID_sect193r2 725 +#define OBJ_sect193r2 OBJ_secg_ellipticCurve,25L + +#define SN_sect233k1 "sect233k1" +#define NID_sect233k1 726 +#define OBJ_sect233k1 OBJ_secg_ellipticCurve,26L + +#define SN_sect233r1 "sect233r1" +#define NID_sect233r1 727 +#define OBJ_sect233r1 OBJ_secg_ellipticCurve,27L + +#define SN_sect239k1 "sect239k1" +#define NID_sect239k1 728 +#define OBJ_sect239k1 OBJ_secg_ellipticCurve,3L + +#define SN_sect283k1 "sect283k1" +#define NID_sect283k1 729 +#define OBJ_sect283k1 OBJ_secg_ellipticCurve,16L + +#define SN_sect283r1 "sect283r1" +#define NID_sect283r1 730 +#define OBJ_sect283r1 OBJ_secg_ellipticCurve,17L + +#define SN_sect409k1 "sect409k1" +#define NID_sect409k1 731 +#define OBJ_sect409k1 OBJ_secg_ellipticCurve,36L + +#define SN_sect409r1 "sect409r1" +#define NID_sect409r1 732 +#define OBJ_sect409r1 OBJ_secg_ellipticCurve,37L + +#define SN_sect571k1 "sect571k1" +#define NID_sect571k1 733 +#define OBJ_sect571k1 OBJ_secg_ellipticCurve,38L + +#define SN_sect571r1 "sect571r1" +#define NID_sect571r1 734 +#define OBJ_sect571r1 OBJ_secg_ellipticCurve,39L + +#define OBJ_wap_wsg_idm_ecid OBJ_wap_wsg,4L + +#define SN_wap_wsg_idm_ecid_wtls1 "wap-wsg-idm-ecid-wtls1" +#define NID_wap_wsg_idm_ecid_wtls1 735 +#define OBJ_wap_wsg_idm_ecid_wtls1 OBJ_wap_wsg_idm_ecid,1L + +#define SN_wap_wsg_idm_ecid_wtls3 "wap-wsg-idm-ecid-wtls3" +#define NID_wap_wsg_idm_ecid_wtls3 736 +#define OBJ_wap_wsg_idm_ecid_wtls3 OBJ_wap_wsg_idm_ecid,3L + +#define SN_wap_wsg_idm_ecid_wtls4 "wap-wsg-idm-ecid-wtls4" +#define NID_wap_wsg_idm_ecid_wtls4 737 +#define OBJ_wap_wsg_idm_ecid_wtls4 OBJ_wap_wsg_idm_ecid,4L + +#define SN_wap_wsg_idm_ecid_wtls5 "wap-wsg-idm-ecid-wtls5" +#define NID_wap_wsg_idm_ecid_wtls5 738 +#define OBJ_wap_wsg_idm_ecid_wtls5 OBJ_wap_wsg_idm_ecid,5L + +#define SN_wap_wsg_idm_ecid_wtls6 "wap-wsg-idm-ecid-wtls6" +#define NID_wap_wsg_idm_ecid_wtls6 739 +#define OBJ_wap_wsg_idm_ecid_wtls6 OBJ_wap_wsg_idm_ecid,6L + +#define SN_wap_wsg_idm_ecid_wtls7 "wap-wsg-idm-ecid-wtls7" +#define NID_wap_wsg_idm_ecid_wtls7 740 +#define OBJ_wap_wsg_idm_ecid_wtls7 OBJ_wap_wsg_idm_ecid,7L + +#define SN_wap_wsg_idm_ecid_wtls8 "wap-wsg-idm-ecid-wtls8" +#define NID_wap_wsg_idm_ecid_wtls8 741 +#define OBJ_wap_wsg_idm_ecid_wtls8 OBJ_wap_wsg_idm_ecid,8L + +#define SN_wap_wsg_idm_ecid_wtls9 "wap-wsg-idm-ecid-wtls9" +#define NID_wap_wsg_idm_ecid_wtls9 742 +#define OBJ_wap_wsg_idm_ecid_wtls9 OBJ_wap_wsg_idm_ecid,9L + +#define SN_wap_wsg_idm_ecid_wtls10 "wap-wsg-idm-ecid-wtls10" +#define NID_wap_wsg_idm_ecid_wtls10 743 +#define OBJ_wap_wsg_idm_ecid_wtls10 OBJ_wap_wsg_idm_ecid,10L + +#define SN_wap_wsg_idm_ecid_wtls11 "wap-wsg-idm-ecid-wtls11" +#define NID_wap_wsg_idm_ecid_wtls11 744 +#define OBJ_wap_wsg_idm_ecid_wtls11 OBJ_wap_wsg_idm_ecid,11L + +#define SN_wap_wsg_idm_ecid_wtls12 "wap-wsg-idm-ecid-wtls12" +#define NID_wap_wsg_idm_ecid_wtls12 745 +#define OBJ_wap_wsg_idm_ecid_wtls12 OBJ_wap_wsg_idm_ecid,12L + +#define SN_cast5_cbc "CAST5-CBC" +#define LN_cast5_cbc "cast5-cbc" +#define NID_cast5_cbc 108 +#define OBJ_cast5_cbc OBJ_ISO_US,113533L,7L,66L,10L + +#define SN_cast5_ecb "CAST5-ECB" +#define LN_cast5_ecb "cast5-ecb" +#define NID_cast5_ecb 109 + +#define SN_cast5_cfb64 "CAST5-CFB" +#define LN_cast5_cfb64 "cast5-cfb" +#define NID_cast5_cfb64 110 + +#define SN_cast5_ofb64 "CAST5-OFB" +#define LN_cast5_ofb64 "cast5-ofb" +#define NID_cast5_ofb64 111 + +#define LN_pbeWithMD5AndCast5_CBC "pbeWithMD5AndCast5CBC" +#define NID_pbeWithMD5AndCast5_CBC 112 +#define OBJ_pbeWithMD5AndCast5_CBC OBJ_ISO_US,113533L,7L,66L,12L + +#define SN_id_PasswordBasedMAC "id-PasswordBasedMAC" +#define LN_id_PasswordBasedMAC "password based MAC" +#define NID_id_PasswordBasedMAC 782 +#define OBJ_id_PasswordBasedMAC OBJ_ISO_US,113533L,7L,66L,13L + +#define SN_id_DHBasedMac "id-DHBasedMac" +#define LN_id_DHBasedMac "Diffie-Hellman based MAC" +#define NID_id_DHBasedMac 783 +#define OBJ_id_DHBasedMac OBJ_ISO_US,113533L,7L,66L,30L + +#define SN_rsadsi "rsadsi" +#define LN_rsadsi "RSA Data Security, Inc." +#define NID_rsadsi 1 +#define OBJ_rsadsi OBJ_ISO_US,113549L + +#define SN_pkcs "pkcs" +#define LN_pkcs "RSA Data Security, Inc. PKCS" +#define NID_pkcs 2 +#define OBJ_pkcs OBJ_rsadsi,1L + +#define SN_pkcs1 "pkcs1" +#define NID_pkcs1 186 +#define OBJ_pkcs1 OBJ_pkcs,1L + +#define LN_rsaEncryption "rsaEncryption" +#define NID_rsaEncryption 6 +#define OBJ_rsaEncryption OBJ_pkcs1,1L + +#define SN_md2WithRSAEncryption "RSA-MD2" +#define LN_md2WithRSAEncryption "md2WithRSAEncryption" +#define NID_md2WithRSAEncryption 7 +#define OBJ_md2WithRSAEncryption OBJ_pkcs1,2L + +#define SN_md4WithRSAEncryption "RSA-MD4" +#define LN_md4WithRSAEncryption "md4WithRSAEncryption" +#define NID_md4WithRSAEncryption 396 +#define OBJ_md4WithRSAEncryption OBJ_pkcs1,3L + +#define SN_md5WithRSAEncryption "RSA-MD5" +#define LN_md5WithRSAEncryption "md5WithRSAEncryption" +#define NID_md5WithRSAEncryption 8 +#define OBJ_md5WithRSAEncryption OBJ_pkcs1,4L + +#define SN_sha1WithRSAEncryption "RSA-SHA1" +#define LN_sha1WithRSAEncryption "sha1WithRSAEncryption" +#define NID_sha1WithRSAEncryption 65 +#define OBJ_sha1WithRSAEncryption OBJ_pkcs1,5L + +#define SN_rsaesOaep "RSAES-OAEP" +#define LN_rsaesOaep "rsaesOaep" +#define NID_rsaesOaep 919 +#define OBJ_rsaesOaep OBJ_pkcs1,7L + +#define SN_mgf1 "MGF1" +#define LN_mgf1 "mgf1" +#define NID_mgf1 911 +#define OBJ_mgf1 OBJ_pkcs1,8L + +#define SN_pSpecified "PSPECIFIED" +#define LN_pSpecified "pSpecified" +#define NID_pSpecified 935 +#define OBJ_pSpecified OBJ_pkcs1,9L + +#define SN_rsassaPss "RSASSA-PSS" +#define LN_rsassaPss "rsassaPss" +#define NID_rsassaPss 912 +#define OBJ_rsassaPss OBJ_pkcs1,10L + +#define SN_sha256WithRSAEncryption "RSA-SHA256" +#define LN_sha256WithRSAEncryption "sha256WithRSAEncryption" +#define NID_sha256WithRSAEncryption 668 +#define OBJ_sha256WithRSAEncryption OBJ_pkcs1,11L + +#define SN_sha384WithRSAEncryption "RSA-SHA384" +#define LN_sha384WithRSAEncryption "sha384WithRSAEncryption" +#define NID_sha384WithRSAEncryption 669 +#define OBJ_sha384WithRSAEncryption OBJ_pkcs1,12L + +#define SN_sha512WithRSAEncryption "RSA-SHA512" +#define LN_sha512WithRSAEncryption "sha512WithRSAEncryption" +#define NID_sha512WithRSAEncryption 670 +#define OBJ_sha512WithRSAEncryption OBJ_pkcs1,13L + +#define SN_sha224WithRSAEncryption "RSA-SHA224" +#define LN_sha224WithRSAEncryption "sha224WithRSAEncryption" +#define NID_sha224WithRSAEncryption 671 +#define OBJ_sha224WithRSAEncryption OBJ_pkcs1,14L + +#define SN_sha512_224WithRSAEncryption "RSA-SHA512/224" +#define LN_sha512_224WithRSAEncryption "sha512-224WithRSAEncryption" +#define NID_sha512_224WithRSAEncryption 1145 +#define OBJ_sha512_224WithRSAEncryption OBJ_pkcs1,15L + +#define SN_sha512_256WithRSAEncryption "RSA-SHA512/256" +#define LN_sha512_256WithRSAEncryption "sha512-256WithRSAEncryption" +#define NID_sha512_256WithRSAEncryption 1146 +#define OBJ_sha512_256WithRSAEncryption OBJ_pkcs1,16L + +#define SN_pkcs3 "pkcs3" +#define NID_pkcs3 27 +#define OBJ_pkcs3 OBJ_pkcs,3L + +#define LN_dhKeyAgreement "dhKeyAgreement" +#define NID_dhKeyAgreement 28 +#define OBJ_dhKeyAgreement OBJ_pkcs3,1L + +#define SN_pkcs5 "pkcs5" +#define NID_pkcs5 187 +#define OBJ_pkcs5 OBJ_pkcs,5L + +#define SN_pbeWithMD2AndDES_CBC "PBE-MD2-DES" +#define LN_pbeWithMD2AndDES_CBC "pbeWithMD2AndDES-CBC" +#define NID_pbeWithMD2AndDES_CBC 9 +#define OBJ_pbeWithMD2AndDES_CBC OBJ_pkcs5,1L + +#define SN_pbeWithMD5AndDES_CBC "PBE-MD5-DES" +#define LN_pbeWithMD5AndDES_CBC "pbeWithMD5AndDES-CBC" +#define NID_pbeWithMD5AndDES_CBC 10 +#define OBJ_pbeWithMD5AndDES_CBC OBJ_pkcs5,3L + +#define SN_pbeWithMD2AndRC2_CBC "PBE-MD2-RC2-64" +#define LN_pbeWithMD2AndRC2_CBC "pbeWithMD2AndRC2-CBC" +#define NID_pbeWithMD2AndRC2_CBC 168 +#define OBJ_pbeWithMD2AndRC2_CBC OBJ_pkcs5,4L + +#define SN_pbeWithMD5AndRC2_CBC "PBE-MD5-RC2-64" +#define LN_pbeWithMD5AndRC2_CBC "pbeWithMD5AndRC2-CBC" +#define NID_pbeWithMD5AndRC2_CBC 169 +#define OBJ_pbeWithMD5AndRC2_CBC OBJ_pkcs5,6L + +#define SN_pbeWithSHA1AndDES_CBC "PBE-SHA1-DES" +#define LN_pbeWithSHA1AndDES_CBC "pbeWithSHA1AndDES-CBC" +#define NID_pbeWithSHA1AndDES_CBC 170 +#define OBJ_pbeWithSHA1AndDES_CBC OBJ_pkcs5,10L + +#define SN_pbeWithSHA1AndRC2_CBC "PBE-SHA1-RC2-64" +#define LN_pbeWithSHA1AndRC2_CBC "pbeWithSHA1AndRC2-CBC" +#define NID_pbeWithSHA1AndRC2_CBC 68 +#define OBJ_pbeWithSHA1AndRC2_CBC OBJ_pkcs5,11L + +#define LN_id_pbkdf2 "PBKDF2" +#define NID_id_pbkdf2 69 +#define OBJ_id_pbkdf2 OBJ_pkcs5,12L + +#define LN_pbes2 "PBES2" +#define NID_pbes2 161 +#define OBJ_pbes2 OBJ_pkcs5,13L + +#define LN_pbmac1 "PBMAC1" +#define NID_pbmac1 162 +#define OBJ_pbmac1 OBJ_pkcs5,14L + +#define SN_pkcs7 "pkcs7" +#define NID_pkcs7 20 +#define OBJ_pkcs7 OBJ_pkcs,7L + +#define LN_pkcs7_data "pkcs7-data" +#define NID_pkcs7_data 21 +#define OBJ_pkcs7_data OBJ_pkcs7,1L + +#define LN_pkcs7_signed "pkcs7-signedData" +#define NID_pkcs7_signed 22 +#define OBJ_pkcs7_signed OBJ_pkcs7,2L + +#define LN_pkcs7_enveloped "pkcs7-envelopedData" +#define NID_pkcs7_enveloped 23 +#define OBJ_pkcs7_enveloped OBJ_pkcs7,3L + +#define LN_pkcs7_signedAndEnveloped "pkcs7-signedAndEnvelopedData" +#define NID_pkcs7_signedAndEnveloped 24 +#define OBJ_pkcs7_signedAndEnveloped OBJ_pkcs7,4L + +#define LN_pkcs7_digest "pkcs7-digestData" +#define NID_pkcs7_digest 25 +#define OBJ_pkcs7_digest OBJ_pkcs7,5L + +#define LN_pkcs7_encrypted "pkcs7-encryptedData" +#define NID_pkcs7_encrypted 26 +#define OBJ_pkcs7_encrypted OBJ_pkcs7,6L + +#define SN_pkcs9 "pkcs9" +#define NID_pkcs9 47 +#define OBJ_pkcs9 OBJ_pkcs,9L + +#define LN_pkcs9_emailAddress "emailAddress" +#define NID_pkcs9_emailAddress 48 +#define OBJ_pkcs9_emailAddress OBJ_pkcs9,1L + +#define LN_pkcs9_unstructuredName "unstructuredName" +#define NID_pkcs9_unstructuredName 49 +#define OBJ_pkcs9_unstructuredName OBJ_pkcs9,2L + +#define LN_pkcs9_contentType "contentType" +#define NID_pkcs9_contentType 50 +#define OBJ_pkcs9_contentType OBJ_pkcs9,3L + +#define LN_pkcs9_messageDigest "messageDigest" +#define NID_pkcs9_messageDigest 51 +#define OBJ_pkcs9_messageDigest OBJ_pkcs9,4L + +#define LN_pkcs9_signingTime "signingTime" +#define NID_pkcs9_signingTime 52 +#define OBJ_pkcs9_signingTime OBJ_pkcs9,5L + +#define LN_pkcs9_countersignature "countersignature" +#define NID_pkcs9_countersignature 53 +#define OBJ_pkcs9_countersignature OBJ_pkcs9,6L + +#define LN_pkcs9_challengePassword "challengePassword" +#define NID_pkcs9_challengePassword 54 +#define OBJ_pkcs9_challengePassword OBJ_pkcs9,7L + +#define LN_pkcs9_unstructuredAddress "unstructuredAddress" +#define NID_pkcs9_unstructuredAddress 55 +#define OBJ_pkcs9_unstructuredAddress OBJ_pkcs9,8L + +#define LN_pkcs9_extCertAttributes "extendedCertificateAttributes" +#define NID_pkcs9_extCertAttributes 56 +#define OBJ_pkcs9_extCertAttributes OBJ_pkcs9,9L + +#define SN_ext_req "extReq" +#define LN_ext_req "Extension Request" +#define NID_ext_req 172 +#define OBJ_ext_req OBJ_pkcs9,14L + +#define SN_SMIMECapabilities "SMIME-CAPS" +#define LN_SMIMECapabilities "S/MIME Capabilities" +#define NID_SMIMECapabilities 167 +#define OBJ_SMIMECapabilities OBJ_pkcs9,15L + +#define SN_SMIME "SMIME" +#define LN_SMIME "S/MIME" +#define NID_SMIME 188 +#define OBJ_SMIME OBJ_pkcs9,16L + +#define SN_id_smime_mod "id-smime-mod" +#define NID_id_smime_mod 189 +#define OBJ_id_smime_mod OBJ_SMIME,0L + +#define SN_id_smime_ct "id-smime-ct" +#define NID_id_smime_ct 190 +#define OBJ_id_smime_ct OBJ_SMIME,1L + +#define SN_id_smime_aa "id-smime-aa" +#define NID_id_smime_aa 191 +#define OBJ_id_smime_aa OBJ_SMIME,2L + +#define SN_id_smime_alg "id-smime-alg" +#define NID_id_smime_alg 192 +#define OBJ_id_smime_alg OBJ_SMIME,3L + +#define SN_id_smime_cd "id-smime-cd" +#define NID_id_smime_cd 193 +#define OBJ_id_smime_cd OBJ_SMIME,4L + +#define SN_id_smime_spq "id-smime-spq" +#define NID_id_smime_spq 194 +#define OBJ_id_smime_spq OBJ_SMIME,5L + +#define SN_id_smime_cti "id-smime-cti" +#define NID_id_smime_cti 195 +#define OBJ_id_smime_cti OBJ_SMIME,6L + +#define SN_id_smime_mod_cms "id-smime-mod-cms" +#define NID_id_smime_mod_cms 196 +#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L + +#define SN_id_smime_mod_ess "id-smime-mod-ess" +#define NID_id_smime_mod_ess 197 +#define OBJ_id_smime_mod_ess OBJ_id_smime_mod,2L + +#define SN_id_smime_mod_oid "id-smime-mod-oid" +#define NID_id_smime_mod_oid 198 +#define OBJ_id_smime_mod_oid OBJ_id_smime_mod,3L + +#define SN_id_smime_mod_msg_v3 "id-smime-mod-msg-v3" +#define NID_id_smime_mod_msg_v3 199 +#define OBJ_id_smime_mod_msg_v3 OBJ_id_smime_mod,4L + +#define SN_id_smime_mod_ets_eSignature_88 "id-smime-mod-ets-eSignature-88" +#define NID_id_smime_mod_ets_eSignature_88 200 +#define OBJ_id_smime_mod_ets_eSignature_88 OBJ_id_smime_mod,5L + +#define SN_id_smime_mod_ets_eSignature_97 "id-smime-mod-ets-eSignature-97" +#define NID_id_smime_mod_ets_eSignature_97 201 +#define OBJ_id_smime_mod_ets_eSignature_97 OBJ_id_smime_mod,6L + +#define SN_id_smime_mod_ets_eSigPolicy_88 "id-smime-mod-ets-eSigPolicy-88" +#define NID_id_smime_mod_ets_eSigPolicy_88 202 +#define OBJ_id_smime_mod_ets_eSigPolicy_88 OBJ_id_smime_mod,7L + +#define SN_id_smime_mod_ets_eSigPolicy_97 "id-smime-mod-ets-eSigPolicy-97" +#define NID_id_smime_mod_ets_eSigPolicy_97 203 +#define OBJ_id_smime_mod_ets_eSigPolicy_97 OBJ_id_smime_mod,8L + +#define SN_id_smime_ct_receipt "id-smime-ct-receipt" +#define NID_id_smime_ct_receipt 204 +#define OBJ_id_smime_ct_receipt OBJ_id_smime_ct,1L + +#define SN_id_smime_ct_authData "id-smime-ct-authData" +#define NID_id_smime_ct_authData 205 +#define OBJ_id_smime_ct_authData OBJ_id_smime_ct,2L + +#define SN_id_smime_ct_publishCert "id-smime-ct-publishCert" +#define NID_id_smime_ct_publishCert 206 +#define OBJ_id_smime_ct_publishCert OBJ_id_smime_ct,3L + +#define SN_id_smime_ct_TSTInfo "id-smime-ct-TSTInfo" +#define NID_id_smime_ct_TSTInfo 207 +#define OBJ_id_smime_ct_TSTInfo OBJ_id_smime_ct,4L + +#define SN_id_smime_ct_TDTInfo "id-smime-ct-TDTInfo" +#define NID_id_smime_ct_TDTInfo 208 +#define OBJ_id_smime_ct_TDTInfo OBJ_id_smime_ct,5L + +#define SN_id_smime_ct_contentInfo "id-smime-ct-contentInfo" +#define NID_id_smime_ct_contentInfo 209 +#define OBJ_id_smime_ct_contentInfo OBJ_id_smime_ct,6L + +#define SN_id_smime_ct_DVCSRequestData "id-smime-ct-DVCSRequestData" +#define NID_id_smime_ct_DVCSRequestData 210 +#define OBJ_id_smime_ct_DVCSRequestData OBJ_id_smime_ct,7L + +#define SN_id_smime_ct_DVCSResponseData "id-smime-ct-DVCSResponseData" +#define NID_id_smime_ct_DVCSResponseData 211 +#define OBJ_id_smime_ct_DVCSResponseData OBJ_id_smime_ct,8L + +#define SN_id_smime_ct_compressedData "id-smime-ct-compressedData" +#define NID_id_smime_ct_compressedData 786 +#define OBJ_id_smime_ct_compressedData OBJ_id_smime_ct,9L + +#define SN_id_smime_ct_contentCollection "id-smime-ct-contentCollection" +#define NID_id_smime_ct_contentCollection 1058 +#define OBJ_id_smime_ct_contentCollection OBJ_id_smime_ct,19L + +#define SN_id_smime_ct_authEnvelopedData "id-smime-ct-authEnvelopedData" +#define NID_id_smime_ct_authEnvelopedData 1059 +#define OBJ_id_smime_ct_authEnvelopedData OBJ_id_smime_ct,23L + +#define SN_id_ct_asciiTextWithCRLF "id-ct-asciiTextWithCRLF" +#define NID_id_ct_asciiTextWithCRLF 787 +#define OBJ_id_ct_asciiTextWithCRLF OBJ_id_smime_ct,27L + +#define SN_id_ct_xml "id-ct-xml" +#define NID_id_ct_xml 1060 +#define OBJ_id_ct_xml OBJ_id_smime_ct,28L + +#define SN_id_smime_aa_receiptRequest "id-smime-aa-receiptRequest" +#define NID_id_smime_aa_receiptRequest 212 +#define OBJ_id_smime_aa_receiptRequest OBJ_id_smime_aa,1L + +#define SN_id_smime_aa_securityLabel "id-smime-aa-securityLabel" +#define NID_id_smime_aa_securityLabel 213 +#define OBJ_id_smime_aa_securityLabel OBJ_id_smime_aa,2L + +#define SN_id_smime_aa_mlExpandHistory "id-smime-aa-mlExpandHistory" +#define NID_id_smime_aa_mlExpandHistory 214 +#define OBJ_id_smime_aa_mlExpandHistory OBJ_id_smime_aa,3L + +#define SN_id_smime_aa_contentHint "id-smime-aa-contentHint" +#define NID_id_smime_aa_contentHint 215 +#define OBJ_id_smime_aa_contentHint OBJ_id_smime_aa,4L + +#define SN_id_smime_aa_msgSigDigest "id-smime-aa-msgSigDigest" +#define NID_id_smime_aa_msgSigDigest 216 +#define OBJ_id_smime_aa_msgSigDigest OBJ_id_smime_aa,5L + +#define SN_id_smime_aa_encapContentType "id-smime-aa-encapContentType" +#define NID_id_smime_aa_encapContentType 217 +#define OBJ_id_smime_aa_encapContentType OBJ_id_smime_aa,6L + +#define SN_id_smime_aa_contentIdentifier "id-smime-aa-contentIdentifier" +#define NID_id_smime_aa_contentIdentifier 218 +#define OBJ_id_smime_aa_contentIdentifier OBJ_id_smime_aa,7L + +#define SN_id_smime_aa_macValue "id-smime-aa-macValue" +#define NID_id_smime_aa_macValue 219 +#define OBJ_id_smime_aa_macValue OBJ_id_smime_aa,8L + +#define SN_id_smime_aa_equivalentLabels "id-smime-aa-equivalentLabels" +#define NID_id_smime_aa_equivalentLabels 220 +#define OBJ_id_smime_aa_equivalentLabels OBJ_id_smime_aa,9L + +#define SN_id_smime_aa_contentReference "id-smime-aa-contentReference" +#define NID_id_smime_aa_contentReference 221 +#define OBJ_id_smime_aa_contentReference OBJ_id_smime_aa,10L + +#define SN_id_smime_aa_encrypKeyPref "id-smime-aa-encrypKeyPref" +#define NID_id_smime_aa_encrypKeyPref 222 +#define OBJ_id_smime_aa_encrypKeyPref OBJ_id_smime_aa,11L + +#define SN_id_smime_aa_signingCertificate "id-smime-aa-signingCertificate" +#define NID_id_smime_aa_signingCertificate 223 +#define OBJ_id_smime_aa_signingCertificate OBJ_id_smime_aa,12L + +#define SN_id_smime_aa_smimeEncryptCerts "id-smime-aa-smimeEncryptCerts" +#define NID_id_smime_aa_smimeEncryptCerts 224 +#define OBJ_id_smime_aa_smimeEncryptCerts OBJ_id_smime_aa,13L + +#define SN_id_smime_aa_timeStampToken "id-smime-aa-timeStampToken" +#define NID_id_smime_aa_timeStampToken 225 +#define OBJ_id_smime_aa_timeStampToken OBJ_id_smime_aa,14L + +#define SN_id_smime_aa_ets_sigPolicyId "id-smime-aa-ets-sigPolicyId" +#define NID_id_smime_aa_ets_sigPolicyId 226 +#define OBJ_id_smime_aa_ets_sigPolicyId OBJ_id_smime_aa,15L + +#define SN_id_smime_aa_ets_commitmentType "id-smime-aa-ets-commitmentType" +#define NID_id_smime_aa_ets_commitmentType 227 +#define OBJ_id_smime_aa_ets_commitmentType OBJ_id_smime_aa,16L + +#define SN_id_smime_aa_ets_signerLocation "id-smime-aa-ets-signerLocation" +#define NID_id_smime_aa_ets_signerLocation 228 +#define OBJ_id_smime_aa_ets_signerLocation OBJ_id_smime_aa,17L + +#define SN_id_smime_aa_ets_signerAttr "id-smime-aa-ets-signerAttr" +#define NID_id_smime_aa_ets_signerAttr 229 +#define OBJ_id_smime_aa_ets_signerAttr OBJ_id_smime_aa,18L + +#define SN_id_smime_aa_ets_otherSigCert "id-smime-aa-ets-otherSigCert" +#define NID_id_smime_aa_ets_otherSigCert 230 +#define OBJ_id_smime_aa_ets_otherSigCert OBJ_id_smime_aa,19L + +#define SN_id_smime_aa_ets_contentTimestamp "id-smime-aa-ets-contentTimestamp" +#define NID_id_smime_aa_ets_contentTimestamp 231 +#define OBJ_id_smime_aa_ets_contentTimestamp OBJ_id_smime_aa,20L + +#define SN_id_smime_aa_ets_CertificateRefs "id-smime-aa-ets-CertificateRefs" +#define NID_id_smime_aa_ets_CertificateRefs 232 +#define OBJ_id_smime_aa_ets_CertificateRefs OBJ_id_smime_aa,21L + +#define SN_id_smime_aa_ets_RevocationRefs "id-smime-aa-ets-RevocationRefs" +#define NID_id_smime_aa_ets_RevocationRefs 233 +#define OBJ_id_smime_aa_ets_RevocationRefs OBJ_id_smime_aa,22L + +#define SN_id_smime_aa_ets_certValues "id-smime-aa-ets-certValues" +#define NID_id_smime_aa_ets_certValues 234 +#define OBJ_id_smime_aa_ets_certValues OBJ_id_smime_aa,23L + +#define SN_id_smime_aa_ets_revocationValues "id-smime-aa-ets-revocationValues" +#define NID_id_smime_aa_ets_revocationValues 235 +#define OBJ_id_smime_aa_ets_revocationValues OBJ_id_smime_aa,24L + +#define SN_id_smime_aa_ets_escTimeStamp "id-smime-aa-ets-escTimeStamp" +#define NID_id_smime_aa_ets_escTimeStamp 236 +#define OBJ_id_smime_aa_ets_escTimeStamp OBJ_id_smime_aa,25L + +#define SN_id_smime_aa_ets_certCRLTimestamp "id-smime-aa-ets-certCRLTimestamp" +#define NID_id_smime_aa_ets_certCRLTimestamp 237 +#define OBJ_id_smime_aa_ets_certCRLTimestamp OBJ_id_smime_aa,26L + +#define SN_id_smime_aa_ets_archiveTimeStamp "id-smime-aa-ets-archiveTimeStamp" +#define NID_id_smime_aa_ets_archiveTimeStamp 238 +#define OBJ_id_smime_aa_ets_archiveTimeStamp OBJ_id_smime_aa,27L + +#define SN_id_smime_aa_signatureType "id-smime-aa-signatureType" +#define NID_id_smime_aa_signatureType 239 +#define OBJ_id_smime_aa_signatureType OBJ_id_smime_aa,28L + +#define SN_id_smime_aa_dvcs_dvc "id-smime-aa-dvcs-dvc" +#define NID_id_smime_aa_dvcs_dvc 240 +#define OBJ_id_smime_aa_dvcs_dvc OBJ_id_smime_aa,29L + +#define SN_id_smime_aa_signingCertificateV2 "id-smime-aa-signingCertificateV2" +#define NID_id_smime_aa_signingCertificateV2 1086 +#define OBJ_id_smime_aa_signingCertificateV2 OBJ_id_smime_aa,47L + +#define SN_id_smime_alg_ESDHwith3DES "id-smime-alg-ESDHwith3DES" +#define NID_id_smime_alg_ESDHwith3DES 241 +#define OBJ_id_smime_alg_ESDHwith3DES OBJ_id_smime_alg,1L + +#define SN_id_smime_alg_ESDHwithRC2 "id-smime-alg-ESDHwithRC2" +#define NID_id_smime_alg_ESDHwithRC2 242 +#define OBJ_id_smime_alg_ESDHwithRC2 OBJ_id_smime_alg,2L + +#define SN_id_smime_alg_3DESwrap "id-smime-alg-3DESwrap" +#define NID_id_smime_alg_3DESwrap 243 +#define OBJ_id_smime_alg_3DESwrap OBJ_id_smime_alg,3L + +#define SN_id_smime_alg_RC2wrap "id-smime-alg-RC2wrap" +#define NID_id_smime_alg_RC2wrap 244 +#define OBJ_id_smime_alg_RC2wrap OBJ_id_smime_alg,4L + +#define SN_id_smime_alg_ESDH "id-smime-alg-ESDH" +#define NID_id_smime_alg_ESDH 245 +#define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L + +#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" +#define NID_id_smime_alg_CMS3DESwrap 246 +#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L + +#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" +#define NID_id_smime_alg_CMSRC2wrap 247 +#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L + +#define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" +#define NID_id_alg_PWRI_KEK 893 +#define OBJ_id_alg_PWRI_KEK OBJ_id_smime_alg,9L + +#define SN_id_smime_cd_ldap "id-smime-cd-ldap" +#define NID_id_smime_cd_ldap 248 +#define OBJ_id_smime_cd_ldap OBJ_id_smime_cd,1L + +#define SN_id_smime_spq_ets_sqt_uri "id-smime-spq-ets-sqt-uri" +#define NID_id_smime_spq_ets_sqt_uri 249 +#define OBJ_id_smime_spq_ets_sqt_uri OBJ_id_smime_spq,1L + +#define SN_id_smime_spq_ets_sqt_unotice "id-smime-spq-ets-sqt-unotice" +#define NID_id_smime_spq_ets_sqt_unotice 250 +#define OBJ_id_smime_spq_ets_sqt_unotice OBJ_id_smime_spq,2L + +#define SN_id_smime_cti_ets_proofOfOrigin "id-smime-cti-ets-proofOfOrigin" +#define NID_id_smime_cti_ets_proofOfOrigin 251 +#define OBJ_id_smime_cti_ets_proofOfOrigin OBJ_id_smime_cti,1L + +#define SN_id_smime_cti_ets_proofOfReceipt "id-smime-cti-ets-proofOfReceipt" +#define NID_id_smime_cti_ets_proofOfReceipt 252 +#define OBJ_id_smime_cti_ets_proofOfReceipt OBJ_id_smime_cti,2L + +#define SN_id_smime_cti_ets_proofOfDelivery "id-smime-cti-ets-proofOfDelivery" +#define NID_id_smime_cti_ets_proofOfDelivery 253 +#define OBJ_id_smime_cti_ets_proofOfDelivery OBJ_id_smime_cti,3L + +#define SN_id_smime_cti_ets_proofOfSender "id-smime-cti-ets-proofOfSender" +#define NID_id_smime_cti_ets_proofOfSender 254 +#define OBJ_id_smime_cti_ets_proofOfSender OBJ_id_smime_cti,4L + +#define SN_id_smime_cti_ets_proofOfApproval "id-smime-cti-ets-proofOfApproval" +#define NID_id_smime_cti_ets_proofOfApproval 255 +#define OBJ_id_smime_cti_ets_proofOfApproval OBJ_id_smime_cti,5L + +#define SN_id_smime_cti_ets_proofOfCreation "id-smime-cti-ets-proofOfCreation" +#define NID_id_smime_cti_ets_proofOfCreation 256 +#define OBJ_id_smime_cti_ets_proofOfCreation OBJ_id_smime_cti,6L + +#define LN_friendlyName "friendlyName" +#define NID_friendlyName 156 +#define OBJ_friendlyName OBJ_pkcs9,20L + +#define LN_localKeyID "localKeyID" +#define NID_localKeyID 157 +#define OBJ_localKeyID OBJ_pkcs9,21L + +#define SN_ms_csp_name "CSPName" +#define LN_ms_csp_name "Microsoft CSP Name" +#define NID_ms_csp_name 417 +#define OBJ_ms_csp_name 1L,3L,6L,1L,4L,1L,311L,17L,1L + +#define SN_LocalKeySet "LocalKeySet" +#define LN_LocalKeySet "Microsoft Local Key set" +#define NID_LocalKeySet 856 +#define OBJ_LocalKeySet 1L,3L,6L,1L,4L,1L,311L,17L,2L + +#define OBJ_certTypes OBJ_pkcs9,22L + +#define LN_x509Certificate "x509Certificate" +#define NID_x509Certificate 158 +#define OBJ_x509Certificate OBJ_certTypes,1L + +#define LN_sdsiCertificate "sdsiCertificate" +#define NID_sdsiCertificate 159 +#define OBJ_sdsiCertificate OBJ_certTypes,2L + +#define OBJ_crlTypes OBJ_pkcs9,23L + +#define LN_x509Crl "x509Crl" +#define NID_x509Crl 160 +#define OBJ_x509Crl OBJ_crlTypes,1L + +#define OBJ_pkcs12 OBJ_pkcs,12L + +#define OBJ_pkcs12_pbeids OBJ_pkcs12,1L + +#define SN_pbe_WithSHA1And128BitRC4 "PBE-SHA1-RC4-128" +#define LN_pbe_WithSHA1And128BitRC4 "pbeWithSHA1And128BitRC4" +#define NID_pbe_WithSHA1And128BitRC4 144 +#define OBJ_pbe_WithSHA1And128BitRC4 OBJ_pkcs12_pbeids,1L + +#define SN_pbe_WithSHA1And40BitRC4 "PBE-SHA1-RC4-40" +#define LN_pbe_WithSHA1And40BitRC4 "pbeWithSHA1And40BitRC4" +#define NID_pbe_WithSHA1And40BitRC4 145 +#define OBJ_pbe_WithSHA1And40BitRC4 OBJ_pkcs12_pbeids,2L + +#define SN_pbe_WithSHA1And3_Key_TripleDES_CBC "PBE-SHA1-3DES" +#define LN_pbe_WithSHA1And3_Key_TripleDES_CBC "pbeWithSHA1And3-KeyTripleDES-CBC" +#define NID_pbe_WithSHA1And3_Key_TripleDES_CBC 146 +#define OBJ_pbe_WithSHA1And3_Key_TripleDES_CBC OBJ_pkcs12_pbeids,3L + +#define SN_pbe_WithSHA1And2_Key_TripleDES_CBC "PBE-SHA1-2DES" +#define LN_pbe_WithSHA1And2_Key_TripleDES_CBC "pbeWithSHA1And2-KeyTripleDES-CBC" +#define NID_pbe_WithSHA1And2_Key_TripleDES_CBC 147 +#define OBJ_pbe_WithSHA1And2_Key_TripleDES_CBC OBJ_pkcs12_pbeids,4L + +#define SN_pbe_WithSHA1And128BitRC2_CBC "PBE-SHA1-RC2-128" +#define LN_pbe_WithSHA1And128BitRC2_CBC "pbeWithSHA1And128BitRC2-CBC" +#define NID_pbe_WithSHA1And128BitRC2_CBC 148 +#define OBJ_pbe_WithSHA1And128BitRC2_CBC OBJ_pkcs12_pbeids,5L + +#define SN_pbe_WithSHA1And40BitRC2_CBC "PBE-SHA1-RC2-40" +#define LN_pbe_WithSHA1And40BitRC2_CBC "pbeWithSHA1And40BitRC2-CBC" +#define NID_pbe_WithSHA1And40BitRC2_CBC 149 +#define OBJ_pbe_WithSHA1And40BitRC2_CBC OBJ_pkcs12_pbeids,6L + +#define OBJ_pkcs12_Version1 OBJ_pkcs12,10L + +#define OBJ_pkcs12_BagIds OBJ_pkcs12_Version1,1L + +#define LN_keyBag "keyBag" +#define NID_keyBag 150 +#define OBJ_keyBag OBJ_pkcs12_BagIds,1L + +#define LN_pkcs8ShroudedKeyBag "pkcs8ShroudedKeyBag" +#define NID_pkcs8ShroudedKeyBag 151 +#define OBJ_pkcs8ShroudedKeyBag OBJ_pkcs12_BagIds,2L + +#define LN_certBag "certBag" +#define NID_certBag 152 +#define OBJ_certBag OBJ_pkcs12_BagIds,3L + +#define LN_crlBag "crlBag" +#define NID_crlBag 153 +#define OBJ_crlBag OBJ_pkcs12_BagIds,4L + +#define LN_secretBag "secretBag" +#define NID_secretBag 154 +#define OBJ_secretBag OBJ_pkcs12_BagIds,5L + +#define LN_safeContentsBag "safeContentsBag" +#define NID_safeContentsBag 155 +#define OBJ_safeContentsBag OBJ_pkcs12_BagIds,6L + +#define SN_md2 "MD2" +#define LN_md2 "md2" +#define NID_md2 3 +#define OBJ_md2 OBJ_rsadsi,2L,2L + +#define SN_md4 "MD4" +#define LN_md4 "md4" +#define NID_md4 257 +#define OBJ_md4 OBJ_rsadsi,2L,4L + +#define SN_md5 "MD5" +#define LN_md5 "md5" +#define NID_md5 4 +#define OBJ_md5 OBJ_rsadsi,2L,5L + +#define SN_md5_sha1 "MD5-SHA1" +#define LN_md5_sha1 "md5-sha1" +#define NID_md5_sha1 114 + +#define LN_hmacWithMD5 "hmacWithMD5" +#define NID_hmacWithMD5 797 +#define OBJ_hmacWithMD5 OBJ_rsadsi,2L,6L + +#define LN_hmacWithSHA1 "hmacWithSHA1" +#define NID_hmacWithSHA1 163 +#define OBJ_hmacWithSHA1 OBJ_rsadsi,2L,7L + +#define SN_sm2 "SM2" +#define LN_sm2 "sm2" +#define NID_sm2 1172 +#define OBJ_sm2 OBJ_sm_scheme,301L + +#define SN_sm3 "SM3" +#define LN_sm3 "sm3" +#define NID_sm3 1143 +#define OBJ_sm3 OBJ_sm_scheme,401L + +#define SN_sm3WithRSAEncryption "RSA-SM3" +#define LN_sm3WithRSAEncryption "sm3WithRSAEncryption" +#define NID_sm3WithRSAEncryption 1144 +#define OBJ_sm3WithRSAEncryption OBJ_sm_scheme,504L + +#define LN_hmacWithSHA224 "hmacWithSHA224" +#define NID_hmacWithSHA224 798 +#define OBJ_hmacWithSHA224 OBJ_rsadsi,2L,8L + +#define LN_hmacWithSHA256 "hmacWithSHA256" +#define NID_hmacWithSHA256 799 +#define OBJ_hmacWithSHA256 OBJ_rsadsi,2L,9L + +#define LN_hmacWithSHA384 "hmacWithSHA384" +#define NID_hmacWithSHA384 800 +#define OBJ_hmacWithSHA384 OBJ_rsadsi,2L,10L + +#define LN_hmacWithSHA512 "hmacWithSHA512" +#define NID_hmacWithSHA512 801 +#define OBJ_hmacWithSHA512 OBJ_rsadsi,2L,11L + +#define LN_hmacWithSHA512_224 "hmacWithSHA512-224" +#define NID_hmacWithSHA512_224 1193 +#define OBJ_hmacWithSHA512_224 OBJ_rsadsi,2L,12L + +#define LN_hmacWithSHA512_256 "hmacWithSHA512-256" +#define NID_hmacWithSHA512_256 1194 +#define OBJ_hmacWithSHA512_256 OBJ_rsadsi,2L,13L + +#define SN_rc2_cbc "RC2-CBC" +#define LN_rc2_cbc "rc2-cbc" +#define NID_rc2_cbc 37 +#define OBJ_rc2_cbc OBJ_rsadsi,3L,2L + +#define SN_rc2_ecb "RC2-ECB" +#define LN_rc2_ecb "rc2-ecb" +#define NID_rc2_ecb 38 + +#define SN_rc2_cfb64 "RC2-CFB" +#define LN_rc2_cfb64 "rc2-cfb" +#define NID_rc2_cfb64 39 + +#define SN_rc2_ofb64 "RC2-OFB" +#define LN_rc2_ofb64 "rc2-ofb" +#define NID_rc2_ofb64 40 + +#define SN_rc2_40_cbc "RC2-40-CBC" +#define LN_rc2_40_cbc "rc2-40-cbc" +#define NID_rc2_40_cbc 98 + +#define SN_rc2_64_cbc "RC2-64-CBC" +#define LN_rc2_64_cbc "rc2-64-cbc" +#define NID_rc2_64_cbc 166 + +#define SN_rc4 "RC4" +#define LN_rc4 "rc4" +#define NID_rc4 5 +#define OBJ_rc4 OBJ_rsadsi,3L,4L + +#define SN_rc4_40 "RC4-40" +#define LN_rc4_40 "rc4-40" +#define NID_rc4_40 97 + +#define SN_des_ede3_cbc "DES-EDE3-CBC" +#define LN_des_ede3_cbc "des-ede3-cbc" +#define NID_des_ede3_cbc 44 +#define OBJ_des_ede3_cbc OBJ_rsadsi,3L,7L + +#define SN_rc5_cbc "RC5-CBC" +#define LN_rc5_cbc "rc5-cbc" +#define NID_rc5_cbc 120 +#define OBJ_rc5_cbc OBJ_rsadsi,3L,8L + +#define SN_rc5_ecb "RC5-ECB" +#define LN_rc5_ecb "rc5-ecb" +#define NID_rc5_ecb 121 + +#define SN_rc5_cfb64 "RC5-CFB" +#define LN_rc5_cfb64 "rc5-cfb" +#define NID_rc5_cfb64 122 + +#define SN_rc5_ofb64 "RC5-OFB" +#define LN_rc5_ofb64 "rc5-ofb" +#define NID_rc5_ofb64 123 + +#define SN_ms_ext_req "msExtReq" +#define LN_ms_ext_req "Microsoft Extension Request" +#define NID_ms_ext_req 171 +#define OBJ_ms_ext_req 1L,3L,6L,1L,4L,1L,311L,2L,1L,14L + +#define SN_ms_code_ind "msCodeInd" +#define LN_ms_code_ind "Microsoft Individual Code Signing" +#define NID_ms_code_ind 134 +#define OBJ_ms_code_ind 1L,3L,6L,1L,4L,1L,311L,2L,1L,21L + +#define SN_ms_code_com "msCodeCom" +#define LN_ms_code_com "Microsoft Commercial Code Signing" +#define NID_ms_code_com 135 +#define OBJ_ms_code_com 1L,3L,6L,1L,4L,1L,311L,2L,1L,22L + +#define SN_ms_ctl_sign "msCTLSign" +#define LN_ms_ctl_sign "Microsoft Trust List Signing" +#define NID_ms_ctl_sign 136 +#define OBJ_ms_ctl_sign 1L,3L,6L,1L,4L,1L,311L,10L,3L,1L + +#define SN_ms_sgc "msSGC" +#define LN_ms_sgc "Microsoft Server Gated Crypto" +#define NID_ms_sgc 137 +#define OBJ_ms_sgc 1L,3L,6L,1L,4L,1L,311L,10L,3L,3L + +#define SN_ms_efs "msEFS" +#define LN_ms_efs "Microsoft Encrypted File System" +#define NID_ms_efs 138 +#define OBJ_ms_efs 1L,3L,6L,1L,4L,1L,311L,10L,3L,4L + +#define SN_ms_smartcard_login "msSmartcardLogin" +#define LN_ms_smartcard_login "Microsoft Smartcardlogin" +#define NID_ms_smartcard_login 648 +#define OBJ_ms_smartcard_login 1L,3L,6L,1L,4L,1L,311L,20L,2L,2L + +#define SN_ms_upn "msUPN" +#define LN_ms_upn "Microsoft Universal Principal Name" +#define NID_ms_upn 649 +#define OBJ_ms_upn 1L,3L,6L,1L,4L,1L,311L,20L,2L,3L + +#define SN_idea_cbc "IDEA-CBC" +#define LN_idea_cbc "idea-cbc" +#define NID_idea_cbc 34 +#define OBJ_idea_cbc 1L,3L,6L,1L,4L,1L,188L,7L,1L,1L,2L + +#define SN_idea_ecb "IDEA-ECB" +#define LN_idea_ecb "idea-ecb" +#define NID_idea_ecb 36 + +#define SN_idea_cfb64 "IDEA-CFB" +#define LN_idea_cfb64 "idea-cfb" +#define NID_idea_cfb64 35 + +#define SN_idea_ofb64 "IDEA-OFB" +#define LN_idea_ofb64 "idea-ofb" +#define NID_idea_ofb64 46 + +#define SN_bf_cbc "BF-CBC" +#define LN_bf_cbc "bf-cbc" +#define NID_bf_cbc 91 +#define OBJ_bf_cbc 1L,3L,6L,1L,4L,1L,3029L,1L,2L + +#define SN_bf_ecb "BF-ECB" +#define LN_bf_ecb "bf-ecb" +#define NID_bf_ecb 92 + +#define SN_bf_cfb64 "BF-CFB" +#define LN_bf_cfb64 "bf-cfb" +#define NID_bf_cfb64 93 + +#define SN_bf_ofb64 "BF-OFB" +#define LN_bf_ofb64 "bf-ofb" +#define NID_bf_ofb64 94 + +#define SN_id_pkix "PKIX" +#define NID_id_pkix 127 +#define OBJ_id_pkix 1L,3L,6L,1L,5L,5L,7L + +#define SN_id_pkix_mod "id-pkix-mod" +#define NID_id_pkix_mod 258 +#define OBJ_id_pkix_mod OBJ_id_pkix,0L + +#define SN_id_pe "id-pe" +#define NID_id_pe 175 +#define OBJ_id_pe OBJ_id_pkix,1L + +#define SN_id_qt "id-qt" +#define NID_id_qt 259 +#define OBJ_id_qt OBJ_id_pkix,2L + +#define SN_id_kp "id-kp" +#define NID_id_kp 128 +#define OBJ_id_kp OBJ_id_pkix,3L + +#define SN_id_it "id-it" +#define NID_id_it 260 +#define OBJ_id_it OBJ_id_pkix,4L + +#define SN_id_pkip "id-pkip" +#define NID_id_pkip 261 +#define OBJ_id_pkip OBJ_id_pkix,5L + +#define SN_id_alg "id-alg" +#define NID_id_alg 262 +#define OBJ_id_alg OBJ_id_pkix,6L + +#define SN_id_cmc "id-cmc" +#define NID_id_cmc 263 +#define OBJ_id_cmc OBJ_id_pkix,7L + +#define SN_id_on "id-on" +#define NID_id_on 264 +#define OBJ_id_on OBJ_id_pkix,8L + +#define SN_id_pda "id-pda" +#define NID_id_pda 265 +#define OBJ_id_pda OBJ_id_pkix,9L + +#define SN_id_aca "id-aca" +#define NID_id_aca 266 +#define OBJ_id_aca OBJ_id_pkix,10L + +#define SN_id_qcs "id-qcs" +#define NID_id_qcs 267 +#define OBJ_id_qcs OBJ_id_pkix,11L + +#define SN_id_cct "id-cct" +#define NID_id_cct 268 +#define OBJ_id_cct OBJ_id_pkix,12L + +#define SN_id_ppl "id-ppl" +#define NID_id_ppl 662 +#define OBJ_id_ppl OBJ_id_pkix,21L + +#define SN_id_ad "id-ad" +#define NID_id_ad 176 +#define OBJ_id_ad OBJ_id_pkix,48L + +#define SN_id_pkix1_explicit_88 "id-pkix1-explicit-88" +#define NID_id_pkix1_explicit_88 269 +#define OBJ_id_pkix1_explicit_88 OBJ_id_pkix_mod,1L + +#define SN_id_pkix1_implicit_88 "id-pkix1-implicit-88" +#define NID_id_pkix1_implicit_88 270 +#define OBJ_id_pkix1_implicit_88 OBJ_id_pkix_mod,2L + +#define SN_id_pkix1_explicit_93 "id-pkix1-explicit-93" +#define NID_id_pkix1_explicit_93 271 +#define OBJ_id_pkix1_explicit_93 OBJ_id_pkix_mod,3L + +#define SN_id_pkix1_implicit_93 "id-pkix1-implicit-93" +#define NID_id_pkix1_implicit_93 272 +#define OBJ_id_pkix1_implicit_93 OBJ_id_pkix_mod,4L + +#define SN_id_mod_crmf "id-mod-crmf" +#define NID_id_mod_crmf 273 +#define OBJ_id_mod_crmf OBJ_id_pkix_mod,5L + +#define SN_id_mod_cmc "id-mod-cmc" +#define NID_id_mod_cmc 274 +#define OBJ_id_mod_cmc OBJ_id_pkix_mod,6L + +#define SN_id_mod_kea_profile_88 "id-mod-kea-profile-88" +#define NID_id_mod_kea_profile_88 275 +#define OBJ_id_mod_kea_profile_88 OBJ_id_pkix_mod,7L + +#define SN_id_mod_kea_profile_93 "id-mod-kea-profile-93" +#define NID_id_mod_kea_profile_93 276 +#define OBJ_id_mod_kea_profile_93 OBJ_id_pkix_mod,8L + +#define SN_id_mod_cmp "id-mod-cmp" +#define NID_id_mod_cmp 277 +#define OBJ_id_mod_cmp OBJ_id_pkix_mod,9L + +#define SN_id_mod_qualified_cert_88 "id-mod-qualified-cert-88" +#define NID_id_mod_qualified_cert_88 278 +#define OBJ_id_mod_qualified_cert_88 OBJ_id_pkix_mod,10L + +#define SN_id_mod_qualified_cert_93 "id-mod-qualified-cert-93" +#define NID_id_mod_qualified_cert_93 279 +#define OBJ_id_mod_qualified_cert_93 OBJ_id_pkix_mod,11L + +#define SN_id_mod_attribute_cert "id-mod-attribute-cert" +#define NID_id_mod_attribute_cert 280 +#define OBJ_id_mod_attribute_cert OBJ_id_pkix_mod,12L + +#define SN_id_mod_timestamp_protocol "id-mod-timestamp-protocol" +#define NID_id_mod_timestamp_protocol 281 +#define OBJ_id_mod_timestamp_protocol OBJ_id_pkix_mod,13L + +#define SN_id_mod_ocsp "id-mod-ocsp" +#define NID_id_mod_ocsp 282 +#define OBJ_id_mod_ocsp OBJ_id_pkix_mod,14L + +#define SN_id_mod_dvcs "id-mod-dvcs" +#define NID_id_mod_dvcs 283 +#define OBJ_id_mod_dvcs OBJ_id_pkix_mod,15L + +#define SN_id_mod_cmp2000 "id-mod-cmp2000" +#define NID_id_mod_cmp2000 284 +#define OBJ_id_mod_cmp2000 OBJ_id_pkix_mod,16L + +#define SN_info_access "authorityInfoAccess" +#define LN_info_access "Authority Information Access" +#define NID_info_access 177 +#define OBJ_info_access OBJ_id_pe,1L + +#define SN_biometricInfo "biometricInfo" +#define LN_biometricInfo "Biometric Info" +#define NID_biometricInfo 285 +#define OBJ_biometricInfo OBJ_id_pe,2L + +#define SN_qcStatements "qcStatements" +#define NID_qcStatements 286 +#define OBJ_qcStatements OBJ_id_pe,3L + +#define SN_ac_auditEntity "ac-auditEntity" +#define NID_ac_auditEntity 287 +#define OBJ_ac_auditEntity OBJ_id_pe,4L + +#define SN_ac_targeting "ac-targeting" +#define NID_ac_targeting 288 +#define OBJ_ac_targeting OBJ_id_pe,5L + +#define SN_aaControls "aaControls" +#define NID_aaControls 289 +#define OBJ_aaControls OBJ_id_pe,6L + +#define SN_sbgp_ipAddrBlock "sbgp-ipAddrBlock" +#define NID_sbgp_ipAddrBlock 290 +#define OBJ_sbgp_ipAddrBlock OBJ_id_pe,7L + +#define SN_sbgp_autonomousSysNum "sbgp-autonomousSysNum" +#define NID_sbgp_autonomousSysNum 291 +#define OBJ_sbgp_autonomousSysNum OBJ_id_pe,8L + +#define SN_sbgp_routerIdentifier "sbgp-routerIdentifier" +#define NID_sbgp_routerIdentifier 292 +#define OBJ_sbgp_routerIdentifier OBJ_id_pe,9L + +#define SN_ac_proxying "ac-proxying" +#define NID_ac_proxying 397 +#define OBJ_ac_proxying OBJ_id_pe,10L + +#define SN_sinfo_access "subjectInfoAccess" +#define LN_sinfo_access "Subject Information Access" +#define NID_sinfo_access 398 +#define OBJ_sinfo_access OBJ_id_pe,11L + +#define SN_proxyCertInfo "proxyCertInfo" +#define LN_proxyCertInfo "Proxy Certificate Information" +#define NID_proxyCertInfo 663 +#define OBJ_proxyCertInfo OBJ_id_pe,14L + +#define SN_tlsfeature "tlsfeature" +#define LN_tlsfeature "TLS Feature" +#define NID_tlsfeature 1020 +#define OBJ_tlsfeature OBJ_id_pe,24L + +#define SN_id_qt_cps "id-qt-cps" +#define LN_id_qt_cps "Policy Qualifier CPS" +#define NID_id_qt_cps 164 +#define OBJ_id_qt_cps OBJ_id_qt,1L + +#define SN_id_qt_unotice "id-qt-unotice" +#define LN_id_qt_unotice "Policy Qualifier User Notice" +#define NID_id_qt_unotice 165 +#define OBJ_id_qt_unotice OBJ_id_qt,2L + +#define SN_textNotice "textNotice" +#define NID_textNotice 293 +#define OBJ_textNotice OBJ_id_qt,3L + +#define SN_server_auth "serverAuth" +#define LN_server_auth "TLS Web Server Authentication" +#define NID_server_auth 129 +#define OBJ_server_auth OBJ_id_kp,1L + +#define SN_client_auth "clientAuth" +#define LN_client_auth "TLS Web Client Authentication" +#define NID_client_auth 130 +#define OBJ_client_auth OBJ_id_kp,2L + +#define SN_code_sign "codeSigning" +#define LN_code_sign "Code Signing" +#define NID_code_sign 131 +#define OBJ_code_sign OBJ_id_kp,3L + +#define SN_email_protect "emailProtection" +#define LN_email_protect "E-mail Protection" +#define NID_email_protect 132 +#define OBJ_email_protect OBJ_id_kp,4L + +#define SN_ipsecEndSystem "ipsecEndSystem" +#define LN_ipsecEndSystem "IPSec End System" +#define NID_ipsecEndSystem 294 +#define OBJ_ipsecEndSystem OBJ_id_kp,5L + +#define SN_ipsecTunnel "ipsecTunnel" +#define LN_ipsecTunnel "IPSec Tunnel" +#define NID_ipsecTunnel 295 +#define OBJ_ipsecTunnel OBJ_id_kp,6L + +#define SN_ipsecUser "ipsecUser" +#define LN_ipsecUser "IPSec User" +#define NID_ipsecUser 296 +#define OBJ_ipsecUser OBJ_id_kp,7L + +#define SN_time_stamp "timeStamping" +#define LN_time_stamp "Time Stamping" +#define NID_time_stamp 133 +#define OBJ_time_stamp OBJ_id_kp,8L + +#define SN_OCSP_sign "OCSPSigning" +#define LN_OCSP_sign "OCSP Signing" +#define NID_OCSP_sign 180 +#define OBJ_OCSP_sign OBJ_id_kp,9L + +#define SN_dvcs "DVCS" +#define LN_dvcs "dvcs" +#define NID_dvcs 297 +#define OBJ_dvcs OBJ_id_kp,10L + +#define SN_ipsec_IKE "ipsecIKE" +#define LN_ipsec_IKE "ipsec Internet Key Exchange" +#define NID_ipsec_IKE 1022 +#define OBJ_ipsec_IKE OBJ_id_kp,17L + +#define SN_capwapAC "capwapAC" +#define LN_capwapAC "Ctrl/provision WAP Access" +#define NID_capwapAC 1023 +#define OBJ_capwapAC OBJ_id_kp,18L + +#define SN_capwapWTP "capwapWTP" +#define LN_capwapWTP "Ctrl/Provision WAP Termination" +#define NID_capwapWTP 1024 +#define OBJ_capwapWTP OBJ_id_kp,19L + +#define SN_sshClient "secureShellClient" +#define LN_sshClient "SSH Client" +#define NID_sshClient 1025 +#define OBJ_sshClient OBJ_id_kp,21L + +#define SN_sshServer "secureShellServer" +#define LN_sshServer "SSH Server" +#define NID_sshServer 1026 +#define OBJ_sshServer OBJ_id_kp,22L + +#define SN_sendRouter "sendRouter" +#define LN_sendRouter "Send Router" +#define NID_sendRouter 1027 +#define OBJ_sendRouter OBJ_id_kp,23L + +#define SN_sendProxiedRouter "sendProxiedRouter" +#define LN_sendProxiedRouter "Send Proxied Router" +#define NID_sendProxiedRouter 1028 +#define OBJ_sendProxiedRouter OBJ_id_kp,24L + +#define SN_sendOwner "sendOwner" +#define LN_sendOwner "Send Owner" +#define NID_sendOwner 1029 +#define OBJ_sendOwner OBJ_id_kp,25L + +#define SN_sendProxiedOwner "sendProxiedOwner" +#define LN_sendProxiedOwner "Send Proxied Owner" +#define NID_sendProxiedOwner 1030 +#define OBJ_sendProxiedOwner OBJ_id_kp,26L + +#define SN_cmcCA "cmcCA" +#define LN_cmcCA "CMC Certificate Authority" +#define NID_cmcCA 1131 +#define OBJ_cmcCA OBJ_id_kp,27L + +#define SN_cmcRA "cmcRA" +#define LN_cmcRA "CMC Registration Authority" +#define NID_cmcRA 1132 +#define OBJ_cmcRA OBJ_id_kp,28L + +#define SN_id_it_caProtEncCert "id-it-caProtEncCert" +#define NID_id_it_caProtEncCert 298 +#define OBJ_id_it_caProtEncCert OBJ_id_it,1L + +#define SN_id_it_signKeyPairTypes "id-it-signKeyPairTypes" +#define NID_id_it_signKeyPairTypes 299 +#define OBJ_id_it_signKeyPairTypes OBJ_id_it,2L + +#define SN_id_it_encKeyPairTypes "id-it-encKeyPairTypes" +#define NID_id_it_encKeyPairTypes 300 +#define OBJ_id_it_encKeyPairTypes OBJ_id_it,3L + +#define SN_id_it_preferredSymmAlg "id-it-preferredSymmAlg" +#define NID_id_it_preferredSymmAlg 301 +#define OBJ_id_it_preferredSymmAlg OBJ_id_it,4L + +#define SN_id_it_caKeyUpdateInfo "id-it-caKeyUpdateInfo" +#define NID_id_it_caKeyUpdateInfo 302 +#define OBJ_id_it_caKeyUpdateInfo OBJ_id_it,5L + +#define SN_id_it_currentCRL "id-it-currentCRL" +#define NID_id_it_currentCRL 303 +#define OBJ_id_it_currentCRL OBJ_id_it,6L + +#define SN_id_it_unsupportedOIDs "id-it-unsupportedOIDs" +#define NID_id_it_unsupportedOIDs 304 +#define OBJ_id_it_unsupportedOIDs OBJ_id_it,7L + +#define SN_id_it_subscriptionRequest "id-it-subscriptionRequest" +#define NID_id_it_subscriptionRequest 305 +#define OBJ_id_it_subscriptionRequest OBJ_id_it,8L + +#define SN_id_it_subscriptionResponse "id-it-subscriptionResponse" +#define NID_id_it_subscriptionResponse 306 +#define OBJ_id_it_subscriptionResponse OBJ_id_it,9L + +#define SN_id_it_keyPairParamReq "id-it-keyPairParamReq" +#define NID_id_it_keyPairParamReq 307 +#define OBJ_id_it_keyPairParamReq OBJ_id_it,10L + +#define SN_id_it_keyPairParamRep "id-it-keyPairParamRep" +#define NID_id_it_keyPairParamRep 308 +#define OBJ_id_it_keyPairParamRep OBJ_id_it,11L + +#define SN_id_it_revPassphrase "id-it-revPassphrase" +#define NID_id_it_revPassphrase 309 +#define OBJ_id_it_revPassphrase OBJ_id_it,12L + +#define SN_id_it_implicitConfirm "id-it-implicitConfirm" +#define NID_id_it_implicitConfirm 310 +#define OBJ_id_it_implicitConfirm OBJ_id_it,13L + +#define SN_id_it_confirmWaitTime "id-it-confirmWaitTime" +#define NID_id_it_confirmWaitTime 311 +#define OBJ_id_it_confirmWaitTime OBJ_id_it,14L + +#define SN_id_it_origPKIMessage "id-it-origPKIMessage" +#define NID_id_it_origPKIMessage 312 +#define OBJ_id_it_origPKIMessage OBJ_id_it,15L + +#define SN_id_it_suppLangTags "id-it-suppLangTags" +#define NID_id_it_suppLangTags 784 +#define OBJ_id_it_suppLangTags OBJ_id_it,16L + +#define SN_id_regCtrl "id-regCtrl" +#define NID_id_regCtrl 313 +#define OBJ_id_regCtrl OBJ_id_pkip,1L + +#define SN_id_regInfo "id-regInfo" +#define NID_id_regInfo 314 +#define OBJ_id_regInfo OBJ_id_pkip,2L + +#define SN_id_regCtrl_regToken "id-regCtrl-regToken" +#define NID_id_regCtrl_regToken 315 +#define OBJ_id_regCtrl_regToken OBJ_id_regCtrl,1L + +#define SN_id_regCtrl_authenticator "id-regCtrl-authenticator" +#define NID_id_regCtrl_authenticator 316 +#define OBJ_id_regCtrl_authenticator OBJ_id_regCtrl,2L + +#define SN_id_regCtrl_pkiPublicationInfo "id-regCtrl-pkiPublicationInfo" +#define NID_id_regCtrl_pkiPublicationInfo 317 +#define OBJ_id_regCtrl_pkiPublicationInfo OBJ_id_regCtrl,3L + +#define SN_id_regCtrl_pkiArchiveOptions "id-regCtrl-pkiArchiveOptions" +#define NID_id_regCtrl_pkiArchiveOptions 318 +#define OBJ_id_regCtrl_pkiArchiveOptions OBJ_id_regCtrl,4L + +#define SN_id_regCtrl_oldCertID "id-regCtrl-oldCertID" +#define NID_id_regCtrl_oldCertID 319 +#define OBJ_id_regCtrl_oldCertID OBJ_id_regCtrl,5L + +#define SN_id_regCtrl_protocolEncrKey "id-regCtrl-protocolEncrKey" +#define NID_id_regCtrl_protocolEncrKey 320 +#define OBJ_id_regCtrl_protocolEncrKey OBJ_id_regCtrl,6L + +#define SN_id_regInfo_utf8Pairs "id-regInfo-utf8Pairs" +#define NID_id_regInfo_utf8Pairs 321 +#define OBJ_id_regInfo_utf8Pairs OBJ_id_regInfo,1L + +#define SN_id_regInfo_certReq "id-regInfo-certReq" +#define NID_id_regInfo_certReq 322 +#define OBJ_id_regInfo_certReq OBJ_id_regInfo,2L + +#define SN_id_alg_des40 "id-alg-des40" +#define NID_id_alg_des40 323 +#define OBJ_id_alg_des40 OBJ_id_alg,1L + +#define SN_id_alg_noSignature "id-alg-noSignature" +#define NID_id_alg_noSignature 324 +#define OBJ_id_alg_noSignature OBJ_id_alg,2L + +#define SN_id_alg_dh_sig_hmac_sha1 "id-alg-dh-sig-hmac-sha1" +#define NID_id_alg_dh_sig_hmac_sha1 325 +#define OBJ_id_alg_dh_sig_hmac_sha1 OBJ_id_alg,3L + +#define SN_id_alg_dh_pop "id-alg-dh-pop" +#define NID_id_alg_dh_pop 326 +#define OBJ_id_alg_dh_pop OBJ_id_alg,4L + +#define SN_id_cmc_statusInfo "id-cmc-statusInfo" +#define NID_id_cmc_statusInfo 327 +#define OBJ_id_cmc_statusInfo OBJ_id_cmc,1L + +#define SN_id_cmc_identification "id-cmc-identification" +#define NID_id_cmc_identification 328 +#define OBJ_id_cmc_identification OBJ_id_cmc,2L + +#define SN_id_cmc_identityProof "id-cmc-identityProof" +#define NID_id_cmc_identityProof 329 +#define OBJ_id_cmc_identityProof OBJ_id_cmc,3L + +#define SN_id_cmc_dataReturn "id-cmc-dataReturn" +#define NID_id_cmc_dataReturn 330 +#define OBJ_id_cmc_dataReturn OBJ_id_cmc,4L + +#define SN_id_cmc_transactionId "id-cmc-transactionId" +#define NID_id_cmc_transactionId 331 +#define OBJ_id_cmc_transactionId OBJ_id_cmc,5L + +#define SN_id_cmc_senderNonce "id-cmc-senderNonce" +#define NID_id_cmc_senderNonce 332 +#define OBJ_id_cmc_senderNonce OBJ_id_cmc,6L + +#define SN_id_cmc_recipientNonce "id-cmc-recipientNonce" +#define NID_id_cmc_recipientNonce 333 +#define OBJ_id_cmc_recipientNonce OBJ_id_cmc,7L + +#define SN_id_cmc_addExtensions "id-cmc-addExtensions" +#define NID_id_cmc_addExtensions 334 +#define OBJ_id_cmc_addExtensions OBJ_id_cmc,8L + +#define SN_id_cmc_encryptedPOP "id-cmc-encryptedPOP" +#define NID_id_cmc_encryptedPOP 335 +#define OBJ_id_cmc_encryptedPOP OBJ_id_cmc,9L + +#define SN_id_cmc_decryptedPOP "id-cmc-decryptedPOP" +#define NID_id_cmc_decryptedPOP 336 +#define OBJ_id_cmc_decryptedPOP OBJ_id_cmc,10L + +#define SN_id_cmc_lraPOPWitness "id-cmc-lraPOPWitness" +#define NID_id_cmc_lraPOPWitness 337 +#define OBJ_id_cmc_lraPOPWitness OBJ_id_cmc,11L + +#define SN_id_cmc_getCert "id-cmc-getCert" +#define NID_id_cmc_getCert 338 +#define OBJ_id_cmc_getCert OBJ_id_cmc,15L + +#define SN_id_cmc_getCRL "id-cmc-getCRL" +#define NID_id_cmc_getCRL 339 +#define OBJ_id_cmc_getCRL OBJ_id_cmc,16L + +#define SN_id_cmc_revokeRequest "id-cmc-revokeRequest" +#define NID_id_cmc_revokeRequest 340 +#define OBJ_id_cmc_revokeRequest OBJ_id_cmc,17L + +#define SN_id_cmc_regInfo "id-cmc-regInfo" +#define NID_id_cmc_regInfo 341 +#define OBJ_id_cmc_regInfo OBJ_id_cmc,18L + +#define SN_id_cmc_responseInfo "id-cmc-responseInfo" +#define NID_id_cmc_responseInfo 342 +#define OBJ_id_cmc_responseInfo OBJ_id_cmc,19L + +#define SN_id_cmc_queryPending "id-cmc-queryPending" +#define NID_id_cmc_queryPending 343 +#define OBJ_id_cmc_queryPending OBJ_id_cmc,21L + +#define SN_id_cmc_popLinkRandom "id-cmc-popLinkRandom" +#define NID_id_cmc_popLinkRandom 344 +#define OBJ_id_cmc_popLinkRandom OBJ_id_cmc,22L + +#define SN_id_cmc_popLinkWitness "id-cmc-popLinkWitness" +#define NID_id_cmc_popLinkWitness 345 +#define OBJ_id_cmc_popLinkWitness OBJ_id_cmc,23L + +#define SN_id_cmc_confirmCertAcceptance "id-cmc-confirmCertAcceptance" +#define NID_id_cmc_confirmCertAcceptance 346 +#define OBJ_id_cmc_confirmCertAcceptance OBJ_id_cmc,24L + +#define SN_id_on_personalData "id-on-personalData" +#define NID_id_on_personalData 347 +#define OBJ_id_on_personalData OBJ_id_on,1L + +#define SN_id_on_permanentIdentifier "id-on-permanentIdentifier" +#define LN_id_on_permanentIdentifier "Permanent Identifier" +#define NID_id_on_permanentIdentifier 858 +#define OBJ_id_on_permanentIdentifier OBJ_id_on,3L + +#define SN_id_pda_dateOfBirth "id-pda-dateOfBirth" +#define NID_id_pda_dateOfBirth 348 +#define OBJ_id_pda_dateOfBirth OBJ_id_pda,1L + +#define SN_id_pda_placeOfBirth "id-pda-placeOfBirth" +#define NID_id_pda_placeOfBirth 349 +#define OBJ_id_pda_placeOfBirth OBJ_id_pda,2L + +#define SN_id_pda_gender "id-pda-gender" +#define NID_id_pda_gender 351 +#define OBJ_id_pda_gender OBJ_id_pda,3L + +#define SN_id_pda_countryOfCitizenship "id-pda-countryOfCitizenship" +#define NID_id_pda_countryOfCitizenship 352 +#define OBJ_id_pda_countryOfCitizenship OBJ_id_pda,4L + +#define SN_id_pda_countryOfResidence "id-pda-countryOfResidence" +#define NID_id_pda_countryOfResidence 353 +#define OBJ_id_pda_countryOfResidence OBJ_id_pda,5L + +#define SN_id_aca_authenticationInfo "id-aca-authenticationInfo" +#define NID_id_aca_authenticationInfo 354 +#define OBJ_id_aca_authenticationInfo OBJ_id_aca,1L + +#define SN_id_aca_accessIdentity "id-aca-accessIdentity" +#define NID_id_aca_accessIdentity 355 +#define OBJ_id_aca_accessIdentity OBJ_id_aca,2L + +#define SN_id_aca_chargingIdentity "id-aca-chargingIdentity" +#define NID_id_aca_chargingIdentity 356 +#define OBJ_id_aca_chargingIdentity OBJ_id_aca,3L + +#define SN_id_aca_group "id-aca-group" +#define NID_id_aca_group 357 +#define OBJ_id_aca_group OBJ_id_aca,4L + +#define SN_id_aca_role "id-aca-role" +#define NID_id_aca_role 358 +#define OBJ_id_aca_role OBJ_id_aca,5L + +#define SN_id_aca_encAttrs "id-aca-encAttrs" +#define NID_id_aca_encAttrs 399 +#define OBJ_id_aca_encAttrs OBJ_id_aca,6L + +#define SN_id_qcs_pkixQCSyntax_v1 "id-qcs-pkixQCSyntax-v1" +#define NID_id_qcs_pkixQCSyntax_v1 359 +#define OBJ_id_qcs_pkixQCSyntax_v1 OBJ_id_qcs,1L + +#define SN_id_cct_crs "id-cct-crs" +#define NID_id_cct_crs 360 +#define OBJ_id_cct_crs OBJ_id_cct,1L + +#define SN_id_cct_PKIData "id-cct-PKIData" +#define NID_id_cct_PKIData 361 +#define OBJ_id_cct_PKIData OBJ_id_cct,2L + +#define SN_id_cct_PKIResponse "id-cct-PKIResponse" +#define NID_id_cct_PKIResponse 362 +#define OBJ_id_cct_PKIResponse OBJ_id_cct,3L + +#define SN_id_ppl_anyLanguage "id-ppl-anyLanguage" +#define LN_id_ppl_anyLanguage "Any language" +#define NID_id_ppl_anyLanguage 664 +#define OBJ_id_ppl_anyLanguage OBJ_id_ppl,0L + +#define SN_id_ppl_inheritAll "id-ppl-inheritAll" +#define LN_id_ppl_inheritAll "Inherit all" +#define NID_id_ppl_inheritAll 665 +#define OBJ_id_ppl_inheritAll OBJ_id_ppl,1L + +#define SN_Independent "id-ppl-independent" +#define LN_Independent "Independent" +#define NID_Independent 667 +#define OBJ_Independent OBJ_id_ppl,2L + +#define SN_ad_OCSP "OCSP" +#define LN_ad_OCSP "OCSP" +#define NID_ad_OCSP 178 +#define OBJ_ad_OCSP OBJ_id_ad,1L + +#define SN_ad_ca_issuers "caIssuers" +#define LN_ad_ca_issuers "CA Issuers" +#define NID_ad_ca_issuers 179 +#define OBJ_ad_ca_issuers OBJ_id_ad,2L + +#define SN_ad_timeStamping "ad_timestamping" +#define LN_ad_timeStamping "AD Time Stamping" +#define NID_ad_timeStamping 363 +#define OBJ_ad_timeStamping OBJ_id_ad,3L + +#define SN_ad_dvcs "AD_DVCS" +#define LN_ad_dvcs "ad dvcs" +#define NID_ad_dvcs 364 +#define OBJ_ad_dvcs OBJ_id_ad,4L + +#define SN_caRepository "caRepository" +#define LN_caRepository "CA Repository" +#define NID_caRepository 785 +#define OBJ_caRepository OBJ_id_ad,5L + +#define OBJ_id_pkix_OCSP OBJ_ad_OCSP + +#define SN_id_pkix_OCSP_basic "basicOCSPResponse" +#define LN_id_pkix_OCSP_basic "Basic OCSP Response" +#define NID_id_pkix_OCSP_basic 365 +#define OBJ_id_pkix_OCSP_basic OBJ_id_pkix_OCSP,1L + +#define SN_id_pkix_OCSP_Nonce "Nonce" +#define LN_id_pkix_OCSP_Nonce "OCSP Nonce" +#define NID_id_pkix_OCSP_Nonce 366 +#define OBJ_id_pkix_OCSP_Nonce OBJ_id_pkix_OCSP,2L + +#define SN_id_pkix_OCSP_CrlID "CrlID" +#define LN_id_pkix_OCSP_CrlID "OCSP CRL ID" +#define NID_id_pkix_OCSP_CrlID 367 +#define OBJ_id_pkix_OCSP_CrlID OBJ_id_pkix_OCSP,3L + +#define SN_id_pkix_OCSP_acceptableResponses "acceptableResponses" +#define LN_id_pkix_OCSP_acceptableResponses "Acceptable OCSP Responses" +#define NID_id_pkix_OCSP_acceptableResponses 368 +#define OBJ_id_pkix_OCSP_acceptableResponses OBJ_id_pkix_OCSP,4L + +#define SN_id_pkix_OCSP_noCheck "noCheck" +#define LN_id_pkix_OCSP_noCheck "OCSP No Check" +#define NID_id_pkix_OCSP_noCheck 369 +#define OBJ_id_pkix_OCSP_noCheck OBJ_id_pkix_OCSP,5L + +#define SN_id_pkix_OCSP_archiveCutoff "archiveCutoff" +#define LN_id_pkix_OCSP_archiveCutoff "OCSP Archive Cutoff" +#define NID_id_pkix_OCSP_archiveCutoff 370 +#define OBJ_id_pkix_OCSP_archiveCutoff OBJ_id_pkix_OCSP,6L + +#define SN_id_pkix_OCSP_serviceLocator "serviceLocator" +#define LN_id_pkix_OCSP_serviceLocator "OCSP Service Locator" +#define NID_id_pkix_OCSP_serviceLocator 371 +#define OBJ_id_pkix_OCSP_serviceLocator OBJ_id_pkix_OCSP,7L + +#define SN_id_pkix_OCSP_extendedStatus "extendedStatus" +#define LN_id_pkix_OCSP_extendedStatus "Extended OCSP Status" +#define NID_id_pkix_OCSP_extendedStatus 372 +#define OBJ_id_pkix_OCSP_extendedStatus OBJ_id_pkix_OCSP,8L + +#define SN_id_pkix_OCSP_valid "valid" +#define NID_id_pkix_OCSP_valid 373 +#define OBJ_id_pkix_OCSP_valid OBJ_id_pkix_OCSP,9L + +#define SN_id_pkix_OCSP_path "path" +#define NID_id_pkix_OCSP_path 374 +#define OBJ_id_pkix_OCSP_path OBJ_id_pkix_OCSP,10L + +#define SN_id_pkix_OCSP_trustRoot "trustRoot" +#define LN_id_pkix_OCSP_trustRoot "Trust Root" +#define NID_id_pkix_OCSP_trustRoot 375 +#define OBJ_id_pkix_OCSP_trustRoot OBJ_id_pkix_OCSP,11L + +#define SN_algorithm "algorithm" +#define LN_algorithm "algorithm" +#define NID_algorithm 376 +#define OBJ_algorithm 1L,3L,14L,3L,2L + +#define SN_md5WithRSA "RSA-NP-MD5" +#define LN_md5WithRSA "md5WithRSA" +#define NID_md5WithRSA 104 +#define OBJ_md5WithRSA OBJ_algorithm,3L + +#define SN_des_ecb "DES-ECB" +#define LN_des_ecb "des-ecb" +#define NID_des_ecb 29 +#define OBJ_des_ecb OBJ_algorithm,6L + +#define SN_des_cbc "DES-CBC" +#define LN_des_cbc "des-cbc" +#define NID_des_cbc 31 +#define OBJ_des_cbc OBJ_algorithm,7L + +#define SN_des_ofb64 "DES-OFB" +#define LN_des_ofb64 "des-ofb" +#define NID_des_ofb64 45 +#define OBJ_des_ofb64 OBJ_algorithm,8L + +#define SN_des_cfb64 "DES-CFB" +#define LN_des_cfb64 "des-cfb" +#define NID_des_cfb64 30 +#define OBJ_des_cfb64 OBJ_algorithm,9L + +#define SN_rsaSignature "rsaSignature" +#define NID_rsaSignature 377 +#define OBJ_rsaSignature OBJ_algorithm,11L + +#define SN_dsa_2 "DSA-old" +#define LN_dsa_2 "dsaEncryption-old" +#define NID_dsa_2 67 +#define OBJ_dsa_2 OBJ_algorithm,12L + +#define SN_dsaWithSHA "DSA-SHA" +#define LN_dsaWithSHA "dsaWithSHA" +#define NID_dsaWithSHA 66 +#define OBJ_dsaWithSHA OBJ_algorithm,13L + +#define SN_shaWithRSAEncryption "RSA-SHA" +#define LN_shaWithRSAEncryption "shaWithRSAEncryption" +#define NID_shaWithRSAEncryption 42 +#define OBJ_shaWithRSAEncryption OBJ_algorithm,15L + +#define SN_des_ede_ecb "DES-EDE" +#define LN_des_ede_ecb "des-ede" +#define NID_des_ede_ecb 32 +#define OBJ_des_ede_ecb OBJ_algorithm,17L + +#define SN_des_ede3_ecb "DES-EDE3" +#define LN_des_ede3_ecb "des-ede3" +#define NID_des_ede3_ecb 33 + +#define SN_des_ede_cbc "DES-EDE-CBC" +#define LN_des_ede_cbc "des-ede-cbc" +#define NID_des_ede_cbc 43 + +#define SN_des_ede_cfb64 "DES-EDE-CFB" +#define LN_des_ede_cfb64 "des-ede-cfb" +#define NID_des_ede_cfb64 60 + +#define SN_des_ede3_cfb64 "DES-EDE3-CFB" +#define LN_des_ede3_cfb64 "des-ede3-cfb" +#define NID_des_ede3_cfb64 61 + +#define SN_des_ede_ofb64 "DES-EDE-OFB" +#define LN_des_ede_ofb64 "des-ede-ofb" +#define NID_des_ede_ofb64 62 + +#define SN_des_ede3_ofb64 "DES-EDE3-OFB" +#define LN_des_ede3_ofb64 "des-ede3-ofb" +#define NID_des_ede3_ofb64 63 + +#define SN_desx_cbc "DESX-CBC" +#define LN_desx_cbc "desx-cbc" +#define NID_desx_cbc 80 + +#define SN_sha "SHA" +#define LN_sha "sha" +#define NID_sha 41 +#define OBJ_sha OBJ_algorithm,18L + +#define SN_sha1 "SHA1" +#define LN_sha1 "sha1" +#define NID_sha1 64 +#define OBJ_sha1 OBJ_algorithm,26L + +#define SN_dsaWithSHA1_2 "DSA-SHA1-old" +#define LN_dsaWithSHA1_2 "dsaWithSHA1-old" +#define NID_dsaWithSHA1_2 70 +#define OBJ_dsaWithSHA1_2 OBJ_algorithm,27L + +#define SN_sha1WithRSA "RSA-SHA1-2" +#define LN_sha1WithRSA "sha1WithRSA" +#define NID_sha1WithRSA 115 +#define OBJ_sha1WithRSA OBJ_algorithm,29L + +#define SN_ripemd160 "RIPEMD160" +#define LN_ripemd160 "ripemd160" +#define NID_ripemd160 117 +#define OBJ_ripemd160 1L,3L,36L,3L,2L,1L + +#define SN_ripemd160WithRSA "RSA-RIPEMD160" +#define LN_ripemd160WithRSA "ripemd160WithRSA" +#define NID_ripemd160WithRSA 119 +#define OBJ_ripemd160WithRSA 1L,3L,36L,3L,3L,1L,2L + +#define SN_blake2b512 "BLAKE2b512" +#define LN_blake2b512 "blake2b512" +#define NID_blake2b512 1056 +#define OBJ_blake2b512 1L,3L,6L,1L,4L,1L,1722L,12L,2L,1L,16L + +#define SN_blake2s256 "BLAKE2s256" +#define LN_blake2s256 "blake2s256" +#define NID_blake2s256 1057 +#define OBJ_blake2s256 1L,3L,6L,1L,4L,1L,1722L,12L,2L,2L,8L + +#define SN_sxnet "SXNetID" +#define LN_sxnet "Strong Extranet ID" +#define NID_sxnet 143 +#define OBJ_sxnet 1L,3L,101L,1L,4L,1L + +#define SN_X500 "X500" +#define LN_X500 "directory services (X.500)" +#define NID_X500 11 +#define OBJ_X500 2L,5L + +#define SN_X509 "X509" +#define NID_X509 12 +#define OBJ_X509 OBJ_X500,4L + +#define SN_commonName "CN" +#define LN_commonName "commonName" +#define NID_commonName 13 +#define OBJ_commonName OBJ_X509,3L + +#define SN_surname "SN" +#define LN_surname "surname" +#define NID_surname 100 +#define OBJ_surname OBJ_X509,4L + +#define LN_serialNumber "serialNumber" +#define NID_serialNumber 105 +#define OBJ_serialNumber OBJ_X509,5L + +#define SN_countryName "C" +#define LN_countryName "countryName" +#define NID_countryName 14 +#define OBJ_countryName OBJ_X509,6L + +#define SN_localityName "L" +#define LN_localityName "localityName" +#define NID_localityName 15 +#define OBJ_localityName OBJ_X509,7L + +#define SN_stateOrProvinceName "ST" +#define LN_stateOrProvinceName "stateOrProvinceName" +#define NID_stateOrProvinceName 16 +#define OBJ_stateOrProvinceName OBJ_X509,8L + +#define SN_streetAddress "street" +#define LN_streetAddress "streetAddress" +#define NID_streetAddress 660 +#define OBJ_streetAddress OBJ_X509,9L + +#define SN_organizationName "O" +#define LN_organizationName "organizationName" +#define NID_organizationName 17 +#define OBJ_organizationName OBJ_X509,10L + +#define SN_organizationalUnitName "OU" +#define LN_organizationalUnitName "organizationalUnitName" +#define NID_organizationalUnitName 18 +#define OBJ_organizationalUnitName OBJ_X509,11L + +#define SN_title "title" +#define LN_title "title" +#define NID_title 106 +#define OBJ_title OBJ_X509,12L + +#define LN_description "description" +#define NID_description 107 +#define OBJ_description OBJ_X509,13L + +#define LN_searchGuide "searchGuide" +#define NID_searchGuide 859 +#define OBJ_searchGuide OBJ_X509,14L + +#define LN_businessCategory "businessCategory" +#define NID_businessCategory 860 +#define OBJ_businessCategory OBJ_X509,15L + +#define LN_postalAddress "postalAddress" +#define NID_postalAddress 861 +#define OBJ_postalAddress OBJ_X509,16L + +#define LN_postalCode "postalCode" +#define NID_postalCode 661 +#define OBJ_postalCode OBJ_X509,17L + +#define LN_postOfficeBox "postOfficeBox" +#define NID_postOfficeBox 862 +#define OBJ_postOfficeBox OBJ_X509,18L + +#define LN_physicalDeliveryOfficeName "physicalDeliveryOfficeName" +#define NID_physicalDeliveryOfficeName 863 +#define OBJ_physicalDeliveryOfficeName OBJ_X509,19L + +#define LN_telephoneNumber "telephoneNumber" +#define NID_telephoneNumber 864 +#define OBJ_telephoneNumber OBJ_X509,20L + +#define LN_telexNumber "telexNumber" +#define NID_telexNumber 865 +#define OBJ_telexNumber OBJ_X509,21L + +#define LN_teletexTerminalIdentifier "teletexTerminalIdentifier" +#define NID_teletexTerminalIdentifier 866 +#define OBJ_teletexTerminalIdentifier OBJ_X509,22L + +#define LN_facsimileTelephoneNumber "facsimileTelephoneNumber" +#define NID_facsimileTelephoneNumber 867 +#define OBJ_facsimileTelephoneNumber OBJ_X509,23L + +#define LN_x121Address "x121Address" +#define NID_x121Address 868 +#define OBJ_x121Address OBJ_X509,24L + +#define LN_internationaliSDNNumber "internationaliSDNNumber" +#define NID_internationaliSDNNumber 869 +#define OBJ_internationaliSDNNumber OBJ_X509,25L + +#define LN_registeredAddress "registeredAddress" +#define NID_registeredAddress 870 +#define OBJ_registeredAddress OBJ_X509,26L + +#define LN_destinationIndicator "destinationIndicator" +#define NID_destinationIndicator 871 +#define OBJ_destinationIndicator OBJ_X509,27L + +#define LN_preferredDeliveryMethod "preferredDeliveryMethod" +#define NID_preferredDeliveryMethod 872 +#define OBJ_preferredDeliveryMethod OBJ_X509,28L + +#define LN_presentationAddress "presentationAddress" +#define NID_presentationAddress 873 +#define OBJ_presentationAddress OBJ_X509,29L + +#define LN_supportedApplicationContext "supportedApplicationContext" +#define NID_supportedApplicationContext 874 +#define OBJ_supportedApplicationContext OBJ_X509,30L + +#define SN_member "member" +#define NID_member 875 +#define OBJ_member OBJ_X509,31L + +#define SN_owner "owner" +#define NID_owner 876 +#define OBJ_owner OBJ_X509,32L + +#define LN_roleOccupant "roleOccupant" +#define NID_roleOccupant 877 +#define OBJ_roleOccupant OBJ_X509,33L + +#define SN_seeAlso "seeAlso" +#define NID_seeAlso 878 +#define OBJ_seeAlso OBJ_X509,34L + +#define LN_userPassword "userPassword" +#define NID_userPassword 879 +#define OBJ_userPassword OBJ_X509,35L + +#define LN_userCertificate "userCertificate" +#define NID_userCertificate 880 +#define OBJ_userCertificate OBJ_X509,36L + +#define LN_cACertificate "cACertificate" +#define NID_cACertificate 881 +#define OBJ_cACertificate OBJ_X509,37L + +#define LN_authorityRevocationList "authorityRevocationList" +#define NID_authorityRevocationList 882 +#define OBJ_authorityRevocationList OBJ_X509,38L + +#define LN_certificateRevocationList "certificateRevocationList" +#define NID_certificateRevocationList 883 +#define OBJ_certificateRevocationList OBJ_X509,39L + +#define LN_crossCertificatePair "crossCertificatePair" +#define NID_crossCertificatePair 884 +#define OBJ_crossCertificatePair OBJ_X509,40L + +#define SN_name "name" +#define LN_name "name" +#define NID_name 173 +#define OBJ_name OBJ_X509,41L + +#define SN_givenName "GN" +#define LN_givenName "givenName" +#define NID_givenName 99 +#define OBJ_givenName OBJ_X509,42L + +#define SN_initials "initials" +#define LN_initials "initials" +#define NID_initials 101 +#define OBJ_initials OBJ_X509,43L + +#define LN_generationQualifier "generationQualifier" +#define NID_generationQualifier 509 +#define OBJ_generationQualifier OBJ_X509,44L + +#define LN_x500UniqueIdentifier "x500UniqueIdentifier" +#define NID_x500UniqueIdentifier 503 +#define OBJ_x500UniqueIdentifier OBJ_X509,45L + +#define SN_dnQualifier "dnQualifier" +#define LN_dnQualifier "dnQualifier" +#define NID_dnQualifier 174 +#define OBJ_dnQualifier OBJ_X509,46L + +#define LN_enhancedSearchGuide "enhancedSearchGuide" +#define NID_enhancedSearchGuide 885 +#define OBJ_enhancedSearchGuide OBJ_X509,47L + +#define LN_protocolInformation "protocolInformation" +#define NID_protocolInformation 886 +#define OBJ_protocolInformation OBJ_X509,48L + +#define LN_distinguishedName "distinguishedName" +#define NID_distinguishedName 887 +#define OBJ_distinguishedName OBJ_X509,49L + +#define LN_uniqueMember "uniqueMember" +#define NID_uniqueMember 888 +#define OBJ_uniqueMember OBJ_X509,50L + +#define LN_houseIdentifier "houseIdentifier" +#define NID_houseIdentifier 889 +#define OBJ_houseIdentifier OBJ_X509,51L + +#define LN_supportedAlgorithms "supportedAlgorithms" +#define NID_supportedAlgorithms 890 +#define OBJ_supportedAlgorithms OBJ_X509,52L + +#define LN_deltaRevocationList "deltaRevocationList" +#define NID_deltaRevocationList 891 +#define OBJ_deltaRevocationList OBJ_X509,53L + +#define SN_dmdName "dmdName" +#define NID_dmdName 892 +#define OBJ_dmdName OBJ_X509,54L + +#define LN_pseudonym "pseudonym" +#define NID_pseudonym 510 +#define OBJ_pseudonym OBJ_X509,65L + +#define SN_role "role" +#define LN_role "role" +#define NID_role 400 +#define OBJ_role OBJ_X509,72L + +#define LN_organizationIdentifier "organizationIdentifier" +#define NID_organizationIdentifier 1089 +#define OBJ_organizationIdentifier OBJ_X509,97L + +#define SN_countryCode3c "c3" +#define LN_countryCode3c "countryCode3c" +#define NID_countryCode3c 1090 +#define OBJ_countryCode3c OBJ_X509,98L + +#define SN_countryCode3n "n3" +#define LN_countryCode3n "countryCode3n" +#define NID_countryCode3n 1091 +#define OBJ_countryCode3n OBJ_X509,99L + +#define LN_dnsName "dnsName" +#define NID_dnsName 1092 +#define OBJ_dnsName OBJ_X509,100L + +#define SN_X500algorithms "X500algorithms" +#define LN_X500algorithms "directory services - algorithms" +#define NID_X500algorithms 378 +#define OBJ_X500algorithms OBJ_X500,8L + +#define SN_rsa "RSA" +#define LN_rsa "rsa" +#define NID_rsa 19 +#define OBJ_rsa OBJ_X500algorithms,1L,1L + +#define SN_mdc2WithRSA "RSA-MDC2" +#define LN_mdc2WithRSA "mdc2WithRSA" +#define NID_mdc2WithRSA 96 +#define OBJ_mdc2WithRSA OBJ_X500algorithms,3L,100L + +#define SN_mdc2 "MDC2" +#define LN_mdc2 "mdc2" +#define NID_mdc2 95 +#define OBJ_mdc2 OBJ_X500algorithms,3L,101L + +#define SN_id_ce "id-ce" +#define NID_id_ce 81 +#define OBJ_id_ce OBJ_X500,29L + +#define SN_subject_directory_attributes "subjectDirectoryAttributes" +#define LN_subject_directory_attributes "X509v3 Subject Directory Attributes" +#define NID_subject_directory_attributes 769 +#define OBJ_subject_directory_attributes OBJ_id_ce,9L + +#define SN_subject_key_identifier "subjectKeyIdentifier" +#define LN_subject_key_identifier "X509v3 Subject Key Identifier" +#define NID_subject_key_identifier 82 +#define OBJ_subject_key_identifier OBJ_id_ce,14L + +#define SN_key_usage "keyUsage" +#define LN_key_usage "X509v3 Key Usage" +#define NID_key_usage 83 +#define OBJ_key_usage OBJ_id_ce,15L + +#define SN_private_key_usage_period "privateKeyUsagePeriod" +#define LN_private_key_usage_period "X509v3 Private Key Usage Period" +#define NID_private_key_usage_period 84 +#define OBJ_private_key_usage_period OBJ_id_ce,16L + +#define SN_subject_alt_name "subjectAltName" +#define LN_subject_alt_name "X509v3 Subject Alternative Name" +#define NID_subject_alt_name 85 +#define OBJ_subject_alt_name OBJ_id_ce,17L + +#define SN_issuer_alt_name "issuerAltName" +#define LN_issuer_alt_name "X509v3 Issuer Alternative Name" +#define NID_issuer_alt_name 86 +#define OBJ_issuer_alt_name OBJ_id_ce,18L + +#define SN_basic_constraints "basicConstraints" +#define LN_basic_constraints "X509v3 Basic Constraints" +#define NID_basic_constraints 87 +#define OBJ_basic_constraints OBJ_id_ce,19L + +#define SN_crl_number "crlNumber" +#define LN_crl_number "X509v3 CRL Number" +#define NID_crl_number 88 +#define OBJ_crl_number OBJ_id_ce,20L + +#define SN_crl_reason "CRLReason" +#define LN_crl_reason "X509v3 CRL Reason Code" +#define NID_crl_reason 141 +#define OBJ_crl_reason OBJ_id_ce,21L + +#define SN_invalidity_date "invalidityDate" +#define LN_invalidity_date "Invalidity Date" +#define NID_invalidity_date 142 +#define OBJ_invalidity_date OBJ_id_ce,24L + +#define SN_delta_crl "deltaCRL" +#define LN_delta_crl "X509v3 Delta CRL Indicator" +#define NID_delta_crl 140 +#define OBJ_delta_crl OBJ_id_ce,27L + +#define SN_issuing_distribution_point "issuingDistributionPoint" +#define LN_issuing_distribution_point "X509v3 Issuing Distribution Point" +#define NID_issuing_distribution_point 770 +#define OBJ_issuing_distribution_point OBJ_id_ce,28L + +#define SN_certificate_issuer "certificateIssuer" +#define LN_certificate_issuer "X509v3 Certificate Issuer" +#define NID_certificate_issuer 771 +#define OBJ_certificate_issuer OBJ_id_ce,29L + +#define SN_name_constraints "nameConstraints" +#define LN_name_constraints "X509v3 Name Constraints" +#define NID_name_constraints 666 +#define OBJ_name_constraints OBJ_id_ce,30L + +#define SN_crl_distribution_points "crlDistributionPoints" +#define LN_crl_distribution_points "X509v3 CRL Distribution Points" +#define NID_crl_distribution_points 103 +#define OBJ_crl_distribution_points OBJ_id_ce,31L + +#define SN_certificate_policies "certificatePolicies" +#define LN_certificate_policies "X509v3 Certificate Policies" +#define NID_certificate_policies 89 +#define OBJ_certificate_policies OBJ_id_ce,32L + +#define SN_any_policy "anyPolicy" +#define LN_any_policy "X509v3 Any Policy" +#define NID_any_policy 746 +#define OBJ_any_policy OBJ_certificate_policies,0L + +#define SN_policy_mappings "policyMappings" +#define LN_policy_mappings "X509v3 Policy Mappings" +#define NID_policy_mappings 747 +#define OBJ_policy_mappings OBJ_id_ce,33L + +#define SN_authority_key_identifier "authorityKeyIdentifier" +#define LN_authority_key_identifier "X509v3 Authority Key Identifier" +#define NID_authority_key_identifier 90 +#define OBJ_authority_key_identifier OBJ_id_ce,35L + +#define SN_policy_constraints "policyConstraints" +#define LN_policy_constraints "X509v3 Policy Constraints" +#define NID_policy_constraints 401 +#define OBJ_policy_constraints OBJ_id_ce,36L + +#define SN_ext_key_usage "extendedKeyUsage" +#define LN_ext_key_usage "X509v3 Extended Key Usage" +#define NID_ext_key_usage 126 +#define OBJ_ext_key_usage OBJ_id_ce,37L + +#define SN_freshest_crl "freshestCRL" +#define LN_freshest_crl "X509v3 Freshest CRL" +#define NID_freshest_crl 857 +#define OBJ_freshest_crl OBJ_id_ce,46L + +#define SN_inhibit_any_policy "inhibitAnyPolicy" +#define LN_inhibit_any_policy "X509v3 Inhibit Any Policy" +#define NID_inhibit_any_policy 748 +#define OBJ_inhibit_any_policy OBJ_id_ce,54L + +#define SN_target_information "targetInformation" +#define LN_target_information "X509v3 AC Targeting" +#define NID_target_information 402 +#define OBJ_target_information OBJ_id_ce,55L + +#define SN_no_rev_avail "noRevAvail" +#define LN_no_rev_avail "X509v3 No Revocation Available" +#define NID_no_rev_avail 403 +#define OBJ_no_rev_avail OBJ_id_ce,56L + +#define SN_anyExtendedKeyUsage "anyExtendedKeyUsage" +#define LN_anyExtendedKeyUsage "Any Extended Key Usage" +#define NID_anyExtendedKeyUsage 910 +#define OBJ_anyExtendedKeyUsage OBJ_ext_key_usage,0L + +#define SN_netscape "Netscape" +#define LN_netscape "Netscape Communications Corp." +#define NID_netscape 57 +#define OBJ_netscape 2L,16L,840L,1L,113730L + +#define SN_netscape_cert_extension "nsCertExt" +#define LN_netscape_cert_extension "Netscape Certificate Extension" +#define NID_netscape_cert_extension 58 +#define OBJ_netscape_cert_extension OBJ_netscape,1L + +#define SN_netscape_data_type "nsDataType" +#define LN_netscape_data_type "Netscape Data Type" +#define NID_netscape_data_type 59 +#define OBJ_netscape_data_type OBJ_netscape,2L + +#define SN_netscape_cert_type "nsCertType" +#define LN_netscape_cert_type "Netscape Cert Type" +#define NID_netscape_cert_type 71 +#define OBJ_netscape_cert_type OBJ_netscape_cert_extension,1L + +#define SN_netscape_base_url "nsBaseUrl" +#define LN_netscape_base_url "Netscape Base Url" +#define NID_netscape_base_url 72 +#define OBJ_netscape_base_url OBJ_netscape_cert_extension,2L + +#define SN_netscape_revocation_url "nsRevocationUrl" +#define LN_netscape_revocation_url "Netscape Revocation Url" +#define NID_netscape_revocation_url 73 +#define OBJ_netscape_revocation_url OBJ_netscape_cert_extension,3L + +#define SN_netscape_ca_revocation_url "nsCaRevocationUrl" +#define LN_netscape_ca_revocation_url "Netscape CA Revocation Url" +#define NID_netscape_ca_revocation_url 74 +#define OBJ_netscape_ca_revocation_url OBJ_netscape_cert_extension,4L + +#define SN_netscape_renewal_url "nsRenewalUrl" +#define LN_netscape_renewal_url "Netscape Renewal Url" +#define NID_netscape_renewal_url 75 +#define OBJ_netscape_renewal_url OBJ_netscape_cert_extension,7L + +#define SN_netscape_ca_policy_url "nsCaPolicyUrl" +#define LN_netscape_ca_policy_url "Netscape CA Policy Url" +#define NID_netscape_ca_policy_url 76 +#define OBJ_netscape_ca_policy_url OBJ_netscape_cert_extension,8L + +#define SN_netscape_ssl_server_name "nsSslServerName" +#define LN_netscape_ssl_server_name "Netscape SSL Server Name" +#define NID_netscape_ssl_server_name 77 +#define OBJ_netscape_ssl_server_name OBJ_netscape_cert_extension,12L + +#define SN_netscape_comment "nsComment" +#define LN_netscape_comment "Netscape Comment" +#define NID_netscape_comment 78 +#define OBJ_netscape_comment OBJ_netscape_cert_extension,13L + +#define SN_netscape_cert_sequence "nsCertSequence" +#define LN_netscape_cert_sequence "Netscape Certificate Sequence" +#define NID_netscape_cert_sequence 79 +#define OBJ_netscape_cert_sequence OBJ_netscape_data_type,5L + +#define SN_ns_sgc "nsSGC" +#define LN_ns_sgc "Netscape Server Gated Crypto" +#define NID_ns_sgc 139 +#define OBJ_ns_sgc OBJ_netscape,4L,1L + +#define SN_org "ORG" +#define LN_org "org" +#define NID_org 379 +#define OBJ_org OBJ_iso,3L + +#define SN_dod "DOD" +#define LN_dod "dod" +#define NID_dod 380 +#define OBJ_dod OBJ_org,6L + +#define SN_iana "IANA" +#define LN_iana "iana" +#define NID_iana 381 +#define OBJ_iana OBJ_dod,1L + +#define OBJ_internet OBJ_iana + +#define SN_Directory "directory" +#define LN_Directory "Directory" +#define NID_Directory 382 +#define OBJ_Directory OBJ_internet,1L + +#define SN_Management "mgmt" +#define LN_Management "Management" +#define NID_Management 383 +#define OBJ_Management OBJ_internet,2L + +#define SN_Experimental "experimental" +#define LN_Experimental "Experimental" +#define NID_Experimental 384 +#define OBJ_Experimental OBJ_internet,3L + +#define SN_Private "private" +#define LN_Private "Private" +#define NID_Private 385 +#define OBJ_Private OBJ_internet,4L + +#define SN_Security "security" +#define LN_Security "Security" +#define NID_Security 386 +#define OBJ_Security OBJ_internet,5L + +#define SN_SNMPv2 "snmpv2" +#define LN_SNMPv2 "SNMPv2" +#define NID_SNMPv2 387 +#define OBJ_SNMPv2 OBJ_internet,6L + +#define LN_Mail "Mail" +#define NID_Mail 388 +#define OBJ_Mail OBJ_internet,7L + +#define SN_Enterprises "enterprises" +#define LN_Enterprises "Enterprises" +#define NID_Enterprises 389 +#define OBJ_Enterprises OBJ_Private,1L + +#define SN_dcObject "dcobject" +#define LN_dcObject "dcObject" +#define NID_dcObject 390 +#define OBJ_dcObject OBJ_Enterprises,1466L,344L + +#define SN_mime_mhs "mime-mhs" +#define LN_mime_mhs "MIME MHS" +#define NID_mime_mhs 504 +#define OBJ_mime_mhs OBJ_Mail,1L + +#define SN_mime_mhs_headings "mime-mhs-headings" +#define LN_mime_mhs_headings "mime-mhs-headings" +#define NID_mime_mhs_headings 505 +#define OBJ_mime_mhs_headings OBJ_mime_mhs,1L + +#define SN_mime_mhs_bodies "mime-mhs-bodies" +#define LN_mime_mhs_bodies "mime-mhs-bodies" +#define NID_mime_mhs_bodies 506 +#define OBJ_mime_mhs_bodies OBJ_mime_mhs,2L + +#define SN_id_hex_partial_message "id-hex-partial-message" +#define LN_id_hex_partial_message "id-hex-partial-message" +#define NID_id_hex_partial_message 507 +#define OBJ_id_hex_partial_message OBJ_mime_mhs_headings,1L + +#define SN_id_hex_multipart_message "id-hex-multipart-message" +#define LN_id_hex_multipart_message "id-hex-multipart-message" +#define NID_id_hex_multipart_message 508 +#define OBJ_id_hex_multipart_message OBJ_mime_mhs_headings,2L + +#define SN_zlib_compression "ZLIB" +#define LN_zlib_compression "zlib compression" +#define NID_zlib_compression 125 +#define OBJ_zlib_compression OBJ_id_smime_alg,8L + +#define OBJ_csor 2L,16L,840L,1L,101L,3L + +#define OBJ_nistAlgorithms OBJ_csor,4L + +#define OBJ_aes OBJ_nistAlgorithms,1L + +#define SN_aes_128_ecb "AES-128-ECB" +#define LN_aes_128_ecb "aes-128-ecb" +#define NID_aes_128_ecb 418 +#define OBJ_aes_128_ecb OBJ_aes,1L + +#define SN_aes_128_cbc "AES-128-CBC" +#define LN_aes_128_cbc "aes-128-cbc" +#define NID_aes_128_cbc 419 +#define OBJ_aes_128_cbc OBJ_aes,2L + +#define SN_aes_128_ofb128 "AES-128-OFB" +#define LN_aes_128_ofb128 "aes-128-ofb" +#define NID_aes_128_ofb128 420 +#define OBJ_aes_128_ofb128 OBJ_aes,3L + +#define SN_aes_128_cfb128 "AES-128-CFB" +#define LN_aes_128_cfb128 "aes-128-cfb" +#define NID_aes_128_cfb128 421 +#define OBJ_aes_128_cfb128 OBJ_aes,4L + +#define SN_id_aes128_wrap "id-aes128-wrap" +#define NID_id_aes128_wrap 788 +#define OBJ_id_aes128_wrap OBJ_aes,5L + +#define SN_aes_128_gcm "id-aes128-GCM" +#define LN_aes_128_gcm "aes-128-gcm" +#define NID_aes_128_gcm 895 +#define OBJ_aes_128_gcm OBJ_aes,6L + +#define SN_aes_128_ccm "id-aes128-CCM" +#define LN_aes_128_ccm "aes-128-ccm" +#define NID_aes_128_ccm 896 +#define OBJ_aes_128_ccm OBJ_aes,7L + +#define SN_id_aes128_wrap_pad "id-aes128-wrap-pad" +#define NID_id_aes128_wrap_pad 897 +#define OBJ_id_aes128_wrap_pad OBJ_aes,8L + +#define SN_aes_192_ecb "AES-192-ECB" +#define LN_aes_192_ecb "aes-192-ecb" +#define NID_aes_192_ecb 422 +#define OBJ_aes_192_ecb OBJ_aes,21L + +#define SN_aes_192_cbc "AES-192-CBC" +#define LN_aes_192_cbc "aes-192-cbc" +#define NID_aes_192_cbc 423 +#define OBJ_aes_192_cbc OBJ_aes,22L + +#define SN_aes_192_ofb128 "AES-192-OFB" +#define LN_aes_192_ofb128 "aes-192-ofb" +#define NID_aes_192_ofb128 424 +#define OBJ_aes_192_ofb128 OBJ_aes,23L + +#define SN_aes_192_cfb128 "AES-192-CFB" +#define LN_aes_192_cfb128 "aes-192-cfb" +#define NID_aes_192_cfb128 425 +#define OBJ_aes_192_cfb128 OBJ_aes,24L + +#define SN_id_aes192_wrap "id-aes192-wrap" +#define NID_id_aes192_wrap 789 +#define OBJ_id_aes192_wrap OBJ_aes,25L + +#define SN_aes_192_gcm "id-aes192-GCM" +#define LN_aes_192_gcm "aes-192-gcm" +#define NID_aes_192_gcm 898 +#define OBJ_aes_192_gcm OBJ_aes,26L + +#define SN_aes_192_ccm "id-aes192-CCM" +#define LN_aes_192_ccm "aes-192-ccm" +#define NID_aes_192_ccm 899 +#define OBJ_aes_192_ccm OBJ_aes,27L + +#define SN_id_aes192_wrap_pad "id-aes192-wrap-pad" +#define NID_id_aes192_wrap_pad 900 +#define OBJ_id_aes192_wrap_pad OBJ_aes,28L + +#define SN_aes_256_ecb "AES-256-ECB" +#define LN_aes_256_ecb "aes-256-ecb" +#define NID_aes_256_ecb 426 +#define OBJ_aes_256_ecb OBJ_aes,41L + +#define SN_aes_256_cbc "AES-256-CBC" +#define LN_aes_256_cbc "aes-256-cbc" +#define NID_aes_256_cbc 427 +#define OBJ_aes_256_cbc OBJ_aes,42L + +#define SN_aes_256_ofb128 "AES-256-OFB" +#define LN_aes_256_ofb128 "aes-256-ofb" +#define NID_aes_256_ofb128 428 +#define OBJ_aes_256_ofb128 OBJ_aes,43L + +#define SN_aes_256_cfb128 "AES-256-CFB" +#define LN_aes_256_cfb128 "aes-256-cfb" +#define NID_aes_256_cfb128 429 +#define OBJ_aes_256_cfb128 OBJ_aes,44L + +#define SN_id_aes256_wrap "id-aes256-wrap" +#define NID_id_aes256_wrap 790 +#define OBJ_id_aes256_wrap OBJ_aes,45L + +#define SN_aes_256_gcm "id-aes256-GCM" +#define LN_aes_256_gcm "aes-256-gcm" +#define NID_aes_256_gcm 901 +#define OBJ_aes_256_gcm OBJ_aes,46L + +#define SN_aes_256_ccm "id-aes256-CCM" +#define LN_aes_256_ccm "aes-256-ccm" +#define NID_aes_256_ccm 902 +#define OBJ_aes_256_ccm OBJ_aes,47L + +#define SN_id_aes256_wrap_pad "id-aes256-wrap-pad" +#define NID_id_aes256_wrap_pad 903 +#define OBJ_id_aes256_wrap_pad OBJ_aes,48L + +#define SN_aes_128_xts "AES-128-XTS" +#define LN_aes_128_xts "aes-128-xts" +#define NID_aes_128_xts 913 +#define OBJ_aes_128_xts OBJ_ieee_siswg,0L,1L,1L + +#define SN_aes_256_xts "AES-256-XTS" +#define LN_aes_256_xts "aes-256-xts" +#define NID_aes_256_xts 914 +#define OBJ_aes_256_xts OBJ_ieee_siswg,0L,1L,2L + +#define SN_aes_128_cfb1 "AES-128-CFB1" +#define LN_aes_128_cfb1 "aes-128-cfb1" +#define NID_aes_128_cfb1 650 + +#define SN_aes_192_cfb1 "AES-192-CFB1" +#define LN_aes_192_cfb1 "aes-192-cfb1" +#define NID_aes_192_cfb1 651 + +#define SN_aes_256_cfb1 "AES-256-CFB1" +#define LN_aes_256_cfb1 "aes-256-cfb1" +#define NID_aes_256_cfb1 652 + +#define SN_aes_128_cfb8 "AES-128-CFB8" +#define LN_aes_128_cfb8 "aes-128-cfb8" +#define NID_aes_128_cfb8 653 + +#define SN_aes_192_cfb8 "AES-192-CFB8" +#define LN_aes_192_cfb8 "aes-192-cfb8" +#define NID_aes_192_cfb8 654 + +#define SN_aes_256_cfb8 "AES-256-CFB8" +#define LN_aes_256_cfb8 "aes-256-cfb8" +#define NID_aes_256_cfb8 655 + +#define SN_aes_128_ctr "AES-128-CTR" +#define LN_aes_128_ctr "aes-128-ctr" +#define NID_aes_128_ctr 904 + +#define SN_aes_192_ctr "AES-192-CTR" +#define LN_aes_192_ctr "aes-192-ctr" +#define NID_aes_192_ctr 905 + +#define SN_aes_256_ctr "AES-256-CTR" +#define LN_aes_256_ctr "aes-256-ctr" +#define NID_aes_256_ctr 906 + +#define SN_aes_128_ocb "AES-128-OCB" +#define LN_aes_128_ocb "aes-128-ocb" +#define NID_aes_128_ocb 958 + +#define SN_aes_192_ocb "AES-192-OCB" +#define LN_aes_192_ocb "aes-192-ocb" +#define NID_aes_192_ocb 959 + +#define SN_aes_256_ocb "AES-256-OCB" +#define LN_aes_256_ocb "aes-256-ocb" +#define NID_aes_256_ocb 960 + +#define SN_des_cfb1 "DES-CFB1" +#define LN_des_cfb1 "des-cfb1" +#define NID_des_cfb1 656 + +#define SN_des_cfb8 "DES-CFB8" +#define LN_des_cfb8 "des-cfb8" +#define NID_des_cfb8 657 + +#define SN_des_ede3_cfb1 "DES-EDE3-CFB1" +#define LN_des_ede3_cfb1 "des-ede3-cfb1" +#define NID_des_ede3_cfb1 658 + +#define SN_des_ede3_cfb8 "DES-EDE3-CFB8" +#define LN_des_ede3_cfb8 "des-ede3-cfb8" +#define NID_des_ede3_cfb8 659 + +#define OBJ_nist_hashalgs OBJ_nistAlgorithms,2L + +#define SN_sha256 "SHA256" +#define LN_sha256 "sha256" +#define NID_sha256 672 +#define OBJ_sha256 OBJ_nist_hashalgs,1L + +#define SN_sha384 "SHA384" +#define LN_sha384 "sha384" +#define NID_sha384 673 +#define OBJ_sha384 OBJ_nist_hashalgs,2L + +#define SN_sha512 "SHA512" +#define LN_sha512 "sha512" +#define NID_sha512 674 +#define OBJ_sha512 OBJ_nist_hashalgs,3L + +#define SN_sha224 "SHA224" +#define LN_sha224 "sha224" +#define NID_sha224 675 +#define OBJ_sha224 OBJ_nist_hashalgs,4L + +#define SN_sha512_224 "SHA512-224" +#define LN_sha512_224 "sha512-224" +#define NID_sha512_224 1094 +#define OBJ_sha512_224 OBJ_nist_hashalgs,5L + +#define SN_sha512_256 "SHA512-256" +#define LN_sha512_256 "sha512-256" +#define NID_sha512_256 1095 +#define OBJ_sha512_256 OBJ_nist_hashalgs,6L + +#define SN_sha3_224 "SHA3-224" +#define LN_sha3_224 "sha3-224" +#define NID_sha3_224 1096 +#define OBJ_sha3_224 OBJ_nist_hashalgs,7L + +#define SN_sha3_256 "SHA3-256" +#define LN_sha3_256 "sha3-256" +#define NID_sha3_256 1097 +#define OBJ_sha3_256 OBJ_nist_hashalgs,8L + +#define SN_sha3_384 "SHA3-384" +#define LN_sha3_384 "sha3-384" +#define NID_sha3_384 1098 +#define OBJ_sha3_384 OBJ_nist_hashalgs,9L + +#define SN_sha3_512 "SHA3-512" +#define LN_sha3_512 "sha3-512" +#define NID_sha3_512 1099 +#define OBJ_sha3_512 OBJ_nist_hashalgs,10L + +#define SN_shake128 "SHAKE128" +#define LN_shake128 "shake128" +#define NID_shake128 1100 +#define OBJ_shake128 OBJ_nist_hashalgs,11L + +#define SN_shake256 "SHAKE256" +#define LN_shake256 "shake256" +#define NID_shake256 1101 +#define OBJ_shake256 OBJ_nist_hashalgs,12L + +#define SN_hmac_sha3_224 "id-hmacWithSHA3-224" +#define LN_hmac_sha3_224 "hmac-sha3-224" +#define NID_hmac_sha3_224 1102 +#define OBJ_hmac_sha3_224 OBJ_nist_hashalgs,13L + +#define SN_hmac_sha3_256 "id-hmacWithSHA3-256" +#define LN_hmac_sha3_256 "hmac-sha3-256" +#define NID_hmac_sha3_256 1103 +#define OBJ_hmac_sha3_256 OBJ_nist_hashalgs,14L + +#define SN_hmac_sha3_384 "id-hmacWithSHA3-384" +#define LN_hmac_sha3_384 "hmac-sha3-384" +#define NID_hmac_sha3_384 1104 +#define OBJ_hmac_sha3_384 OBJ_nist_hashalgs,15L + +#define SN_hmac_sha3_512 "id-hmacWithSHA3-512" +#define LN_hmac_sha3_512 "hmac-sha3-512" +#define NID_hmac_sha3_512 1105 +#define OBJ_hmac_sha3_512 OBJ_nist_hashalgs,16L + +#define OBJ_dsa_with_sha2 OBJ_nistAlgorithms,3L + +#define SN_dsa_with_SHA224 "dsa_with_SHA224" +#define NID_dsa_with_SHA224 802 +#define OBJ_dsa_with_SHA224 OBJ_dsa_with_sha2,1L + +#define SN_dsa_with_SHA256 "dsa_with_SHA256" +#define NID_dsa_with_SHA256 803 +#define OBJ_dsa_with_SHA256 OBJ_dsa_with_sha2,2L + +#define OBJ_sigAlgs OBJ_nistAlgorithms,3L + +#define SN_dsa_with_SHA384 "id-dsa-with-sha384" +#define LN_dsa_with_SHA384 "dsa_with_SHA384" +#define NID_dsa_with_SHA384 1106 +#define OBJ_dsa_with_SHA384 OBJ_sigAlgs,3L + +#define SN_dsa_with_SHA512 "id-dsa-with-sha512" +#define LN_dsa_with_SHA512 "dsa_with_SHA512" +#define NID_dsa_with_SHA512 1107 +#define OBJ_dsa_with_SHA512 OBJ_sigAlgs,4L + +#define SN_dsa_with_SHA3_224 "id-dsa-with-sha3-224" +#define LN_dsa_with_SHA3_224 "dsa_with_SHA3-224" +#define NID_dsa_with_SHA3_224 1108 +#define OBJ_dsa_with_SHA3_224 OBJ_sigAlgs,5L + +#define SN_dsa_with_SHA3_256 "id-dsa-with-sha3-256" +#define LN_dsa_with_SHA3_256 "dsa_with_SHA3-256" +#define NID_dsa_with_SHA3_256 1109 +#define OBJ_dsa_with_SHA3_256 OBJ_sigAlgs,6L + +#define SN_dsa_with_SHA3_384 "id-dsa-with-sha3-384" +#define LN_dsa_with_SHA3_384 "dsa_with_SHA3-384" +#define NID_dsa_with_SHA3_384 1110 +#define OBJ_dsa_with_SHA3_384 OBJ_sigAlgs,7L + +#define SN_dsa_with_SHA3_512 "id-dsa-with-sha3-512" +#define LN_dsa_with_SHA3_512 "dsa_with_SHA3-512" +#define NID_dsa_with_SHA3_512 1111 +#define OBJ_dsa_with_SHA3_512 OBJ_sigAlgs,8L + +#define SN_ecdsa_with_SHA3_224 "id-ecdsa-with-sha3-224" +#define LN_ecdsa_with_SHA3_224 "ecdsa_with_SHA3-224" +#define NID_ecdsa_with_SHA3_224 1112 +#define OBJ_ecdsa_with_SHA3_224 OBJ_sigAlgs,9L + +#define SN_ecdsa_with_SHA3_256 "id-ecdsa-with-sha3-256" +#define LN_ecdsa_with_SHA3_256 "ecdsa_with_SHA3-256" +#define NID_ecdsa_with_SHA3_256 1113 +#define OBJ_ecdsa_with_SHA3_256 OBJ_sigAlgs,10L + +#define SN_ecdsa_with_SHA3_384 "id-ecdsa-with-sha3-384" +#define LN_ecdsa_with_SHA3_384 "ecdsa_with_SHA3-384" +#define NID_ecdsa_with_SHA3_384 1114 +#define OBJ_ecdsa_with_SHA3_384 OBJ_sigAlgs,11L + +#define SN_ecdsa_with_SHA3_512 "id-ecdsa-with-sha3-512" +#define LN_ecdsa_with_SHA3_512 "ecdsa_with_SHA3-512" +#define NID_ecdsa_with_SHA3_512 1115 +#define OBJ_ecdsa_with_SHA3_512 OBJ_sigAlgs,12L + +#define SN_RSA_SHA3_224 "id-rsassa-pkcs1-v1_5-with-sha3-224" +#define LN_RSA_SHA3_224 "RSA-SHA3-224" +#define NID_RSA_SHA3_224 1116 +#define OBJ_RSA_SHA3_224 OBJ_sigAlgs,13L + +#define SN_RSA_SHA3_256 "id-rsassa-pkcs1-v1_5-with-sha3-256" +#define LN_RSA_SHA3_256 "RSA-SHA3-256" +#define NID_RSA_SHA3_256 1117 +#define OBJ_RSA_SHA3_256 OBJ_sigAlgs,14L + +#define SN_RSA_SHA3_384 "id-rsassa-pkcs1-v1_5-with-sha3-384" +#define LN_RSA_SHA3_384 "RSA-SHA3-384" +#define NID_RSA_SHA3_384 1118 +#define OBJ_RSA_SHA3_384 OBJ_sigAlgs,15L + +#define SN_RSA_SHA3_512 "id-rsassa-pkcs1-v1_5-with-sha3-512" +#define LN_RSA_SHA3_512 "RSA-SHA3-512" +#define NID_RSA_SHA3_512 1119 +#define OBJ_RSA_SHA3_512 OBJ_sigAlgs,16L + +#define SN_hold_instruction_code "holdInstructionCode" +#define LN_hold_instruction_code "Hold Instruction Code" +#define NID_hold_instruction_code 430 +#define OBJ_hold_instruction_code OBJ_id_ce,23L + +#define OBJ_holdInstruction OBJ_X9_57,2L + +#define SN_hold_instruction_none "holdInstructionNone" +#define LN_hold_instruction_none "Hold Instruction None" +#define NID_hold_instruction_none 431 +#define OBJ_hold_instruction_none OBJ_holdInstruction,1L + +#define SN_hold_instruction_call_issuer "holdInstructionCallIssuer" +#define LN_hold_instruction_call_issuer "Hold Instruction Call Issuer" +#define NID_hold_instruction_call_issuer 432 +#define OBJ_hold_instruction_call_issuer OBJ_holdInstruction,2L + +#define SN_hold_instruction_reject "holdInstructionReject" +#define LN_hold_instruction_reject "Hold Instruction Reject" +#define NID_hold_instruction_reject 433 +#define OBJ_hold_instruction_reject OBJ_holdInstruction,3L + +#define SN_data "data" +#define NID_data 434 +#define OBJ_data OBJ_itu_t,9L + +#define SN_pss "pss" +#define NID_pss 435 +#define OBJ_pss OBJ_data,2342L + +#define SN_ucl "ucl" +#define NID_ucl 436 +#define OBJ_ucl OBJ_pss,19200300L + +#define SN_pilot "pilot" +#define NID_pilot 437 +#define OBJ_pilot OBJ_ucl,100L + +#define LN_pilotAttributeType "pilotAttributeType" +#define NID_pilotAttributeType 438 +#define OBJ_pilotAttributeType OBJ_pilot,1L + +#define LN_pilotAttributeSyntax "pilotAttributeSyntax" +#define NID_pilotAttributeSyntax 439 +#define OBJ_pilotAttributeSyntax OBJ_pilot,3L + +#define LN_pilotObjectClass "pilotObjectClass" +#define NID_pilotObjectClass 440 +#define OBJ_pilotObjectClass OBJ_pilot,4L + +#define LN_pilotGroups "pilotGroups" +#define NID_pilotGroups 441 +#define OBJ_pilotGroups OBJ_pilot,10L + +#define LN_iA5StringSyntax "iA5StringSyntax" +#define NID_iA5StringSyntax 442 +#define OBJ_iA5StringSyntax OBJ_pilotAttributeSyntax,4L + +#define LN_caseIgnoreIA5StringSyntax "caseIgnoreIA5StringSyntax" +#define NID_caseIgnoreIA5StringSyntax 443 +#define OBJ_caseIgnoreIA5StringSyntax OBJ_pilotAttributeSyntax,5L + +#define LN_pilotObject "pilotObject" +#define NID_pilotObject 444 +#define OBJ_pilotObject OBJ_pilotObjectClass,3L + +#define LN_pilotPerson "pilotPerson" +#define NID_pilotPerson 445 +#define OBJ_pilotPerson OBJ_pilotObjectClass,4L + +#define SN_account "account" +#define NID_account 446 +#define OBJ_account OBJ_pilotObjectClass,5L + +#define SN_document "document" +#define NID_document 447 +#define OBJ_document OBJ_pilotObjectClass,6L + +#define SN_room "room" +#define NID_room 448 +#define OBJ_room OBJ_pilotObjectClass,7L + +#define LN_documentSeries "documentSeries" +#define NID_documentSeries 449 +#define OBJ_documentSeries OBJ_pilotObjectClass,9L + +#define SN_Domain "domain" +#define LN_Domain "Domain" +#define NID_Domain 392 +#define OBJ_Domain OBJ_pilotObjectClass,13L + +#define LN_rFC822localPart "rFC822localPart" +#define NID_rFC822localPart 450 +#define OBJ_rFC822localPart OBJ_pilotObjectClass,14L + +#define LN_dNSDomain "dNSDomain" +#define NID_dNSDomain 451 +#define OBJ_dNSDomain OBJ_pilotObjectClass,15L + +#define LN_domainRelatedObject "domainRelatedObject" +#define NID_domainRelatedObject 452 +#define OBJ_domainRelatedObject OBJ_pilotObjectClass,17L + +#define LN_friendlyCountry "friendlyCountry" +#define NID_friendlyCountry 453 +#define OBJ_friendlyCountry OBJ_pilotObjectClass,18L + +#define LN_simpleSecurityObject "simpleSecurityObject" +#define NID_simpleSecurityObject 454 +#define OBJ_simpleSecurityObject OBJ_pilotObjectClass,19L + +#define LN_pilotOrganization "pilotOrganization" +#define NID_pilotOrganization 455 +#define OBJ_pilotOrganization OBJ_pilotObjectClass,20L + +#define LN_pilotDSA "pilotDSA" +#define NID_pilotDSA 456 +#define OBJ_pilotDSA OBJ_pilotObjectClass,21L + +#define LN_qualityLabelledData "qualityLabelledData" +#define NID_qualityLabelledData 457 +#define OBJ_qualityLabelledData OBJ_pilotObjectClass,22L + +#define SN_userId "UID" +#define LN_userId "userId" +#define NID_userId 458 +#define OBJ_userId OBJ_pilotAttributeType,1L + +#define LN_textEncodedORAddress "textEncodedORAddress" +#define NID_textEncodedORAddress 459 +#define OBJ_textEncodedORAddress OBJ_pilotAttributeType,2L + +#define SN_rfc822Mailbox "mail" +#define LN_rfc822Mailbox "rfc822Mailbox" +#define NID_rfc822Mailbox 460 +#define OBJ_rfc822Mailbox OBJ_pilotAttributeType,3L + +#define SN_info "info" +#define NID_info 461 +#define OBJ_info OBJ_pilotAttributeType,4L + +#define LN_favouriteDrink "favouriteDrink" +#define NID_favouriteDrink 462 +#define OBJ_favouriteDrink OBJ_pilotAttributeType,5L + +#define LN_roomNumber "roomNumber" +#define NID_roomNumber 463 +#define OBJ_roomNumber OBJ_pilotAttributeType,6L + +#define SN_photo "photo" +#define NID_photo 464 +#define OBJ_photo OBJ_pilotAttributeType,7L + +#define LN_userClass "userClass" +#define NID_userClass 465 +#define OBJ_userClass OBJ_pilotAttributeType,8L + +#define SN_host "host" +#define NID_host 466 +#define OBJ_host OBJ_pilotAttributeType,9L + +#define SN_manager "manager" +#define NID_manager 467 +#define OBJ_manager OBJ_pilotAttributeType,10L + +#define LN_documentIdentifier "documentIdentifier" +#define NID_documentIdentifier 468 +#define OBJ_documentIdentifier OBJ_pilotAttributeType,11L + +#define LN_documentTitle "documentTitle" +#define NID_documentTitle 469 +#define OBJ_documentTitle OBJ_pilotAttributeType,12L + +#define LN_documentVersion "documentVersion" +#define NID_documentVersion 470 +#define OBJ_documentVersion OBJ_pilotAttributeType,13L + +#define LN_documentAuthor "documentAuthor" +#define NID_documentAuthor 471 +#define OBJ_documentAuthor OBJ_pilotAttributeType,14L + +#define LN_documentLocation "documentLocation" +#define NID_documentLocation 472 +#define OBJ_documentLocation OBJ_pilotAttributeType,15L + +#define LN_homeTelephoneNumber "homeTelephoneNumber" +#define NID_homeTelephoneNumber 473 +#define OBJ_homeTelephoneNumber OBJ_pilotAttributeType,20L + +#define SN_secretary "secretary" +#define NID_secretary 474 +#define OBJ_secretary OBJ_pilotAttributeType,21L + +#define LN_otherMailbox "otherMailbox" +#define NID_otherMailbox 475 +#define OBJ_otherMailbox OBJ_pilotAttributeType,22L + +#define LN_lastModifiedTime "lastModifiedTime" +#define NID_lastModifiedTime 476 +#define OBJ_lastModifiedTime OBJ_pilotAttributeType,23L + +#define LN_lastModifiedBy "lastModifiedBy" +#define NID_lastModifiedBy 477 +#define OBJ_lastModifiedBy OBJ_pilotAttributeType,24L + +#define SN_domainComponent "DC" +#define LN_domainComponent "domainComponent" +#define NID_domainComponent 391 +#define OBJ_domainComponent OBJ_pilotAttributeType,25L + +#define LN_aRecord "aRecord" +#define NID_aRecord 478 +#define OBJ_aRecord OBJ_pilotAttributeType,26L + +#define LN_pilotAttributeType27 "pilotAttributeType27" +#define NID_pilotAttributeType27 479 +#define OBJ_pilotAttributeType27 OBJ_pilotAttributeType,27L + +#define LN_mXRecord "mXRecord" +#define NID_mXRecord 480 +#define OBJ_mXRecord OBJ_pilotAttributeType,28L + +#define LN_nSRecord "nSRecord" +#define NID_nSRecord 481 +#define OBJ_nSRecord OBJ_pilotAttributeType,29L + +#define LN_sOARecord "sOARecord" +#define NID_sOARecord 482 +#define OBJ_sOARecord OBJ_pilotAttributeType,30L + +#define LN_cNAMERecord "cNAMERecord" +#define NID_cNAMERecord 483 +#define OBJ_cNAMERecord OBJ_pilotAttributeType,31L + +#define LN_associatedDomain "associatedDomain" +#define NID_associatedDomain 484 +#define OBJ_associatedDomain OBJ_pilotAttributeType,37L + +#define LN_associatedName "associatedName" +#define NID_associatedName 485 +#define OBJ_associatedName OBJ_pilotAttributeType,38L + +#define LN_homePostalAddress "homePostalAddress" +#define NID_homePostalAddress 486 +#define OBJ_homePostalAddress OBJ_pilotAttributeType,39L + +#define LN_personalTitle "personalTitle" +#define NID_personalTitle 487 +#define OBJ_personalTitle OBJ_pilotAttributeType,40L + +#define LN_mobileTelephoneNumber "mobileTelephoneNumber" +#define NID_mobileTelephoneNumber 488 +#define OBJ_mobileTelephoneNumber OBJ_pilotAttributeType,41L + +#define LN_pagerTelephoneNumber "pagerTelephoneNumber" +#define NID_pagerTelephoneNumber 489 +#define OBJ_pagerTelephoneNumber OBJ_pilotAttributeType,42L + +#define LN_friendlyCountryName "friendlyCountryName" +#define NID_friendlyCountryName 490 +#define OBJ_friendlyCountryName OBJ_pilotAttributeType,43L + +#define SN_uniqueIdentifier "uid" +#define LN_uniqueIdentifier "uniqueIdentifier" +#define NID_uniqueIdentifier 102 +#define OBJ_uniqueIdentifier OBJ_pilotAttributeType,44L + +#define LN_organizationalStatus "organizationalStatus" +#define NID_organizationalStatus 491 +#define OBJ_organizationalStatus OBJ_pilotAttributeType,45L + +#define LN_janetMailbox "janetMailbox" +#define NID_janetMailbox 492 +#define OBJ_janetMailbox OBJ_pilotAttributeType,46L + +#define LN_mailPreferenceOption "mailPreferenceOption" +#define NID_mailPreferenceOption 493 +#define OBJ_mailPreferenceOption OBJ_pilotAttributeType,47L + +#define LN_buildingName "buildingName" +#define NID_buildingName 494 +#define OBJ_buildingName OBJ_pilotAttributeType,48L + +#define LN_dSAQuality "dSAQuality" +#define NID_dSAQuality 495 +#define OBJ_dSAQuality OBJ_pilotAttributeType,49L + +#define LN_singleLevelQuality "singleLevelQuality" +#define NID_singleLevelQuality 496 +#define OBJ_singleLevelQuality OBJ_pilotAttributeType,50L + +#define LN_subtreeMinimumQuality "subtreeMinimumQuality" +#define NID_subtreeMinimumQuality 497 +#define OBJ_subtreeMinimumQuality OBJ_pilotAttributeType,51L + +#define LN_subtreeMaximumQuality "subtreeMaximumQuality" +#define NID_subtreeMaximumQuality 498 +#define OBJ_subtreeMaximumQuality OBJ_pilotAttributeType,52L + +#define LN_personalSignature "personalSignature" +#define NID_personalSignature 499 +#define OBJ_personalSignature OBJ_pilotAttributeType,53L + +#define LN_dITRedirect "dITRedirect" +#define NID_dITRedirect 500 +#define OBJ_dITRedirect OBJ_pilotAttributeType,54L + +#define SN_audio "audio" +#define NID_audio 501 +#define OBJ_audio OBJ_pilotAttributeType,55L + +#define LN_documentPublisher "documentPublisher" +#define NID_documentPublisher 502 +#define OBJ_documentPublisher OBJ_pilotAttributeType,56L + +#define SN_id_set "id-set" +#define LN_id_set "Secure Electronic Transactions" +#define NID_id_set 512 +#define OBJ_id_set OBJ_international_organizations,42L + +#define SN_set_ctype "set-ctype" +#define LN_set_ctype "content types" +#define NID_set_ctype 513 +#define OBJ_set_ctype OBJ_id_set,0L + +#define SN_set_msgExt "set-msgExt" +#define LN_set_msgExt "message extensions" +#define NID_set_msgExt 514 +#define OBJ_set_msgExt OBJ_id_set,1L + +#define SN_set_attr "set-attr" +#define NID_set_attr 515 +#define OBJ_set_attr OBJ_id_set,3L + +#define SN_set_policy "set-policy" +#define NID_set_policy 516 +#define OBJ_set_policy OBJ_id_set,5L + +#define SN_set_certExt "set-certExt" +#define LN_set_certExt "certificate extensions" +#define NID_set_certExt 517 +#define OBJ_set_certExt OBJ_id_set,7L + +#define SN_set_brand "set-brand" +#define NID_set_brand 518 +#define OBJ_set_brand OBJ_id_set,8L + +#define SN_setct_PANData "setct-PANData" +#define NID_setct_PANData 519 +#define OBJ_setct_PANData OBJ_set_ctype,0L + +#define SN_setct_PANToken "setct-PANToken" +#define NID_setct_PANToken 520 +#define OBJ_setct_PANToken OBJ_set_ctype,1L + +#define SN_setct_PANOnly "setct-PANOnly" +#define NID_setct_PANOnly 521 +#define OBJ_setct_PANOnly OBJ_set_ctype,2L + +#define SN_setct_OIData "setct-OIData" +#define NID_setct_OIData 522 +#define OBJ_setct_OIData OBJ_set_ctype,3L + +#define SN_setct_PI "setct-PI" +#define NID_setct_PI 523 +#define OBJ_setct_PI OBJ_set_ctype,4L + +#define SN_setct_PIData "setct-PIData" +#define NID_setct_PIData 524 +#define OBJ_setct_PIData OBJ_set_ctype,5L + +#define SN_setct_PIDataUnsigned "setct-PIDataUnsigned" +#define NID_setct_PIDataUnsigned 525 +#define OBJ_setct_PIDataUnsigned OBJ_set_ctype,6L + +#define SN_setct_HODInput "setct-HODInput" +#define NID_setct_HODInput 526 +#define OBJ_setct_HODInput OBJ_set_ctype,7L + +#define SN_setct_AuthResBaggage "setct-AuthResBaggage" +#define NID_setct_AuthResBaggage 527 +#define OBJ_setct_AuthResBaggage OBJ_set_ctype,8L + +#define SN_setct_AuthRevReqBaggage "setct-AuthRevReqBaggage" +#define NID_setct_AuthRevReqBaggage 528 +#define OBJ_setct_AuthRevReqBaggage OBJ_set_ctype,9L + +#define SN_setct_AuthRevResBaggage "setct-AuthRevResBaggage" +#define NID_setct_AuthRevResBaggage 529 +#define OBJ_setct_AuthRevResBaggage OBJ_set_ctype,10L + +#define SN_setct_CapTokenSeq "setct-CapTokenSeq" +#define NID_setct_CapTokenSeq 530 +#define OBJ_setct_CapTokenSeq OBJ_set_ctype,11L + +#define SN_setct_PInitResData "setct-PInitResData" +#define NID_setct_PInitResData 531 +#define OBJ_setct_PInitResData OBJ_set_ctype,12L + +#define SN_setct_PI_TBS "setct-PI-TBS" +#define NID_setct_PI_TBS 532 +#define OBJ_setct_PI_TBS OBJ_set_ctype,13L + +#define SN_setct_PResData "setct-PResData" +#define NID_setct_PResData 533 +#define OBJ_setct_PResData OBJ_set_ctype,14L + +#define SN_setct_AuthReqTBS "setct-AuthReqTBS" +#define NID_setct_AuthReqTBS 534 +#define OBJ_setct_AuthReqTBS OBJ_set_ctype,16L + +#define SN_setct_AuthResTBS "setct-AuthResTBS" +#define NID_setct_AuthResTBS 535 +#define OBJ_setct_AuthResTBS OBJ_set_ctype,17L + +#define SN_setct_AuthResTBSX "setct-AuthResTBSX" +#define NID_setct_AuthResTBSX 536 +#define OBJ_setct_AuthResTBSX OBJ_set_ctype,18L + +#define SN_setct_AuthTokenTBS "setct-AuthTokenTBS" +#define NID_setct_AuthTokenTBS 537 +#define OBJ_setct_AuthTokenTBS OBJ_set_ctype,19L + +#define SN_setct_CapTokenData "setct-CapTokenData" +#define NID_setct_CapTokenData 538 +#define OBJ_setct_CapTokenData OBJ_set_ctype,20L + +#define SN_setct_CapTokenTBS "setct-CapTokenTBS" +#define NID_setct_CapTokenTBS 539 +#define OBJ_setct_CapTokenTBS OBJ_set_ctype,21L + +#define SN_setct_AcqCardCodeMsg "setct-AcqCardCodeMsg" +#define NID_setct_AcqCardCodeMsg 540 +#define OBJ_setct_AcqCardCodeMsg OBJ_set_ctype,22L + +#define SN_setct_AuthRevReqTBS "setct-AuthRevReqTBS" +#define NID_setct_AuthRevReqTBS 541 +#define OBJ_setct_AuthRevReqTBS OBJ_set_ctype,23L + +#define SN_setct_AuthRevResData "setct-AuthRevResData" +#define NID_setct_AuthRevResData 542 +#define OBJ_setct_AuthRevResData OBJ_set_ctype,24L + +#define SN_setct_AuthRevResTBS "setct-AuthRevResTBS" +#define NID_setct_AuthRevResTBS 543 +#define OBJ_setct_AuthRevResTBS OBJ_set_ctype,25L + +#define SN_setct_CapReqTBS "setct-CapReqTBS" +#define NID_setct_CapReqTBS 544 +#define OBJ_setct_CapReqTBS OBJ_set_ctype,26L + +#define SN_setct_CapReqTBSX "setct-CapReqTBSX" +#define NID_setct_CapReqTBSX 545 +#define OBJ_setct_CapReqTBSX OBJ_set_ctype,27L + +#define SN_setct_CapResData "setct-CapResData" +#define NID_setct_CapResData 546 +#define OBJ_setct_CapResData OBJ_set_ctype,28L + +#define SN_setct_CapRevReqTBS "setct-CapRevReqTBS" +#define NID_setct_CapRevReqTBS 547 +#define OBJ_setct_CapRevReqTBS OBJ_set_ctype,29L + +#define SN_setct_CapRevReqTBSX "setct-CapRevReqTBSX" +#define NID_setct_CapRevReqTBSX 548 +#define OBJ_setct_CapRevReqTBSX OBJ_set_ctype,30L + +#define SN_setct_CapRevResData "setct-CapRevResData" +#define NID_setct_CapRevResData 549 +#define OBJ_setct_CapRevResData OBJ_set_ctype,31L + +#define SN_setct_CredReqTBS "setct-CredReqTBS" +#define NID_setct_CredReqTBS 550 +#define OBJ_setct_CredReqTBS OBJ_set_ctype,32L + +#define SN_setct_CredReqTBSX "setct-CredReqTBSX" +#define NID_setct_CredReqTBSX 551 +#define OBJ_setct_CredReqTBSX OBJ_set_ctype,33L + +#define SN_setct_CredResData "setct-CredResData" +#define NID_setct_CredResData 552 +#define OBJ_setct_CredResData OBJ_set_ctype,34L + +#define SN_setct_CredRevReqTBS "setct-CredRevReqTBS" +#define NID_setct_CredRevReqTBS 553 +#define OBJ_setct_CredRevReqTBS OBJ_set_ctype,35L + +#define SN_setct_CredRevReqTBSX "setct-CredRevReqTBSX" +#define NID_setct_CredRevReqTBSX 554 +#define OBJ_setct_CredRevReqTBSX OBJ_set_ctype,36L + +#define SN_setct_CredRevResData "setct-CredRevResData" +#define NID_setct_CredRevResData 555 +#define OBJ_setct_CredRevResData OBJ_set_ctype,37L + +#define SN_setct_PCertReqData "setct-PCertReqData" +#define NID_setct_PCertReqData 556 +#define OBJ_setct_PCertReqData OBJ_set_ctype,38L + +#define SN_setct_PCertResTBS "setct-PCertResTBS" +#define NID_setct_PCertResTBS 557 +#define OBJ_setct_PCertResTBS OBJ_set_ctype,39L + +#define SN_setct_BatchAdminReqData "setct-BatchAdminReqData" +#define NID_setct_BatchAdminReqData 558 +#define OBJ_setct_BatchAdminReqData OBJ_set_ctype,40L + +#define SN_setct_BatchAdminResData "setct-BatchAdminResData" +#define NID_setct_BatchAdminResData 559 +#define OBJ_setct_BatchAdminResData OBJ_set_ctype,41L + +#define SN_setct_CardCInitResTBS "setct-CardCInitResTBS" +#define NID_setct_CardCInitResTBS 560 +#define OBJ_setct_CardCInitResTBS OBJ_set_ctype,42L + +#define SN_setct_MeAqCInitResTBS "setct-MeAqCInitResTBS" +#define NID_setct_MeAqCInitResTBS 561 +#define OBJ_setct_MeAqCInitResTBS OBJ_set_ctype,43L + +#define SN_setct_RegFormResTBS "setct-RegFormResTBS" +#define NID_setct_RegFormResTBS 562 +#define OBJ_setct_RegFormResTBS OBJ_set_ctype,44L + +#define SN_setct_CertReqData "setct-CertReqData" +#define NID_setct_CertReqData 563 +#define OBJ_setct_CertReqData OBJ_set_ctype,45L + +#define SN_setct_CertReqTBS "setct-CertReqTBS" +#define NID_setct_CertReqTBS 564 +#define OBJ_setct_CertReqTBS OBJ_set_ctype,46L + +#define SN_setct_CertResData "setct-CertResData" +#define NID_setct_CertResData 565 +#define OBJ_setct_CertResData OBJ_set_ctype,47L + +#define SN_setct_CertInqReqTBS "setct-CertInqReqTBS" +#define NID_setct_CertInqReqTBS 566 +#define OBJ_setct_CertInqReqTBS OBJ_set_ctype,48L + +#define SN_setct_ErrorTBS "setct-ErrorTBS" +#define NID_setct_ErrorTBS 567 +#define OBJ_setct_ErrorTBS OBJ_set_ctype,49L + +#define SN_setct_PIDualSignedTBE "setct-PIDualSignedTBE" +#define NID_setct_PIDualSignedTBE 568 +#define OBJ_setct_PIDualSignedTBE OBJ_set_ctype,50L + +#define SN_setct_PIUnsignedTBE "setct-PIUnsignedTBE" +#define NID_setct_PIUnsignedTBE 569 +#define OBJ_setct_PIUnsignedTBE OBJ_set_ctype,51L + +#define SN_setct_AuthReqTBE "setct-AuthReqTBE" +#define NID_setct_AuthReqTBE 570 +#define OBJ_setct_AuthReqTBE OBJ_set_ctype,52L + +#define SN_setct_AuthResTBE "setct-AuthResTBE" +#define NID_setct_AuthResTBE 571 +#define OBJ_setct_AuthResTBE OBJ_set_ctype,53L + +#define SN_setct_AuthResTBEX "setct-AuthResTBEX" +#define NID_setct_AuthResTBEX 572 +#define OBJ_setct_AuthResTBEX OBJ_set_ctype,54L + +#define SN_setct_AuthTokenTBE "setct-AuthTokenTBE" +#define NID_setct_AuthTokenTBE 573 +#define OBJ_setct_AuthTokenTBE OBJ_set_ctype,55L + +#define SN_setct_CapTokenTBE "setct-CapTokenTBE" +#define NID_setct_CapTokenTBE 574 +#define OBJ_setct_CapTokenTBE OBJ_set_ctype,56L + +#define SN_setct_CapTokenTBEX "setct-CapTokenTBEX" +#define NID_setct_CapTokenTBEX 575 +#define OBJ_setct_CapTokenTBEX OBJ_set_ctype,57L + +#define SN_setct_AcqCardCodeMsgTBE "setct-AcqCardCodeMsgTBE" +#define NID_setct_AcqCardCodeMsgTBE 576 +#define OBJ_setct_AcqCardCodeMsgTBE OBJ_set_ctype,58L + +#define SN_setct_AuthRevReqTBE "setct-AuthRevReqTBE" +#define NID_setct_AuthRevReqTBE 577 +#define OBJ_setct_AuthRevReqTBE OBJ_set_ctype,59L + +#define SN_setct_AuthRevResTBE "setct-AuthRevResTBE" +#define NID_setct_AuthRevResTBE 578 +#define OBJ_setct_AuthRevResTBE OBJ_set_ctype,60L + +#define SN_setct_AuthRevResTBEB "setct-AuthRevResTBEB" +#define NID_setct_AuthRevResTBEB 579 +#define OBJ_setct_AuthRevResTBEB OBJ_set_ctype,61L + +#define SN_setct_CapReqTBE "setct-CapReqTBE" +#define NID_setct_CapReqTBE 580 +#define OBJ_setct_CapReqTBE OBJ_set_ctype,62L + +#define SN_setct_CapReqTBEX "setct-CapReqTBEX" +#define NID_setct_CapReqTBEX 581 +#define OBJ_setct_CapReqTBEX OBJ_set_ctype,63L + +#define SN_setct_CapResTBE "setct-CapResTBE" +#define NID_setct_CapResTBE 582 +#define OBJ_setct_CapResTBE OBJ_set_ctype,64L + +#define SN_setct_CapRevReqTBE "setct-CapRevReqTBE" +#define NID_setct_CapRevReqTBE 583 +#define OBJ_setct_CapRevReqTBE OBJ_set_ctype,65L + +#define SN_setct_CapRevReqTBEX "setct-CapRevReqTBEX" +#define NID_setct_CapRevReqTBEX 584 +#define OBJ_setct_CapRevReqTBEX OBJ_set_ctype,66L + +#define SN_setct_CapRevResTBE "setct-CapRevResTBE" +#define NID_setct_CapRevResTBE 585 +#define OBJ_setct_CapRevResTBE OBJ_set_ctype,67L + +#define SN_setct_CredReqTBE "setct-CredReqTBE" +#define NID_setct_CredReqTBE 586 +#define OBJ_setct_CredReqTBE OBJ_set_ctype,68L + +#define SN_setct_CredReqTBEX "setct-CredReqTBEX" +#define NID_setct_CredReqTBEX 587 +#define OBJ_setct_CredReqTBEX OBJ_set_ctype,69L + +#define SN_setct_CredResTBE "setct-CredResTBE" +#define NID_setct_CredResTBE 588 +#define OBJ_setct_CredResTBE OBJ_set_ctype,70L + +#define SN_setct_CredRevReqTBE "setct-CredRevReqTBE" +#define NID_setct_CredRevReqTBE 589 +#define OBJ_setct_CredRevReqTBE OBJ_set_ctype,71L + +#define SN_setct_CredRevReqTBEX "setct-CredRevReqTBEX" +#define NID_setct_CredRevReqTBEX 590 +#define OBJ_setct_CredRevReqTBEX OBJ_set_ctype,72L + +#define SN_setct_CredRevResTBE "setct-CredRevResTBE" +#define NID_setct_CredRevResTBE 591 +#define OBJ_setct_CredRevResTBE OBJ_set_ctype,73L + +#define SN_setct_BatchAdminReqTBE "setct-BatchAdminReqTBE" +#define NID_setct_BatchAdminReqTBE 592 +#define OBJ_setct_BatchAdminReqTBE OBJ_set_ctype,74L + +#define SN_setct_BatchAdminResTBE "setct-BatchAdminResTBE" +#define NID_setct_BatchAdminResTBE 593 +#define OBJ_setct_BatchAdminResTBE OBJ_set_ctype,75L + +#define SN_setct_RegFormReqTBE "setct-RegFormReqTBE" +#define NID_setct_RegFormReqTBE 594 +#define OBJ_setct_RegFormReqTBE OBJ_set_ctype,76L + +#define SN_setct_CertReqTBE "setct-CertReqTBE" +#define NID_setct_CertReqTBE 595 +#define OBJ_setct_CertReqTBE OBJ_set_ctype,77L + +#define SN_setct_CertReqTBEX "setct-CertReqTBEX" +#define NID_setct_CertReqTBEX 596 +#define OBJ_setct_CertReqTBEX OBJ_set_ctype,78L + +#define SN_setct_CertResTBE "setct-CertResTBE" +#define NID_setct_CertResTBE 597 +#define OBJ_setct_CertResTBE OBJ_set_ctype,79L + +#define SN_setct_CRLNotificationTBS "setct-CRLNotificationTBS" +#define NID_setct_CRLNotificationTBS 598 +#define OBJ_setct_CRLNotificationTBS OBJ_set_ctype,80L + +#define SN_setct_CRLNotificationResTBS "setct-CRLNotificationResTBS" +#define NID_setct_CRLNotificationResTBS 599 +#define OBJ_setct_CRLNotificationResTBS OBJ_set_ctype,81L + +#define SN_setct_BCIDistributionTBS "setct-BCIDistributionTBS" +#define NID_setct_BCIDistributionTBS 600 +#define OBJ_setct_BCIDistributionTBS OBJ_set_ctype,82L + +#define SN_setext_genCrypt "setext-genCrypt" +#define LN_setext_genCrypt "generic cryptogram" +#define NID_setext_genCrypt 601 +#define OBJ_setext_genCrypt OBJ_set_msgExt,1L + +#define SN_setext_miAuth "setext-miAuth" +#define LN_setext_miAuth "merchant initiated auth" +#define NID_setext_miAuth 602 +#define OBJ_setext_miAuth OBJ_set_msgExt,3L + +#define SN_setext_pinSecure "setext-pinSecure" +#define NID_setext_pinSecure 603 +#define OBJ_setext_pinSecure OBJ_set_msgExt,4L + +#define SN_setext_pinAny "setext-pinAny" +#define NID_setext_pinAny 604 +#define OBJ_setext_pinAny OBJ_set_msgExt,5L + +#define SN_setext_track2 "setext-track2" +#define NID_setext_track2 605 +#define OBJ_setext_track2 OBJ_set_msgExt,7L + +#define SN_setext_cv "setext-cv" +#define LN_setext_cv "additional verification" +#define NID_setext_cv 606 +#define OBJ_setext_cv OBJ_set_msgExt,8L + +#define SN_set_policy_root "set-policy-root" +#define NID_set_policy_root 607 +#define OBJ_set_policy_root OBJ_set_policy,0L + +#define SN_setCext_hashedRoot "setCext-hashedRoot" +#define NID_setCext_hashedRoot 608 +#define OBJ_setCext_hashedRoot OBJ_set_certExt,0L + +#define SN_setCext_certType "setCext-certType" +#define NID_setCext_certType 609 +#define OBJ_setCext_certType OBJ_set_certExt,1L + +#define SN_setCext_merchData "setCext-merchData" +#define NID_setCext_merchData 610 +#define OBJ_setCext_merchData OBJ_set_certExt,2L + +#define SN_setCext_cCertRequired "setCext-cCertRequired" +#define NID_setCext_cCertRequired 611 +#define OBJ_setCext_cCertRequired OBJ_set_certExt,3L + +#define SN_setCext_tunneling "setCext-tunneling" +#define NID_setCext_tunneling 612 +#define OBJ_setCext_tunneling OBJ_set_certExt,4L + +#define SN_setCext_setExt "setCext-setExt" +#define NID_setCext_setExt 613 +#define OBJ_setCext_setExt OBJ_set_certExt,5L + +#define SN_setCext_setQualf "setCext-setQualf" +#define NID_setCext_setQualf 614 +#define OBJ_setCext_setQualf OBJ_set_certExt,6L + +#define SN_setCext_PGWYcapabilities "setCext-PGWYcapabilities" +#define NID_setCext_PGWYcapabilities 615 +#define OBJ_setCext_PGWYcapabilities OBJ_set_certExt,7L + +#define SN_setCext_TokenIdentifier "setCext-TokenIdentifier" +#define NID_setCext_TokenIdentifier 616 +#define OBJ_setCext_TokenIdentifier OBJ_set_certExt,8L + +#define SN_setCext_Track2Data "setCext-Track2Data" +#define NID_setCext_Track2Data 617 +#define OBJ_setCext_Track2Data OBJ_set_certExt,9L + +#define SN_setCext_TokenType "setCext-TokenType" +#define NID_setCext_TokenType 618 +#define OBJ_setCext_TokenType OBJ_set_certExt,10L + +#define SN_setCext_IssuerCapabilities "setCext-IssuerCapabilities" +#define NID_setCext_IssuerCapabilities 619 +#define OBJ_setCext_IssuerCapabilities OBJ_set_certExt,11L + +#define SN_setAttr_Cert "setAttr-Cert" +#define NID_setAttr_Cert 620 +#define OBJ_setAttr_Cert OBJ_set_attr,0L + +#define SN_setAttr_PGWYcap "setAttr-PGWYcap" +#define LN_setAttr_PGWYcap "payment gateway capabilities" +#define NID_setAttr_PGWYcap 621 +#define OBJ_setAttr_PGWYcap OBJ_set_attr,1L + +#define SN_setAttr_TokenType "setAttr-TokenType" +#define NID_setAttr_TokenType 622 +#define OBJ_setAttr_TokenType OBJ_set_attr,2L + +#define SN_setAttr_IssCap "setAttr-IssCap" +#define LN_setAttr_IssCap "issuer capabilities" +#define NID_setAttr_IssCap 623 +#define OBJ_setAttr_IssCap OBJ_set_attr,3L + +#define SN_set_rootKeyThumb "set-rootKeyThumb" +#define NID_set_rootKeyThumb 624 +#define OBJ_set_rootKeyThumb OBJ_setAttr_Cert,0L + +#define SN_set_addPolicy "set-addPolicy" +#define NID_set_addPolicy 625 +#define OBJ_set_addPolicy OBJ_setAttr_Cert,1L + +#define SN_setAttr_Token_EMV "setAttr-Token-EMV" +#define NID_setAttr_Token_EMV 626 +#define OBJ_setAttr_Token_EMV OBJ_setAttr_TokenType,1L + +#define SN_setAttr_Token_B0Prime "setAttr-Token-B0Prime" +#define NID_setAttr_Token_B0Prime 627 +#define OBJ_setAttr_Token_B0Prime OBJ_setAttr_TokenType,2L + +#define SN_setAttr_IssCap_CVM "setAttr-IssCap-CVM" +#define NID_setAttr_IssCap_CVM 628 +#define OBJ_setAttr_IssCap_CVM OBJ_setAttr_IssCap,3L + +#define SN_setAttr_IssCap_T2 "setAttr-IssCap-T2" +#define NID_setAttr_IssCap_T2 629 +#define OBJ_setAttr_IssCap_T2 OBJ_setAttr_IssCap,4L + +#define SN_setAttr_IssCap_Sig "setAttr-IssCap-Sig" +#define NID_setAttr_IssCap_Sig 630 +#define OBJ_setAttr_IssCap_Sig OBJ_setAttr_IssCap,5L + +#define SN_setAttr_GenCryptgrm "setAttr-GenCryptgrm" +#define LN_setAttr_GenCryptgrm "generate cryptogram" +#define NID_setAttr_GenCryptgrm 631 +#define OBJ_setAttr_GenCryptgrm OBJ_setAttr_IssCap_CVM,1L + +#define SN_setAttr_T2Enc "setAttr-T2Enc" +#define LN_setAttr_T2Enc "encrypted track 2" +#define NID_setAttr_T2Enc 632 +#define OBJ_setAttr_T2Enc OBJ_setAttr_IssCap_T2,1L + +#define SN_setAttr_T2cleartxt "setAttr-T2cleartxt" +#define LN_setAttr_T2cleartxt "cleartext track 2" +#define NID_setAttr_T2cleartxt 633 +#define OBJ_setAttr_T2cleartxt OBJ_setAttr_IssCap_T2,2L + +#define SN_setAttr_TokICCsig "setAttr-TokICCsig" +#define LN_setAttr_TokICCsig "ICC or token signature" +#define NID_setAttr_TokICCsig 634 +#define OBJ_setAttr_TokICCsig OBJ_setAttr_IssCap_Sig,1L + +#define SN_setAttr_SecDevSig "setAttr-SecDevSig" +#define LN_setAttr_SecDevSig "secure device signature" +#define NID_setAttr_SecDevSig 635 +#define OBJ_setAttr_SecDevSig OBJ_setAttr_IssCap_Sig,2L + +#define SN_set_brand_IATA_ATA "set-brand-IATA-ATA" +#define NID_set_brand_IATA_ATA 636 +#define OBJ_set_brand_IATA_ATA OBJ_set_brand,1L + +#define SN_set_brand_Diners "set-brand-Diners" +#define NID_set_brand_Diners 637 +#define OBJ_set_brand_Diners OBJ_set_brand,30L + +#define SN_set_brand_AmericanExpress "set-brand-AmericanExpress" +#define NID_set_brand_AmericanExpress 638 +#define OBJ_set_brand_AmericanExpress OBJ_set_brand,34L + +#define SN_set_brand_JCB "set-brand-JCB" +#define NID_set_brand_JCB 639 +#define OBJ_set_brand_JCB OBJ_set_brand,35L + +#define SN_set_brand_Visa "set-brand-Visa" +#define NID_set_brand_Visa 640 +#define OBJ_set_brand_Visa OBJ_set_brand,4L + +#define SN_set_brand_MasterCard "set-brand-MasterCard" +#define NID_set_brand_MasterCard 641 +#define OBJ_set_brand_MasterCard OBJ_set_brand,5L + +#define SN_set_brand_Novus "set-brand-Novus" +#define NID_set_brand_Novus 642 +#define OBJ_set_brand_Novus OBJ_set_brand,6011L + +#define SN_des_cdmf "DES-CDMF" +#define LN_des_cdmf "des-cdmf" +#define NID_des_cdmf 643 +#define OBJ_des_cdmf OBJ_rsadsi,3L,10L + +#define SN_rsaOAEPEncryptionSET "rsaOAEPEncryptionSET" +#define NID_rsaOAEPEncryptionSET 644 +#define OBJ_rsaOAEPEncryptionSET OBJ_rsadsi,1L,1L,6L + +#define SN_ipsec3 "Oakley-EC2N-3" +#define LN_ipsec3 "ipsec3" +#define NID_ipsec3 749 + +#define SN_ipsec4 "Oakley-EC2N-4" +#define LN_ipsec4 "ipsec4" +#define NID_ipsec4 750 + +#define SN_whirlpool "whirlpool" +#define NID_whirlpool 804 +#define OBJ_whirlpool OBJ_iso,0L,10118L,3L,0L,55L + +#define SN_cryptopro "cryptopro" +#define NID_cryptopro 805 +#define OBJ_cryptopro OBJ_member_body,643L,2L,2L + +#define SN_cryptocom "cryptocom" +#define NID_cryptocom 806 +#define OBJ_cryptocom OBJ_member_body,643L,2L,9L + +#define SN_id_tc26 "id-tc26" +#define NID_id_tc26 974 +#define OBJ_id_tc26 OBJ_member_body,643L,7L,1L + +#define SN_id_GostR3411_94_with_GostR3410_2001 "id-GostR3411-94-with-GostR3410-2001" +#define LN_id_GostR3411_94_with_GostR3410_2001 "GOST R 34.11-94 with GOST R 34.10-2001" +#define NID_id_GostR3411_94_with_GostR3410_2001 807 +#define OBJ_id_GostR3411_94_with_GostR3410_2001 OBJ_cryptopro,3L + +#define SN_id_GostR3411_94_with_GostR3410_94 "id-GostR3411-94-with-GostR3410-94" +#define LN_id_GostR3411_94_with_GostR3410_94 "GOST R 34.11-94 with GOST R 34.10-94" +#define NID_id_GostR3411_94_with_GostR3410_94 808 +#define OBJ_id_GostR3411_94_with_GostR3410_94 OBJ_cryptopro,4L + +#define SN_id_GostR3411_94 "md_gost94" +#define LN_id_GostR3411_94 "GOST R 34.11-94" +#define NID_id_GostR3411_94 809 +#define OBJ_id_GostR3411_94 OBJ_cryptopro,9L + +#define SN_id_HMACGostR3411_94 "id-HMACGostR3411-94" +#define LN_id_HMACGostR3411_94 "HMAC GOST 34.11-94" +#define NID_id_HMACGostR3411_94 810 +#define OBJ_id_HMACGostR3411_94 OBJ_cryptopro,10L + +#define SN_id_GostR3410_2001 "gost2001" +#define LN_id_GostR3410_2001 "GOST R 34.10-2001" +#define NID_id_GostR3410_2001 811 +#define OBJ_id_GostR3410_2001 OBJ_cryptopro,19L + +#define SN_id_GostR3410_94 "gost94" +#define LN_id_GostR3410_94 "GOST R 34.10-94" +#define NID_id_GostR3410_94 812 +#define OBJ_id_GostR3410_94 OBJ_cryptopro,20L + +#define SN_id_Gost28147_89 "gost89" +#define LN_id_Gost28147_89 "GOST 28147-89" +#define NID_id_Gost28147_89 813 +#define OBJ_id_Gost28147_89 OBJ_cryptopro,21L + +#define SN_gost89_cnt "gost89-cnt" +#define NID_gost89_cnt 814 + +#define SN_gost89_cnt_12 "gost89-cnt-12" +#define NID_gost89_cnt_12 975 + +#define SN_gost89_cbc "gost89-cbc" +#define NID_gost89_cbc 1009 + +#define SN_gost89_ecb "gost89-ecb" +#define NID_gost89_ecb 1010 + +#define SN_gost89_ctr "gost89-ctr" +#define NID_gost89_ctr 1011 + +#define SN_id_Gost28147_89_MAC "gost-mac" +#define LN_id_Gost28147_89_MAC "GOST 28147-89 MAC" +#define NID_id_Gost28147_89_MAC 815 +#define OBJ_id_Gost28147_89_MAC OBJ_cryptopro,22L + +#define SN_gost_mac_12 "gost-mac-12" +#define NID_gost_mac_12 976 + +#define SN_id_GostR3411_94_prf "prf-gostr3411-94" +#define LN_id_GostR3411_94_prf "GOST R 34.11-94 PRF" +#define NID_id_GostR3411_94_prf 816 +#define OBJ_id_GostR3411_94_prf OBJ_cryptopro,23L + +#define SN_id_GostR3410_2001DH "id-GostR3410-2001DH" +#define LN_id_GostR3410_2001DH "GOST R 34.10-2001 DH" +#define NID_id_GostR3410_2001DH 817 +#define OBJ_id_GostR3410_2001DH OBJ_cryptopro,98L + +#define SN_id_GostR3410_94DH "id-GostR3410-94DH" +#define LN_id_GostR3410_94DH "GOST R 34.10-94 DH" +#define NID_id_GostR3410_94DH 818 +#define OBJ_id_GostR3410_94DH OBJ_cryptopro,99L + +#define SN_id_Gost28147_89_CryptoPro_KeyMeshing "id-Gost28147-89-CryptoPro-KeyMeshing" +#define NID_id_Gost28147_89_CryptoPro_KeyMeshing 819 +#define OBJ_id_Gost28147_89_CryptoPro_KeyMeshing OBJ_cryptopro,14L,1L + +#define SN_id_Gost28147_89_None_KeyMeshing "id-Gost28147-89-None-KeyMeshing" +#define NID_id_Gost28147_89_None_KeyMeshing 820 +#define OBJ_id_Gost28147_89_None_KeyMeshing OBJ_cryptopro,14L,0L + +#define SN_id_GostR3411_94_TestParamSet "id-GostR3411-94-TestParamSet" +#define NID_id_GostR3411_94_TestParamSet 821 +#define OBJ_id_GostR3411_94_TestParamSet OBJ_cryptopro,30L,0L + +#define SN_id_GostR3411_94_CryptoProParamSet "id-GostR3411-94-CryptoProParamSet" +#define NID_id_GostR3411_94_CryptoProParamSet 822 +#define OBJ_id_GostR3411_94_CryptoProParamSet OBJ_cryptopro,30L,1L + +#define SN_id_Gost28147_89_TestParamSet "id-Gost28147-89-TestParamSet" +#define NID_id_Gost28147_89_TestParamSet 823 +#define OBJ_id_Gost28147_89_TestParamSet OBJ_cryptopro,31L,0L + +#define SN_id_Gost28147_89_CryptoPro_A_ParamSet "id-Gost28147-89-CryptoPro-A-ParamSet" +#define NID_id_Gost28147_89_CryptoPro_A_ParamSet 824 +#define OBJ_id_Gost28147_89_CryptoPro_A_ParamSet OBJ_cryptopro,31L,1L + +#define SN_id_Gost28147_89_CryptoPro_B_ParamSet "id-Gost28147-89-CryptoPro-B-ParamSet" +#define NID_id_Gost28147_89_CryptoPro_B_ParamSet 825 +#define OBJ_id_Gost28147_89_CryptoPro_B_ParamSet OBJ_cryptopro,31L,2L + +#define SN_id_Gost28147_89_CryptoPro_C_ParamSet "id-Gost28147-89-CryptoPro-C-ParamSet" +#define NID_id_Gost28147_89_CryptoPro_C_ParamSet 826 +#define OBJ_id_Gost28147_89_CryptoPro_C_ParamSet OBJ_cryptopro,31L,3L + +#define SN_id_Gost28147_89_CryptoPro_D_ParamSet "id-Gost28147-89-CryptoPro-D-ParamSet" +#define NID_id_Gost28147_89_CryptoPro_D_ParamSet 827 +#define OBJ_id_Gost28147_89_CryptoPro_D_ParamSet OBJ_cryptopro,31L,4L + +#define SN_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet "id-Gost28147-89-CryptoPro-Oscar-1-1-ParamSet" +#define NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet 828 +#define OBJ_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet OBJ_cryptopro,31L,5L + +#define SN_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet "id-Gost28147-89-CryptoPro-Oscar-1-0-ParamSet" +#define NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet 829 +#define OBJ_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet OBJ_cryptopro,31L,6L + +#define SN_id_Gost28147_89_CryptoPro_RIC_1_ParamSet "id-Gost28147-89-CryptoPro-RIC-1-ParamSet" +#define NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet 830 +#define OBJ_id_Gost28147_89_CryptoPro_RIC_1_ParamSet OBJ_cryptopro,31L,7L + +#define SN_id_GostR3410_94_TestParamSet "id-GostR3410-94-TestParamSet" +#define NID_id_GostR3410_94_TestParamSet 831 +#define OBJ_id_GostR3410_94_TestParamSet OBJ_cryptopro,32L,0L + +#define SN_id_GostR3410_94_CryptoPro_A_ParamSet "id-GostR3410-94-CryptoPro-A-ParamSet" +#define NID_id_GostR3410_94_CryptoPro_A_ParamSet 832 +#define OBJ_id_GostR3410_94_CryptoPro_A_ParamSet OBJ_cryptopro,32L,2L + +#define SN_id_GostR3410_94_CryptoPro_B_ParamSet "id-GostR3410-94-CryptoPro-B-ParamSet" +#define NID_id_GostR3410_94_CryptoPro_B_ParamSet 833 +#define OBJ_id_GostR3410_94_CryptoPro_B_ParamSet OBJ_cryptopro,32L,3L + +#define SN_id_GostR3410_94_CryptoPro_C_ParamSet "id-GostR3410-94-CryptoPro-C-ParamSet" +#define NID_id_GostR3410_94_CryptoPro_C_ParamSet 834 +#define OBJ_id_GostR3410_94_CryptoPro_C_ParamSet OBJ_cryptopro,32L,4L + +#define SN_id_GostR3410_94_CryptoPro_D_ParamSet "id-GostR3410-94-CryptoPro-D-ParamSet" +#define NID_id_GostR3410_94_CryptoPro_D_ParamSet 835 +#define OBJ_id_GostR3410_94_CryptoPro_D_ParamSet OBJ_cryptopro,32L,5L + +#define SN_id_GostR3410_94_CryptoPro_XchA_ParamSet "id-GostR3410-94-CryptoPro-XchA-ParamSet" +#define NID_id_GostR3410_94_CryptoPro_XchA_ParamSet 836 +#define OBJ_id_GostR3410_94_CryptoPro_XchA_ParamSet OBJ_cryptopro,33L,1L + +#define SN_id_GostR3410_94_CryptoPro_XchB_ParamSet "id-GostR3410-94-CryptoPro-XchB-ParamSet" +#define NID_id_GostR3410_94_CryptoPro_XchB_ParamSet 837 +#define OBJ_id_GostR3410_94_CryptoPro_XchB_ParamSet OBJ_cryptopro,33L,2L + +#define SN_id_GostR3410_94_CryptoPro_XchC_ParamSet "id-GostR3410-94-CryptoPro-XchC-ParamSet" +#define NID_id_GostR3410_94_CryptoPro_XchC_ParamSet 838 +#define OBJ_id_GostR3410_94_CryptoPro_XchC_ParamSet OBJ_cryptopro,33L,3L + +#define SN_id_GostR3410_2001_TestParamSet "id-GostR3410-2001-TestParamSet" +#define NID_id_GostR3410_2001_TestParamSet 839 +#define OBJ_id_GostR3410_2001_TestParamSet OBJ_cryptopro,35L,0L + +#define SN_id_GostR3410_2001_CryptoPro_A_ParamSet "id-GostR3410-2001-CryptoPro-A-ParamSet" +#define NID_id_GostR3410_2001_CryptoPro_A_ParamSet 840 +#define OBJ_id_GostR3410_2001_CryptoPro_A_ParamSet OBJ_cryptopro,35L,1L + +#define SN_id_GostR3410_2001_CryptoPro_B_ParamSet "id-GostR3410-2001-CryptoPro-B-ParamSet" +#define NID_id_GostR3410_2001_CryptoPro_B_ParamSet 841 +#define OBJ_id_GostR3410_2001_CryptoPro_B_ParamSet OBJ_cryptopro,35L,2L + +#define SN_id_GostR3410_2001_CryptoPro_C_ParamSet "id-GostR3410-2001-CryptoPro-C-ParamSet" +#define NID_id_GostR3410_2001_CryptoPro_C_ParamSet 842 +#define OBJ_id_GostR3410_2001_CryptoPro_C_ParamSet OBJ_cryptopro,35L,3L + +#define SN_id_GostR3410_2001_CryptoPro_XchA_ParamSet "id-GostR3410-2001-CryptoPro-XchA-ParamSet" +#define NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet 843 +#define OBJ_id_GostR3410_2001_CryptoPro_XchA_ParamSet OBJ_cryptopro,36L,0L + +#define SN_id_GostR3410_2001_CryptoPro_XchB_ParamSet "id-GostR3410-2001-CryptoPro-XchB-ParamSet" +#define NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet 844 +#define OBJ_id_GostR3410_2001_CryptoPro_XchB_ParamSet OBJ_cryptopro,36L,1L + +#define SN_id_GostR3410_94_a "id-GostR3410-94-a" +#define NID_id_GostR3410_94_a 845 +#define OBJ_id_GostR3410_94_a OBJ_id_GostR3410_94,1L + +#define SN_id_GostR3410_94_aBis "id-GostR3410-94-aBis" +#define NID_id_GostR3410_94_aBis 846 +#define OBJ_id_GostR3410_94_aBis OBJ_id_GostR3410_94,2L + +#define SN_id_GostR3410_94_b "id-GostR3410-94-b" +#define NID_id_GostR3410_94_b 847 +#define OBJ_id_GostR3410_94_b OBJ_id_GostR3410_94,3L + +#define SN_id_GostR3410_94_bBis "id-GostR3410-94-bBis" +#define NID_id_GostR3410_94_bBis 848 +#define OBJ_id_GostR3410_94_bBis OBJ_id_GostR3410_94,4L + +#define SN_id_Gost28147_89_cc "id-Gost28147-89-cc" +#define LN_id_Gost28147_89_cc "GOST 28147-89 Cryptocom ParamSet" +#define NID_id_Gost28147_89_cc 849 +#define OBJ_id_Gost28147_89_cc OBJ_cryptocom,1L,6L,1L + +#define SN_id_GostR3410_94_cc "gost94cc" +#define LN_id_GostR3410_94_cc "GOST 34.10-94 Cryptocom" +#define NID_id_GostR3410_94_cc 850 +#define OBJ_id_GostR3410_94_cc OBJ_cryptocom,1L,5L,3L + +#define SN_id_GostR3410_2001_cc "gost2001cc" +#define LN_id_GostR3410_2001_cc "GOST 34.10-2001 Cryptocom" +#define NID_id_GostR3410_2001_cc 851 +#define OBJ_id_GostR3410_2001_cc OBJ_cryptocom,1L,5L,4L + +#define SN_id_GostR3411_94_with_GostR3410_94_cc "id-GostR3411-94-with-GostR3410-94-cc" +#define LN_id_GostR3411_94_with_GostR3410_94_cc "GOST R 34.11-94 with GOST R 34.10-94 Cryptocom" +#define NID_id_GostR3411_94_with_GostR3410_94_cc 852 +#define OBJ_id_GostR3411_94_with_GostR3410_94_cc OBJ_cryptocom,1L,3L,3L + +#define SN_id_GostR3411_94_with_GostR3410_2001_cc "id-GostR3411-94-with-GostR3410-2001-cc" +#define LN_id_GostR3411_94_with_GostR3410_2001_cc "GOST R 34.11-94 with GOST R 34.10-2001 Cryptocom" +#define NID_id_GostR3411_94_with_GostR3410_2001_cc 853 +#define OBJ_id_GostR3411_94_with_GostR3410_2001_cc OBJ_cryptocom,1L,3L,4L + +#define SN_id_GostR3410_2001_ParamSet_cc "id-GostR3410-2001-ParamSet-cc" +#define LN_id_GostR3410_2001_ParamSet_cc "GOST R 3410-2001 Parameter Set Cryptocom" +#define NID_id_GostR3410_2001_ParamSet_cc 854 +#define OBJ_id_GostR3410_2001_ParamSet_cc OBJ_cryptocom,1L,8L,1L + +#define SN_id_tc26_algorithms "id-tc26-algorithms" +#define NID_id_tc26_algorithms 977 +#define OBJ_id_tc26_algorithms OBJ_id_tc26,1L + +#define SN_id_tc26_sign "id-tc26-sign" +#define NID_id_tc26_sign 978 +#define OBJ_id_tc26_sign OBJ_id_tc26_algorithms,1L + +#define SN_id_GostR3410_2012_256 "gost2012_256" +#define LN_id_GostR3410_2012_256 "GOST R 34.10-2012 with 256 bit modulus" +#define NID_id_GostR3410_2012_256 979 +#define OBJ_id_GostR3410_2012_256 OBJ_id_tc26_sign,1L + +#define SN_id_GostR3410_2012_512 "gost2012_512" +#define LN_id_GostR3410_2012_512 "GOST R 34.10-2012 with 512 bit modulus" +#define NID_id_GostR3410_2012_512 980 +#define OBJ_id_GostR3410_2012_512 OBJ_id_tc26_sign,2L + +#define SN_id_tc26_digest "id-tc26-digest" +#define NID_id_tc26_digest 981 +#define OBJ_id_tc26_digest OBJ_id_tc26_algorithms,2L + +#define SN_id_GostR3411_2012_256 "md_gost12_256" +#define LN_id_GostR3411_2012_256 "GOST R 34.11-2012 with 256 bit hash" +#define NID_id_GostR3411_2012_256 982 +#define OBJ_id_GostR3411_2012_256 OBJ_id_tc26_digest,2L + +#define SN_id_GostR3411_2012_512 "md_gost12_512" +#define LN_id_GostR3411_2012_512 "GOST R 34.11-2012 with 512 bit hash" +#define NID_id_GostR3411_2012_512 983 +#define OBJ_id_GostR3411_2012_512 OBJ_id_tc26_digest,3L + +#define SN_id_tc26_signwithdigest "id-tc26-signwithdigest" +#define NID_id_tc26_signwithdigest 984 +#define OBJ_id_tc26_signwithdigest OBJ_id_tc26_algorithms,3L + +#define SN_id_tc26_signwithdigest_gost3410_2012_256 "id-tc26-signwithdigest-gost3410-2012-256" +#define LN_id_tc26_signwithdigest_gost3410_2012_256 "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)" +#define NID_id_tc26_signwithdigest_gost3410_2012_256 985 +#define OBJ_id_tc26_signwithdigest_gost3410_2012_256 OBJ_id_tc26_signwithdigest,2L + +#define SN_id_tc26_signwithdigest_gost3410_2012_512 "id-tc26-signwithdigest-gost3410-2012-512" +#define LN_id_tc26_signwithdigest_gost3410_2012_512 "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)" +#define NID_id_tc26_signwithdigest_gost3410_2012_512 986 +#define OBJ_id_tc26_signwithdigest_gost3410_2012_512 OBJ_id_tc26_signwithdigest,3L + +#define SN_id_tc26_mac "id-tc26-mac" +#define NID_id_tc26_mac 987 +#define OBJ_id_tc26_mac OBJ_id_tc26_algorithms,4L + +#define SN_id_tc26_hmac_gost_3411_2012_256 "id-tc26-hmac-gost-3411-2012-256" +#define LN_id_tc26_hmac_gost_3411_2012_256 "HMAC GOST 34.11-2012 256 bit" +#define NID_id_tc26_hmac_gost_3411_2012_256 988 +#define OBJ_id_tc26_hmac_gost_3411_2012_256 OBJ_id_tc26_mac,1L + +#define SN_id_tc26_hmac_gost_3411_2012_512 "id-tc26-hmac-gost-3411-2012-512" +#define LN_id_tc26_hmac_gost_3411_2012_512 "HMAC GOST 34.11-2012 512 bit" +#define NID_id_tc26_hmac_gost_3411_2012_512 989 +#define OBJ_id_tc26_hmac_gost_3411_2012_512 OBJ_id_tc26_mac,2L + +#define SN_id_tc26_cipher "id-tc26-cipher" +#define NID_id_tc26_cipher 990 +#define OBJ_id_tc26_cipher OBJ_id_tc26_algorithms,5L + +#define SN_id_tc26_cipher_gostr3412_2015_magma "id-tc26-cipher-gostr3412-2015-magma" +#define NID_id_tc26_cipher_gostr3412_2015_magma 1173 +#define OBJ_id_tc26_cipher_gostr3412_2015_magma OBJ_id_tc26_cipher,1L + +#define SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm "id-tc26-cipher-gostr3412-2015-magma-ctracpkm" +#define NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm 1174 +#define OBJ_id_tc26_cipher_gostr3412_2015_magma_ctracpkm OBJ_id_tc26_cipher_gostr3412_2015_magma,1L + +#define SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac "id-tc26-cipher-gostr3412-2015-magma-ctracpkm-omac" +#define NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac 1175 +#define OBJ_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac OBJ_id_tc26_cipher_gostr3412_2015_magma,2L + +#define SN_id_tc26_cipher_gostr3412_2015_kuznyechik "id-tc26-cipher-gostr3412-2015-kuznyechik" +#define NID_id_tc26_cipher_gostr3412_2015_kuznyechik 1176 +#define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik OBJ_id_tc26_cipher,2L + +#define SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm "id-tc26-cipher-gostr3412-2015-kuznyechik-ctracpkm" +#define NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm 1177 +#define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik,1L + +#define SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac "id-tc26-cipher-gostr3412-2015-kuznyechik-ctracpkm-omac" +#define NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac 1178 +#define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik,2L + +#define SN_id_tc26_agreement "id-tc26-agreement" +#define NID_id_tc26_agreement 991 +#define OBJ_id_tc26_agreement OBJ_id_tc26_algorithms,6L + +#define SN_id_tc26_agreement_gost_3410_2012_256 "id-tc26-agreement-gost-3410-2012-256" +#define NID_id_tc26_agreement_gost_3410_2012_256 992 +#define OBJ_id_tc26_agreement_gost_3410_2012_256 OBJ_id_tc26_agreement,1L + +#define SN_id_tc26_agreement_gost_3410_2012_512 "id-tc26-agreement-gost-3410-2012-512" +#define NID_id_tc26_agreement_gost_3410_2012_512 993 +#define OBJ_id_tc26_agreement_gost_3410_2012_512 OBJ_id_tc26_agreement,2L + +#define SN_id_tc26_wrap "id-tc26-wrap" +#define NID_id_tc26_wrap 1179 +#define OBJ_id_tc26_wrap OBJ_id_tc26_algorithms,7L + +#define SN_id_tc26_wrap_gostr3412_2015_magma "id-tc26-wrap-gostr3412-2015-magma" +#define NID_id_tc26_wrap_gostr3412_2015_magma 1180 +#define OBJ_id_tc26_wrap_gostr3412_2015_magma OBJ_id_tc26_wrap,1L + +#define SN_id_tc26_wrap_gostr3412_2015_magma_kexp15 "id-tc26-wrap-gostr3412-2015-magma-kexp15" +#define NID_id_tc26_wrap_gostr3412_2015_magma_kexp15 1181 +#define OBJ_id_tc26_wrap_gostr3412_2015_magma_kexp15 OBJ_id_tc26_wrap_gostr3412_2015_magma,1L + +#define SN_id_tc26_wrap_gostr3412_2015_kuznyechik "id-tc26-wrap-gostr3412-2015-kuznyechik" +#define NID_id_tc26_wrap_gostr3412_2015_kuznyechik 1182 +#define OBJ_id_tc26_wrap_gostr3412_2015_kuznyechik OBJ_id_tc26_wrap,2L + +#define SN_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 "id-tc26-wrap-gostr3412-2015-kuznyechik-kexp15" +#define NID_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 1183 +#define OBJ_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 OBJ_id_tc26_wrap_gostr3412_2015_magma,1L + +#define SN_id_tc26_constants "id-tc26-constants" +#define NID_id_tc26_constants 994 +#define OBJ_id_tc26_constants OBJ_id_tc26,2L + +#define SN_id_tc26_sign_constants "id-tc26-sign-constants" +#define NID_id_tc26_sign_constants 995 +#define OBJ_id_tc26_sign_constants OBJ_id_tc26_constants,1L + +#define SN_id_tc26_gost_3410_2012_256_constants "id-tc26-gost-3410-2012-256-constants" +#define NID_id_tc26_gost_3410_2012_256_constants 1147 +#define OBJ_id_tc26_gost_3410_2012_256_constants OBJ_id_tc26_sign_constants,1L + +#define SN_id_tc26_gost_3410_2012_256_paramSetA "id-tc26-gost-3410-2012-256-paramSetA" +#define LN_id_tc26_gost_3410_2012_256_paramSetA "GOST R 34.10-2012 (256 bit) ParamSet A" +#define NID_id_tc26_gost_3410_2012_256_paramSetA 1148 +#define OBJ_id_tc26_gost_3410_2012_256_paramSetA OBJ_id_tc26_gost_3410_2012_256_constants,1L + +#define SN_id_tc26_gost_3410_2012_256_paramSetB "id-tc26-gost-3410-2012-256-paramSetB" +#define LN_id_tc26_gost_3410_2012_256_paramSetB "GOST R 34.10-2012 (256 bit) ParamSet B" +#define NID_id_tc26_gost_3410_2012_256_paramSetB 1184 +#define OBJ_id_tc26_gost_3410_2012_256_paramSetB OBJ_id_tc26_gost_3410_2012_256_constants,2L + +#define SN_id_tc26_gost_3410_2012_256_paramSetC "id-tc26-gost-3410-2012-256-paramSetC" +#define LN_id_tc26_gost_3410_2012_256_paramSetC "GOST R 34.10-2012 (256 bit) ParamSet C" +#define NID_id_tc26_gost_3410_2012_256_paramSetC 1185 +#define OBJ_id_tc26_gost_3410_2012_256_paramSetC OBJ_id_tc26_gost_3410_2012_256_constants,3L + +#define SN_id_tc26_gost_3410_2012_256_paramSetD "id-tc26-gost-3410-2012-256-paramSetD" +#define LN_id_tc26_gost_3410_2012_256_paramSetD "GOST R 34.10-2012 (256 bit) ParamSet D" +#define NID_id_tc26_gost_3410_2012_256_paramSetD 1186 +#define OBJ_id_tc26_gost_3410_2012_256_paramSetD OBJ_id_tc26_gost_3410_2012_256_constants,4L + +#define SN_id_tc26_gost_3410_2012_512_constants "id-tc26-gost-3410-2012-512-constants" +#define NID_id_tc26_gost_3410_2012_512_constants 996 +#define OBJ_id_tc26_gost_3410_2012_512_constants OBJ_id_tc26_sign_constants,2L + +#define SN_id_tc26_gost_3410_2012_512_paramSetTest "id-tc26-gost-3410-2012-512-paramSetTest" +#define LN_id_tc26_gost_3410_2012_512_paramSetTest "GOST R 34.10-2012 (512 bit) testing parameter set" +#define NID_id_tc26_gost_3410_2012_512_paramSetTest 997 +#define OBJ_id_tc26_gost_3410_2012_512_paramSetTest OBJ_id_tc26_gost_3410_2012_512_constants,0L + +#define SN_id_tc26_gost_3410_2012_512_paramSetA "id-tc26-gost-3410-2012-512-paramSetA" +#define LN_id_tc26_gost_3410_2012_512_paramSetA "GOST R 34.10-2012 (512 bit) ParamSet A" +#define NID_id_tc26_gost_3410_2012_512_paramSetA 998 +#define OBJ_id_tc26_gost_3410_2012_512_paramSetA OBJ_id_tc26_gost_3410_2012_512_constants,1L + +#define SN_id_tc26_gost_3410_2012_512_paramSetB "id-tc26-gost-3410-2012-512-paramSetB" +#define LN_id_tc26_gost_3410_2012_512_paramSetB "GOST R 34.10-2012 (512 bit) ParamSet B" +#define NID_id_tc26_gost_3410_2012_512_paramSetB 999 +#define OBJ_id_tc26_gost_3410_2012_512_paramSetB OBJ_id_tc26_gost_3410_2012_512_constants,2L + +#define SN_id_tc26_gost_3410_2012_512_paramSetC "id-tc26-gost-3410-2012-512-paramSetC" +#define LN_id_tc26_gost_3410_2012_512_paramSetC "GOST R 34.10-2012 (512 bit) ParamSet C" +#define NID_id_tc26_gost_3410_2012_512_paramSetC 1149 +#define OBJ_id_tc26_gost_3410_2012_512_paramSetC OBJ_id_tc26_gost_3410_2012_512_constants,3L + +#define SN_id_tc26_digest_constants "id-tc26-digest-constants" +#define NID_id_tc26_digest_constants 1000 +#define OBJ_id_tc26_digest_constants OBJ_id_tc26_constants,2L + +#define SN_id_tc26_cipher_constants "id-tc26-cipher-constants" +#define NID_id_tc26_cipher_constants 1001 +#define OBJ_id_tc26_cipher_constants OBJ_id_tc26_constants,5L + +#define SN_id_tc26_gost_28147_constants "id-tc26-gost-28147-constants" +#define NID_id_tc26_gost_28147_constants 1002 +#define OBJ_id_tc26_gost_28147_constants OBJ_id_tc26_cipher_constants,1L + +#define SN_id_tc26_gost_28147_param_Z "id-tc26-gost-28147-param-Z" +#define LN_id_tc26_gost_28147_param_Z "GOST 28147-89 TC26 parameter set" +#define NID_id_tc26_gost_28147_param_Z 1003 +#define OBJ_id_tc26_gost_28147_param_Z OBJ_id_tc26_gost_28147_constants,1L + +#define SN_INN "INN" +#define LN_INN "INN" +#define NID_INN 1004 +#define OBJ_INN OBJ_member_body,643L,3L,131L,1L,1L + +#define SN_OGRN "OGRN" +#define LN_OGRN "OGRN" +#define NID_OGRN 1005 +#define OBJ_OGRN OBJ_member_body,643L,100L,1L + +#define SN_SNILS "SNILS" +#define LN_SNILS "SNILS" +#define NID_SNILS 1006 +#define OBJ_SNILS OBJ_member_body,643L,100L,3L + +#define SN_subjectSignTool "subjectSignTool" +#define LN_subjectSignTool "Signing Tool of Subject" +#define NID_subjectSignTool 1007 +#define OBJ_subjectSignTool OBJ_member_body,643L,100L,111L + +#define SN_issuerSignTool "issuerSignTool" +#define LN_issuerSignTool "Signing Tool of Issuer" +#define NID_issuerSignTool 1008 +#define OBJ_issuerSignTool OBJ_member_body,643L,100L,112L + +#define SN_grasshopper_ecb "grasshopper-ecb" +#define NID_grasshopper_ecb 1012 + +#define SN_grasshopper_ctr "grasshopper-ctr" +#define NID_grasshopper_ctr 1013 + +#define SN_grasshopper_ofb "grasshopper-ofb" +#define NID_grasshopper_ofb 1014 + +#define SN_grasshopper_cbc "grasshopper-cbc" +#define NID_grasshopper_cbc 1015 + +#define SN_grasshopper_cfb "grasshopper-cfb" +#define NID_grasshopper_cfb 1016 + +#define SN_grasshopper_mac "grasshopper-mac" +#define NID_grasshopper_mac 1017 + +#define SN_magma_ecb "magma-ecb" +#define NID_magma_ecb 1187 + +#define SN_magma_ctr "magma-ctr" +#define NID_magma_ctr 1188 + +#define SN_magma_ofb "magma-ofb" +#define NID_magma_ofb 1189 + +#define SN_magma_cbc "magma-cbc" +#define NID_magma_cbc 1190 + +#define SN_magma_cfb "magma-cfb" +#define NID_magma_cfb 1191 + +#define SN_magma_mac "magma-mac" +#define NID_magma_mac 1192 + +#define SN_camellia_128_cbc "CAMELLIA-128-CBC" +#define LN_camellia_128_cbc "camellia-128-cbc" +#define NID_camellia_128_cbc 751 +#define OBJ_camellia_128_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,2L + +#define SN_camellia_192_cbc "CAMELLIA-192-CBC" +#define LN_camellia_192_cbc "camellia-192-cbc" +#define NID_camellia_192_cbc 752 +#define OBJ_camellia_192_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,3L + +#define SN_camellia_256_cbc "CAMELLIA-256-CBC" +#define LN_camellia_256_cbc "camellia-256-cbc" +#define NID_camellia_256_cbc 753 +#define OBJ_camellia_256_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,4L + +#define SN_id_camellia128_wrap "id-camellia128-wrap" +#define NID_id_camellia128_wrap 907 +#define OBJ_id_camellia128_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,2L + +#define SN_id_camellia192_wrap "id-camellia192-wrap" +#define NID_id_camellia192_wrap 908 +#define OBJ_id_camellia192_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,3L + +#define SN_id_camellia256_wrap "id-camellia256-wrap" +#define NID_id_camellia256_wrap 909 +#define OBJ_id_camellia256_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,4L + +#define OBJ_ntt_ds 0L,3L,4401L,5L + +#define OBJ_camellia OBJ_ntt_ds,3L,1L,9L + +#define SN_camellia_128_ecb "CAMELLIA-128-ECB" +#define LN_camellia_128_ecb "camellia-128-ecb" +#define NID_camellia_128_ecb 754 +#define OBJ_camellia_128_ecb OBJ_camellia,1L + +#define SN_camellia_128_ofb128 "CAMELLIA-128-OFB" +#define LN_camellia_128_ofb128 "camellia-128-ofb" +#define NID_camellia_128_ofb128 766 +#define OBJ_camellia_128_ofb128 OBJ_camellia,3L + +#define SN_camellia_128_cfb128 "CAMELLIA-128-CFB" +#define LN_camellia_128_cfb128 "camellia-128-cfb" +#define NID_camellia_128_cfb128 757 +#define OBJ_camellia_128_cfb128 OBJ_camellia,4L + +#define SN_camellia_128_gcm "CAMELLIA-128-GCM" +#define LN_camellia_128_gcm "camellia-128-gcm" +#define NID_camellia_128_gcm 961 +#define OBJ_camellia_128_gcm OBJ_camellia,6L + +#define SN_camellia_128_ccm "CAMELLIA-128-CCM" +#define LN_camellia_128_ccm "camellia-128-ccm" +#define NID_camellia_128_ccm 962 +#define OBJ_camellia_128_ccm OBJ_camellia,7L + +#define SN_camellia_128_ctr "CAMELLIA-128-CTR" +#define LN_camellia_128_ctr "camellia-128-ctr" +#define NID_camellia_128_ctr 963 +#define OBJ_camellia_128_ctr OBJ_camellia,9L + +#define SN_camellia_128_cmac "CAMELLIA-128-CMAC" +#define LN_camellia_128_cmac "camellia-128-cmac" +#define NID_camellia_128_cmac 964 +#define OBJ_camellia_128_cmac OBJ_camellia,10L + +#define SN_camellia_192_ecb "CAMELLIA-192-ECB" +#define LN_camellia_192_ecb "camellia-192-ecb" +#define NID_camellia_192_ecb 755 +#define OBJ_camellia_192_ecb OBJ_camellia,21L + +#define SN_camellia_192_ofb128 "CAMELLIA-192-OFB" +#define LN_camellia_192_ofb128 "camellia-192-ofb" +#define NID_camellia_192_ofb128 767 +#define OBJ_camellia_192_ofb128 OBJ_camellia,23L + +#define SN_camellia_192_cfb128 "CAMELLIA-192-CFB" +#define LN_camellia_192_cfb128 "camellia-192-cfb" +#define NID_camellia_192_cfb128 758 +#define OBJ_camellia_192_cfb128 OBJ_camellia,24L + +#define SN_camellia_192_gcm "CAMELLIA-192-GCM" +#define LN_camellia_192_gcm "camellia-192-gcm" +#define NID_camellia_192_gcm 965 +#define OBJ_camellia_192_gcm OBJ_camellia,26L + +#define SN_camellia_192_ccm "CAMELLIA-192-CCM" +#define LN_camellia_192_ccm "camellia-192-ccm" +#define NID_camellia_192_ccm 966 +#define OBJ_camellia_192_ccm OBJ_camellia,27L + +#define SN_camellia_192_ctr "CAMELLIA-192-CTR" +#define LN_camellia_192_ctr "camellia-192-ctr" +#define NID_camellia_192_ctr 967 +#define OBJ_camellia_192_ctr OBJ_camellia,29L + +#define SN_camellia_192_cmac "CAMELLIA-192-CMAC" +#define LN_camellia_192_cmac "camellia-192-cmac" +#define NID_camellia_192_cmac 968 +#define OBJ_camellia_192_cmac OBJ_camellia,30L + +#define SN_camellia_256_ecb "CAMELLIA-256-ECB" +#define LN_camellia_256_ecb "camellia-256-ecb" +#define NID_camellia_256_ecb 756 +#define OBJ_camellia_256_ecb OBJ_camellia,41L + +#define SN_camellia_256_ofb128 "CAMELLIA-256-OFB" +#define LN_camellia_256_ofb128 "camellia-256-ofb" +#define NID_camellia_256_ofb128 768 +#define OBJ_camellia_256_ofb128 OBJ_camellia,43L + +#define SN_camellia_256_cfb128 "CAMELLIA-256-CFB" +#define LN_camellia_256_cfb128 "camellia-256-cfb" +#define NID_camellia_256_cfb128 759 +#define OBJ_camellia_256_cfb128 OBJ_camellia,44L + +#define SN_camellia_256_gcm "CAMELLIA-256-GCM" +#define LN_camellia_256_gcm "camellia-256-gcm" +#define NID_camellia_256_gcm 969 +#define OBJ_camellia_256_gcm OBJ_camellia,46L + +#define SN_camellia_256_ccm "CAMELLIA-256-CCM" +#define LN_camellia_256_ccm "camellia-256-ccm" +#define NID_camellia_256_ccm 970 +#define OBJ_camellia_256_ccm OBJ_camellia,47L + +#define SN_camellia_256_ctr "CAMELLIA-256-CTR" +#define LN_camellia_256_ctr "camellia-256-ctr" +#define NID_camellia_256_ctr 971 +#define OBJ_camellia_256_ctr OBJ_camellia,49L + +#define SN_camellia_256_cmac "CAMELLIA-256-CMAC" +#define LN_camellia_256_cmac "camellia-256-cmac" +#define NID_camellia_256_cmac 972 +#define OBJ_camellia_256_cmac OBJ_camellia,50L + +#define SN_camellia_128_cfb1 "CAMELLIA-128-CFB1" +#define LN_camellia_128_cfb1 "camellia-128-cfb1" +#define NID_camellia_128_cfb1 760 + +#define SN_camellia_192_cfb1 "CAMELLIA-192-CFB1" +#define LN_camellia_192_cfb1 "camellia-192-cfb1" +#define NID_camellia_192_cfb1 761 + +#define SN_camellia_256_cfb1 "CAMELLIA-256-CFB1" +#define LN_camellia_256_cfb1 "camellia-256-cfb1" +#define NID_camellia_256_cfb1 762 + +#define SN_camellia_128_cfb8 "CAMELLIA-128-CFB8" +#define LN_camellia_128_cfb8 "camellia-128-cfb8" +#define NID_camellia_128_cfb8 763 + +#define SN_camellia_192_cfb8 "CAMELLIA-192-CFB8" +#define LN_camellia_192_cfb8 "camellia-192-cfb8" +#define NID_camellia_192_cfb8 764 + +#define SN_camellia_256_cfb8 "CAMELLIA-256-CFB8" +#define LN_camellia_256_cfb8 "camellia-256-cfb8" +#define NID_camellia_256_cfb8 765 + +#define OBJ_aria 1L,2L,410L,200046L,1L,1L + +#define SN_aria_128_ecb "ARIA-128-ECB" +#define LN_aria_128_ecb "aria-128-ecb" +#define NID_aria_128_ecb 1065 +#define OBJ_aria_128_ecb OBJ_aria,1L + +#define SN_aria_128_cbc "ARIA-128-CBC" +#define LN_aria_128_cbc "aria-128-cbc" +#define NID_aria_128_cbc 1066 +#define OBJ_aria_128_cbc OBJ_aria,2L + +#define SN_aria_128_cfb128 "ARIA-128-CFB" +#define LN_aria_128_cfb128 "aria-128-cfb" +#define NID_aria_128_cfb128 1067 +#define OBJ_aria_128_cfb128 OBJ_aria,3L + +#define SN_aria_128_ofb128 "ARIA-128-OFB" +#define LN_aria_128_ofb128 "aria-128-ofb" +#define NID_aria_128_ofb128 1068 +#define OBJ_aria_128_ofb128 OBJ_aria,4L + +#define SN_aria_128_ctr "ARIA-128-CTR" +#define LN_aria_128_ctr "aria-128-ctr" +#define NID_aria_128_ctr 1069 +#define OBJ_aria_128_ctr OBJ_aria,5L + +#define SN_aria_192_ecb "ARIA-192-ECB" +#define LN_aria_192_ecb "aria-192-ecb" +#define NID_aria_192_ecb 1070 +#define OBJ_aria_192_ecb OBJ_aria,6L + +#define SN_aria_192_cbc "ARIA-192-CBC" +#define LN_aria_192_cbc "aria-192-cbc" +#define NID_aria_192_cbc 1071 +#define OBJ_aria_192_cbc OBJ_aria,7L + +#define SN_aria_192_cfb128 "ARIA-192-CFB" +#define LN_aria_192_cfb128 "aria-192-cfb" +#define NID_aria_192_cfb128 1072 +#define OBJ_aria_192_cfb128 OBJ_aria,8L + +#define SN_aria_192_ofb128 "ARIA-192-OFB" +#define LN_aria_192_ofb128 "aria-192-ofb" +#define NID_aria_192_ofb128 1073 +#define OBJ_aria_192_ofb128 OBJ_aria,9L + +#define SN_aria_192_ctr "ARIA-192-CTR" +#define LN_aria_192_ctr "aria-192-ctr" +#define NID_aria_192_ctr 1074 +#define OBJ_aria_192_ctr OBJ_aria,10L + +#define SN_aria_256_ecb "ARIA-256-ECB" +#define LN_aria_256_ecb "aria-256-ecb" +#define NID_aria_256_ecb 1075 +#define OBJ_aria_256_ecb OBJ_aria,11L + +#define SN_aria_256_cbc "ARIA-256-CBC" +#define LN_aria_256_cbc "aria-256-cbc" +#define NID_aria_256_cbc 1076 +#define OBJ_aria_256_cbc OBJ_aria,12L + +#define SN_aria_256_cfb128 "ARIA-256-CFB" +#define LN_aria_256_cfb128 "aria-256-cfb" +#define NID_aria_256_cfb128 1077 +#define OBJ_aria_256_cfb128 OBJ_aria,13L + +#define SN_aria_256_ofb128 "ARIA-256-OFB" +#define LN_aria_256_ofb128 "aria-256-ofb" +#define NID_aria_256_ofb128 1078 +#define OBJ_aria_256_ofb128 OBJ_aria,14L + +#define SN_aria_256_ctr "ARIA-256-CTR" +#define LN_aria_256_ctr "aria-256-ctr" +#define NID_aria_256_ctr 1079 +#define OBJ_aria_256_ctr OBJ_aria,15L + +#define SN_aria_128_cfb1 "ARIA-128-CFB1" +#define LN_aria_128_cfb1 "aria-128-cfb1" +#define NID_aria_128_cfb1 1080 + +#define SN_aria_192_cfb1 "ARIA-192-CFB1" +#define LN_aria_192_cfb1 "aria-192-cfb1" +#define NID_aria_192_cfb1 1081 + +#define SN_aria_256_cfb1 "ARIA-256-CFB1" +#define LN_aria_256_cfb1 "aria-256-cfb1" +#define NID_aria_256_cfb1 1082 + +#define SN_aria_128_cfb8 "ARIA-128-CFB8" +#define LN_aria_128_cfb8 "aria-128-cfb8" +#define NID_aria_128_cfb8 1083 + +#define SN_aria_192_cfb8 "ARIA-192-CFB8" +#define LN_aria_192_cfb8 "aria-192-cfb8" +#define NID_aria_192_cfb8 1084 + +#define SN_aria_256_cfb8 "ARIA-256-CFB8" +#define LN_aria_256_cfb8 "aria-256-cfb8" +#define NID_aria_256_cfb8 1085 + +#define SN_aria_128_ccm "ARIA-128-CCM" +#define LN_aria_128_ccm "aria-128-ccm" +#define NID_aria_128_ccm 1120 +#define OBJ_aria_128_ccm OBJ_aria,37L + +#define SN_aria_192_ccm "ARIA-192-CCM" +#define LN_aria_192_ccm "aria-192-ccm" +#define NID_aria_192_ccm 1121 +#define OBJ_aria_192_ccm OBJ_aria,38L + +#define SN_aria_256_ccm "ARIA-256-CCM" +#define LN_aria_256_ccm "aria-256-ccm" +#define NID_aria_256_ccm 1122 +#define OBJ_aria_256_ccm OBJ_aria,39L + +#define SN_aria_128_gcm "ARIA-128-GCM" +#define LN_aria_128_gcm "aria-128-gcm" +#define NID_aria_128_gcm 1123 +#define OBJ_aria_128_gcm OBJ_aria,34L + +#define SN_aria_192_gcm "ARIA-192-GCM" +#define LN_aria_192_gcm "aria-192-gcm" +#define NID_aria_192_gcm 1124 +#define OBJ_aria_192_gcm OBJ_aria,35L + +#define SN_aria_256_gcm "ARIA-256-GCM" +#define LN_aria_256_gcm "aria-256-gcm" +#define NID_aria_256_gcm 1125 +#define OBJ_aria_256_gcm OBJ_aria,36L + +#define SN_kisa "KISA" +#define LN_kisa "kisa" +#define NID_kisa 773 +#define OBJ_kisa OBJ_member_body,410L,200004L + +#define SN_seed_ecb "SEED-ECB" +#define LN_seed_ecb "seed-ecb" +#define NID_seed_ecb 776 +#define OBJ_seed_ecb OBJ_kisa,1L,3L + +#define SN_seed_cbc "SEED-CBC" +#define LN_seed_cbc "seed-cbc" +#define NID_seed_cbc 777 +#define OBJ_seed_cbc OBJ_kisa,1L,4L + +#define SN_seed_cfb128 "SEED-CFB" +#define LN_seed_cfb128 "seed-cfb" +#define NID_seed_cfb128 779 +#define OBJ_seed_cfb128 OBJ_kisa,1L,5L + +#define SN_seed_ofb128 "SEED-OFB" +#define LN_seed_ofb128 "seed-ofb" +#define NID_seed_ofb128 778 +#define OBJ_seed_ofb128 OBJ_kisa,1L,6L + +#define SN_sm4_ecb "SM4-ECB" +#define LN_sm4_ecb "sm4-ecb" +#define NID_sm4_ecb 1133 +#define OBJ_sm4_ecb OBJ_sm_scheme,104L,1L + +#define SN_sm4_cbc "SM4-CBC" +#define LN_sm4_cbc "sm4-cbc" +#define NID_sm4_cbc 1134 +#define OBJ_sm4_cbc OBJ_sm_scheme,104L,2L + +#define SN_sm4_ofb128 "SM4-OFB" +#define LN_sm4_ofb128 "sm4-ofb" +#define NID_sm4_ofb128 1135 +#define OBJ_sm4_ofb128 OBJ_sm_scheme,104L,3L + +#define SN_sm4_cfb128 "SM4-CFB" +#define LN_sm4_cfb128 "sm4-cfb" +#define NID_sm4_cfb128 1137 +#define OBJ_sm4_cfb128 OBJ_sm_scheme,104L,4L + +#define SN_sm4_cfb1 "SM4-CFB1" +#define LN_sm4_cfb1 "sm4-cfb1" +#define NID_sm4_cfb1 1136 +#define OBJ_sm4_cfb1 OBJ_sm_scheme,104L,5L + +#define SN_sm4_cfb8 "SM4-CFB8" +#define LN_sm4_cfb8 "sm4-cfb8" +#define NID_sm4_cfb8 1138 +#define OBJ_sm4_cfb8 OBJ_sm_scheme,104L,6L + +#define SN_sm4_ctr "SM4-CTR" +#define LN_sm4_ctr "sm4-ctr" +#define NID_sm4_ctr 1139 +#define OBJ_sm4_ctr OBJ_sm_scheme,104L,7L + +#define SN_hmac "HMAC" +#define LN_hmac "hmac" +#define NID_hmac 855 + +#define SN_cmac "CMAC" +#define LN_cmac "cmac" +#define NID_cmac 894 + +#define SN_rc4_hmac_md5 "RC4-HMAC-MD5" +#define LN_rc4_hmac_md5 "rc4-hmac-md5" +#define NID_rc4_hmac_md5 915 + +#define SN_aes_128_cbc_hmac_sha1 "AES-128-CBC-HMAC-SHA1" +#define LN_aes_128_cbc_hmac_sha1 "aes-128-cbc-hmac-sha1" +#define NID_aes_128_cbc_hmac_sha1 916 + +#define SN_aes_192_cbc_hmac_sha1 "AES-192-CBC-HMAC-SHA1" +#define LN_aes_192_cbc_hmac_sha1 "aes-192-cbc-hmac-sha1" +#define NID_aes_192_cbc_hmac_sha1 917 + +#define SN_aes_256_cbc_hmac_sha1 "AES-256-CBC-HMAC-SHA1" +#define LN_aes_256_cbc_hmac_sha1 "aes-256-cbc-hmac-sha1" +#define NID_aes_256_cbc_hmac_sha1 918 + +#define SN_aes_128_cbc_hmac_sha256 "AES-128-CBC-HMAC-SHA256" +#define LN_aes_128_cbc_hmac_sha256 "aes-128-cbc-hmac-sha256" +#define NID_aes_128_cbc_hmac_sha256 948 + +#define SN_aes_192_cbc_hmac_sha256 "AES-192-CBC-HMAC-SHA256" +#define LN_aes_192_cbc_hmac_sha256 "aes-192-cbc-hmac-sha256" +#define NID_aes_192_cbc_hmac_sha256 949 + +#define SN_aes_256_cbc_hmac_sha256 "AES-256-CBC-HMAC-SHA256" +#define LN_aes_256_cbc_hmac_sha256 "aes-256-cbc-hmac-sha256" +#define NID_aes_256_cbc_hmac_sha256 950 + +#define SN_chacha20_poly1305 "ChaCha20-Poly1305" +#define LN_chacha20_poly1305 "chacha20-poly1305" +#define NID_chacha20_poly1305 1018 + +#define SN_chacha20 "ChaCha20" +#define LN_chacha20 "chacha20" +#define NID_chacha20 1019 + +#define SN_dhpublicnumber "dhpublicnumber" +#define LN_dhpublicnumber "X9.42 DH" +#define NID_dhpublicnumber 920 +#define OBJ_dhpublicnumber OBJ_ISO_US,10046L,2L,1L + +#define SN_brainpoolP160r1 "brainpoolP160r1" +#define NID_brainpoolP160r1 921 +#define OBJ_brainpoolP160r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,1L + +#define SN_brainpoolP160t1 "brainpoolP160t1" +#define NID_brainpoolP160t1 922 +#define OBJ_brainpoolP160t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,2L + +#define SN_brainpoolP192r1 "brainpoolP192r1" +#define NID_brainpoolP192r1 923 +#define OBJ_brainpoolP192r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,3L + +#define SN_brainpoolP192t1 "brainpoolP192t1" +#define NID_brainpoolP192t1 924 +#define OBJ_brainpoolP192t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,4L + +#define SN_brainpoolP224r1 "brainpoolP224r1" +#define NID_brainpoolP224r1 925 +#define OBJ_brainpoolP224r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,5L + +#define SN_brainpoolP224t1 "brainpoolP224t1" +#define NID_brainpoolP224t1 926 +#define OBJ_brainpoolP224t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,6L + +#define SN_brainpoolP256r1 "brainpoolP256r1" +#define NID_brainpoolP256r1 927 +#define OBJ_brainpoolP256r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,7L + +#define SN_brainpoolP256t1 "brainpoolP256t1" +#define NID_brainpoolP256t1 928 +#define OBJ_brainpoolP256t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,8L + +#define SN_brainpoolP320r1 "brainpoolP320r1" +#define NID_brainpoolP320r1 929 +#define OBJ_brainpoolP320r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,9L + +#define SN_brainpoolP320t1 "brainpoolP320t1" +#define NID_brainpoolP320t1 930 +#define OBJ_brainpoolP320t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,10L + +#define SN_brainpoolP384r1 "brainpoolP384r1" +#define NID_brainpoolP384r1 931 +#define OBJ_brainpoolP384r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,11L + +#define SN_brainpoolP384t1 "brainpoolP384t1" +#define NID_brainpoolP384t1 932 +#define OBJ_brainpoolP384t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,12L + +#define SN_brainpoolP512r1 "brainpoolP512r1" +#define NID_brainpoolP512r1 933 +#define OBJ_brainpoolP512r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,13L + +#define SN_brainpoolP512t1 "brainpoolP512t1" +#define NID_brainpoolP512t1 934 +#define OBJ_brainpoolP512t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,14L + +#define OBJ_x9_63_scheme 1L,3L,133L,16L,840L,63L,0L + +#define OBJ_secg_scheme OBJ_certicom_arc,1L + +#define SN_dhSinglePass_stdDH_sha1kdf_scheme "dhSinglePass-stdDH-sha1kdf-scheme" +#define NID_dhSinglePass_stdDH_sha1kdf_scheme 936 +#define OBJ_dhSinglePass_stdDH_sha1kdf_scheme OBJ_x9_63_scheme,2L + +#define SN_dhSinglePass_stdDH_sha224kdf_scheme "dhSinglePass-stdDH-sha224kdf-scheme" +#define NID_dhSinglePass_stdDH_sha224kdf_scheme 937 +#define OBJ_dhSinglePass_stdDH_sha224kdf_scheme OBJ_secg_scheme,11L,0L + +#define SN_dhSinglePass_stdDH_sha256kdf_scheme "dhSinglePass-stdDH-sha256kdf-scheme" +#define NID_dhSinglePass_stdDH_sha256kdf_scheme 938 +#define OBJ_dhSinglePass_stdDH_sha256kdf_scheme OBJ_secg_scheme,11L,1L + +#define SN_dhSinglePass_stdDH_sha384kdf_scheme "dhSinglePass-stdDH-sha384kdf-scheme" +#define NID_dhSinglePass_stdDH_sha384kdf_scheme 939 +#define OBJ_dhSinglePass_stdDH_sha384kdf_scheme OBJ_secg_scheme,11L,2L + +#define SN_dhSinglePass_stdDH_sha512kdf_scheme "dhSinglePass-stdDH-sha512kdf-scheme" +#define NID_dhSinglePass_stdDH_sha512kdf_scheme 940 +#define OBJ_dhSinglePass_stdDH_sha512kdf_scheme OBJ_secg_scheme,11L,3L + +#define SN_dhSinglePass_cofactorDH_sha1kdf_scheme "dhSinglePass-cofactorDH-sha1kdf-scheme" +#define NID_dhSinglePass_cofactorDH_sha1kdf_scheme 941 +#define OBJ_dhSinglePass_cofactorDH_sha1kdf_scheme OBJ_x9_63_scheme,3L + +#define SN_dhSinglePass_cofactorDH_sha224kdf_scheme "dhSinglePass-cofactorDH-sha224kdf-scheme" +#define NID_dhSinglePass_cofactorDH_sha224kdf_scheme 942 +#define OBJ_dhSinglePass_cofactorDH_sha224kdf_scheme OBJ_secg_scheme,14L,0L + +#define SN_dhSinglePass_cofactorDH_sha256kdf_scheme "dhSinglePass-cofactorDH-sha256kdf-scheme" +#define NID_dhSinglePass_cofactorDH_sha256kdf_scheme 943 +#define OBJ_dhSinglePass_cofactorDH_sha256kdf_scheme OBJ_secg_scheme,14L,1L + +#define SN_dhSinglePass_cofactorDH_sha384kdf_scheme "dhSinglePass-cofactorDH-sha384kdf-scheme" +#define NID_dhSinglePass_cofactorDH_sha384kdf_scheme 944 +#define OBJ_dhSinglePass_cofactorDH_sha384kdf_scheme OBJ_secg_scheme,14L,2L + +#define SN_dhSinglePass_cofactorDH_sha512kdf_scheme "dhSinglePass-cofactorDH-sha512kdf-scheme" +#define NID_dhSinglePass_cofactorDH_sha512kdf_scheme 945 +#define OBJ_dhSinglePass_cofactorDH_sha512kdf_scheme OBJ_secg_scheme,14L,3L + +#define SN_dh_std_kdf "dh-std-kdf" +#define NID_dh_std_kdf 946 + +#define SN_dh_cofactor_kdf "dh-cofactor-kdf" +#define NID_dh_cofactor_kdf 947 + +#define SN_ct_precert_scts "ct_precert_scts" +#define LN_ct_precert_scts "CT Precertificate SCTs" +#define NID_ct_precert_scts 951 +#define OBJ_ct_precert_scts 1L,3L,6L,1L,4L,1L,11129L,2L,4L,2L + +#define SN_ct_precert_poison "ct_precert_poison" +#define LN_ct_precert_poison "CT Precertificate Poison" +#define NID_ct_precert_poison 952 +#define OBJ_ct_precert_poison 1L,3L,6L,1L,4L,1L,11129L,2L,4L,3L + +#define SN_ct_precert_signer "ct_precert_signer" +#define LN_ct_precert_signer "CT Precertificate Signer" +#define NID_ct_precert_signer 953 +#define OBJ_ct_precert_signer 1L,3L,6L,1L,4L,1L,11129L,2L,4L,4L + +#define SN_ct_cert_scts "ct_cert_scts" +#define LN_ct_cert_scts "CT Certificate SCTs" +#define NID_ct_cert_scts 954 +#define OBJ_ct_cert_scts 1L,3L,6L,1L,4L,1L,11129L,2L,4L,5L + +#define SN_jurisdictionLocalityName "jurisdictionL" +#define LN_jurisdictionLocalityName "jurisdictionLocalityName" +#define NID_jurisdictionLocalityName 955 +#define OBJ_jurisdictionLocalityName 1L,3L,6L,1L,4L,1L,311L,60L,2L,1L,1L + +#define SN_jurisdictionStateOrProvinceName "jurisdictionST" +#define LN_jurisdictionStateOrProvinceName "jurisdictionStateOrProvinceName" +#define NID_jurisdictionStateOrProvinceName 956 +#define OBJ_jurisdictionStateOrProvinceName 1L,3L,6L,1L,4L,1L,311L,60L,2L,1L,2L + +#define SN_jurisdictionCountryName "jurisdictionC" +#define LN_jurisdictionCountryName "jurisdictionCountryName" +#define NID_jurisdictionCountryName 957 +#define OBJ_jurisdictionCountryName 1L,3L,6L,1L,4L,1L,311L,60L,2L,1L,3L + +#define SN_id_scrypt "id-scrypt" +#define LN_id_scrypt "scrypt" +#define NID_id_scrypt 973 +#define OBJ_id_scrypt 1L,3L,6L,1L,4L,1L,11591L,4L,11L + +#define SN_tls1_prf "TLS1-PRF" +#define LN_tls1_prf "tls1-prf" +#define NID_tls1_prf 1021 + +#define SN_hkdf "HKDF" +#define LN_hkdf "hkdf" +#define NID_hkdf 1036 + +#define SN_id_pkinit "id-pkinit" +#define NID_id_pkinit 1031 +#define OBJ_id_pkinit 1L,3L,6L,1L,5L,2L,3L + +#define SN_pkInitClientAuth "pkInitClientAuth" +#define LN_pkInitClientAuth "PKINIT Client Auth" +#define NID_pkInitClientAuth 1032 +#define OBJ_pkInitClientAuth OBJ_id_pkinit,4L + +#define SN_pkInitKDC "pkInitKDC" +#define LN_pkInitKDC "Signing KDC Response" +#define NID_pkInitKDC 1033 +#define OBJ_pkInitKDC OBJ_id_pkinit,5L + +#define SN_X25519 "X25519" +#define NID_X25519 1034 +#define OBJ_X25519 1L,3L,101L,110L + +#define SN_X448 "X448" +#define NID_X448 1035 +#define OBJ_X448 1L,3L,101L,111L + +#define SN_ED25519 "ED25519" +#define NID_ED25519 1087 +#define OBJ_ED25519 1L,3L,101L,112L + +#define SN_ED448 "ED448" +#define NID_ED448 1088 +#define OBJ_ED448 1L,3L,101L,113L + +#define SN_kx_rsa "KxRSA" +#define LN_kx_rsa "kx-rsa" +#define NID_kx_rsa 1037 + +#define SN_kx_ecdhe "KxECDHE" +#define LN_kx_ecdhe "kx-ecdhe" +#define NID_kx_ecdhe 1038 + +#define SN_kx_dhe "KxDHE" +#define LN_kx_dhe "kx-dhe" +#define NID_kx_dhe 1039 + +#define SN_kx_ecdhe_psk "KxECDHE-PSK" +#define LN_kx_ecdhe_psk "kx-ecdhe-psk" +#define NID_kx_ecdhe_psk 1040 + +#define SN_kx_dhe_psk "KxDHE-PSK" +#define LN_kx_dhe_psk "kx-dhe-psk" +#define NID_kx_dhe_psk 1041 + +#define SN_kx_rsa_psk "KxRSA_PSK" +#define LN_kx_rsa_psk "kx-rsa-psk" +#define NID_kx_rsa_psk 1042 + +#define SN_kx_psk "KxPSK" +#define LN_kx_psk "kx-psk" +#define NID_kx_psk 1043 + +#define SN_kx_srp "KxSRP" +#define LN_kx_srp "kx-srp" +#define NID_kx_srp 1044 + +#define SN_kx_gost "KxGOST" +#define LN_kx_gost "kx-gost" +#define NID_kx_gost 1045 + +#define SN_kx_any "KxANY" +#define LN_kx_any "kx-any" +#define NID_kx_any 1063 + +#define SN_auth_rsa "AuthRSA" +#define LN_auth_rsa "auth-rsa" +#define NID_auth_rsa 1046 + +#define SN_auth_ecdsa "AuthECDSA" +#define LN_auth_ecdsa "auth-ecdsa" +#define NID_auth_ecdsa 1047 + +#define SN_auth_psk "AuthPSK" +#define LN_auth_psk "auth-psk" +#define NID_auth_psk 1048 + +#define SN_auth_dss "AuthDSS" +#define LN_auth_dss "auth-dss" +#define NID_auth_dss 1049 + +#define SN_auth_gost01 "AuthGOST01" +#define LN_auth_gost01 "auth-gost01" +#define NID_auth_gost01 1050 + +#define SN_auth_gost12 "AuthGOST12" +#define LN_auth_gost12 "auth-gost12" +#define NID_auth_gost12 1051 + +#define SN_auth_srp "AuthSRP" +#define LN_auth_srp "auth-srp" +#define NID_auth_srp 1052 + +#define SN_auth_null "AuthNULL" +#define LN_auth_null "auth-null" +#define NID_auth_null 1053 + +#define SN_auth_any "AuthANY" +#define LN_auth_any "auth-any" +#define NID_auth_any 1064 + +#define SN_poly1305 "Poly1305" +#define LN_poly1305 "poly1305" +#define NID_poly1305 1061 + +#define SN_siphash "SipHash" +#define LN_siphash "siphash" +#define NID_siphash 1062 + +#define SN_ffdhe2048 "ffdhe2048" +#define NID_ffdhe2048 1126 + +#define SN_ffdhe3072 "ffdhe3072" +#define NID_ffdhe3072 1127 + +#define SN_ffdhe4096 "ffdhe4096" +#define NID_ffdhe4096 1128 + +#define SN_ffdhe6144 "ffdhe6144" +#define NID_ffdhe6144 1129 + +#define SN_ffdhe8192 "ffdhe8192" +#define NID_ffdhe8192 1130 + +#define SN_ISO_UA "ISO-UA" +#define NID_ISO_UA 1150 +#define OBJ_ISO_UA OBJ_member_body,804L + +#define SN_ua_pki "ua-pki" +#define NID_ua_pki 1151 +#define OBJ_ua_pki OBJ_ISO_UA,2L,1L,1L,1L + +#define SN_dstu28147 "dstu28147" +#define LN_dstu28147 "DSTU Gost 28147-2009" +#define NID_dstu28147 1152 +#define OBJ_dstu28147 OBJ_ua_pki,1L,1L,1L + +#define SN_dstu28147_ofb "dstu28147-ofb" +#define LN_dstu28147_ofb "DSTU Gost 28147-2009 OFB mode" +#define NID_dstu28147_ofb 1153 +#define OBJ_dstu28147_ofb OBJ_dstu28147,2L + +#define SN_dstu28147_cfb "dstu28147-cfb" +#define LN_dstu28147_cfb "DSTU Gost 28147-2009 CFB mode" +#define NID_dstu28147_cfb 1154 +#define OBJ_dstu28147_cfb OBJ_dstu28147,3L + +#define SN_dstu28147_wrap "dstu28147-wrap" +#define LN_dstu28147_wrap "DSTU Gost 28147-2009 key wrap" +#define NID_dstu28147_wrap 1155 +#define OBJ_dstu28147_wrap OBJ_dstu28147,5L + +#define SN_hmacWithDstu34311 "hmacWithDstu34311" +#define LN_hmacWithDstu34311 "HMAC DSTU Gost 34311-95" +#define NID_hmacWithDstu34311 1156 +#define OBJ_hmacWithDstu34311 OBJ_ua_pki,1L,1L,2L + +#define SN_dstu34311 "dstu34311" +#define LN_dstu34311 "DSTU Gost 34311-95" +#define NID_dstu34311 1157 +#define OBJ_dstu34311 OBJ_ua_pki,1L,2L,1L + +#define SN_dstu4145le "dstu4145le" +#define LN_dstu4145le "DSTU 4145-2002 little endian" +#define NID_dstu4145le 1158 +#define OBJ_dstu4145le OBJ_ua_pki,1L,3L,1L,1L + +#define SN_dstu4145be "dstu4145be" +#define LN_dstu4145be "DSTU 4145-2002 big endian" +#define NID_dstu4145be 1159 +#define OBJ_dstu4145be OBJ_dstu4145le,1L,1L + +#define SN_uacurve0 "uacurve0" +#define LN_uacurve0 "DSTU curve 0" +#define NID_uacurve0 1160 +#define OBJ_uacurve0 OBJ_dstu4145le,2L,0L + +#define SN_uacurve1 "uacurve1" +#define LN_uacurve1 "DSTU curve 1" +#define NID_uacurve1 1161 +#define OBJ_uacurve1 OBJ_dstu4145le,2L,1L + +#define SN_uacurve2 "uacurve2" +#define LN_uacurve2 "DSTU curve 2" +#define NID_uacurve2 1162 +#define OBJ_uacurve2 OBJ_dstu4145le,2L,2L + +#define SN_uacurve3 "uacurve3" +#define LN_uacurve3 "DSTU curve 3" +#define NID_uacurve3 1163 +#define OBJ_uacurve3 OBJ_dstu4145le,2L,3L + +#define SN_uacurve4 "uacurve4" +#define LN_uacurve4 "DSTU curve 4" +#define NID_uacurve4 1164 +#define OBJ_uacurve4 OBJ_dstu4145le,2L,4L + +#define SN_uacurve5 "uacurve5" +#define LN_uacurve5 "DSTU curve 5" +#define NID_uacurve5 1165 +#define OBJ_uacurve5 OBJ_dstu4145le,2L,5L + +#define SN_uacurve6 "uacurve6" +#define LN_uacurve6 "DSTU curve 6" +#define NID_uacurve6 1166 +#define OBJ_uacurve6 OBJ_dstu4145le,2L,6L + +#define SN_uacurve7 "uacurve7" +#define LN_uacurve7 "DSTU curve 7" +#define NID_uacurve7 1167 +#define OBJ_uacurve7 OBJ_dstu4145le,2L,7L + +#define SN_uacurve8 "uacurve8" +#define LN_uacurve8 "DSTU curve 8" +#define NID_uacurve8 1168 +#define OBJ_uacurve8 OBJ_dstu4145le,2L,8L + +#define SN_uacurve9 "uacurve9" +#define LN_uacurve9 "DSTU curve 9" +#define NID_uacurve9 1169 +#define OBJ_uacurve9 OBJ_dstu4145le,2L,9L diff --git a/include/openssl/objects.h b/include/openssl/objects.h new file mode 100644 index 0000000..29004e2 --- /dev/null +++ b/include/openssl/objects.h @@ -0,0 +1,175 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OBJECTS_H +# define HEADER_OBJECTS_H + +# include +# include +# include +# include + +# define OBJ_NAME_TYPE_UNDEF 0x00 +# define OBJ_NAME_TYPE_MD_METH 0x01 +# define OBJ_NAME_TYPE_CIPHER_METH 0x02 +# define OBJ_NAME_TYPE_PKEY_METH 0x03 +# define OBJ_NAME_TYPE_COMP_METH 0x04 +# define OBJ_NAME_TYPE_NUM 0x05 + +# define OBJ_NAME_ALIAS 0x8000 + +# define OBJ_BSEARCH_VALUE_ON_NOMATCH 0x01 +# define OBJ_BSEARCH_FIRST_VALUE_ON_MATCH 0x02 + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct obj_name_st { + int type; + int alias; + const char *name; + const char *data; +} OBJ_NAME; + +# define OBJ_create_and_add_object(a,b,c) OBJ_create(a,b,c) + +int OBJ_NAME_init(void); +int OBJ_NAME_new_index(unsigned long (*hash_func) (const char *), + int (*cmp_func) (const char *, const char *), + void (*free_func) (const char *, int, const char *)); +const char *OBJ_NAME_get(const char *name, int type); +int OBJ_NAME_add(const char *name, int type, const char *data); +int OBJ_NAME_remove(const char *name, int type); +void OBJ_NAME_cleanup(int type); /* -1 for everything */ +void OBJ_NAME_do_all(int type, void (*fn) (const OBJ_NAME *, void *arg), + void *arg); +void OBJ_NAME_do_all_sorted(int type, + void (*fn) (const OBJ_NAME *, void *arg), + void *arg); + +ASN1_OBJECT *OBJ_dup(const ASN1_OBJECT *o); +ASN1_OBJECT *OBJ_nid2obj(int n); +const char *OBJ_nid2ln(int n); +const char *OBJ_nid2sn(int n); +int OBJ_obj2nid(const ASN1_OBJECT *o); +ASN1_OBJECT *OBJ_txt2obj(const char *s, int no_name); +int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name); +int OBJ_txt2nid(const char *s); +int OBJ_ln2nid(const char *s); +int OBJ_sn2nid(const char *s); +int OBJ_cmp(const ASN1_OBJECT *a, const ASN1_OBJECT *b); +const void *OBJ_bsearch_(const void *key, const void *base, int num, int size, + int (*cmp) (const void *, const void *)); +const void *OBJ_bsearch_ex_(const void *key, const void *base, int num, + int size, + int (*cmp) (const void *, const void *), + int flags); + +# define _DECLARE_OBJ_BSEARCH_CMP_FN(scope, type1, type2, nm) \ + static int nm##_cmp_BSEARCH_CMP_FN(const void *, const void *); \ + static int nm##_cmp(type1 const *, type2 const *); \ + scope type2 * OBJ_bsearch_##nm(type1 *key, type2 const *base, int num) + +# define DECLARE_OBJ_BSEARCH_CMP_FN(type1, type2, cmp) \ + _DECLARE_OBJ_BSEARCH_CMP_FN(static, type1, type2, cmp) +# define DECLARE_OBJ_BSEARCH_GLOBAL_CMP_FN(type1, type2, nm) \ + type2 * OBJ_bsearch_##nm(type1 *key, type2 const *base, int num) + +/*- + * Unsolved problem: if a type is actually a pointer type, like + * nid_triple is, then its impossible to get a const where you need + * it. Consider: + * + * typedef int nid_triple[3]; + * const void *a_; + * const nid_triple const *a = a_; + * + * The assignment discards a const because what you really want is: + * + * const int const * const *a = a_; + * + * But if you do that, you lose the fact that a is an array of 3 ints, + * which breaks comparison functions. + * + * Thus we end up having to cast, sadly, or unpack the + * declarations. Or, as I finally did in this case, declare nid_triple + * to be a struct, which it should have been in the first place. + * + * Ben, August 2008. + * + * Also, strictly speaking not all types need be const, but handling + * the non-constness means a lot of complication, and in practice + * comparison routines do always not touch their arguments. + */ + +# define IMPLEMENT_OBJ_BSEARCH_CMP_FN(type1, type2, nm) \ + static int nm##_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_) \ + { \ + type1 const *a = a_; \ + type2 const *b = b_; \ + return nm##_cmp(a,b); \ + } \ + static type2 *OBJ_bsearch_##nm(type1 *key, type2 const *base, int num) \ + { \ + return (type2 *)OBJ_bsearch_(key, base, num, sizeof(type2), \ + nm##_cmp_BSEARCH_CMP_FN); \ + } \ + extern void dummy_prototype(void) + +# define IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(type1, type2, nm) \ + static int nm##_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_) \ + { \ + type1 const *a = a_; \ + type2 const *b = b_; \ + return nm##_cmp(a,b); \ + } \ + type2 *OBJ_bsearch_##nm(type1 *key, type2 const *base, int num) \ + { \ + return (type2 *)OBJ_bsearch_(key, base, num, sizeof(type2), \ + nm##_cmp_BSEARCH_CMP_FN); \ + } \ + extern void dummy_prototype(void) + +# define OBJ_bsearch(type1,key,type2,base,num,cmp) \ + ((type2 *)OBJ_bsearch_(CHECKED_PTR_OF(type1,key),CHECKED_PTR_OF(type2,base), \ + num,sizeof(type2), \ + ((void)CHECKED_PTR_OF(type1,cmp##_type_1), \ + (void)CHECKED_PTR_OF(type2,cmp##_type_2), \ + cmp##_BSEARCH_CMP_FN))) + +# define OBJ_bsearch_ex(type1,key,type2,base,num,cmp,flags) \ + ((type2 *)OBJ_bsearch_ex_(CHECKED_PTR_OF(type1,key),CHECKED_PTR_OF(type2,base), \ + num,sizeof(type2), \ + ((void)CHECKED_PTR_OF(type1,cmp##_type_1), \ + (void)type_2=CHECKED_PTR_OF(type2,cmp##_type_2), \ + cmp##_BSEARCH_CMP_FN)),flags) + +int OBJ_new_nid(int num); +int OBJ_add_object(const ASN1_OBJECT *obj); +int OBJ_create(const char *oid, const char *sn, const char *ln); +#if OPENSSL_API_COMPAT < 0x10100000L +# define OBJ_cleanup() while(0) continue +#endif +int OBJ_create_objects(BIO *in); + +size_t OBJ_length(const ASN1_OBJECT *obj); +const unsigned char *OBJ_get0_data(const ASN1_OBJECT *obj); + +int OBJ_find_sigid_algs(int signid, int *pdig_nid, int *ppkey_nid); +int OBJ_find_sigid_by_algs(int *psignid, int dig_nid, int pkey_nid); +int OBJ_add_sigid(int signid, int dig_id, int pkey_id); +void OBJ_sigid_free(void); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/objectserr.h b/include/openssl/objectserr.h new file mode 100644 index 0000000..02308df --- /dev/null +++ b/include/openssl/objectserr.h @@ -0,0 +1,38 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OBJERR_H +# define HEADER_OBJERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_OBJ_strings(void); + +/* + * OBJ function codes. + */ +# define OBJ_F_OBJ_ADD_OBJECT 105 +# define OBJ_F_OBJ_ADD_SIGID 107 +# define OBJ_F_OBJ_CREATE 100 +# define OBJ_F_OBJ_DUP 101 +# define OBJ_F_OBJ_NAME_NEW_INDEX 106 +# define OBJ_F_OBJ_NID2LN 102 +# define OBJ_F_OBJ_NID2OBJ 103 +# define OBJ_F_OBJ_NID2SN 104 +# define OBJ_F_OBJ_TXT2OBJ 108 + +/* + * OBJ reason codes. + */ +# define OBJ_R_OID_EXISTS 102 +# define OBJ_R_UNKNOWN_NID 101 + +#endif diff --git a/include/openssl/ocsp.h b/include/openssl/ocsp.h new file mode 100644 index 0000000..5a1d75e --- /dev/null +++ b/include/openssl/ocsp.h @@ -0,0 +1,355 @@ +/* + * Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OCSP_H +# define HEADER_OCSP_H + +#include + +/* + * These definitions are outside the OPENSSL_NO_OCSP guard because although for + * historical reasons they have OCSP_* names, they can actually be used + * independently of OCSP. E.g. see RFC5280 + */ +/*- + * CRLReason ::= ENUMERATED { + * unspecified (0), + * keyCompromise (1), + * cACompromise (2), + * affiliationChanged (3), + * superseded (4), + * cessationOfOperation (5), + * certificateHold (6), + * removeFromCRL (8) } + */ +# define OCSP_REVOKED_STATUS_NOSTATUS -1 +# define OCSP_REVOKED_STATUS_UNSPECIFIED 0 +# define OCSP_REVOKED_STATUS_KEYCOMPROMISE 1 +# define OCSP_REVOKED_STATUS_CACOMPROMISE 2 +# define OCSP_REVOKED_STATUS_AFFILIATIONCHANGED 3 +# define OCSP_REVOKED_STATUS_SUPERSEDED 4 +# define OCSP_REVOKED_STATUS_CESSATIONOFOPERATION 5 +# define OCSP_REVOKED_STATUS_CERTIFICATEHOLD 6 +# define OCSP_REVOKED_STATUS_REMOVEFROMCRL 8 + + +# ifndef OPENSSL_NO_OCSP + +# include +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Various flags and values */ + +# define OCSP_DEFAULT_NONCE_LENGTH 16 + +# define OCSP_NOCERTS 0x1 +# define OCSP_NOINTERN 0x2 +# define OCSP_NOSIGS 0x4 +# define OCSP_NOCHAIN 0x8 +# define OCSP_NOVERIFY 0x10 +# define OCSP_NOEXPLICIT 0x20 +# define OCSP_NOCASIGN 0x40 +# define OCSP_NODELEGATED 0x80 +# define OCSP_NOCHECKS 0x100 +# define OCSP_TRUSTOTHER 0x200 +# define OCSP_RESPID_KEY 0x400 +# define OCSP_NOTIME 0x800 + +typedef struct ocsp_cert_id_st OCSP_CERTID; + +DEFINE_STACK_OF(OCSP_CERTID) + +typedef struct ocsp_one_request_st OCSP_ONEREQ; + +DEFINE_STACK_OF(OCSP_ONEREQ) + +typedef struct ocsp_req_info_st OCSP_REQINFO; +typedef struct ocsp_signature_st OCSP_SIGNATURE; +typedef struct ocsp_request_st OCSP_REQUEST; + +# define OCSP_RESPONSE_STATUS_SUCCESSFUL 0 +# define OCSP_RESPONSE_STATUS_MALFORMEDREQUEST 1 +# define OCSP_RESPONSE_STATUS_INTERNALERROR 2 +# define OCSP_RESPONSE_STATUS_TRYLATER 3 +# define OCSP_RESPONSE_STATUS_SIGREQUIRED 5 +# define OCSP_RESPONSE_STATUS_UNAUTHORIZED 6 + +typedef struct ocsp_resp_bytes_st OCSP_RESPBYTES; + +# define V_OCSP_RESPID_NAME 0 +# define V_OCSP_RESPID_KEY 1 + +DEFINE_STACK_OF(OCSP_RESPID) +DECLARE_ASN1_FUNCTIONS(OCSP_RESPID) + +typedef struct ocsp_revoked_info_st OCSP_REVOKEDINFO; + +# define V_OCSP_CERTSTATUS_GOOD 0 +# define V_OCSP_CERTSTATUS_REVOKED 1 +# define V_OCSP_CERTSTATUS_UNKNOWN 2 + +typedef struct ocsp_cert_status_st OCSP_CERTSTATUS; +typedef struct ocsp_single_response_st OCSP_SINGLERESP; + +DEFINE_STACK_OF(OCSP_SINGLERESP) + +typedef struct ocsp_response_data_st OCSP_RESPDATA; + +typedef struct ocsp_basic_response_st OCSP_BASICRESP; + +typedef struct ocsp_crl_id_st OCSP_CRLID; +typedef struct ocsp_service_locator_st OCSP_SERVICELOC; + +# define PEM_STRING_OCSP_REQUEST "OCSP REQUEST" +# define PEM_STRING_OCSP_RESPONSE "OCSP RESPONSE" + +# define d2i_OCSP_REQUEST_bio(bp,p) ASN1_d2i_bio_of(OCSP_REQUEST,OCSP_REQUEST_new,d2i_OCSP_REQUEST,bp,p) + +# define d2i_OCSP_RESPONSE_bio(bp,p) ASN1_d2i_bio_of(OCSP_RESPONSE,OCSP_RESPONSE_new,d2i_OCSP_RESPONSE,bp,p) + +# define PEM_read_bio_OCSP_REQUEST(bp,x,cb) (OCSP_REQUEST *)PEM_ASN1_read_bio( \ + (char *(*)())d2i_OCSP_REQUEST,PEM_STRING_OCSP_REQUEST, \ + bp,(char **)(x),cb,NULL) + +# define PEM_read_bio_OCSP_RESPONSE(bp,x,cb)(OCSP_RESPONSE *)PEM_ASN1_read_bio(\ + (char *(*)())d2i_OCSP_RESPONSE,PEM_STRING_OCSP_RESPONSE, \ + bp,(char **)(x),cb,NULL) + +# define PEM_write_bio_OCSP_REQUEST(bp,o) \ + PEM_ASN1_write_bio((int (*)())i2d_OCSP_REQUEST,PEM_STRING_OCSP_REQUEST,\ + bp,(char *)(o), NULL,NULL,0,NULL,NULL) + +# define PEM_write_bio_OCSP_RESPONSE(bp,o) \ + PEM_ASN1_write_bio((int (*)())i2d_OCSP_RESPONSE,PEM_STRING_OCSP_RESPONSE,\ + bp,(char *)(o), NULL,NULL,0,NULL,NULL) + +# define i2d_OCSP_RESPONSE_bio(bp,o) ASN1_i2d_bio_of(OCSP_RESPONSE,i2d_OCSP_RESPONSE,bp,o) + +# define i2d_OCSP_REQUEST_bio(bp,o) ASN1_i2d_bio_of(OCSP_REQUEST,i2d_OCSP_REQUEST,bp,o) + +# define ASN1_BIT_STRING_digest(data,type,md,len) \ + ASN1_item_digest(ASN1_ITEM_rptr(ASN1_BIT_STRING),type,data,md,len) + +# define OCSP_CERTSTATUS_dup(cs)\ + (OCSP_CERTSTATUS*)ASN1_dup((int(*)())i2d_OCSP_CERTSTATUS,\ + (char *(*)())d2i_OCSP_CERTSTATUS,(char *)(cs)) + +OCSP_CERTID *OCSP_CERTID_dup(OCSP_CERTID *id); + +OCSP_RESPONSE *OCSP_sendreq_bio(BIO *b, const char *path, OCSP_REQUEST *req); +OCSP_REQ_CTX *OCSP_sendreq_new(BIO *io, const char *path, OCSP_REQUEST *req, + int maxline); +int OCSP_REQ_CTX_nbio(OCSP_REQ_CTX *rctx); +int OCSP_sendreq_nbio(OCSP_RESPONSE **presp, OCSP_REQ_CTX *rctx); +OCSP_REQ_CTX *OCSP_REQ_CTX_new(BIO *io, int maxline); +void OCSP_REQ_CTX_free(OCSP_REQ_CTX *rctx); +void OCSP_set_max_response_length(OCSP_REQ_CTX *rctx, unsigned long len); +int OCSP_REQ_CTX_i2d(OCSP_REQ_CTX *rctx, const ASN1_ITEM *it, + ASN1_VALUE *val); +int OCSP_REQ_CTX_nbio_d2i(OCSP_REQ_CTX *rctx, ASN1_VALUE **pval, + const ASN1_ITEM *it); +BIO *OCSP_REQ_CTX_get0_mem_bio(OCSP_REQ_CTX *rctx); +int OCSP_REQ_CTX_i2d(OCSP_REQ_CTX *rctx, const ASN1_ITEM *it, + ASN1_VALUE *val); +int OCSP_REQ_CTX_http(OCSP_REQ_CTX *rctx, const char *op, const char *path); +int OCSP_REQ_CTX_set1_req(OCSP_REQ_CTX *rctx, OCSP_REQUEST *req); +int OCSP_REQ_CTX_add1_header(OCSP_REQ_CTX *rctx, + const char *name, const char *value); + +OCSP_CERTID *OCSP_cert_to_id(const EVP_MD *dgst, const X509 *subject, + const X509 *issuer); + +OCSP_CERTID *OCSP_cert_id_new(const EVP_MD *dgst, + const X509_NAME *issuerName, + const ASN1_BIT_STRING *issuerKey, + const ASN1_INTEGER *serialNumber); + +OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid); + +int OCSP_request_add1_nonce(OCSP_REQUEST *req, unsigned char *val, int len); +int OCSP_basic_add1_nonce(OCSP_BASICRESP *resp, unsigned char *val, int len); +int OCSP_check_nonce(OCSP_REQUEST *req, OCSP_BASICRESP *bs); +int OCSP_copy_nonce(OCSP_BASICRESP *resp, OCSP_REQUEST *req); + +int OCSP_request_set1_name(OCSP_REQUEST *req, X509_NAME *nm); +int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert); + +int OCSP_request_sign(OCSP_REQUEST *req, + X509 *signer, + EVP_PKEY *key, + const EVP_MD *dgst, + STACK_OF(X509) *certs, unsigned long flags); + +int OCSP_response_status(OCSP_RESPONSE *resp); +OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp); + +const ASN1_OCTET_STRING *OCSP_resp_get0_signature(const OCSP_BASICRESP *bs); +const X509_ALGOR *OCSP_resp_get0_tbs_sigalg(const OCSP_BASICRESP *bs); +const OCSP_RESPDATA *OCSP_resp_get0_respdata(const OCSP_BASICRESP *bs); +int OCSP_resp_get0_signer(OCSP_BASICRESP *bs, X509 **signer, + STACK_OF(X509) *extra_certs); + +int OCSP_resp_count(OCSP_BASICRESP *bs); +OCSP_SINGLERESP *OCSP_resp_get0(OCSP_BASICRESP *bs, int idx); +const ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(const OCSP_BASICRESP* bs); +const STACK_OF(X509) *OCSP_resp_get0_certs(const OCSP_BASICRESP *bs); +int OCSP_resp_get0_id(const OCSP_BASICRESP *bs, + const ASN1_OCTET_STRING **pid, + const X509_NAME **pname); +int OCSP_resp_get1_id(const OCSP_BASICRESP *bs, + ASN1_OCTET_STRING **pid, + X509_NAME **pname); + +int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last); +int OCSP_single_get0_status(OCSP_SINGLERESP *single, int *reason, + ASN1_GENERALIZEDTIME **revtime, + ASN1_GENERALIZEDTIME **thisupd, + ASN1_GENERALIZEDTIME **nextupd); +int OCSP_resp_find_status(OCSP_BASICRESP *bs, OCSP_CERTID *id, int *status, + int *reason, + ASN1_GENERALIZEDTIME **revtime, + ASN1_GENERALIZEDTIME **thisupd, + ASN1_GENERALIZEDTIME **nextupd); +int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd, + ASN1_GENERALIZEDTIME *nextupd, long sec, long maxsec); + +int OCSP_request_verify(OCSP_REQUEST *req, STACK_OF(X509) *certs, + X509_STORE *store, unsigned long flags); + +int OCSP_parse_url(const char *url, char **phost, char **pport, char **ppath, + int *pssl); + +int OCSP_id_issuer_cmp(OCSP_CERTID *a, OCSP_CERTID *b); +int OCSP_id_cmp(OCSP_CERTID *a, OCSP_CERTID *b); + +int OCSP_request_onereq_count(OCSP_REQUEST *req); +OCSP_ONEREQ *OCSP_request_onereq_get0(OCSP_REQUEST *req, int i); +OCSP_CERTID *OCSP_onereq_get0_id(OCSP_ONEREQ *one); +int OCSP_id_get0_info(ASN1_OCTET_STRING **piNameHash, ASN1_OBJECT **pmd, + ASN1_OCTET_STRING **pikeyHash, + ASN1_INTEGER **pserial, OCSP_CERTID *cid); +int OCSP_request_is_signed(OCSP_REQUEST *req); +OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs); +OCSP_SINGLERESP *OCSP_basic_add1_status(OCSP_BASICRESP *rsp, + OCSP_CERTID *cid, + int status, int reason, + ASN1_TIME *revtime, + ASN1_TIME *thisupd, + ASN1_TIME *nextupd); +int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert); +int OCSP_basic_sign(OCSP_BASICRESP *brsp, + X509 *signer, EVP_PKEY *key, const EVP_MD *dgst, + STACK_OF(X509) *certs, unsigned long flags); +int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp, + X509 *signer, EVP_MD_CTX *ctx, + STACK_OF(X509) *certs, unsigned long flags); +int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert); +int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert); +int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert); + +X509_EXTENSION *OCSP_crlID_new(const char *url, long *n, char *tim); + +X509_EXTENSION *OCSP_accept_responses_new(char **oids); + +X509_EXTENSION *OCSP_archive_cutoff_new(char *tim); + +X509_EXTENSION *OCSP_url_svcloc_new(X509_NAME *issuer, const char **urls); + +int OCSP_REQUEST_get_ext_count(OCSP_REQUEST *x); +int OCSP_REQUEST_get_ext_by_NID(OCSP_REQUEST *x, int nid, int lastpos); +int OCSP_REQUEST_get_ext_by_OBJ(OCSP_REQUEST *x, const ASN1_OBJECT *obj, + int lastpos); +int OCSP_REQUEST_get_ext_by_critical(OCSP_REQUEST *x, int crit, int lastpos); +X509_EXTENSION *OCSP_REQUEST_get_ext(OCSP_REQUEST *x, int loc); +X509_EXTENSION *OCSP_REQUEST_delete_ext(OCSP_REQUEST *x, int loc); +void *OCSP_REQUEST_get1_ext_d2i(OCSP_REQUEST *x, int nid, int *crit, + int *idx); +int OCSP_REQUEST_add1_ext_i2d(OCSP_REQUEST *x, int nid, void *value, int crit, + unsigned long flags); +int OCSP_REQUEST_add_ext(OCSP_REQUEST *x, X509_EXTENSION *ex, int loc); + +int OCSP_ONEREQ_get_ext_count(OCSP_ONEREQ *x); +int OCSP_ONEREQ_get_ext_by_NID(OCSP_ONEREQ *x, int nid, int lastpos); +int OCSP_ONEREQ_get_ext_by_OBJ(OCSP_ONEREQ *x, const ASN1_OBJECT *obj, int lastpos); +int OCSP_ONEREQ_get_ext_by_critical(OCSP_ONEREQ *x, int crit, int lastpos); +X509_EXTENSION *OCSP_ONEREQ_get_ext(OCSP_ONEREQ *x, int loc); +X509_EXTENSION *OCSP_ONEREQ_delete_ext(OCSP_ONEREQ *x, int loc); +void *OCSP_ONEREQ_get1_ext_d2i(OCSP_ONEREQ *x, int nid, int *crit, int *idx); +int OCSP_ONEREQ_add1_ext_i2d(OCSP_ONEREQ *x, int nid, void *value, int crit, + unsigned long flags); +int OCSP_ONEREQ_add_ext(OCSP_ONEREQ *x, X509_EXTENSION *ex, int loc); + +int OCSP_BASICRESP_get_ext_count(OCSP_BASICRESP *x); +int OCSP_BASICRESP_get_ext_by_NID(OCSP_BASICRESP *x, int nid, int lastpos); +int OCSP_BASICRESP_get_ext_by_OBJ(OCSP_BASICRESP *x, const ASN1_OBJECT *obj, + int lastpos); +int OCSP_BASICRESP_get_ext_by_critical(OCSP_BASICRESP *x, int crit, + int lastpos); +X509_EXTENSION *OCSP_BASICRESP_get_ext(OCSP_BASICRESP *x, int loc); +X509_EXTENSION *OCSP_BASICRESP_delete_ext(OCSP_BASICRESP *x, int loc); +void *OCSP_BASICRESP_get1_ext_d2i(OCSP_BASICRESP *x, int nid, int *crit, + int *idx); +int OCSP_BASICRESP_add1_ext_i2d(OCSP_BASICRESP *x, int nid, void *value, + int crit, unsigned long flags); +int OCSP_BASICRESP_add_ext(OCSP_BASICRESP *x, X509_EXTENSION *ex, int loc); + +int OCSP_SINGLERESP_get_ext_count(OCSP_SINGLERESP *x); +int OCSP_SINGLERESP_get_ext_by_NID(OCSP_SINGLERESP *x, int nid, int lastpos); +int OCSP_SINGLERESP_get_ext_by_OBJ(OCSP_SINGLERESP *x, const ASN1_OBJECT *obj, + int lastpos); +int OCSP_SINGLERESP_get_ext_by_critical(OCSP_SINGLERESP *x, int crit, + int lastpos); +X509_EXTENSION *OCSP_SINGLERESP_get_ext(OCSP_SINGLERESP *x, int loc); +X509_EXTENSION *OCSP_SINGLERESP_delete_ext(OCSP_SINGLERESP *x, int loc); +void *OCSP_SINGLERESP_get1_ext_d2i(OCSP_SINGLERESP *x, int nid, int *crit, + int *idx); +int OCSP_SINGLERESP_add1_ext_i2d(OCSP_SINGLERESP *x, int nid, void *value, + int crit, unsigned long flags); +int OCSP_SINGLERESP_add_ext(OCSP_SINGLERESP *x, X509_EXTENSION *ex, int loc); +const OCSP_CERTID *OCSP_SINGLERESP_get0_id(const OCSP_SINGLERESP *x); + +DECLARE_ASN1_FUNCTIONS(OCSP_SINGLERESP) +DECLARE_ASN1_FUNCTIONS(OCSP_CERTSTATUS) +DECLARE_ASN1_FUNCTIONS(OCSP_REVOKEDINFO) +DECLARE_ASN1_FUNCTIONS(OCSP_BASICRESP) +DECLARE_ASN1_FUNCTIONS(OCSP_RESPDATA) +DECLARE_ASN1_FUNCTIONS(OCSP_RESPID) +DECLARE_ASN1_FUNCTIONS(OCSP_RESPONSE) +DECLARE_ASN1_FUNCTIONS(OCSP_RESPBYTES) +DECLARE_ASN1_FUNCTIONS(OCSP_ONEREQ) +DECLARE_ASN1_FUNCTIONS(OCSP_CERTID) +DECLARE_ASN1_FUNCTIONS(OCSP_REQUEST) +DECLARE_ASN1_FUNCTIONS(OCSP_SIGNATURE) +DECLARE_ASN1_FUNCTIONS(OCSP_REQINFO) +DECLARE_ASN1_FUNCTIONS(OCSP_CRLID) +DECLARE_ASN1_FUNCTIONS(OCSP_SERVICELOC) + +const char *OCSP_response_status_str(long s); +const char *OCSP_cert_status_str(long s); +const char *OCSP_crl_reason_str(long s); + +int OCSP_REQUEST_print(BIO *bp, OCSP_REQUEST *a, unsigned long flags); +int OCSP_RESPONSE_print(BIO *bp, OCSP_RESPONSE *o, unsigned long flags); + +int OCSP_basic_verify(OCSP_BASICRESP *bs, STACK_OF(X509) *certs, + X509_STORE *st, unsigned long flags); + + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/ocsperr.h b/include/openssl/ocsperr.h new file mode 100644 index 0000000..d081fd5 --- /dev/null +++ b/include/openssl/ocsperr.h @@ -0,0 +1,74 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OCSPERR_H +# define HEADER_OCSPERR_H + +# include + +# ifndef OPENSSL_NO_OCSP + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_OCSP_strings(void); + +/* + * OCSP function codes. + */ +# define OCSP_F_D2I_OCSP_NONCE 102 +# define OCSP_F_OCSP_BASIC_ADD1_STATUS 103 +# define OCSP_F_OCSP_BASIC_SIGN 104 +# define OCSP_F_OCSP_BASIC_SIGN_CTX 119 +# define OCSP_F_OCSP_BASIC_VERIFY 105 +# define OCSP_F_OCSP_CERT_ID_NEW 101 +# define OCSP_F_OCSP_CHECK_DELEGATED 106 +# define OCSP_F_OCSP_CHECK_IDS 107 +# define OCSP_F_OCSP_CHECK_ISSUER 108 +# define OCSP_F_OCSP_CHECK_VALIDITY 115 +# define OCSP_F_OCSP_MATCH_ISSUERID 109 +# define OCSP_F_OCSP_PARSE_URL 114 +# define OCSP_F_OCSP_REQUEST_SIGN 110 +# define OCSP_F_OCSP_REQUEST_VERIFY 116 +# define OCSP_F_OCSP_RESPONSE_GET1_BASIC 111 +# define OCSP_F_PARSE_HTTP_LINE1 118 + +/* + * OCSP reason codes. + */ +# define OCSP_R_CERTIFICATE_VERIFY_ERROR 101 +# define OCSP_R_DIGEST_ERR 102 +# define OCSP_R_ERROR_IN_NEXTUPDATE_FIELD 122 +# define OCSP_R_ERROR_IN_THISUPDATE_FIELD 123 +# define OCSP_R_ERROR_PARSING_URL 121 +# define OCSP_R_MISSING_OCSPSIGNING_USAGE 103 +# define OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE 124 +# define OCSP_R_NOT_BASIC_RESPONSE 104 +# define OCSP_R_NO_CERTIFICATES_IN_CHAIN 105 +# define OCSP_R_NO_RESPONSE_DATA 108 +# define OCSP_R_NO_REVOKED_TIME 109 +# define OCSP_R_NO_SIGNER_KEY 130 +# define OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 110 +# define OCSP_R_REQUEST_NOT_SIGNED 128 +# define OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA 111 +# define OCSP_R_ROOT_CA_NOT_TRUSTED 112 +# define OCSP_R_SERVER_RESPONSE_ERROR 114 +# define OCSP_R_SERVER_RESPONSE_PARSE_ERROR 115 +# define OCSP_R_SIGNATURE_FAILURE 117 +# define OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND 118 +# define OCSP_R_STATUS_EXPIRED 125 +# define OCSP_R_STATUS_NOT_YET_VALID 126 +# define OCSP_R_STATUS_TOO_OLD 127 +# define OCSP_R_UNKNOWN_MESSAGE_DIGEST 119 +# define OCSP_R_UNKNOWN_NID 120 +# define OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE 129 + +# endif +#endif diff --git a/include/openssl/opensslconf.h b/include/openssl/opensslconf.h new file mode 100644 index 0000000..9fccb14 --- /dev/null +++ b/include/openssl/opensslconf.h @@ -0,0 +1,198 @@ +/* + * WARNING: do not edit! + * Generated by Makefile from include/openssl/opensslconf.h.in + * + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef OPENSSL_ALGORITHM_DEFINES +# error OPENSSL_ALGORITHM_DEFINES no longer supported +#endif + +/* + * OpenSSL was configured with the following options: + */ + +#ifndef OPENSSL_SYS_MINGW64 +# define OPENSSL_SYS_MINGW64 1 +#endif +#ifndef OPENSSL_NO_MD2 +# define OPENSSL_NO_MD2 +#endif +#ifndef OPENSSL_NO_RC5 +# define OPENSSL_NO_RC5 +#endif +#ifndef OPENSSL_THREADS +# define OPENSSL_THREADS +#endif +#ifndef OPENSSL_RAND_SEED_OS +# define OPENSSL_RAND_SEED_OS +#endif +#ifndef OPENSSL_NO_ASAN +# define OPENSSL_NO_ASAN +#endif +#ifndef OPENSSL_NO_CRYPTO_MDEBUG +# define OPENSSL_NO_CRYPTO_MDEBUG +#endif +#ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE +# define OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE +#endif +#ifndef OPENSSL_NO_DEVCRYPTOENG +# define OPENSSL_NO_DEVCRYPTOENG +#endif +#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 +# define OPENSSL_NO_EC_NISTP_64_GCC_128 +#endif +#ifndef OPENSSL_NO_EGD +# define OPENSSL_NO_EGD +#endif +#ifndef OPENSSL_NO_EXTERNAL_TESTS +# define OPENSSL_NO_EXTERNAL_TESTS +#endif +#ifndef OPENSSL_NO_FUZZ_AFL +# define OPENSSL_NO_FUZZ_AFL +#endif +#ifndef OPENSSL_NO_FUZZ_LIBFUZZER +# define OPENSSL_NO_FUZZ_LIBFUZZER +#endif +#ifndef OPENSSL_NO_HEARTBEATS +# define OPENSSL_NO_HEARTBEATS +#endif +#ifndef OPENSSL_NO_MSAN +# define OPENSSL_NO_MSAN +#endif +#ifndef OPENSSL_NO_SCTP +# define OPENSSL_NO_SCTP +#endif +#ifndef OPENSSL_NO_SSL_TRACE +# define OPENSSL_NO_SSL_TRACE +#endif +#ifndef OPENSSL_NO_SSL3 +# define OPENSSL_NO_SSL3 +#endif +#ifndef OPENSSL_NO_SSL3_METHOD +# define OPENSSL_NO_SSL3_METHOD +#endif +#ifndef OPENSSL_NO_UBSAN +# define OPENSSL_NO_UBSAN +#endif +#ifndef OPENSSL_NO_UNIT_TEST +# define OPENSSL_NO_UNIT_TEST +#endif +#ifndef OPENSSL_NO_WEAK_SSL_CIPHERS +# define OPENSSL_NO_WEAK_SSL_CIPHERS +#endif +#ifndef OPENSSL_NO_DYNAMIC_ENGINE +# define OPENSSL_NO_DYNAMIC_ENGINE +#endif +#ifndef OPENSSL_NO_AFALGENG +# define OPENSSL_NO_AFALGENG +#endif + + +/* + * Sometimes OPENSSSL_NO_xxx ends up with an empty file and some compilers + * don't like that. This will hopefully silence them. + */ +#define NON_EMPTY_TRANSLATION_UNIT static void *dummy = &dummy; + +/* + * Applications should use -DOPENSSL_API_COMPAT= to suppress the + * declarations of functions deprecated in or before . Otherwise, they + * still won't see them if the library has been built to disable deprecated + * functions. + */ +#ifndef DECLARE_DEPRECATED +# define DECLARE_DEPRECATED(f) f; +# ifdef __GNUC__ +# if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 0) +# undef DECLARE_DEPRECATED +# define DECLARE_DEPRECATED(f) f __attribute__ ((deprecated)); +# endif +# endif +#endif + +#ifndef OPENSSL_FILE +# ifdef OPENSSL_NO_FILENAMES +# define OPENSSL_FILE "" +# define OPENSSL_LINE 0 +# else +# define OPENSSL_FILE __FILE__ +# define OPENSSL_LINE __LINE__ +# endif +#endif + +#ifndef OPENSSL_MIN_API +# define OPENSSL_MIN_API 0 +#endif + +#if !defined(OPENSSL_API_COMPAT) || OPENSSL_API_COMPAT < OPENSSL_MIN_API +# undef OPENSSL_API_COMPAT +# define OPENSSL_API_COMPAT OPENSSL_MIN_API +#endif + +/* + * Do not deprecate things to be deprecated in version 1.2.0 before the + * OpenSSL version number matches. + */ +#if OPENSSL_VERSION_NUMBER < 0x10200000L +# define DEPRECATEDIN_1_2_0(f) f; +#elif OPENSSL_API_COMPAT < 0x10200000L +# define DEPRECATEDIN_1_2_0(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_1_2_0(f) +#endif + +#if OPENSSL_API_COMPAT < 0x10100000L +# define DEPRECATEDIN_1_1_0(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_1_1_0(f) +#endif + +#if OPENSSL_API_COMPAT < 0x10000000L +# define DEPRECATEDIN_1_0_0(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_1_0_0(f) +#endif + +#if OPENSSL_API_COMPAT < 0x00908000L +# define DEPRECATEDIN_0_9_8(f) DECLARE_DEPRECATED(f) +#else +# define DEPRECATEDIN_0_9_8(f) +#endif + +/* Generate 80386 code? */ +#undef I386_ONLY + +#undef OPENSSL_UNISTD +#define OPENSSL_UNISTD + +#define OPENSSL_EXPORT_VAR_AS_FUNCTION + +/* + * The following are cipher-specific, but are part of the public API. + */ +#if !defined(OPENSSL_SYS_UEFI) +# undef BN_LLONG +/* Only one for the following should be defined */ +# undef SIXTY_FOUR_BIT_LONG +# define SIXTY_FOUR_BIT +# undef THIRTY_TWO_BIT +#endif + +#define RC4_INT unsigned int + +#ifdef __cplusplus +} +#endif diff --git a/include/openssl/opensslv.h b/include/openssl/opensslv.h new file mode 100644 index 0000000..9e66fc1 --- /dev/null +++ b/include/openssl/opensslv.h @@ -0,0 +1,101 @@ +/* + * Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OPENSSLV_H +# define HEADER_OPENSSLV_H + +#ifdef __cplusplus +extern "C" { +#endif + +/*- + * Numeric release version identifier: + * MNNFFPPS: major minor fix patch status + * The status nibble has one of the values 0 for development, 1 to e for betas + * 1 to 14, and f for release. The patch level is exactly that. + * For example: + * 0.9.3-dev 0x00903000 + * 0.9.3-beta1 0x00903001 + * 0.9.3-beta2-dev 0x00903002 + * 0.9.3-beta2 0x00903002 (same as ...beta2-dev) + * 0.9.3 0x0090300f + * 0.9.3a 0x0090301f + * 0.9.4 0x0090400f + * 1.2.3z 0x102031af + * + * For continuity reasons (because 0.9.5 is already out, and is coded + * 0x00905100), between 0.9.5 and 0.9.6 the coding of the patch level + * part is slightly different, by setting the highest bit. This means + * that 0.9.5a looks like this: 0x0090581f. At 0.9.6, we can start + * with 0x0090600S... + * + * (Prior to 0.9.3-dev a different scheme was used: 0.9.2b is 0x0922.) + * (Prior to 0.9.5a beta1, a different scheme was used: MMNNFFRBB for + * major minor fix final patch/beta) + */ +# define OPENSSL_VERSION_NUMBER 0x1010100fL +# define OPENSSL_VERSION_TEXT "OpenSSL 1.1.1 11 Sep 2018" + +/*- + * The macros below are to be used for shared library (.so, .dll, ...) + * versioning. That kind of versioning works a bit differently between + * operating systems. The most usual scheme is to set a major and a minor + * number, and have the runtime loader check that the major number is equal + * to what it was at application link time, while the minor number has to + * be greater or equal to what it was at application link time. With this + * scheme, the version number is usually part of the file name, like this: + * + * libcrypto.so.0.9 + * + * Some unixen also make a softlink with the major version number only: + * + * libcrypto.so.0 + * + * On Tru64 and IRIX 6.x it works a little bit differently. There, the + * shared library version is stored in the file, and is actually a series + * of versions, separated by colons. The rightmost version present in the + * library when linking an application is stored in the application to be + * matched at run time. When the application is run, a check is done to + * see if the library version stored in the application matches any of the + * versions in the version string of the library itself. + * This version string can be constructed in any way, depending on what + * kind of matching is desired. However, to implement the same scheme as + * the one used in the other unixen, all compatible versions, from lowest + * to highest, should be part of the string. Consecutive builds would + * give the following versions strings: + * + * 3.0 + * 3.0:3.1 + * 3.0:3.1:3.2 + * 4.0 + * 4.0:4.1 + * + * Notice how version 4 is completely incompatible with version, and + * therefore give the breach you can see. + * + * There may be other schemes as well that I haven't yet discovered. + * + * So, here's the way it works here: first of all, the library version + * number doesn't need at all to match the overall OpenSSL version. + * However, it's nice and more understandable if it actually does. + * The current library version is stored in the macro SHLIB_VERSION_NUMBER, + * which is just a piece of text in the format "M.m.e" (Major, minor, edit). + * For the sake of Tru64, IRIX, and any other OS that behaves in similar ways, + * we need to keep a history of version numbers, which is done in the + * macro SHLIB_VERSION_HISTORY. The numbers are separated by colons and + * should only keep the versions that are binary compatible with the current. + */ +# define SHLIB_VERSION_HISTORY "" +# define SHLIB_VERSION_NUMBER "1.1" + + +#ifdef __cplusplus +} +#endif +#endif /* HEADER_OPENSSLV_H */ diff --git a/include/openssl/ossl_typ.h b/include/openssl/ossl_typ.h new file mode 100644 index 0000000..66f231a --- /dev/null +++ b/include/openssl/ossl_typ.h @@ -0,0 +1,196 @@ +/* + * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OPENSSL_TYPES_H +# define HEADER_OPENSSL_TYPES_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +# include + +# ifdef NO_ASN1_TYPEDEFS +# define ASN1_INTEGER ASN1_STRING +# define ASN1_ENUMERATED ASN1_STRING +# define ASN1_BIT_STRING ASN1_STRING +# define ASN1_OCTET_STRING ASN1_STRING +# define ASN1_PRINTABLESTRING ASN1_STRING +# define ASN1_T61STRING ASN1_STRING +# define ASN1_IA5STRING ASN1_STRING +# define ASN1_UTCTIME ASN1_STRING +# define ASN1_GENERALIZEDTIME ASN1_STRING +# define ASN1_TIME ASN1_STRING +# define ASN1_GENERALSTRING ASN1_STRING +# define ASN1_UNIVERSALSTRING ASN1_STRING +# define ASN1_BMPSTRING ASN1_STRING +# define ASN1_VISIBLESTRING ASN1_STRING +# define ASN1_UTF8STRING ASN1_STRING +# define ASN1_BOOLEAN int +# define ASN1_NULL int +# else +typedef struct asn1_string_st ASN1_INTEGER; +typedef struct asn1_string_st ASN1_ENUMERATED; +typedef struct asn1_string_st ASN1_BIT_STRING; +typedef struct asn1_string_st ASN1_OCTET_STRING; +typedef struct asn1_string_st ASN1_PRINTABLESTRING; +typedef struct asn1_string_st ASN1_T61STRING; +typedef struct asn1_string_st ASN1_IA5STRING; +typedef struct asn1_string_st ASN1_GENERALSTRING; +typedef struct asn1_string_st ASN1_UNIVERSALSTRING; +typedef struct asn1_string_st ASN1_BMPSTRING; +typedef struct asn1_string_st ASN1_UTCTIME; +typedef struct asn1_string_st ASN1_TIME; +typedef struct asn1_string_st ASN1_GENERALIZEDTIME; +typedef struct asn1_string_st ASN1_VISIBLESTRING; +typedef struct asn1_string_st ASN1_UTF8STRING; +typedef struct asn1_string_st ASN1_STRING; +typedef int ASN1_BOOLEAN; +typedef int ASN1_NULL; +# endif + +typedef struct asn1_object_st ASN1_OBJECT; + +typedef struct ASN1_ITEM_st ASN1_ITEM; +typedef struct asn1_pctx_st ASN1_PCTX; +typedef struct asn1_sctx_st ASN1_SCTX; + +# ifdef _WIN32 +# undef X509_NAME +# undef X509_EXTENSIONS +# undef PKCS7_ISSUER_AND_SERIAL +# undef PKCS7_SIGNER_INFO +# undef OCSP_REQUEST +# undef OCSP_RESPONSE +# endif + +# ifdef BIGNUM +# undef BIGNUM +# endif +struct dane_st; +typedef struct bio_st BIO; +typedef struct bignum_st BIGNUM; +typedef struct bignum_ctx BN_CTX; +typedef struct bn_blinding_st BN_BLINDING; +typedef struct bn_mont_ctx_st BN_MONT_CTX; +typedef struct bn_recp_ctx_st BN_RECP_CTX; +typedef struct bn_gencb_st BN_GENCB; + +typedef struct buf_mem_st BUF_MEM; + +typedef struct evp_cipher_st EVP_CIPHER; +typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX; +typedef struct evp_md_st EVP_MD; +typedef struct evp_md_ctx_st EVP_MD_CTX; +typedef struct evp_pkey_st EVP_PKEY; + +typedef struct evp_pkey_asn1_method_st EVP_PKEY_ASN1_METHOD; + +typedef struct evp_pkey_method_st EVP_PKEY_METHOD; +typedef struct evp_pkey_ctx_st EVP_PKEY_CTX; + +typedef struct evp_Encode_Ctx_st EVP_ENCODE_CTX; + +typedef struct hmac_ctx_st HMAC_CTX; + +typedef struct dh_st DH; +typedef struct dh_method DH_METHOD; + +typedef struct dsa_st DSA; +typedef struct dsa_method DSA_METHOD; + +typedef struct rsa_st RSA; +typedef struct rsa_meth_st RSA_METHOD; + +typedef struct ec_key_st EC_KEY; +typedef struct ec_key_method_st EC_KEY_METHOD; + +typedef struct rand_meth_st RAND_METHOD; +typedef struct rand_drbg_st RAND_DRBG; + +typedef struct ssl_dane_st SSL_DANE; +typedef struct x509_st X509; +typedef struct X509_algor_st X509_ALGOR; +typedef struct X509_crl_st X509_CRL; +typedef struct x509_crl_method_st X509_CRL_METHOD; +typedef struct x509_revoked_st X509_REVOKED; +typedef struct X509_name_st X509_NAME; +typedef struct X509_pubkey_st X509_PUBKEY; +typedef struct x509_store_st X509_STORE; +typedef struct x509_store_ctx_st X509_STORE_CTX; + +typedef struct x509_object_st X509_OBJECT; +typedef struct x509_lookup_st X509_LOOKUP; +typedef struct x509_lookup_method_st X509_LOOKUP_METHOD; +typedef struct X509_VERIFY_PARAM_st X509_VERIFY_PARAM; + +typedef struct x509_sig_info_st X509_SIG_INFO; + +typedef struct pkcs8_priv_key_info_st PKCS8_PRIV_KEY_INFO; + +typedef struct v3_ext_ctx X509V3_CTX; +typedef struct conf_st CONF; +typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS; + +typedef struct ui_st UI; +typedef struct ui_method_st UI_METHOD; + +typedef struct engine_st ENGINE; +typedef struct ssl_st SSL; +typedef struct ssl_ctx_st SSL_CTX; + +typedef struct comp_ctx_st COMP_CTX; +typedef struct comp_method_st COMP_METHOD; + +typedef struct X509_POLICY_NODE_st X509_POLICY_NODE; +typedef struct X509_POLICY_LEVEL_st X509_POLICY_LEVEL; +typedef struct X509_POLICY_TREE_st X509_POLICY_TREE; +typedef struct X509_POLICY_CACHE_st X509_POLICY_CACHE; + +typedef struct AUTHORITY_KEYID_st AUTHORITY_KEYID; +typedef struct DIST_POINT_st DIST_POINT; +typedef struct ISSUING_DIST_POINT_st ISSUING_DIST_POINT; +typedef struct NAME_CONSTRAINTS_st NAME_CONSTRAINTS; + +typedef struct crypto_ex_data_st CRYPTO_EX_DATA; + +typedef struct ocsp_req_ctx_st OCSP_REQ_CTX; +typedef struct ocsp_response_st OCSP_RESPONSE; +typedef struct ocsp_responder_id_st OCSP_RESPID; + +typedef struct sct_st SCT; +typedef struct sct_ctx_st SCT_CTX; +typedef struct ctlog_st CTLOG; +typedef struct ctlog_store_st CTLOG_STORE; +typedef struct ct_policy_eval_ctx_st CT_POLICY_EVAL_CTX; + +typedef struct ossl_store_info_st OSSL_STORE_INFO; +typedef struct ossl_store_search_st OSSL_STORE_SEARCH; + +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L && \ + defined(INTMAX_MAX) && defined(UINTMAX_MAX) +typedef intmax_t ossl_intmax_t; +typedef uintmax_t ossl_uintmax_t; +#else +/* + * Not long long, because the C-library can only be expected to provide + * strtoll(), strtoull() at the same time as intmax_t and strtoimax(), + * strtoumax(). Since we use these for parsing arguments, we need the + * conversion functions, not just the sizes. + */ +typedef long ossl_intmax_t; +typedef unsigned long ossl_uintmax_t; +#endif + +#ifdef __cplusplus +} +#endif +#endif /* def HEADER_OPENSSL_TYPES_H */ diff --git a/include/openssl/pem.h b/include/openssl/pem.h new file mode 100644 index 0000000..7514f7a --- /dev/null +++ b/include/openssl/pem.h @@ -0,0 +1,378 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PEM_H +# define HEADER_PEM_H + +# include +# include +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +# define PEM_BUFSIZE 1024 + +# define PEM_STRING_X509_OLD "X509 CERTIFICATE" +# define PEM_STRING_X509 "CERTIFICATE" +# define PEM_STRING_X509_TRUSTED "TRUSTED CERTIFICATE" +# define PEM_STRING_X509_REQ_OLD "NEW CERTIFICATE REQUEST" +# define PEM_STRING_X509_REQ "CERTIFICATE REQUEST" +# define PEM_STRING_X509_CRL "X509 CRL" +# define PEM_STRING_EVP_PKEY "ANY PRIVATE KEY" +# define PEM_STRING_PUBLIC "PUBLIC KEY" +# define PEM_STRING_RSA "RSA PRIVATE KEY" +# define PEM_STRING_RSA_PUBLIC "RSA PUBLIC KEY" +# define PEM_STRING_DSA "DSA PRIVATE KEY" +# define PEM_STRING_DSA_PUBLIC "DSA PUBLIC KEY" +# define PEM_STRING_PKCS7 "PKCS7" +# define PEM_STRING_PKCS7_SIGNED "PKCS #7 SIGNED DATA" +# define PEM_STRING_PKCS8 "ENCRYPTED PRIVATE KEY" +# define PEM_STRING_PKCS8INF "PRIVATE KEY" +# define PEM_STRING_DHPARAMS "DH PARAMETERS" +# define PEM_STRING_DHXPARAMS "X9.42 DH PARAMETERS" +# define PEM_STRING_SSL_SESSION "SSL SESSION PARAMETERS" +# define PEM_STRING_DSAPARAMS "DSA PARAMETERS" +# define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY" +# define PEM_STRING_ECPARAMETERS "EC PARAMETERS" +# define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" +# define PEM_STRING_PARAMETERS "PARAMETERS" +# define PEM_STRING_CMS "CMS" + +# define PEM_TYPE_ENCRYPTED 10 +# define PEM_TYPE_MIC_ONLY 20 +# define PEM_TYPE_MIC_CLEAR 30 +# define PEM_TYPE_CLEAR 40 + +/* + * These macros make the PEM_read/PEM_write functions easier to maintain and + * write. Now they are all implemented with either: IMPLEMENT_PEM_rw(...) or + * IMPLEMENT_PEM_rw_cb(...) + */ + +# ifdef OPENSSL_NO_STDIO + +# define IMPLEMENT_PEM_read_fp(name, type, str, asn1) /**/ +# define IMPLEMENT_PEM_write_fp(name, type, str, asn1) /**/ +# define IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) /**/ +# define IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) /**/ +# define IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) /**/ +# else + +# define IMPLEMENT_PEM_read_fp(name, type, str, asn1) \ +type *PEM_read_##name(FILE *fp, type **x, pem_password_cb *cb, void *u)\ +{ \ +return PEM_ASN1_read((d2i_of_void *)d2i_##asn1, str,fp,(void **)x,cb,u); \ +} + +# define IMPLEMENT_PEM_write_fp(name, type, str, asn1) \ +int PEM_write_##name(FILE *fp, type *x) \ +{ \ +return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,x,NULL,NULL,0,NULL,NULL); \ +} + +# define IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) \ +int PEM_write_##name(FILE *fp, const type *x) \ +{ \ +return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,(void *)x,NULL,NULL,0,NULL,NULL); \ +} + +# define IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) \ +int PEM_write_##name(FILE *fp, type *x, const EVP_CIPHER *enc, \ + unsigned char *kstr, int klen, pem_password_cb *cb, \ + void *u) \ + { \ + return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,x,enc,kstr,klen,cb,u); \ + } + +# define IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) \ +int PEM_write_##name(FILE *fp, type *x, const EVP_CIPHER *enc, \ + unsigned char *kstr, int klen, pem_password_cb *cb, \ + void *u) \ + { \ + return PEM_ASN1_write((i2d_of_void *)i2d_##asn1,str,fp,x,enc,kstr,klen,cb,u); \ + } + +# endif + +# define IMPLEMENT_PEM_read_bio(name, type, str, asn1) \ +type *PEM_read_bio_##name(BIO *bp, type **x, pem_password_cb *cb, void *u)\ +{ \ +return PEM_ASN1_read_bio((d2i_of_void *)d2i_##asn1, str,bp,(void **)x,cb,u); \ +} + +# define IMPLEMENT_PEM_write_bio(name, type, str, asn1) \ +int PEM_write_bio_##name(BIO *bp, type *x) \ +{ \ +return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,x,NULL,NULL,0,NULL,NULL); \ +} + +# define IMPLEMENT_PEM_write_bio_const(name, type, str, asn1) \ +int PEM_write_bio_##name(BIO *bp, const type *x) \ +{ \ +return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,(void *)x,NULL,NULL,0,NULL,NULL); \ +} + +# define IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \ +int PEM_write_bio_##name(BIO *bp, type *x, const EVP_CIPHER *enc, \ + unsigned char *kstr, int klen, pem_password_cb *cb, void *u) \ + { \ + return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,x,enc,kstr,klen,cb,u); \ + } + +# define IMPLEMENT_PEM_write_cb_bio_const(name, type, str, asn1) \ +int PEM_write_bio_##name(BIO *bp, type *x, const EVP_CIPHER *enc, \ + unsigned char *kstr, int klen, pem_password_cb *cb, void *u) \ + { \ + return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1,str,bp,(void *)x,enc,kstr,klen,cb,u); \ + } + +# define IMPLEMENT_PEM_write(name, type, str, asn1) \ + IMPLEMENT_PEM_write_bio(name, type, str, asn1) \ + IMPLEMENT_PEM_write_fp(name, type, str, asn1) + +# define IMPLEMENT_PEM_write_const(name, type, str, asn1) \ + IMPLEMENT_PEM_write_bio_const(name, type, str, asn1) \ + IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) + +# define IMPLEMENT_PEM_write_cb(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) + +# define IMPLEMENT_PEM_write_cb_const(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb_bio_const(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) + +# define IMPLEMENT_PEM_read(name, type, str, asn1) \ + IMPLEMENT_PEM_read_bio(name, type, str, asn1) \ + IMPLEMENT_PEM_read_fp(name, type, str, asn1) + +# define IMPLEMENT_PEM_rw(name, type, str, asn1) \ + IMPLEMENT_PEM_read(name, type, str, asn1) \ + IMPLEMENT_PEM_write(name, type, str, asn1) + +# define IMPLEMENT_PEM_rw_const(name, type, str, asn1) \ + IMPLEMENT_PEM_read(name, type, str, asn1) \ + IMPLEMENT_PEM_write_const(name, type, str, asn1) + +# define IMPLEMENT_PEM_rw_cb(name, type, str, asn1) \ + IMPLEMENT_PEM_read(name, type, str, asn1) \ + IMPLEMENT_PEM_write_cb(name, type, str, asn1) + +/* These are the same except they are for the declarations */ + +# if defined(OPENSSL_NO_STDIO) + +# define DECLARE_PEM_read_fp(name, type) /**/ +# define DECLARE_PEM_write_fp(name, type) /**/ +# define DECLARE_PEM_write_fp_const(name, type) /**/ +# define DECLARE_PEM_write_cb_fp(name, type) /**/ +# else + +# define DECLARE_PEM_read_fp(name, type) \ + type *PEM_read_##name(FILE *fp, type **x, pem_password_cb *cb, void *u); + +# define DECLARE_PEM_write_fp(name, type) \ + int PEM_write_##name(FILE *fp, type *x); + +# define DECLARE_PEM_write_fp_const(name, type) \ + int PEM_write_##name(FILE *fp, const type *x); + +# define DECLARE_PEM_write_cb_fp(name, type) \ + int PEM_write_##name(FILE *fp, type *x, const EVP_CIPHER *enc, \ + unsigned char *kstr, int klen, pem_password_cb *cb, void *u); + +# endif + +# define DECLARE_PEM_read_bio(name, type) \ + type *PEM_read_bio_##name(BIO *bp, type **x, pem_password_cb *cb, void *u); + +# define DECLARE_PEM_write_bio(name, type) \ + int PEM_write_bio_##name(BIO *bp, type *x); + +# define DECLARE_PEM_write_bio_const(name, type) \ + int PEM_write_bio_##name(BIO *bp, const type *x); + +# define DECLARE_PEM_write_cb_bio(name, type) \ + int PEM_write_bio_##name(BIO *bp, type *x, const EVP_CIPHER *enc, \ + unsigned char *kstr, int klen, pem_password_cb *cb, void *u); + +# define DECLARE_PEM_write(name, type) \ + DECLARE_PEM_write_bio(name, type) \ + DECLARE_PEM_write_fp(name, type) +# define DECLARE_PEM_write_const(name, type) \ + DECLARE_PEM_write_bio_const(name, type) \ + DECLARE_PEM_write_fp_const(name, type) +# define DECLARE_PEM_write_cb(name, type) \ + DECLARE_PEM_write_cb_bio(name, type) \ + DECLARE_PEM_write_cb_fp(name, type) +# define DECLARE_PEM_read(name, type) \ + DECLARE_PEM_read_bio(name, type) \ + DECLARE_PEM_read_fp(name, type) +# define DECLARE_PEM_rw(name, type) \ + DECLARE_PEM_read(name, type) \ + DECLARE_PEM_write(name, type) +# define DECLARE_PEM_rw_const(name, type) \ + DECLARE_PEM_read(name, type) \ + DECLARE_PEM_write_const(name, type) +# define DECLARE_PEM_rw_cb(name, type) \ + DECLARE_PEM_read(name, type) \ + DECLARE_PEM_write_cb(name, type) +typedef int pem_password_cb (char *buf, int size, int rwflag, void *userdata); + +int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher); +int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *len, + pem_password_cb *callback, void *u); + +int PEM_read_bio(BIO *bp, char **name, char **header, + unsigned char **data, long *len); +# define PEM_FLAG_SECURE 0x1 +# define PEM_FLAG_EAY_COMPATIBLE 0x2 +# define PEM_FLAG_ONLY_B64 0x4 +int PEM_read_bio_ex(BIO *bp, char **name, char **header, + unsigned char **data, long *len, unsigned int flags); +int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm, + const char *name, BIO *bp, pem_password_cb *cb, + void *u); +int PEM_write_bio(BIO *bp, const char *name, const char *hdr, + const unsigned char *data, long len); +int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, + const char *name, BIO *bp, pem_password_cb *cb, + void *u); +void *PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x, + pem_password_cb *cb, void *u); +int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x, + const EVP_CIPHER *enc, unsigned char *kstr, int klen, + pem_password_cb *cb, void *u); + +STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk, + pem_password_cb *cb, void *u); +int PEM_X509_INFO_write_bio(BIO *bp, X509_INFO *xi, EVP_CIPHER *enc, + unsigned char *kstr, int klen, + pem_password_cb *cd, void *u); + +#ifndef OPENSSL_NO_STDIO +int PEM_read(FILE *fp, char **name, char **header, + unsigned char **data, long *len); +int PEM_write(FILE *fp, const char *name, const char *hdr, + const unsigned char *data, long len); +void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x, + pem_password_cb *cb, void *u); +int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, + void *x, const EVP_CIPHER *enc, unsigned char *kstr, + int klen, pem_password_cb *callback, void *u); +STACK_OF(X509_INFO) *PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, + pem_password_cb *cb, void *u); +#endif + +int PEM_SignInit(EVP_MD_CTX *ctx, EVP_MD *type); +int PEM_SignUpdate(EVP_MD_CTX *ctx, unsigned char *d, unsigned int cnt); +int PEM_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, + unsigned int *siglen, EVP_PKEY *pkey); + +/* The default pem_password_cb that's used internally */ +int PEM_def_callback(char *buf, int num, int rwflag, void *userdata); +void PEM_proc_type(char *buf, int type); +void PEM_dek_info(char *buf, const char *type, int len, char *str); + +# include + +DECLARE_PEM_rw(X509, X509) +DECLARE_PEM_rw(X509_AUX, X509) +DECLARE_PEM_rw(X509_REQ, X509_REQ) +DECLARE_PEM_write(X509_REQ_NEW, X509_REQ) +DECLARE_PEM_rw(X509_CRL, X509_CRL) +DECLARE_PEM_rw(PKCS7, PKCS7) +DECLARE_PEM_rw(NETSCAPE_CERT_SEQUENCE, NETSCAPE_CERT_SEQUENCE) +DECLARE_PEM_rw(PKCS8, X509_SIG) +DECLARE_PEM_rw(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO) +# ifndef OPENSSL_NO_RSA +DECLARE_PEM_rw_cb(RSAPrivateKey, RSA) +DECLARE_PEM_rw_const(RSAPublicKey, RSA) +DECLARE_PEM_rw(RSA_PUBKEY, RSA) +# endif +# ifndef OPENSSL_NO_DSA +DECLARE_PEM_rw_cb(DSAPrivateKey, DSA) +DECLARE_PEM_rw(DSA_PUBKEY, DSA) +DECLARE_PEM_rw_const(DSAparams, DSA) +# endif +# ifndef OPENSSL_NO_EC +DECLARE_PEM_rw_const(ECPKParameters, EC_GROUP) +DECLARE_PEM_rw_cb(ECPrivateKey, EC_KEY) +DECLARE_PEM_rw(EC_PUBKEY, EC_KEY) +# endif +# ifndef OPENSSL_NO_DH +DECLARE_PEM_rw_const(DHparams, DH) +DECLARE_PEM_write_const(DHxparams, DH) +# endif +DECLARE_PEM_rw_cb(PrivateKey, EVP_PKEY) +DECLARE_PEM_rw(PUBKEY, EVP_PKEY) + +int PEM_write_bio_PrivateKey_traditional(BIO *bp, EVP_PKEY *x, + const EVP_CIPHER *enc, + unsigned char *kstr, int klen, + pem_password_cb *cb, void *u); + +int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, EVP_PKEY *x, int nid, + char *kstr, int klen, + pem_password_cb *cb, void *u); +int PEM_write_bio_PKCS8PrivateKey(BIO *, EVP_PKEY *, const EVP_CIPHER *, + char *, int, pem_password_cb *, void *); +int i2d_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, + char *kstr, int klen, + pem_password_cb *cb, void *u); +int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, EVP_PKEY *x, int nid, + char *kstr, int klen, + pem_password_cb *cb, void *u); +EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, + void *u); + +# ifndef OPENSSL_NO_STDIO +int i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, + char *kstr, int klen, + pem_password_cb *cb, void *u); +int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, EVP_PKEY *x, int nid, + char *kstr, int klen, + pem_password_cb *cb, void *u); +int PEM_write_PKCS8PrivateKey_nid(FILE *fp, EVP_PKEY *x, int nid, + char *kstr, int klen, + pem_password_cb *cb, void *u); + +EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, + void *u); + +int PEM_write_PKCS8PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, + char *kstr, int klen, pem_password_cb *cd, + void *u); +# endif +EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x); +int PEM_write_bio_Parameters(BIO *bp, EVP_PKEY *x); + +# ifndef OPENSSL_NO_DSA +EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length); +EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length); +EVP_PKEY *b2i_PrivateKey_bio(BIO *in); +EVP_PKEY *b2i_PublicKey_bio(BIO *in); +int i2b_PrivateKey_bio(BIO *out, EVP_PKEY *pk); +int i2b_PublicKey_bio(BIO *out, EVP_PKEY *pk); +# ifndef OPENSSL_NO_RC4 +EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u); +int i2b_PVK_bio(BIO *out, EVP_PKEY *pk, int enclevel, + pem_password_cb *cb, void *u); +# endif +# endif + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/pem2.h b/include/openssl/pem2.h new file mode 100644 index 0000000..cf0b244 --- /dev/null +++ b/include/openssl/pem2.h @@ -0,0 +1,13 @@ +/* + * Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PEM2_H +# define HEADER_PEM2_H +# include +#endif diff --git a/include/openssl/pemerr.h b/include/openssl/pemerr.h new file mode 100644 index 0000000..cd61b82 --- /dev/null +++ b/include/openssl/pemerr.h @@ -0,0 +1,99 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PEMERR_H +# define HEADER_PEMERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_PEM_strings(void); + +/* + * PEM function codes. + */ +# define PEM_F_B2I_DSS 127 +# define PEM_F_B2I_PVK_BIO 128 +# define PEM_F_B2I_RSA 129 +# define PEM_F_CHECK_BITLEN_DSA 130 +# define PEM_F_CHECK_BITLEN_RSA 131 +# define PEM_F_D2I_PKCS8PRIVATEKEY_BIO 120 +# define PEM_F_D2I_PKCS8PRIVATEKEY_FP 121 +# define PEM_F_DO_B2I 132 +# define PEM_F_DO_B2I_BIO 133 +# define PEM_F_DO_BLOB_HEADER 134 +# define PEM_F_DO_I2B 146 +# define PEM_F_DO_PK8PKEY 126 +# define PEM_F_DO_PK8PKEY_FP 125 +# define PEM_F_DO_PVK_BODY 135 +# define PEM_F_DO_PVK_HEADER 136 +# define PEM_F_GET_HEADER_AND_DATA 143 +# define PEM_F_GET_NAME 144 +# define PEM_F_I2B_PVK 137 +# define PEM_F_I2B_PVK_BIO 138 +# define PEM_F_LOAD_IV 101 +# define PEM_F_PEM_ASN1_READ 102 +# define PEM_F_PEM_ASN1_READ_BIO 103 +# define PEM_F_PEM_ASN1_WRITE 104 +# define PEM_F_PEM_ASN1_WRITE_BIO 105 +# define PEM_F_PEM_DEF_CALLBACK 100 +# define PEM_F_PEM_DO_HEADER 106 +# define PEM_F_PEM_GET_EVP_CIPHER_INFO 107 +# define PEM_F_PEM_READ 108 +# define PEM_F_PEM_READ_BIO 109 +# define PEM_F_PEM_READ_BIO_DHPARAMS 141 +# define PEM_F_PEM_READ_BIO_EX 145 +# define PEM_F_PEM_READ_BIO_PARAMETERS 140 +# define PEM_F_PEM_READ_BIO_PRIVATEKEY 123 +# define PEM_F_PEM_READ_DHPARAMS 142 +# define PEM_F_PEM_READ_PRIVATEKEY 124 +# define PEM_F_PEM_SIGNFINAL 112 +# define PEM_F_PEM_WRITE 113 +# define PEM_F_PEM_WRITE_BIO 114 +# define PEM_F_PEM_WRITE_PRIVATEKEY 139 +# define PEM_F_PEM_X509_INFO_READ 115 +# define PEM_F_PEM_X509_INFO_READ_BIO 116 +# define PEM_F_PEM_X509_INFO_WRITE_BIO 117 + +/* + * PEM reason codes. + */ +# define PEM_R_BAD_BASE64_DECODE 100 +# define PEM_R_BAD_DECRYPT 101 +# define PEM_R_BAD_END_LINE 102 +# define PEM_R_BAD_IV_CHARS 103 +# define PEM_R_BAD_MAGIC_NUMBER 116 +# define PEM_R_BAD_PASSWORD_READ 104 +# define PEM_R_BAD_VERSION_NUMBER 117 +# define PEM_R_BIO_WRITE_FAILURE 118 +# define PEM_R_CIPHER_IS_NULL 127 +# define PEM_R_ERROR_CONVERTING_PRIVATE_KEY 115 +# define PEM_R_EXPECTING_PRIVATE_KEY_BLOB 119 +# define PEM_R_EXPECTING_PUBLIC_KEY_BLOB 120 +# define PEM_R_HEADER_TOO_LONG 128 +# define PEM_R_INCONSISTENT_HEADER 121 +# define PEM_R_KEYBLOB_HEADER_PARSE_ERROR 122 +# define PEM_R_KEYBLOB_TOO_SHORT 123 +# define PEM_R_MISSING_DEK_IV 129 +# define PEM_R_NOT_DEK_INFO 105 +# define PEM_R_NOT_ENCRYPTED 106 +# define PEM_R_NOT_PROC_TYPE 107 +# define PEM_R_NO_START_LINE 108 +# define PEM_R_PROBLEMS_GETTING_PASSWORD 109 +# define PEM_R_PVK_DATA_TOO_SHORT 124 +# define PEM_R_PVK_TOO_SHORT 125 +# define PEM_R_READ_KEY 111 +# define PEM_R_SHORT_HEADER 112 +# define PEM_R_UNEXPECTED_DEK_IV 130 +# define PEM_R_UNSUPPORTED_CIPHER 113 +# define PEM_R_UNSUPPORTED_ENCRYPTION 114 +# define PEM_R_UNSUPPORTED_KEY_COMPONENTS 126 + +#endif diff --git a/include/openssl/pkcs12.h b/include/openssl/pkcs12.h new file mode 100644 index 0000000..433303e --- /dev/null +++ b/include/openssl/pkcs12.h @@ -0,0 +1,223 @@ +/* + * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PKCS12_H +# define HEADER_PKCS12_H + +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +# define PKCS12_KEY_ID 1 +# define PKCS12_IV_ID 2 +# define PKCS12_MAC_ID 3 + +/* Default iteration count */ +# ifndef PKCS12_DEFAULT_ITER +# define PKCS12_DEFAULT_ITER PKCS5_DEFAULT_ITER +# endif + +# define PKCS12_MAC_KEY_LENGTH 20 + +# define PKCS12_SALT_LEN 8 + +/* It's not clear if these are actually needed... */ +# define PKCS12_key_gen PKCS12_key_gen_utf8 +# define PKCS12_add_friendlyname PKCS12_add_friendlyname_utf8 + +/* MS key usage constants */ + +# define KEY_EX 0x10 +# define KEY_SIG 0x80 + +typedef struct PKCS12_MAC_DATA_st PKCS12_MAC_DATA; + +typedef struct PKCS12_st PKCS12; + +typedef struct PKCS12_SAFEBAG_st PKCS12_SAFEBAG; + +DEFINE_STACK_OF(PKCS12_SAFEBAG) + +typedef struct pkcs12_bag_st PKCS12_BAGS; + +# define PKCS12_ERROR 0 +# define PKCS12_OK 1 + +/* Compatibility macros */ + +#if OPENSSL_API_COMPAT < 0x10100000L + +# define M_PKCS12_bag_type PKCS12_bag_type +# define M_PKCS12_cert_bag_type PKCS12_cert_bag_type +# define M_PKCS12_crl_bag_type PKCS12_cert_bag_type + +# define PKCS12_certbag2x509 PKCS12_SAFEBAG_get1_cert +# define PKCS12_certbag2scrl PKCS12_SAFEBAG_get1_crl +# define PKCS12_bag_type PKCS12_SAFEBAG_get_nid +# define PKCS12_cert_bag_type PKCS12_SAFEBAG_get_bag_nid +# define PKCS12_x5092certbag PKCS12_SAFEBAG_create_cert +# define PKCS12_x509crl2certbag PKCS12_SAFEBAG_create_crl +# define PKCS12_MAKE_KEYBAG PKCS12_SAFEBAG_create0_p8inf +# define PKCS12_MAKE_SHKEYBAG PKCS12_SAFEBAG_create_pkcs8_encrypt + +#endif + +DEPRECATEDIN_1_1_0(ASN1_TYPE *PKCS12_get_attr(const PKCS12_SAFEBAG *bag, int attr_nid)) + +ASN1_TYPE *PKCS8_get_attr(PKCS8_PRIV_KEY_INFO *p8, int attr_nid); +int PKCS12_mac_present(const PKCS12 *p12); +void PKCS12_get0_mac(const ASN1_OCTET_STRING **pmac, + const X509_ALGOR **pmacalg, + const ASN1_OCTET_STRING **psalt, + const ASN1_INTEGER **piter, + const PKCS12 *p12); + +const ASN1_TYPE *PKCS12_SAFEBAG_get0_attr(const PKCS12_SAFEBAG *bag, + int attr_nid); +const ASN1_OBJECT *PKCS12_SAFEBAG_get0_type(const PKCS12_SAFEBAG *bag); +int PKCS12_SAFEBAG_get_nid(const PKCS12_SAFEBAG *bag); +int PKCS12_SAFEBAG_get_bag_nid(const PKCS12_SAFEBAG *bag); + +X509 *PKCS12_SAFEBAG_get1_cert(const PKCS12_SAFEBAG *bag); +X509_CRL *PKCS12_SAFEBAG_get1_crl(const PKCS12_SAFEBAG *bag); +const STACK_OF(PKCS12_SAFEBAG) * +PKCS12_SAFEBAG_get0_safes(const PKCS12_SAFEBAG *bag); +const PKCS8_PRIV_KEY_INFO *PKCS12_SAFEBAG_get0_p8inf(const PKCS12_SAFEBAG *bag); +const X509_SIG *PKCS12_SAFEBAG_get0_pkcs8(const PKCS12_SAFEBAG *bag); + +PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_cert(X509 *x509); +PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_crl(X509_CRL *crl); +PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_p8inf(PKCS8_PRIV_KEY_INFO *p8); +PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_pkcs8(X509_SIG *p8); +PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt(int pbe_nid, + const char *pass, + int passlen, + unsigned char *salt, + int saltlen, int iter, + PKCS8_PRIV_KEY_INFO *p8inf); + +PKCS12_SAFEBAG *PKCS12_item_pack_safebag(void *obj, const ASN1_ITEM *it, + int nid1, int nid2); +PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(const X509_SIG *p8, const char *pass, + int passlen); +PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey(const PKCS12_SAFEBAG *bag, + const char *pass, int passlen); +X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, + const char *pass, int passlen, unsigned char *salt, + int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8); +X509_SIG *PKCS8_set0_pbe(const char *pass, int passlen, + PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe); +PKCS7 *PKCS12_pack_p7data(STACK_OF(PKCS12_SAFEBAG) *sk); +STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7data(PKCS7 *p7); +PKCS7 *PKCS12_pack_p7encdata(int pbe_nid, const char *pass, int passlen, + unsigned char *salt, int saltlen, int iter, + STACK_OF(PKCS12_SAFEBAG) *bags); +STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7encdata(PKCS7 *p7, const char *pass, + int passlen); + +int PKCS12_pack_authsafes(PKCS12 *p12, STACK_OF(PKCS7) *safes); +STACK_OF(PKCS7) *PKCS12_unpack_authsafes(const PKCS12 *p12); + +int PKCS12_add_localkeyid(PKCS12_SAFEBAG *bag, unsigned char *name, + int namelen); +int PKCS12_add_friendlyname_asc(PKCS12_SAFEBAG *bag, const char *name, + int namelen); +int PKCS12_add_friendlyname_utf8(PKCS12_SAFEBAG *bag, const char *name, + int namelen); +int PKCS12_add_CSPName_asc(PKCS12_SAFEBAG *bag, const char *name, + int namelen); +int PKCS12_add_friendlyname_uni(PKCS12_SAFEBAG *bag, + const unsigned char *name, int namelen); +int PKCS8_add_keyusage(PKCS8_PRIV_KEY_INFO *p8, int usage); +ASN1_TYPE *PKCS12_get_attr_gen(const STACK_OF(X509_ATTRIBUTE) *attrs, + int attr_nid); +char *PKCS12_get_friendlyname(PKCS12_SAFEBAG *bag); +const STACK_OF(X509_ATTRIBUTE) * +PKCS12_SAFEBAG_get0_attrs(const PKCS12_SAFEBAG *bag); +unsigned char *PKCS12_pbe_crypt(const X509_ALGOR *algor, + const char *pass, int passlen, + const unsigned char *in, int inlen, + unsigned char **data, int *datalen, + int en_de); +void *PKCS12_item_decrypt_d2i(const X509_ALGOR *algor, const ASN1_ITEM *it, + const char *pass, int passlen, + const ASN1_OCTET_STRING *oct, int zbuf); +ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor, + const ASN1_ITEM *it, + const char *pass, int passlen, + void *obj, int zbuf); +PKCS12 *PKCS12_init(int mode); +int PKCS12_key_gen_asc(const char *pass, int passlen, unsigned char *salt, + int saltlen, int id, int iter, int n, + unsigned char *out, const EVP_MD *md_type); +int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, + int saltlen, int id, int iter, int n, + unsigned char *out, const EVP_MD *md_type); +int PKCS12_key_gen_utf8(const char *pass, int passlen, unsigned char *salt, + int saltlen, int id, int iter, int n, + unsigned char *out, const EVP_MD *md_type); +int PKCS12_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, + ASN1_TYPE *param, const EVP_CIPHER *cipher, + const EVP_MD *md_type, int en_de); +int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen, + unsigned char *mac, unsigned int *maclen); +int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen); +int PKCS12_set_mac(PKCS12 *p12, const char *pass, int passlen, + unsigned char *salt, int saltlen, int iter, + const EVP_MD *md_type); +int PKCS12_setup_mac(PKCS12 *p12, int iter, unsigned char *salt, + int saltlen, const EVP_MD *md_type); +unsigned char *OPENSSL_asc2uni(const char *asc, int asclen, + unsigned char **uni, int *unilen); +char *OPENSSL_uni2asc(const unsigned char *uni, int unilen); +unsigned char *OPENSSL_utf82uni(const char *asc, int asclen, + unsigned char **uni, int *unilen); +char *OPENSSL_uni2utf8(const unsigned char *uni, int unilen); + +DECLARE_ASN1_FUNCTIONS(PKCS12) +DECLARE_ASN1_FUNCTIONS(PKCS12_MAC_DATA) +DECLARE_ASN1_FUNCTIONS(PKCS12_SAFEBAG) +DECLARE_ASN1_FUNCTIONS(PKCS12_BAGS) + +DECLARE_ASN1_ITEM(PKCS12_SAFEBAGS) +DECLARE_ASN1_ITEM(PKCS12_AUTHSAFES) + +void PKCS12_PBE_add(void); +int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, + STACK_OF(X509) **ca); +PKCS12 *PKCS12_create(const char *pass, const char *name, EVP_PKEY *pkey, + X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, + int iter, int mac_iter, int keytype); + +PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert); +PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags, + EVP_PKEY *key, int key_usage, int iter, + int key_nid, const char *pass); +int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags, + int safe_nid, int iter, const char *pass); +PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int p7_nid); + +int i2d_PKCS12_bio(BIO *bp, PKCS12 *p12); +# ifndef OPENSSL_NO_STDIO +int i2d_PKCS12_fp(FILE *fp, PKCS12 *p12); +# endif +PKCS12 *d2i_PKCS12_bio(BIO *bp, PKCS12 **p12); +# ifndef OPENSSL_NO_STDIO +PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12); +# endif +int PKCS12_newpass(PKCS12 *p12, const char *oldpass, const char *newpass); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/pkcs12err.h b/include/openssl/pkcs12err.h new file mode 100644 index 0000000..c7184ff --- /dev/null +++ b/include/openssl/pkcs12err.h @@ -0,0 +1,77 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PKCS12ERR_H +# define HEADER_PKCS12ERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_PKCS12_strings(void); + +/* + * PKCS12 function codes. + */ +# define PKCS12_F_OPENSSL_ASC2UNI 121 +# define PKCS12_F_OPENSSL_UNI2ASC 124 +# define PKCS12_F_OPENSSL_UNI2UTF8 127 +# define PKCS12_F_OPENSSL_UTF82UNI 129 +# define PKCS12_F_PKCS12_CREATE 105 +# define PKCS12_F_PKCS12_GEN_MAC 107 +# define PKCS12_F_PKCS12_INIT 109 +# define PKCS12_F_PKCS12_ITEM_DECRYPT_D2I 106 +# define PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT 108 +# define PKCS12_F_PKCS12_ITEM_PACK_SAFEBAG 117 +# define PKCS12_F_PKCS12_KEY_GEN_ASC 110 +# define PKCS12_F_PKCS12_KEY_GEN_UNI 111 +# define PKCS12_F_PKCS12_KEY_GEN_UTF8 116 +# define PKCS12_F_PKCS12_NEWPASS 128 +# define PKCS12_F_PKCS12_PACK_P7DATA 114 +# define PKCS12_F_PKCS12_PACK_P7ENCDATA 115 +# define PKCS12_F_PKCS12_PARSE 118 +# define PKCS12_F_PKCS12_PBE_CRYPT 119 +# define PKCS12_F_PKCS12_PBE_KEYIVGEN 120 +# define PKCS12_F_PKCS12_SAFEBAG_CREATE0_P8INF 112 +# define PKCS12_F_PKCS12_SAFEBAG_CREATE0_PKCS8 113 +# define PKCS12_F_PKCS12_SAFEBAG_CREATE_PKCS8_ENCRYPT 133 +# define PKCS12_F_PKCS12_SETUP_MAC 122 +# define PKCS12_F_PKCS12_SET_MAC 123 +# define PKCS12_F_PKCS12_UNPACK_AUTHSAFES 130 +# define PKCS12_F_PKCS12_UNPACK_P7DATA 131 +# define PKCS12_F_PKCS12_VERIFY_MAC 126 +# define PKCS12_F_PKCS8_ENCRYPT 125 +# define PKCS12_F_PKCS8_SET0_PBE 132 + +/* + * PKCS12 reason codes. + */ +# define PKCS12_R_CANT_PACK_STRUCTURE 100 +# define PKCS12_R_CONTENT_TYPE_NOT_DATA 121 +# define PKCS12_R_DECODE_ERROR 101 +# define PKCS12_R_ENCODE_ERROR 102 +# define PKCS12_R_ENCRYPT_ERROR 103 +# define PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE 120 +# define PKCS12_R_INVALID_NULL_ARGUMENT 104 +# define PKCS12_R_INVALID_NULL_PKCS12_POINTER 105 +# define PKCS12_R_IV_GEN_ERROR 106 +# define PKCS12_R_KEY_GEN_ERROR 107 +# define PKCS12_R_MAC_ABSENT 108 +# define PKCS12_R_MAC_GENERATION_ERROR 109 +# define PKCS12_R_MAC_SETUP_ERROR 110 +# define PKCS12_R_MAC_STRING_SET_ERROR 111 +# define PKCS12_R_MAC_VERIFY_FAILURE 113 +# define PKCS12_R_PARSE_ERROR 114 +# define PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR 115 +# define PKCS12_R_PKCS12_CIPHERFINAL_ERROR 116 +# define PKCS12_R_PKCS12_PBE_CRYPT_ERROR 117 +# define PKCS12_R_UNKNOWN_DIGEST_ALGORITHM 118 +# define PKCS12_R_UNSUPPORTED_PKCS12_MODE 119 + +#endif diff --git a/include/openssl/pkcs7.h b/include/openssl/pkcs7.h new file mode 100644 index 0000000..8c805d2 --- /dev/null +++ b/include/openssl/pkcs7.h @@ -0,0 +1,319 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PKCS7_H +# define HEADER_PKCS7_H + +# include +# include +# include + +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/*- +Encryption_ID DES-CBC +Digest_ID MD5 +Digest_Encryption_ID rsaEncryption +Key_Encryption_ID rsaEncryption +*/ + +typedef struct pkcs7_issuer_and_serial_st { + X509_NAME *issuer; + ASN1_INTEGER *serial; +} PKCS7_ISSUER_AND_SERIAL; + +typedef struct pkcs7_signer_info_st { + ASN1_INTEGER *version; /* version 1 */ + PKCS7_ISSUER_AND_SERIAL *issuer_and_serial; + X509_ALGOR *digest_alg; + STACK_OF(X509_ATTRIBUTE) *auth_attr; /* [ 0 ] */ + X509_ALGOR *digest_enc_alg; + ASN1_OCTET_STRING *enc_digest; + STACK_OF(X509_ATTRIBUTE) *unauth_attr; /* [ 1 ] */ + /* The private key to sign with */ + EVP_PKEY *pkey; +} PKCS7_SIGNER_INFO; + +DEFINE_STACK_OF(PKCS7_SIGNER_INFO) + +typedef struct pkcs7_recip_info_st { + ASN1_INTEGER *version; /* version 0 */ + PKCS7_ISSUER_AND_SERIAL *issuer_and_serial; + X509_ALGOR *key_enc_algor; + ASN1_OCTET_STRING *enc_key; + X509 *cert; /* get the pub-key from this */ +} PKCS7_RECIP_INFO; + +DEFINE_STACK_OF(PKCS7_RECIP_INFO) + +typedef struct pkcs7_signed_st { + ASN1_INTEGER *version; /* version 1 */ + STACK_OF(X509_ALGOR) *md_algs; /* md used */ + STACK_OF(X509) *cert; /* [ 0 ] */ + STACK_OF(X509_CRL) *crl; /* [ 1 ] */ + STACK_OF(PKCS7_SIGNER_INFO) *signer_info; + struct pkcs7_st *contents; +} PKCS7_SIGNED; +/* + * The above structure is very very similar to PKCS7_SIGN_ENVELOPE. How about + * merging the two + */ + +typedef struct pkcs7_enc_content_st { + ASN1_OBJECT *content_type; + X509_ALGOR *algorithm; + ASN1_OCTET_STRING *enc_data; /* [ 0 ] */ + const EVP_CIPHER *cipher; +} PKCS7_ENC_CONTENT; + +typedef struct pkcs7_enveloped_st { + ASN1_INTEGER *version; /* version 0 */ + STACK_OF(PKCS7_RECIP_INFO) *recipientinfo; + PKCS7_ENC_CONTENT *enc_data; +} PKCS7_ENVELOPE; + +typedef struct pkcs7_signedandenveloped_st { + ASN1_INTEGER *version; /* version 1 */ + STACK_OF(X509_ALGOR) *md_algs; /* md used */ + STACK_OF(X509) *cert; /* [ 0 ] */ + STACK_OF(X509_CRL) *crl; /* [ 1 ] */ + STACK_OF(PKCS7_SIGNER_INFO) *signer_info; + PKCS7_ENC_CONTENT *enc_data; + STACK_OF(PKCS7_RECIP_INFO) *recipientinfo; +} PKCS7_SIGN_ENVELOPE; + +typedef struct pkcs7_digest_st { + ASN1_INTEGER *version; /* version 0 */ + X509_ALGOR *md; /* md used */ + struct pkcs7_st *contents; + ASN1_OCTET_STRING *digest; +} PKCS7_DIGEST; + +typedef struct pkcs7_encrypted_st { + ASN1_INTEGER *version; /* version 0 */ + PKCS7_ENC_CONTENT *enc_data; +} PKCS7_ENCRYPT; + +typedef struct pkcs7_st { + /* + * The following is non NULL if it contains ASN1 encoding of this + * structure + */ + unsigned char *asn1; + long length; +# define PKCS7_S_HEADER 0 +# define PKCS7_S_BODY 1 +# define PKCS7_S_TAIL 2 + int state; /* used during processing */ + int detached; + ASN1_OBJECT *type; + /* content as defined by the type */ + /* + * all encryption/message digests are applied to the 'contents', leaving + * out the 'type' field. + */ + union { + char *ptr; + /* NID_pkcs7_data */ + ASN1_OCTET_STRING *data; + /* NID_pkcs7_signed */ + PKCS7_SIGNED *sign; + /* NID_pkcs7_enveloped */ + PKCS7_ENVELOPE *enveloped; + /* NID_pkcs7_signedAndEnveloped */ + PKCS7_SIGN_ENVELOPE *signed_and_enveloped; + /* NID_pkcs7_digest */ + PKCS7_DIGEST *digest; + /* NID_pkcs7_encrypted */ + PKCS7_ENCRYPT *encrypted; + /* Anything else */ + ASN1_TYPE *other; + } d; +} PKCS7; + +DEFINE_STACK_OF(PKCS7) + +# define PKCS7_OP_SET_DETACHED_SIGNATURE 1 +# define PKCS7_OP_GET_DETACHED_SIGNATURE 2 + +# define PKCS7_get_signed_attributes(si) ((si)->auth_attr) +# define PKCS7_get_attributes(si) ((si)->unauth_attr) + +# define PKCS7_type_is_signed(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_signed) +# define PKCS7_type_is_encrypted(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_encrypted) +# define PKCS7_type_is_enveloped(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_enveloped) +# define PKCS7_type_is_signedAndEnveloped(a) \ + (OBJ_obj2nid((a)->type) == NID_pkcs7_signedAndEnveloped) +# define PKCS7_type_is_data(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_data) +# define PKCS7_type_is_digest(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_digest) + +# define PKCS7_set_detached(p,v) \ + PKCS7_ctrl(p,PKCS7_OP_SET_DETACHED_SIGNATURE,v,NULL) +# define PKCS7_get_detached(p) \ + PKCS7_ctrl(p,PKCS7_OP_GET_DETACHED_SIGNATURE,0,NULL) + +# define PKCS7_is_detached(p7) (PKCS7_type_is_signed(p7) && PKCS7_get_detached(p7)) + +/* S/MIME related flags */ + +# define PKCS7_TEXT 0x1 +# define PKCS7_NOCERTS 0x2 +# define PKCS7_NOSIGS 0x4 +# define PKCS7_NOCHAIN 0x8 +# define PKCS7_NOINTERN 0x10 +# define PKCS7_NOVERIFY 0x20 +# define PKCS7_DETACHED 0x40 +# define PKCS7_BINARY 0x80 +# define PKCS7_NOATTR 0x100 +# define PKCS7_NOSMIMECAP 0x200 +# define PKCS7_NOOLDMIMETYPE 0x400 +# define PKCS7_CRLFEOL 0x800 +# define PKCS7_STREAM 0x1000 +# define PKCS7_NOCRL 0x2000 +# define PKCS7_PARTIAL 0x4000 +# define PKCS7_REUSE_DIGEST 0x8000 +# define PKCS7_NO_DUAL_CONTENT 0x10000 + +/* Flags: for compatibility with older code */ + +# define SMIME_TEXT PKCS7_TEXT +# define SMIME_NOCERTS PKCS7_NOCERTS +# define SMIME_NOSIGS PKCS7_NOSIGS +# define SMIME_NOCHAIN PKCS7_NOCHAIN +# define SMIME_NOINTERN PKCS7_NOINTERN +# define SMIME_NOVERIFY PKCS7_NOVERIFY +# define SMIME_DETACHED PKCS7_DETACHED +# define SMIME_BINARY PKCS7_BINARY +# define SMIME_NOATTR PKCS7_NOATTR + +/* CRLF ASCII canonicalisation */ +# define SMIME_ASCIICRLF 0x80000 + +DECLARE_ASN1_FUNCTIONS(PKCS7_ISSUER_AND_SERIAL) + +int PKCS7_ISSUER_AND_SERIAL_digest(PKCS7_ISSUER_AND_SERIAL *data, + const EVP_MD *type, unsigned char *md, + unsigned int *len); +# ifndef OPENSSL_NO_STDIO +PKCS7 *d2i_PKCS7_fp(FILE *fp, PKCS7 **p7); +int i2d_PKCS7_fp(FILE *fp, PKCS7 *p7); +# endif +PKCS7 *PKCS7_dup(PKCS7 *p7); +PKCS7 *d2i_PKCS7_bio(BIO *bp, PKCS7 **p7); +int i2d_PKCS7_bio(BIO *bp, PKCS7 *p7); +int i2d_PKCS7_bio_stream(BIO *out, PKCS7 *p7, BIO *in, int flags); +int PEM_write_bio_PKCS7_stream(BIO *out, PKCS7 *p7, BIO *in, int flags); + +DECLARE_ASN1_FUNCTIONS(PKCS7_SIGNER_INFO) +DECLARE_ASN1_FUNCTIONS(PKCS7_RECIP_INFO) +DECLARE_ASN1_FUNCTIONS(PKCS7_SIGNED) +DECLARE_ASN1_FUNCTIONS(PKCS7_ENC_CONTENT) +DECLARE_ASN1_FUNCTIONS(PKCS7_ENVELOPE) +DECLARE_ASN1_FUNCTIONS(PKCS7_SIGN_ENVELOPE) +DECLARE_ASN1_FUNCTIONS(PKCS7_DIGEST) +DECLARE_ASN1_FUNCTIONS(PKCS7_ENCRYPT) +DECLARE_ASN1_FUNCTIONS(PKCS7) + +DECLARE_ASN1_ITEM(PKCS7_ATTR_SIGN) +DECLARE_ASN1_ITEM(PKCS7_ATTR_VERIFY) + +DECLARE_ASN1_NDEF_FUNCTION(PKCS7) +DECLARE_ASN1_PRINT_FUNCTION(PKCS7) + +long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg); + +int PKCS7_set_type(PKCS7 *p7, int type); +int PKCS7_set0_type_other(PKCS7 *p7, int type, ASN1_TYPE *other); +int PKCS7_set_content(PKCS7 *p7, PKCS7 *p7_data); +int PKCS7_SIGNER_INFO_set(PKCS7_SIGNER_INFO *p7i, X509 *x509, EVP_PKEY *pkey, + const EVP_MD *dgst); +int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si); +int PKCS7_add_signer(PKCS7 *p7, PKCS7_SIGNER_INFO *p7i); +int PKCS7_add_certificate(PKCS7 *p7, X509 *x509); +int PKCS7_add_crl(PKCS7 *p7, X509_CRL *x509); +int PKCS7_content_new(PKCS7 *p7, int nid); +int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx, + BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si); +int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si, + X509 *x509); + +BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio); +int PKCS7_dataFinal(PKCS7 *p7, BIO *bio); +BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert); + +PKCS7_SIGNER_INFO *PKCS7_add_signature(PKCS7 *p7, X509 *x509, + EVP_PKEY *pkey, const EVP_MD *dgst); +X509 *PKCS7_cert_from_signer_info(PKCS7 *p7, PKCS7_SIGNER_INFO *si); +int PKCS7_set_digest(PKCS7 *p7, const EVP_MD *md); +STACK_OF(PKCS7_SIGNER_INFO) *PKCS7_get_signer_info(PKCS7 *p7); + +PKCS7_RECIP_INFO *PKCS7_add_recipient(PKCS7 *p7, X509 *x509); +void PKCS7_SIGNER_INFO_get0_algs(PKCS7_SIGNER_INFO *si, EVP_PKEY **pk, + X509_ALGOR **pdig, X509_ALGOR **psig); +void PKCS7_RECIP_INFO_get0_alg(PKCS7_RECIP_INFO *ri, X509_ALGOR **penc); +int PKCS7_add_recipient_info(PKCS7 *p7, PKCS7_RECIP_INFO *ri); +int PKCS7_RECIP_INFO_set(PKCS7_RECIP_INFO *p7i, X509 *x509); +int PKCS7_set_cipher(PKCS7 *p7, const EVP_CIPHER *cipher); +int PKCS7_stream(unsigned char ***boundary, PKCS7 *p7); + +PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx); +ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk); +int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int type, + void *data); +int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype, + void *value); +ASN1_TYPE *PKCS7_get_attribute(PKCS7_SIGNER_INFO *si, int nid); +ASN1_TYPE *PKCS7_get_signed_attribute(PKCS7_SIGNER_INFO *si, int nid); +int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si, + STACK_OF(X509_ATTRIBUTE) *sk); +int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si, + STACK_OF(X509_ATTRIBUTE) *sk); + +PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, int flags); + +PKCS7_SIGNER_INFO *PKCS7_sign_add_signer(PKCS7 *p7, + X509 *signcert, EVP_PKEY *pkey, + const EVP_MD *md, int flags); + +int PKCS7_final(PKCS7 *p7, BIO *data, int flags); +int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store, + BIO *indata, BIO *out, int flags); +STACK_OF(X509) *PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs, + int flags); +PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher, + int flags); +int PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data, + int flags); + +int PKCS7_add_attrib_smimecap(PKCS7_SIGNER_INFO *si, + STACK_OF(X509_ALGOR) *cap); +STACK_OF(X509_ALGOR) *PKCS7_get_smimecap(PKCS7_SIGNER_INFO *si); +int PKCS7_simple_smimecap(STACK_OF(X509_ALGOR) *sk, int nid, int arg); + +int PKCS7_add_attrib_content_type(PKCS7_SIGNER_INFO *si, ASN1_OBJECT *coid); +int PKCS7_add0_attrib_signing_time(PKCS7_SIGNER_INFO *si, ASN1_TIME *t); +int PKCS7_add1_attrib_digest(PKCS7_SIGNER_INFO *si, + const unsigned char *md, int mdlen); + +int SMIME_write_PKCS7(BIO *bio, PKCS7 *p7, BIO *data, int flags); +PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont); + +BIO *BIO_new_PKCS7(BIO *out, PKCS7 *p7); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/pkcs7err.h b/include/openssl/pkcs7err.h new file mode 100644 index 0000000..0ba418d --- /dev/null +++ b/include/openssl/pkcs7err.h @@ -0,0 +1,99 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_PKCS7ERR_H +# define HEADER_PKCS7ERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_PKCS7_strings(void); + +/* + * PKCS7 function codes. + */ +# define PKCS7_F_DO_PKCS7_SIGNED_ATTRIB 136 +# define PKCS7_F_PKCS7_ADD0_ATTRIB_SIGNING_TIME 135 +# define PKCS7_F_PKCS7_ADD_ATTRIB_SMIMECAP 118 +# define PKCS7_F_PKCS7_ADD_CERTIFICATE 100 +# define PKCS7_F_PKCS7_ADD_CRL 101 +# define PKCS7_F_PKCS7_ADD_RECIPIENT_INFO 102 +# define PKCS7_F_PKCS7_ADD_SIGNATURE 131 +# define PKCS7_F_PKCS7_ADD_SIGNER 103 +# define PKCS7_F_PKCS7_BIO_ADD_DIGEST 125 +# define PKCS7_F_PKCS7_COPY_EXISTING_DIGEST 138 +# define PKCS7_F_PKCS7_CTRL 104 +# define PKCS7_F_PKCS7_DATADECODE 112 +# define PKCS7_F_PKCS7_DATAFINAL 128 +# define PKCS7_F_PKCS7_DATAINIT 105 +# define PKCS7_F_PKCS7_DATAVERIFY 107 +# define PKCS7_F_PKCS7_DECRYPT 114 +# define PKCS7_F_PKCS7_DECRYPT_RINFO 133 +# define PKCS7_F_PKCS7_ENCODE_RINFO 132 +# define PKCS7_F_PKCS7_ENCRYPT 115 +# define PKCS7_F_PKCS7_FINAL 134 +# define PKCS7_F_PKCS7_FIND_DIGEST 127 +# define PKCS7_F_PKCS7_GET0_SIGNERS 124 +# define PKCS7_F_PKCS7_RECIP_INFO_SET 130 +# define PKCS7_F_PKCS7_SET_CIPHER 108 +# define PKCS7_F_PKCS7_SET_CONTENT 109 +# define PKCS7_F_PKCS7_SET_DIGEST 126 +# define PKCS7_F_PKCS7_SET_TYPE 110 +# define PKCS7_F_PKCS7_SIGN 116 +# define PKCS7_F_PKCS7_SIGNATUREVERIFY 113 +# define PKCS7_F_PKCS7_SIGNER_INFO_SET 129 +# define PKCS7_F_PKCS7_SIGNER_INFO_SIGN 139 +# define PKCS7_F_PKCS7_SIGN_ADD_SIGNER 137 +# define PKCS7_F_PKCS7_SIMPLE_SMIMECAP 119 +# define PKCS7_F_PKCS7_VERIFY 117 + +/* + * PKCS7 reason codes. + */ +# define PKCS7_R_CERTIFICATE_VERIFY_ERROR 117 +# define PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER 144 +# define PKCS7_R_CIPHER_NOT_INITIALIZED 116 +# define PKCS7_R_CONTENT_AND_DATA_PRESENT 118 +# define PKCS7_R_CTRL_ERROR 152 +# define PKCS7_R_DECRYPT_ERROR 119 +# define PKCS7_R_DIGEST_FAILURE 101 +# define PKCS7_R_ENCRYPTION_CTRL_FAILURE 149 +# define PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 150 +# define PKCS7_R_ERROR_ADDING_RECIPIENT 120 +# define PKCS7_R_ERROR_SETTING_CIPHER 121 +# define PKCS7_R_INVALID_NULL_POINTER 143 +# define PKCS7_R_INVALID_SIGNED_DATA_TYPE 155 +# define PKCS7_R_NO_CONTENT 122 +# define PKCS7_R_NO_DEFAULT_DIGEST 151 +# define PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND 154 +# define PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE 115 +# define PKCS7_R_NO_SIGNATURES_ON_DATA 123 +# define PKCS7_R_NO_SIGNERS 142 +# define PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE 104 +# define PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR 124 +# define PKCS7_R_PKCS7_ADD_SIGNER_ERROR 153 +# define PKCS7_R_PKCS7_DATASIGN 145 +# define PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 127 +# define PKCS7_R_SIGNATURE_FAILURE 105 +# define PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND 128 +# define PKCS7_R_SIGNING_CTRL_FAILURE 147 +# define PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 148 +# define PKCS7_R_SMIME_TEXT_ERROR 129 +# define PKCS7_R_UNABLE_TO_FIND_CERTIFICATE 106 +# define PKCS7_R_UNABLE_TO_FIND_MEM_BIO 107 +# define PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST 108 +# define PKCS7_R_UNKNOWN_DIGEST_TYPE 109 +# define PKCS7_R_UNKNOWN_OPERATION 110 +# define PKCS7_R_UNSUPPORTED_CIPHER_TYPE 111 +# define PKCS7_R_UNSUPPORTED_CONTENT_TYPE 112 +# define PKCS7_R_WRONG_CONTENT_TYPE 113 +# define PKCS7_R_WRONG_PKCS7_TYPE 114 + +#endif diff --git a/include/openssl/rand.h b/include/openssl/rand.h new file mode 100644 index 0000000..3f80276 --- /dev/null +++ b/include/openssl/rand.h @@ -0,0 +1,77 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RAND_H +# define HEADER_RAND_H + +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +struct rand_meth_st { + int (*seed) (const void *buf, int num); + int (*bytes) (unsigned char *buf, int num); + void (*cleanup) (void); + int (*add) (const void *buf, int num, double randomness); + int (*pseudorand) (unsigned char *buf, int num); + int (*status) (void); +}; + +int RAND_set_rand_method(const RAND_METHOD *meth); +const RAND_METHOD *RAND_get_rand_method(void); +# ifndef OPENSSL_NO_ENGINE +int RAND_set_rand_engine(ENGINE *engine); +# endif + +RAND_METHOD *RAND_OpenSSL(void); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define RAND_cleanup() while(0) continue +# endif +int RAND_bytes(unsigned char *buf, int num); +int RAND_priv_bytes(unsigned char *buf, int num); +DEPRECATEDIN_1_1_0(int RAND_pseudo_bytes(unsigned char *buf, int num)) + +void RAND_seed(const void *buf, int num); +void RAND_keep_random_devices_open(int keep); + +# if defined(__ANDROID__) && defined(__NDK_FPABI__) +__NDK_FPABI__ /* __attribute__((pcs("aapcs"))) on ARM */ +# endif +void RAND_add(const void *buf, int num, double randomness); +int RAND_load_file(const char *file, long max_bytes); +int RAND_write_file(const char *file); +const char *RAND_file_name(char *file, size_t num); +int RAND_status(void); + +# ifndef OPENSSL_NO_EGD +int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes); +int RAND_egd(const char *path); +int RAND_egd_bytes(const char *path, int bytes); +# endif + +int RAND_poll(void); + +# if defined(_WIN32) && (defined(BASETYPES) || defined(_WINDEF_H)) +/* application has to include in order to use these */ +DEPRECATEDIN_1_1_0(void RAND_screen(void)) +DEPRECATEDIN_1_1_0(int RAND_event(UINT, WPARAM, LPARAM)) +# endif + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/rand_drbg.h b/include/openssl/rand_drbg.h new file mode 100644 index 0000000..34aea6f --- /dev/null +++ b/include/openssl/rand_drbg.h @@ -0,0 +1,120 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DRBG_RAND_H +# define HEADER_DRBG_RAND_H + +# include +# include + + +/* In CTR mode, disable derivation function ctr_df */ +# define RAND_DRBG_FLAG_CTR_NO_DF 0x1 + +/* A logical OR of all used flag bits (currently there is only one) */ +# define RAND_DRBG_USED_FLAGS ( \ + RAND_DRBG_FLAG_CTR_NO_DF \ + ) + +/* + * Default security strength (in the sense of [NIST SP 800-90Ar1]) + * + * NIST SP 800-90Ar1 supports the strength of the DRBG being smaller than that + * of the cipher by collecting less entropy. The current DRBG implemantion does + * not take RAND_DRBG_STRENGTH into account and sets the strength of the DRBG + * to that of the cipher. + * + * RAND_DRBG_STRENGTH is currently only used for the legacy RAND + * implementation. + * + * Currently supported ciphers are: NID_aes_128_ctr, NID_aes_192_ctr and + * NID_aes_256_ctr + */ +# define RAND_DRBG_STRENGTH 256 +# define RAND_DRBG_TYPE NID_aes_256_ctr +# define RAND_DRBG_FLAGS 0 + + +# ifdef __cplusplus +extern "C" { +# endif + +/* + * Object lifetime functions. + */ +RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent); +RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent); +int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags); +int RAND_DRBG_set_defaults(int type, unsigned int flags); +int RAND_DRBG_instantiate(RAND_DRBG *drbg, + const unsigned char *pers, size_t perslen); +int RAND_DRBG_uninstantiate(RAND_DRBG *drbg); +void RAND_DRBG_free(RAND_DRBG *drbg); + +/* + * Object "use" functions. + */ +int RAND_DRBG_reseed(RAND_DRBG *drbg, + const unsigned char *adin, size_t adinlen, + int prediction_resistance); +int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen, + int prediction_resistance, + const unsigned char *adin, size_t adinlen); +int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen); + +int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval); +int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval); + +int RAND_DRBG_set_reseed_defaults( + unsigned int master_reseed_interval, + unsigned int slave_reseed_interval, + time_t master_reseed_time_interval, + time_t slave_reseed_time_interval + ); + +RAND_DRBG *RAND_DRBG_get0_master(void); +RAND_DRBG *RAND_DRBG_get0_public(void); +RAND_DRBG *RAND_DRBG_get0_private(void); + +/* + * EXDATA + */ +# define RAND_DRBG_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_DRBG, l, p, newf, dupf, freef) +int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg); +void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx); + +/* + * Callback function typedefs + */ +typedef size_t (*RAND_DRBG_get_entropy_fn)(RAND_DRBG *drbg, + unsigned char **pout, + int entropy, size_t min_len, + size_t max_len, + int prediction_resistance); +typedef void (*RAND_DRBG_cleanup_entropy_fn)(RAND_DRBG *ctx, + unsigned char *out, size_t outlen); +typedef size_t (*RAND_DRBG_get_nonce_fn)(RAND_DRBG *drbg, unsigned char **pout, + int entropy, size_t min_len, + size_t max_len); +typedef void (*RAND_DRBG_cleanup_nonce_fn)(RAND_DRBG *drbg, + unsigned char *out, size_t outlen); + +int RAND_DRBG_set_callbacks(RAND_DRBG *drbg, + RAND_DRBG_get_entropy_fn get_entropy, + RAND_DRBG_cleanup_entropy_fn cleanup_entropy, + RAND_DRBG_get_nonce_fn get_nonce, + RAND_DRBG_cleanup_nonce_fn cleanup_nonce); + + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/include/openssl/randerr.h b/include/openssl/randerr.h new file mode 100644 index 0000000..128f4de --- /dev/null +++ b/include/openssl/randerr.h @@ -0,0 +1,88 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RANDERR_H +# define HEADER_RANDERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_RAND_strings(void); + +/* + * RAND function codes. + */ +# define RAND_F_DRBG_BYTES 101 +# define RAND_F_DRBG_GET_ENTROPY 105 +# define RAND_F_DRBG_SETUP 117 +# define RAND_F_GET_ENTROPY 106 +# define RAND_F_RAND_BYTES 100 +# define RAND_F_RAND_DRBG_ENABLE_LOCKING 119 +# define RAND_F_RAND_DRBG_GENERATE 107 +# define RAND_F_RAND_DRBG_GET_ENTROPY 120 +# define RAND_F_RAND_DRBG_GET_NONCE 123 +# define RAND_F_RAND_DRBG_INSTANTIATE 108 +# define RAND_F_RAND_DRBG_NEW 109 +# define RAND_F_RAND_DRBG_RESEED 110 +# define RAND_F_RAND_DRBG_RESTART 102 +# define RAND_F_RAND_DRBG_SET 104 +# define RAND_F_RAND_DRBG_SET_DEFAULTS 121 +# define RAND_F_RAND_DRBG_UNINSTANTIATE 118 +# define RAND_F_RAND_LOAD_FILE 111 +# define RAND_F_RAND_POOL_ACQUIRE_ENTROPY 122 +# define RAND_F_RAND_POOL_ADD 103 +# define RAND_F_RAND_POOL_ADD_BEGIN 113 +# define RAND_F_RAND_POOL_ADD_END 114 +# define RAND_F_RAND_POOL_BYTES_NEEDED 115 +# define RAND_F_RAND_POOL_NEW 116 +# define RAND_F_RAND_WRITE_FILE 112 + +/* + * RAND reason codes. + */ +# define RAND_R_ADDITIONAL_INPUT_TOO_LONG 102 +# define RAND_R_ALREADY_INSTANTIATED 103 +# define RAND_R_ARGUMENT_OUT_OF_RANGE 105 +# define RAND_R_CANNOT_OPEN_FILE 121 +# define RAND_R_DRBG_ALREADY_INITIALIZED 129 +# define RAND_R_DRBG_NOT_INITIALISED 104 +# define RAND_R_ENTROPY_INPUT_TOO_LONG 106 +# define RAND_R_ENTROPY_OUT_OF_RANGE 124 +# define RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED 127 +# define RAND_R_ERROR_INITIALISING_DRBG 107 +# define RAND_R_ERROR_INSTANTIATING_DRBG 108 +# define RAND_R_ERROR_RETRIEVING_ADDITIONAL_INPUT 109 +# define RAND_R_ERROR_RETRIEVING_ENTROPY 110 +# define RAND_R_ERROR_RETRIEVING_NONCE 111 +# define RAND_R_FAILED_TO_CREATE_LOCK 126 +# define RAND_R_FUNC_NOT_IMPLEMENTED 101 +# define RAND_R_FWRITE_ERROR 123 +# define RAND_R_GENERATE_ERROR 112 +# define RAND_R_INTERNAL_ERROR 113 +# define RAND_R_IN_ERROR_STATE 114 +# define RAND_R_NOT_A_REGULAR_FILE 122 +# define RAND_R_NOT_INSTANTIATED 115 +# define RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED 128 +# define RAND_R_PARENT_LOCKING_NOT_ENABLED 130 +# define RAND_R_PARENT_STRENGTH_TOO_WEAK 131 +# define RAND_R_PERSONALISATION_STRING_TOO_LONG 116 +# define RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED 133 +# define RAND_R_PRNG_NOT_SEEDED 100 +# define RAND_R_RANDOM_POOL_OVERFLOW 125 +# define RAND_R_RANDOM_POOL_UNDERFLOW 134 +# define RAND_R_REQUEST_TOO_LARGE_FOR_DRBG 117 +# define RAND_R_RESEED_ERROR 118 +# define RAND_R_SELFTEST_FAILURE 119 +# define RAND_R_TOO_LITTLE_NONCE_REQUESTED 135 +# define RAND_R_TOO_MUCH_NONCE_REQUESTED 136 +# define RAND_R_UNSUPPORTED_DRBG_FLAGS 132 +# define RAND_R_UNSUPPORTED_DRBG_TYPE 120 + +#endif diff --git a/include/openssl/rc2.h b/include/openssl/rc2.h new file mode 100644 index 0000000..6046ac5 --- /dev/null +++ b/include/openssl/rc2.h @@ -0,0 +1,51 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RC2_H +# define HEADER_RC2_H + +# include + +# ifndef OPENSSL_NO_RC2 +# ifdef __cplusplus +extern "C" { +# endif + +typedef unsigned int RC2_INT; + +# define RC2_ENCRYPT 1 +# define RC2_DECRYPT 0 + +# define RC2_BLOCK 8 +# define RC2_KEY_LENGTH 16 + +typedef struct rc2_key_st { + RC2_INT data[64]; +} RC2_KEY; + +void RC2_set_key(RC2_KEY *key, int len, const unsigned char *data, int bits); +void RC2_ecb_encrypt(const unsigned char *in, unsigned char *out, + RC2_KEY *key, int enc); +void RC2_encrypt(unsigned long *data, RC2_KEY *key); +void RC2_decrypt(unsigned long *data, RC2_KEY *key); +void RC2_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, + RC2_KEY *ks, unsigned char *iv, int enc); +void RC2_cfb64_encrypt(const unsigned char *in, unsigned char *out, + long length, RC2_KEY *schedule, unsigned char *ivec, + int *num, int enc); +void RC2_ofb64_encrypt(const unsigned char *in, unsigned char *out, + long length, RC2_KEY *schedule, unsigned char *ivec, + int *num); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/rc4.h b/include/openssl/rc4.h new file mode 100644 index 0000000..a0b3206 --- /dev/null +++ b/include/openssl/rc4.h @@ -0,0 +1,36 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RC4_H +# define HEADER_RC4_H + +# include + +# ifndef OPENSSL_NO_RC4 +# include +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct rc4_key_st { + RC4_INT x, y; + RC4_INT data[256]; +} RC4_KEY; + +const char *RC4_options(void); +void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data); +void RC4(RC4_KEY *key, size_t len, const unsigned char *indata, + unsigned char *outdata); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/rc5.h b/include/openssl/rc5.h new file mode 100644 index 0000000..a64f6ba --- /dev/null +++ b/include/openssl/rc5.h @@ -0,0 +1,63 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RC5_H +# define HEADER_RC5_H + +# include + +# ifndef OPENSSL_NO_RC5 +# ifdef __cplusplus +extern "C" { +# endif + +# define RC5_ENCRYPT 1 +# define RC5_DECRYPT 0 + +# define RC5_32_INT unsigned int + +# define RC5_32_BLOCK 8 +# define RC5_32_KEY_LENGTH 16/* This is a default, max is 255 */ + +/* + * This are the only values supported. Tweak the code if you want more The + * most supported modes will be RC5-32/12/16 RC5-32/16/8 + */ +# define RC5_8_ROUNDS 8 +# define RC5_12_ROUNDS 12 +# define RC5_16_ROUNDS 16 + +typedef struct rc5_key_st { + /* Number of rounds */ + int rounds; + RC5_32_INT data[2 * (RC5_16_ROUNDS + 1)]; +} RC5_32_KEY; + +void RC5_32_set_key(RC5_32_KEY *key, int len, const unsigned char *data, + int rounds); +void RC5_32_ecb_encrypt(const unsigned char *in, unsigned char *out, + RC5_32_KEY *key, int enc); +void RC5_32_encrypt(unsigned long *data, RC5_32_KEY *key); +void RC5_32_decrypt(unsigned long *data, RC5_32_KEY *key); +void RC5_32_cbc_encrypt(const unsigned char *in, unsigned char *out, + long length, RC5_32_KEY *ks, unsigned char *iv, + int enc); +void RC5_32_cfb64_encrypt(const unsigned char *in, unsigned char *out, + long length, RC5_32_KEY *schedule, + unsigned char *ivec, int *num, int enc); +void RC5_32_ofb64_encrypt(const unsigned char *in, unsigned char *out, + long length, RC5_32_KEY *schedule, + unsigned char *ivec, int *num); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/ripemd.h b/include/openssl/ripemd.h new file mode 100644 index 0000000..fa87102 --- /dev/null +++ b/include/openssl/ripemd.h @@ -0,0 +1,47 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RIPEMD_H +# define HEADER_RIPEMD_H + +# include + +#ifndef OPENSSL_NO_RMD160 +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +# define RIPEMD160_LONG unsigned int + +# define RIPEMD160_CBLOCK 64 +# define RIPEMD160_LBLOCK (RIPEMD160_CBLOCK/4) +# define RIPEMD160_DIGEST_LENGTH 20 + +typedef struct RIPEMD160state_st { + RIPEMD160_LONG A, B, C, D, E; + RIPEMD160_LONG Nl, Nh; + RIPEMD160_LONG data[RIPEMD160_LBLOCK]; + unsigned int num; +} RIPEMD160_CTX; + +int RIPEMD160_Init(RIPEMD160_CTX *c); +int RIPEMD160_Update(RIPEMD160_CTX *c, const void *data, size_t len); +int RIPEMD160_Final(unsigned char *md, RIPEMD160_CTX *c); +unsigned char *RIPEMD160(const unsigned char *d, size_t n, unsigned char *md); +void RIPEMD160_Transform(RIPEMD160_CTX *c, const unsigned char *b); + +# ifdef __cplusplus +} +# endif +# endif + + +#endif diff --git a/include/openssl/rsa.h b/include/openssl/rsa.h new file mode 100644 index 0000000..354d4db --- /dev/null +++ b/include/openssl/rsa.h @@ -0,0 +1,512 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RSA_H +# define HEADER_RSA_H + +# include + +# ifndef OPENSSL_NO_RSA +# include +# include +# include +# include +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# endif +# include +# ifdef __cplusplus +extern "C" { +# endif + +/* The types RSA and RSA_METHOD are defined in ossl_typ.h */ + +# ifndef OPENSSL_RSA_MAX_MODULUS_BITS +# define OPENSSL_RSA_MAX_MODULUS_BITS 16384 +# endif + +# define OPENSSL_RSA_FIPS_MIN_MODULUS_BITS 1024 + +# ifndef OPENSSL_RSA_SMALL_MODULUS_BITS +# define OPENSSL_RSA_SMALL_MODULUS_BITS 3072 +# endif +# ifndef OPENSSL_RSA_MAX_PUBEXP_BITS + +/* exponent limit enforced for "large" modulus only */ +# define OPENSSL_RSA_MAX_PUBEXP_BITS 64 +# endif + +# define RSA_3 0x3L +# define RSA_F4 0x10001L + +/* based on RFC 8017 appendix A.1.2 */ +# define RSA_ASN1_VERSION_DEFAULT 0 +# define RSA_ASN1_VERSION_MULTI 1 + +# define RSA_DEFAULT_PRIME_NUM 2 + +# define RSA_METHOD_FLAG_NO_CHECK 0x0001/* don't check pub/private + * match */ + +# define RSA_FLAG_CACHE_PUBLIC 0x0002 +# define RSA_FLAG_CACHE_PRIVATE 0x0004 +# define RSA_FLAG_BLINDING 0x0008 +# define RSA_FLAG_THREAD_SAFE 0x0010 +/* + * This flag means the private key operations will be handled by rsa_mod_exp + * and that they do not depend on the private key components being present: + * for example a key stored in external hardware. Without this flag + * bn_mod_exp gets called when private key components are absent. + */ +# define RSA_FLAG_EXT_PKEY 0x0020 + +/* + * new with 0.9.6j and 0.9.7b; the built-in + * RSA implementation now uses blinding by + * default (ignoring RSA_FLAG_BLINDING), + * but other engines might not need it + */ +# define RSA_FLAG_NO_BLINDING 0x0080 +# if OPENSSL_API_COMPAT < 0x10100000L +/* + * Does nothing. Previously this switched off constant time behaviour. + */ +# define RSA_FLAG_NO_CONSTTIME 0x0000 +# endif +# if OPENSSL_API_COMPAT < 0x00908000L +/* deprecated name for the flag*/ +/* + * new with 0.9.7h; the built-in RSA + * implementation now uses constant time + * modular exponentiation for secret exponents + * by default. This flag causes the + * faster variable sliding window method to + * be used for all exponents. + */ +# define RSA_FLAG_NO_EXP_CONSTTIME RSA_FLAG_NO_CONSTTIME +# endif + +# define EVP_PKEY_CTX_set_rsa_padding(ctx, pad) \ + RSA_pkey_ctx_ctrl(ctx, -1, EVP_PKEY_CTRL_RSA_PADDING, pad, NULL) + +# define EVP_PKEY_CTX_get_rsa_padding(ctx, ppad) \ + RSA_pkey_ctx_ctrl(ctx, -1, EVP_PKEY_CTRL_GET_RSA_PADDING, 0, ppad) + +# define EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, len) \ + RSA_pkey_ctx_ctrl(ctx, (EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY), \ + EVP_PKEY_CTRL_RSA_PSS_SALTLEN, len, NULL) +/* Salt length matches digest */ +# define RSA_PSS_SALTLEN_DIGEST -1 +/* Verify only: auto detect salt length */ +# define RSA_PSS_SALTLEN_AUTO -2 +/* Set salt length to maximum possible */ +# define RSA_PSS_SALTLEN_MAX -3 +/* Old compatible max salt length for sign only */ +# define RSA_PSS_SALTLEN_MAX_SIGN -2 + +# define EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(ctx, len) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_RSA_PSS_SALTLEN, len, NULL) + +# define EVP_PKEY_CTX_get_rsa_pss_saltlen(ctx, plen) \ + RSA_pkey_ctx_ctrl(ctx, (EVP_PKEY_OP_SIGN|EVP_PKEY_OP_VERIFY), \ + EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN, 0, plen) + +# define EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, bits) \ + RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_RSA_KEYGEN_BITS, bits, NULL) + +# define EVP_PKEY_CTX_set_rsa_keygen_pubexp(ctx, pubexp) \ + RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP, 0, pubexp) + +# define EVP_PKEY_CTX_set_rsa_keygen_primes(ctx, primes) \ + RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_RSA_KEYGEN_PRIMES, primes, NULL) + +# define EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, md) \ + RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, \ + EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(ctx, md) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA_PSS, EVP_PKEY_OP_KEYGEN, \ + EVP_PKEY_CTRL_RSA_MGF1_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_set_rsa_oaep_md(ctx, md) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \ + EVP_PKEY_CTRL_RSA_OAEP_MD, 0, (void *)(md)) + +# define EVP_PKEY_CTX_get_rsa_mgf1_md(ctx, pmd) \ + RSA_pkey_ctx_ctrl(ctx, EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, \ + EVP_PKEY_CTRL_GET_RSA_MGF1_MD, 0, (void *)(pmd)) + +# define EVP_PKEY_CTX_get_rsa_oaep_md(ctx, pmd) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \ + EVP_PKEY_CTRL_GET_RSA_OAEP_MD, 0, (void *)(pmd)) + +# define EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, l, llen) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \ + EVP_PKEY_CTRL_RSA_OAEP_LABEL, llen, (void *)(l)) + +# define EVP_PKEY_CTX_get0_rsa_oaep_label(ctx, l) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA, EVP_PKEY_OP_TYPE_CRYPT, \ + EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL, 0, (void *)(l)) + +# define EVP_PKEY_CTX_set_rsa_pss_keygen_md(ctx, md) \ + EVP_PKEY_CTX_ctrl(ctx, EVP_PKEY_RSA_PSS, \ + EVP_PKEY_OP_TYPE_KEYGEN, EVP_PKEY_CTRL_MD, \ + 0, (void *)(md)) + +# define EVP_PKEY_CTRL_RSA_PADDING (EVP_PKEY_ALG_CTRL + 1) +# define EVP_PKEY_CTRL_RSA_PSS_SALTLEN (EVP_PKEY_ALG_CTRL + 2) + +# define EVP_PKEY_CTRL_RSA_KEYGEN_BITS (EVP_PKEY_ALG_CTRL + 3) +# define EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP (EVP_PKEY_ALG_CTRL + 4) +# define EVP_PKEY_CTRL_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 5) + +# define EVP_PKEY_CTRL_GET_RSA_PADDING (EVP_PKEY_ALG_CTRL + 6) +# define EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN (EVP_PKEY_ALG_CTRL + 7) +# define EVP_PKEY_CTRL_GET_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 8) + +# define EVP_PKEY_CTRL_RSA_OAEP_MD (EVP_PKEY_ALG_CTRL + 9) +# define EVP_PKEY_CTRL_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 10) + +# define EVP_PKEY_CTRL_GET_RSA_OAEP_MD (EVP_PKEY_ALG_CTRL + 11) +# define EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 12) + +# define EVP_PKEY_CTRL_RSA_KEYGEN_PRIMES (EVP_PKEY_ALG_CTRL + 13) + +# define RSA_PKCS1_PADDING 1 +# define RSA_SSLV23_PADDING 2 +# define RSA_NO_PADDING 3 +# define RSA_PKCS1_OAEP_PADDING 4 +# define RSA_X931_PADDING 5 +/* EVP_PKEY_ only */ +# define RSA_PKCS1_PSS_PADDING 6 + +# define RSA_PKCS1_PADDING_SIZE 11 + +# define RSA_set_app_data(s,arg) RSA_set_ex_data(s,0,arg) +# define RSA_get_app_data(s) RSA_get_ex_data(s,0) + +RSA *RSA_new(void); +RSA *RSA_new_method(ENGINE *engine); +int RSA_bits(const RSA *rsa); +int RSA_size(const RSA *rsa); +int RSA_security_bits(const RSA *rsa); + +int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d); +int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q); +int RSA_set0_crt_params(RSA *r,BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp); +int RSA_set0_multi_prime_params(RSA *r, BIGNUM *primes[], BIGNUM *exps[], + BIGNUM *coeffs[], int pnum); +void RSA_get0_key(const RSA *r, + const BIGNUM **n, const BIGNUM **e, const BIGNUM **d); +void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q); +int RSA_get_multi_prime_extra_count(const RSA *r); +int RSA_get0_multi_prime_factors(const RSA *r, const BIGNUM *primes[]); +void RSA_get0_crt_params(const RSA *r, + const BIGNUM **dmp1, const BIGNUM **dmq1, + const BIGNUM **iqmp); +int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[], + const BIGNUM *coeffs[]); +const BIGNUM *RSA_get0_n(const RSA *d); +const BIGNUM *RSA_get0_e(const RSA *d); +const BIGNUM *RSA_get0_d(const RSA *d); +const BIGNUM *RSA_get0_p(const RSA *d); +const BIGNUM *RSA_get0_q(const RSA *d); +const BIGNUM *RSA_get0_dmp1(const RSA *r); +const BIGNUM *RSA_get0_dmq1(const RSA *r); +const BIGNUM *RSA_get0_iqmp(const RSA *r); +void RSA_clear_flags(RSA *r, int flags); +int RSA_test_flags(const RSA *r, int flags); +void RSA_set_flags(RSA *r, int flags); +int RSA_get_version(RSA *r); +ENGINE *RSA_get0_engine(const RSA *r); + +/* Deprecated version */ +DEPRECATEDIN_0_9_8(RSA *RSA_generate_key(int bits, unsigned long e, void + (*callback) (int, int, void *), + void *cb_arg)) + +/* New version */ +int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); +/* Multi-prime version */ +int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes, + BIGNUM *e, BN_GENCB *cb); + +int RSA_X931_derive_ex(RSA *rsa, BIGNUM *p1, BIGNUM *p2, BIGNUM *q1, + BIGNUM *q2, const BIGNUM *Xp1, const BIGNUM *Xp2, + const BIGNUM *Xp, const BIGNUM *Xq1, const BIGNUM *Xq2, + const BIGNUM *Xq, const BIGNUM *e, BN_GENCB *cb); +int RSA_X931_generate_key_ex(RSA *rsa, int bits, const BIGNUM *e, + BN_GENCB *cb); + +int RSA_check_key(const RSA *); +int RSA_check_key_ex(const RSA *, BN_GENCB *cb); + /* next 4 return -1 on error */ +int RSA_public_encrypt(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +int RSA_private_encrypt(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +int RSA_public_decrypt(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +int RSA_private_decrypt(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +void RSA_free(RSA *r); +/* "up" the RSA object's reference count */ +int RSA_up_ref(RSA *r); + +int RSA_flags(const RSA *r); + +void RSA_set_default_method(const RSA_METHOD *meth); +const RSA_METHOD *RSA_get_default_method(void); +const RSA_METHOD *RSA_null_method(void); +const RSA_METHOD *RSA_get_method(const RSA *rsa); +int RSA_set_method(RSA *rsa, const RSA_METHOD *meth); + +/* these are the actual RSA functions */ +const RSA_METHOD *RSA_PKCS1_OpenSSL(void); + +int RSA_pkey_ctx_ctrl(EVP_PKEY_CTX *ctx, int optype, int cmd, int p1, void *p2); + +DECLARE_ASN1_ENCODE_FUNCTIONS_const(RSA, RSAPublicKey) +DECLARE_ASN1_ENCODE_FUNCTIONS_const(RSA, RSAPrivateKey) + +typedef struct rsa_pss_params_st { + X509_ALGOR *hashAlgorithm; + X509_ALGOR *maskGenAlgorithm; + ASN1_INTEGER *saltLength; + ASN1_INTEGER *trailerField; + /* Decoded hash algorithm from maskGenAlgorithm */ + X509_ALGOR *maskHash; +} RSA_PSS_PARAMS; + +DECLARE_ASN1_FUNCTIONS(RSA_PSS_PARAMS) + +typedef struct rsa_oaep_params_st { + X509_ALGOR *hashFunc; + X509_ALGOR *maskGenFunc; + X509_ALGOR *pSourceFunc; + /* Decoded hash algorithm from maskGenFunc */ + X509_ALGOR *maskHash; +} RSA_OAEP_PARAMS; + +DECLARE_ASN1_FUNCTIONS(RSA_OAEP_PARAMS) + +# ifndef OPENSSL_NO_STDIO +int RSA_print_fp(FILE *fp, const RSA *r, int offset); +# endif + +int RSA_print(BIO *bp, const RSA *r, int offset); + +/* + * The following 2 functions sign and verify a X509_SIG ASN1 object inside + * PKCS#1 padded RSA encryption + */ +int RSA_sign(int type, const unsigned char *m, unsigned int m_length, + unsigned char *sigret, unsigned int *siglen, RSA *rsa); +int RSA_verify(int type, const unsigned char *m, unsigned int m_length, + const unsigned char *sigbuf, unsigned int siglen, RSA *rsa); + +/* + * The following 2 function sign and verify a ASN1_OCTET_STRING object inside + * PKCS#1 padded RSA encryption + */ +int RSA_sign_ASN1_OCTET_STRING(int type, + const unsigned char *m, unsigned int m_length, + unsigned char *sigret, unsigned int *siglen, + RSA *rsa); +int RSA_verify_ASN1_OCTET_STRING(int type, const unsigned char *m, + unsigned int m_length, unsigned char *sigbuf, + unsigned int siglen, RSA *rsa); + +int RSA_blinding_on(RSA *rsa, BN_CTX *ctx); +void RSA_blinding_off(RSA *rsa); +BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *ctx); + +int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, + const unsigned char *f, int fl); +int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, + const unsigned char *f, int fl, + int rsa_len); +int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, + const unsigned char *f, int fl); +int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen, + const unsigned char *f, int fl, + int rsa_len); +int PKCS1_MGF1(unsigned char *mask, long len, const unsigned char *seed, + long seedlen, const EVP_MD *dgst); +int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen, + const unsigned char *f, int fl, + const unsigned char *p, int pl); +int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen, + const unsigned char *f, int fl, int rsa_len, + const unsigned char *p, int pl); +int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, + const unsigned char *from, int flen, + const unsigned char *param, int plen, + const EVP_MD *md, const EVP_MD *mgf1md); +int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, + const unsigned char *from, int flen, + int num, const unsigned char *param, + int plen, const EVP_MD *md, + const EVP_MD *mgf1md); +int RSA_padding_add_SSLv23(unsigned char *to, int tlen, + const unsigned char *f, int fl); +int RSA_padding_check_SSLv23(unsigned char *to, int tlen, + const unsigned char *f, int fl, int rsa_len); +int RSA_padding_add_none(unsigned char *to, int tlen, const unsigned char *f, + int fl); +int RSA_padding_check_none(unsigned char *to, int tlen, + const unsigned char *f, int fl, int rsa_len); +int RSA_padding_add_X931(unsigned char *to, int tlen, const unsigned char *f, + int fl); +int RSA_padding_check_X931(unsigned char *to, int tlen, + const unsigned char *f, int fl, int rsa_len); +int RSA_X931_hash_id(int nid); + +int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash, + const EVP_MD *Hash, const unsigned char *EM, + int sLen); +int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM, + const unsigned char *mHash, const EVP_MD *Hash, + int sLen); + +int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, + const EVP_MD *Hash, const EVP_MD *mgf1Hash, + const unsigned char *EM, int sLen); + +int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM, + const unsigned char *mHash, + const EVP_MD *Hash, const EVP_MD *mgf1Hash, + int sLen); + +#define RSA_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_RSA, l, p, newf, dupf, freef) +int RSA_set_ex_data(RSA *r, int idx, void *arg); +void *RSA_get_ex_data(const RSA *r, int idx); + +RSA *RSAPublicKey_dup(RSA *rsa); +RSA *RSAPrivateKey_dup(RSA *rsa); + +/* + * If this flag is set the RSA method is FIPS compliant and can be used in + * FIPS mode. This is set in the validated module method. If an application + * sets this flag in its own methods it is its responsibility to ensure the + * result is compliant. + */ + +# define RSA_FLAG_FIPS_METHOD 0x0400 + +/* + * If this flag is set the operations normally disabled in FIPS mode are + * permitted it is then the applications responsibility to ensure that the + * usage is compliant. + */ + +# define RSA_FLAG_NON_FIPS_ALLOW 0x0400 +/* + * Application has decided PRNG is good enough to generate a key: don't + * check. + */ +# define RSA_FLAG_CHECKED 0x0800 + +RSA_METHOD *RSA_meth_new(const char *name, int flags); +void RSA_meth_free(RSA_METHOD *meth); +RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth); +const char *RSA_meth_get0_name(const RSA_METHOD *meth); +int RSA_meth_set1_name(RSA_METHOD *meth, const char *name); +int RSA_meth_get_flags(const RSA_METHOD *meth); +int RSA_meth_set_flags(RSA_METHOD *meth, int flags); +void *RSA_meth_get0_app_data(const RSA_METHOD *meth); +int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data); +int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth)) + (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +int RSA_meth_set_pub_enc(RSA_METHOD *rsa, + int (*pub_enc) (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding)); +int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth)) + (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +int RSA_meth_set_pub_dec(RSA_METHOD *rsa, + int (*pub_dec) (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding)); +int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth)) + (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +int RSA_meth_set_priv_enc(RSA_METHOD *rsa, + int (*priv_enc) (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding)); +int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth)) + (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); +int RSA_meth_set_priv_dec(RSA_METHOD *rsa, + int (*priv_dec) (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding)); +int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth)) + (BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); +int RSA_meth_set_mod_exp(RSA_METHOD *rsa, + int (*mod_exp) (BIGNUM *r0, const BIGNUM *I, RSA *rsa, + BN_CTX *ctx)); +int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth)) + (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); +int RSA_meth_set_bn_mod_exp(RSA_METHOD *rsa, + int (*bn_mod_exp) (BIGNUM *r, + const BIGNUM *a, + const BIGNUM *p, + const BIGNUM *m, + BN_CTX *ctx, + BN_MONT_CTX *m_ctx)); +int (*RSA_meth_get_init(const RSA_METHOD *meth)) (RSA *rsa); +int RSA_meth_set_init(RSA_METHOD *rsa, int (*init) (RSA *rsa)); +int (*RSA_meth_get_finish(const RSA_METHOD *meth)) (RSA *rsa); +int RSA_meth_set_finish(RSA_METHOD *rsa, int (*finish) (RSA *rsa)); +int (*RSA_meth_get_sign(const RSA_METHOD *meth)) + (int type, + const unsigned char *m, unsigned int m_length, + unsigned char *sigret, unsigned int *siglen, + const RSA *rsa); +int RSA_meth_set_sign(RSA_METHOD *rsa, + int (*sign) (int type, const unsigned char *m, + unsigned int m_length, + unsigned char *sigret, unsigned int *siglen, + const RSA *rsa)); +int (*RSA_meth_get_verify(const RSA_METHOD *meth)) + (int dtype, const unsigned char *m, + unsigned int m_length, const unsigned char *sigbuf, + unsigned int siglen, const RSA *rsa); +int RSA_meth_set_verify(RSA_METHOD *rsa, + int (*verify) (int dtype, const unsigned char *m, + unsigned int m_length, + const unsigned char *sigbuf, + unsigned int siglen, const RSA *rsa)); +int (*RSA_meth_get_keygen(const RSA_METHOD *meth)) + (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); +int RSA_meth_set_keygen(RSA_METHOD *rsa, + int (*keygen) (RSA *rsa, int bits, BIGNUM *e, + BN_GENCB *cb)); +int (*RSA_meth_get_multi_prime_keygen(const RSA_METHOD *meth)) + (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb); +int RSA_meth_set_multi_prime_keygen(RSA_METHOD *meth, + int (*keygen) (RSA *rsa, int bits, + int primes, BIGNUM *e, + BN_GENCB *cb)); + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/rsaerr.h b/include/openssl/rsaerr.h new file mode 100644 index 0000000..d5bc01c --- /dev/null +++ b/include/openssl/rsaerr.h @@ -0,0 +1,162 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_RSAERR_H +# define HEADER_RSAERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_RSA_strings(void); + +/* + * RSA function codes. + */ +# define RSA_F_CHECK_PADDING_MD 140 +# define RSA_F_ENCODE_PKCS1 146 +# define RSA_F_INT_RSA_VERIFY 145 +# define RSA_F_OLD_RSA_PRIV_DECODE 147 +# define RSA_F_PKEY_PSS_INIT 165 +# define RSA_F_PKEY_RSA_CTRL 143 +# define RSA_F_PKEY_RSA_CTRL_STR 144 +# define RSA_F_PKEY_RSA_SIGN 142 +# define RSA_F_PKEY_RSA_VERIFY 149 +# define RSA_F_PKEY_RSA_VERIFYRECOVER 141 +# define RSA_F_RSA_ALGOR_TO_MD 156 +# define RSA_F_RSA_BUILTIN_KEYGEN 129 +# define RSA_F_RSA_CHECK_KEY 123 +# define RSA_F_RSA_CHECK_KEY_EX 160 +# define RSA_F_RSA_CMS_DECRYPT 159 +# define RSA_F_RSA_CMS_VERIFY 158 +# define RSA_F_RSA_ITEM_VERIFY 148 +# define RSA_F_RSA_METH_DUP 161 +# define RSA_F_RSA_METH_NEW 162 +# define RSA_F_RSA_METH_SET1_NAME 163 +# define RSA_F_RSA_MGF1_TO_MD 157 +# define RSA_F_RSA_MULTIP_INFO_NEW 166 +# define RSA_F_RSA_NEW_METHOD 106 +# define RSA_F_RSA_NULL 124 +# define RSA_F_RSA_NULL_PRIVATE_DECRYPT 132 +# define RSA_F_RSA_NULL_PRIVATE_ENCRYPT 133 +# define RSA_F_RSA_NULL_PUBLIC_DECRYPT 134 +# define RSA_F_RSA_NULL_PUBLIC_ENCRYPT 135 +# define RSA_F_RSA_OSSL_PRIVATE_DECRYPT 101 +# define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT 102 +# define RSA_F_RSA_OSSL_PUBLIC_DECRYPT 103 +# define RSA_F_RSA_OSSL_PUBLIC_ENCRYPT 104 +# define RSA_F_RSA_PADDING_ADD_NONE 107 +# define RSA_F_RSA_PADDING_ADD_PKCS1_OAEP 121 +# define RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1 154 +# define RSA_F_RSA_PADDING_ADD_PKCS1_PSS 125 +# define RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1 152 +# define RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1 108 +# define RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2 109 +# define RSA_F_RSA_PADDING_ADD_SSLV23 110 +# define RSA_F_RSA_PADDING_ADD_X931 127 +# define RSA_F_RSA_PADDING_CHECK_NONE 111 +# define RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP 122 +# define RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1 153 +# define RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1 112 +# define RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2 113 +# define RSA_F_RSA_PADDING_CHECK_SSLV23 114 +# define RSA_F_RSA_PADDING_CHECK_X931 128 +# define RSA_F_RSA_PARAM_DECODE 164 +# define RSA_F_RSA_PRINT 115 +# define RSA_F_RSA_PRINT_FP 116 +# define RSA_F_RSA_PRIV_DECODE 150 +# define RSA_F_RSA_PRIV_ENCODE 138 +# define RSA_F_RSA_PSS_GET_PARAM 151 +# define RSA_F_RSA_PSS_TO_CTX 155 +# define RSA_F_RSA_PUB_DECODE 139 +# define RSA_F_RSA_SETUP_BLINDING 136 +# define RSA_F_RSA_SIGN 117 +# define RSA_F_RSA_SIGN_ASN1_OCTET_STRING 118 +# define RSA_F_RSA_VERIFY 119 +# define RSA_F_RSA_VERIFY_ASN1_OCTET_STRING 120 +# define RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1 126 +# define RSA_F_SETUP_TBUF 167 + +/* + * RSA reason codes. + */ +# define RSA_R_ALGORITHM_MISMATCH 100 +# define RSA_R_BAD_E_VALUE 101 +# define RSA_R_BAD_FIXED_HEADER_DECRYPT 102 +# define RSA_R_BAD_PAD_BYTE_COUNT 103 +# define RSA_R_BAD_SIGNATURE 104 +# define RSA_R_BLOCK_TYPE_IS_NOT_01 106 +# define RSA_R_BLOCK_TYPE_IS_NOT_02 107 +# define RSA_R_DATA_GREATER_THAN_MOD_LEN 108 +# define RSA_R_DATA_TOO_LARGE 109 +# define RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE 110 +# define RSA_R_DATA_TOO_LARGE_FOR_MODULUS 132 +# define RSA_R_DATA_TOO_SMALL 111 +# define RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE 122 +# define RSA_R_DIGEST_DOES_NOT_MATCH 158 +# define RSA_R_DIGEST_NOT_ALLOWED 145 +# define RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY 112 +# define RSA_R_DMP1_NOT_CONGRUENT_TO_D 124 +# define RSA_R_DMQ1_NOT_CONGRUENT_TO_D 125 +# define RSA_R_D_E_NOT_CONGRUENT_TO_1 123 +# define RSA_R_FIRST_OCTET_INVALID 133 +# define RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE 144 +# define RSA_R_INVALID_DIGEST 157 +# define RSA_R_INVALID_DIGEST_LENGTH 143 +# define RSA_R_INVALID_HEADER 137 +# define RSA_R_INVALID_LABEL 160 +# define RSA_R_INVALID_MESSAGE_LENGTH 131 +# define RSA_R_INVALID_MGF1_MD 156 +# define RSA_R_INVALID_MULTI_PRIME_KEY 167 +# define RSA_R_INVALID_OAEP_PARAMETERS 161 +# define RSA_R_INVALID_PADDING 138 +# define RSA_R_INVALID_PADDING_MODE 141 +# define RSA_R_INVALID_PSS_PARAMETERS 149 +# define RSA_R_INVALID_PSS_SALTLEN 146 +# define RSA_R_INVALID_SALT_LENGTH 150 +# define RSA_R_INVALID_TRAILER 139 +# define RSA_R_INVALID_X931_DIGEST 142 +# define RSA_R_IQMP_NOT_INVERSE_OF_Q 126 +# define RSA_R_KEY_PRIME_NUM_INVALID 165 +# define RSA_R_KEY_SIZE_TOO_SMALL 120 +# define RSA_R_LAST_OCTET_INVALID 134 +# define RSA_R_MGF1_DIGEST_NOT_ALLOWED 152 +# define RSA_R_MODULUS_TOO_LARGE 105 +# define RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R 168 +# define RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D 169 +# define RSA_R_MP_R_NOT_PRIME 170 +# define RSA_R_NO_PUBLIC_EXPONENT 140 +# define RSA_R_NULL_BEFORE_BLOCK_MISSING 113 +# define RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES 172 +# define RSA_R_N_DOES_NOT_EQUAL_P_Q 127 +# define RSA_R_OAEP_DECODING_ERROR 121 +# define RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 148 +# define RSA_R_PADDING_CHECK_FAILED 114 +# define RSA_R_PKCS_DECODING_ERROR 159 +# define RSA_R_PSS_SALTLEN_TOO_SMALL 164 +# define RSA_R_P_NOT_PRIME 128 +# define RSA_R_Q_NOT_PRIME 129 +# define RSA_R_RSA_OPERATIONS_NOT_SUPPORTED 130 +# define RSA_R_SLEN_CHECK_FAILED 136 +# define RSA_R_SLEN_RECOVERY_FAILED 135 +# define RSA_R_SSLV3_ROLLBACK_ATTACK 115 +# define RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD 116 +# define RSA_R_UNKNOWN_ALGORITHM_TYPE 117 +# define RSA_R_UNKNOWN_DIGEST 166 +# define RSA_R_UNKNOWN_MASK_DIGEST 151 +# define RSA_R_UNKNOWN_PADDING_TYPE 118 +# define RSA_R_UNSUPPORTED_ENCRYPTION_TYPE 162 +# define RSA_R_UNSUPPORTED_LABEL_SOURCE 163 +# define RSA_R_UNSUPPORTED_MASK_ALGORITHM 153 +# define RSA_R_UNSUPPORTED_MASK_PARAMETER 154 +# define RSA_R_UNSUPPORTED_SIGNATURE_TYPE 155 +# define RSA_R_VALUE_MISSING 147 +# define RSA_R_WRONG_SIGNATURE_LENGTH 119 + +#endif diff --git a/include/openssl/safestack.h b/include/openssl/safestack.h new file mode 100644 index 0000000..3a003af --- /dev/null +++ b/include/openssl/safestack.h @@ -0,0 +1,172 @@ +/* + * Copyright 1999-2017 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SAFESTACK_H +# define HEADER_SAFESTACK_H + +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +# define STACK_OF(type) struct stack_st_##type + +# define SKM_DEFINE_STACK_OF(t1, t2, t3) \ + STACK_OF(t1); \ + typedef int (*sk_##t1##_compfunc)(const t3 * const *a, const t3 *const *b); \ + typedef void (*sk_##t1##_freefunc)(t3 *a); \ + typedef t3 * (*sk_##t1##_copyfunc)(const t3 *a); \ + static ossl_inline int sk_##t1##_num(const STACK_OF(t1) *sk) \ + { \ + return OPENSSL_sk_num((const OPENSSL_STACK *)sk); \ + } \ + static ossl_inline t2 *sk_##t1##_value(const STACK_OF(t1) *sk, int idx) \ + { \ + return (t2 *)OPENSSL_sk_value((const OPENSSL_STACK *)sk, idx); \ + } \ + static ossl_inline STACK_OF(t1) *sk_##t1##_new(sk_##t1##_compfunc compare) \ + { \ + return (STACK_OF(t1) *)OPENSSL_sk_new((OPENSSL_sk_compfunc)compare); \ + } \ + static ossl_inline STACK_OF(t1) *sk_##t1##_new_null(void) \ + { \ + return (STACK_OF(t1) *)OPENSSL_sk_new_null(); \ + } \ + static ossl_inline STACK_OF(t1) *sk_##t1##_new_reserve(sk_##t1##_compfunc compare, int n) \ + { \ + return (STACK_OF(t1) *)OPENSSL_sk_new_reserve((OPENSSL_sk_compfunc)compare, n); \ + } \ + static ossl_inline int sk_##t1##_reserve(STACK_OF(t1) *sk, int n) \ + { \ + return OPENSSL_sk_reserve((OPENSSL_STACK *)sk, n); \ + } \ + static ossl_inline void sk_##t1##_free(STACK_OF(t1) *sk) \ + { \ + OPENSSL_sk_free((OPENSSL_STACK *)sk); \ + } \ + static ossl_inline void sk_##t1##_zero(STACK_OF(t1) *sk) \ + { \ + OPENSSL_sk_zero((OPENSSL_STACK *)sk); \ + } \ + static ossl_inline t2 *sk_##t1##_delete(STACK_OF(t1) *sk, int i) \ + { \ + return (t2 *)OPENSSL_sk_delete((OPENSSL_STACK *)sk, i); \ + } \ + static ossl_inline t2 *sk_##t1##_delete_ptr(STACK_OF(t1) *sk, t2 *ptr) \ + { \ + return (t2 *)OPENSSL_sk_delete_ptr((OPENSSL_STACK *)sk, \ + (const void *)ptr); \ + } \ + static ossl_inline int sk_##t1##_push(STACK_OF(t1) *sk, t2 *ptr) \ + { \ + return OPENSSL_sk_push((OPENSSL_STACK *)sk, (const void *)ptr); \ + } \ + static ossl_inline int sk_##t1##_unshift(STACK_OF(t1) *sk, t2 *ptr) \ + { \ + return OPENSSL_sk_unshift((OPENSSL_STACK *)sk, (const void *)ptr); \ + } \ + static ossl_inline t2 *sk_##t1##_pop(STACK_OF(t1) *sk) \ + { \ + return (t2 *)OPENSSL_sk_pop((OPENSSL_STACK *)sk); \ + } \ + static ossl_inline t2 *sk_##t1##_shift(STACK_OF(t1) *sk) \ + { \ + return (t2 *)OPENSSL_sk_shift((OPENSSL_STACK *)sk); \ + } \ + static ossl_inline void sk_##t1##_pop_free(STACK_OF(t1) *sk, sk_##t1##_freefunc freefunc) \ + { \ + OPENSSL_sk_pop_free((OPENSSL_STACK *)sk, (OPENSSL_sk_freefunc)freefunc); \ + } \ + static ossl_inline int sk_##t1##_insert(STACK_OF(t1) *sk, t2 *ptr, int idx) \ + { \ + return OPENSSL_sk_insert((OPENSSL_STACK *)sk, (const void *)ptr, idx); \ + } \ + static ossl_inline t2 *sk_##t1##_set(STACK_OF(t1) *sk, int idx, t2 *ptr) \ + { \ + return (t2 *)OPENSSL_sk_set((OPENSSL_STACK *)sk, idx, (const void *)ptr); \ + } \ + static ossl_inline int sk_##t1##_find(STACK_OF(t1) *sk, t2 *ptr) \ + { \ + return OPENSSL_sk_find((OPENSSL_STACK *)sk, (const void *)ptr); \ + } \ + static ossl_inline int sk_##t1##_find_ex(STACK_OF(t1) *sk, t2 *ptr) \ + { \ + return OPENSSL_sk_find_ex((OPENSSL_STACK *)sk, (const void *)ptr); \ + } \ + static ossl_inline void sk_##t1##_sort(STACK_OF(t1) *sk) \ + { \ + OPENSSL_sk_sort((OPENSSL_STACK *)sk); \ + } \ + static ossl_inline int sk_##t1##_is_sorted(const STACK_OF(t1) *sk) \ + { \ + return OPENSSL_sk_is_sorted((const OPENSSL_STACK *)sk); \ + } \ + static ossl_inline STACK_OF(t1) * sk_##t1##_dup(const STACK_OF(t1) *sk) \ + { \ + return (STACK_OF(t1) *)OPENSSL_sk_dup((const OPENSSL_STACK *)sk); \ + } \ + static ossl_inline STACK_OF(t1) *sk_##t1##_deep_copy(const STACK_OF(t1) *sk, \ + sk_##t1##_copyfunc copyfunc, \ + sk_##t1##_freefunc freefunc) \ + { \ + return (STACK_OF(t1) *)OPENSSL_sk_deep_copy((const OPENSSL_STACK *)sk, \ + (OPENSSL_sk_copyfunc)copyfunc, \ + (OPENSSL_sk_freefunc)freefunc); \ + } \ + static ossl_inline sk_##t1##_compfunc sk_##t1##_set_cmp_func(STACK_OF(t1) *sk, sk_##t1##_compfunc compare) \ + { \ + return (sk_##t1##_compfunc)OPENSSL_sk_set_cmp_func((OPENSSL_STACK *)sk, (OPENSSL_sk_compfunc)compare); \ + } + +# define DEFINE_SPECIAL_STACK_OF(t1, t2) SKM_DEFINE_STACK_OF(t1, t2, t2) +# define DEFINE_STACK_OF(t) SKM_DEFINE_STACK_OF(t, t, t) +# define DEFINE_SPECIAL_STACK_OF_CONST(t1, t2) \ + SKM_DEFINE_STACK_OF(t1, const t2, t2) +# define DEFINE_STACK_OF_CONST(t) SKM_DEFINE_STACK_OF(t, const t, t) + +/*- + * Strings are special: normally an lhash entry will point to a single + * (somewhat) mutable object. In the case of strings: + * + * a) Instead of a single char, there is an array of chars, NUL-terminated. + * b) The string may have be immutable. + * + * So, they need their own declarations. Especially important for + * type-checking tools, such as Deputy. + * + * In practice, however, it appears to be hard to have a const + * string. For now, I'm settling for dealing with the fact it is a + * string at all. + */ +typedef char *OPENSSL_STRING; +typedef const char *OPENSSL_CSTRING; + +/*- + * Confusingly, LHASH_OF(STRING) deals with char ** throughout, but + * STACK_OF(STRING) is really more like STACK_OF(char), only, as mentioned + * above, instead of a single char each entry is a NUL-terminated array of + * chars. So, we have to implement STRING specially for STACK_OF. This is + * dealt with in the autogenerated macros below. + */ +DEFINE_SPECIAL_STACK_OF(OPENSSL_STRING, char) +DEFINE_SPECIAL_STACK_OF_CONST(OPENSSL_CSTRING, char) + +/* + * Similarly, we sometimes use a block of characters, NOT nul-terminated. + * These should also be distinguished from "normal" stacks. + */ +typedef void *OPENSSL_BLOCK; +DEFINE_SPECIAL_STACK_OF(OPENSSL_BLOCK, void) + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/seed.h b/include/openssl/seed.h new file mode 100644 index 0000000..c2f5883 --- /dev/null +++ b/include/openssl/seed.h @@ -0,0 +1,96 @@ +/* + * Copyright 2007-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * Copyright (c) 2007 KISA(Korea Information Security Agency). All rights reserved. + * + * 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. Neither the name of author 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifndef HEADER_SEED_H +# define HEADER_SEED_H + +# include + +# ifndef OPENSSL_NO_SEED +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* look whether we need 'long' to get 32 bits */ +# ifdef AES_LONG +# ifndef SEED_LONG +# define SEED_LONG 1 +# endif +# endif + +# include + +# define SEED_BLOCK_SIZE 16 +# define SEED_KEY_LENGTH 16 + +typedef struct seed_key_st { +# ifdef SEED_LONG + unsigned long data[32]; +# else + unsigned int data[32]; +# endif +} SEED_KEY_SCHEDULE; + +void SEED_set_key(const unsigned char rawkey[SEED_KEY_LENGTH], + SEED_KEY_SCHEDULE *ks); + +void SEED_encrypt(const unsigned char s[SEED_BLOCK_SIZE], + unsigned char d[SEED_BLOCK_SIZE], + const SEED_KEY_SCHEDULE *ks); +void SEED_decrypt(const unsigned char s[SEED_BLOCK_SIZE], + unsigned char d[SEED_BLOCK_SIZE], + const SEED_KEY_SCHEDULE *ks); + +void SEED_ecb_encrypt(const unsigned char *in, unsigned char *out, + const SEED_KEY_SCHEDULE *ks, int enc); +void SEED_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, + const SEED_KEY_SCHEDULE *ks, + unsigned char ivec[SEED_BLOCK_SIZE], int enc); +void SEED_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const SEED_KEY_SCHEDULE *ks, + unsigned char ivec[SEED_BLOCK_SIZE], int *num, + int enc); +void SEED_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const SEED_KEY_SCHEDULE *ks, + unsigned char ivec[SEED_BLOCK_SIZE], int *num); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/sha.h b/include/openssl/sha.h new file mode 100644 index 0000000..d823414 --- /dev/null +++ b/include/openssl/sha.h @@ -0,0 +1,119 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SHA_H +# define HEADER_SHA_H + +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/*- + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + * ! SHA_LONG has to be at least 32 bits wide. ! + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + */ +# define SHA_LONG unsigned int + +# define SHA_LBLOCK 16 +# define SHA_CBLOCK (SHA_LBLOCK*4)/* SHA treats input data as a + * contiguous array of 32 bit wide + * big-endian values. */ +# define SHA_LAST_BLOCK (SHA_CBLOCK-8) +# define SHA_DIGEST_LENGTH 20 + +typedef struct SHAstate_st { + SHA_LONG h0, h1, h2, h3, h4; + SHA_LONG Nl, Nh; + SHA_LONG data[SHA_LBLOCK]; + unsigned int num; +} SHA_CTX; + +int SHA1_Init(SHA_CTX *c); +int SHA1_Update(SHA_CTX *c, const void *data, size_t len); +int SHA1_Final(unsigned char *md, SHA_CTX *c); +unsigned char *SHA1(const unsigned char *d, size_t n, unsigned char *md); +void SHA1_Transform(SHA_CTX *c, const unsigned char *data); + +# define SHA256_CBLOCK (SHA_LBLOCK*4)/* SHA-256 treats input data as a + * contiguous array of 32 bit wide + * big-endian values. */ + +typedef struct SHA256state_st { + SHA_LONG h[8]; + SHA_LONG Nl, Nh; + SHA_LONG data[SHA_LBLOCK]; + unsigned int num, md_len; +} SHA256_CTX; + +int SHA224_Init(SHA256_CTX *c); +int SHA224_Update(SHA256_CTX *c, const void *data, size_t len); +int SHA224_Final(unsigned char *md, SHA256_CTX *c); +unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md); +int SHA256_Init(SHA256_CTX *c); +int SHA256_Update(SHA256_CTX *c, const void *data, size_t len); +int SHA256_Final(unsigned char *md, SHA256_CTX *c); +unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md); +void SHA256_Transform(SHA256_CTX *c, const unsigned char *data); + +# define SHA224_DIGEST_LENGTH 28 +# define SHA256_DIGEST_LENGTH 32 +# define SHA384_DIGEST_LENGTH 48 +# define SHA512_DIGEST_LENGTH 64 + +/* + * Unlike 32-bit digest algorithms, SHA-512 *relies* on SHA_LONG64 + * being exactly 64-bit wide. See Implementation Notes in sha512.c + * for further details. + */ +/* + * SHA-512 treats input data as a + * contiguous array of 64 bit + * wide big-endian values. + */ +# define SHA512_CBLOCK (SHA_LBLOCK*8) +# if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__) +# define SHA_LONG64 unsigned __int64 +# define U64(C) C##UI64 +# elif defined(__arch64__) +# define SHA_LONG64 unsigned long +# define U64(C) C##UL +# else +# define SHA_LONG64 unsigned long long +# define U64(C) C##ULL +# endif + +typedef struct SHA512state_st { + SHA_LONG64 h[8]; + SHA_LONG64 Nl, Nh; + union { + SHA_LONG64 d[SHA_LBLOCK]; + unsigned char p[SHA512_CBLOCK]; + } u; + unsigned int num, md_len; +} SHA512_CTX; + +int SHA384_Init(SHA512_CTX *c); +int SHA384_Update(SHA512_CTX *c, const void *data, size_t len); +int SHA384_Final(unsigned char *md, SHA512_CTX *c); +unsigned char *SHA384(const unsigned char *d, size_t n, unsigned char *md); +int SHA512_Init(SHA512_CTX *c); +int SHA512_Update(SHA512_CTX *c, const void *data, size_t len); +int SHA512_Final(unsigned char *md, SHA512_CTX *c); +unsigned char *SHA512(const unsigned char *d, size_t n, unsigned char *md); +void SHA512_Transform(SHA512_CTX *c, const unsigned char *data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/srp.h b/include/openssl/srp.h new file mode 100644 index 0000000..8ed1402 --- /dev/null +++ b/include/openssl/srp.h @@ -0,0 +1,135 @@ +/* + * Copyright 2004-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2004, EdelKey Project. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + * + * Originally written by Christophe Renou and Peter Sylvester, + * for the EdelKey project. + */ + +#ifndef HEADER_SRP_H +# define HEADER_SRP_H + +#include + +#ifndef OPENSSL_NO_SRP +# include +# include +# include +# include +# include + +# ifdef __cplusplus +extern "C" { +# endif + +typedef struct SRP_gN_cache_st { + char *b64_bn; + BIGNUM *bn; +} SRP_gN_cache; + + +DEFINE_STACK_OF(SRP_gN_cache) + +typedef struct SRP_user_pwd_st { + /* Owned by us. */ + char *id; + BIGNUM *s; + BIGNUM *v; + /* Not owned by us. */ + const BIGNUM *g; + const BIGNUM *N; + /* Owned by us. */ + char *info; +} SRP_user_pwd; + +void SRP_user_pwd_free(SRP_user_pwd *user_pwd); + +DEFINE_STACK_OF(SRP_user_pwd) + +typedef struct SRP_VBASE_st { + STACK_OF(SRP_user_pwd) *users_pwd; + STACK_OF(SRP_gN_cache) *gN_cache; +/* to simulate a user */ + char *seed_key; + const BIGNUM *default_g; + const BIGNUM *default_N; +} SRP_VBASE; + +/* + * Internal structure storing N and g pair + */ +typedef struct SRP_gN_st { + char *id; + const BIGNUM *g; + const BIGNUM *N; +} SRP_gN; + +DEFINE_STACK_OF(SRP_gN) + +SRP_VBASE *SRP_VBASE_new(char *seed_key); +void SRP_VBASE_free(SRP_VBASE *vb); +int SRP_VBASE_init(SRP_VBASE *vb, char *verifier_file); + +/* This method ignores the configured seed and fails for an unknown user. */ +DEPRECATEDIN_1_1_0(SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username)) +/* NOTE: unlike in SRP_VBASE_get_by_user, caller owns the returned pointer.*/ +SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username); + +char *SRP_create_verifier(const char *user, const char *pass, char **salt, + char **verifier, const char *N, const char *g); +int SRP_create_verifier_BN(const char *user, const char *pass, BIGNUM **salt, + BIGNUM **verifier, const BIGNUM *N, + const BIGNUM *g); + +# define SRP_NO_ERROR 0 +# define SRP_ERR_VBASE_INCOMPLETE_FILE 1 +# define SRP_ERR_VBASE_BN_LIB 2 +# define SRP_ERR_OPEN_FILE 3 +# define SRP_ERR_MEMORY 4 + +# define DB_srptype 0 +# define DB_srpverifier 1 +# define DB_srpsalt 2 +# define DB_srpid 3 +# define DB_srpgN 4 +# define DB_srpinfo 5 +# undef DB_NUMBER +# define DB_NUMBER 6 + +# define DB_SRP_INDEX 'I' +# define DB_SRP_VALID 'V' +# define DB_SRP_REVOKED 'R' +# define DB_SRP_MODIF 'v' + +/* see srp.c */ +char *SRP_check_known_gN_param(const BIGNUM *g, const BIGNUM *N); +SRP_gN *SRP_get_default_gN(const char *id); + +/* server side .... */ +BIGNUM *SRP_Calc_server_key(const BIGNUM *A, const BIGNUM *v, const BIGNUM *u, + const BIGNUM *b, const BIGNUM *N); +BIGNUM *SRP_Calc_B(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g, + const BIGNUM *v); +int SRP_Verify_A_mod_N(const BIGNUM *A, const BIGNUM *N); +BIGNUM *SRP_Calc_u(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N); + +/* client side .... */ +BIGNUM *SRP_Calc_x(const BIGNUM *s, const char *user, const char *pass); +BIGNUM *SRP_Calc_A(const BIGNUM *a, const BIGNUM *N, const BIGNUM *g); +BIGNUM *SRP_Calc_client_key(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g, + const BIGNUM *x, const BIGNUM *a, const BIGNUM *u); +int SRP_Verify_B_mod_N(const BIGNUM *B, const BIGNUM *N); + +# define SRP_MINIMAL_N 1024 + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/srtp.h b/include/openssl/srtp.h new file mode 100644 index 0000000..5b291f4 --- /dev/null +++ b/include/openssl/srtp.h @@ -0,0 +1,50 @@ +/* + * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * DTLS code by Eric Rescorla + * + * Copyright (C) 2006, Network Resonance, Inc. Copyright (C) 2011, RTFM, Inc. + */ + +#ifndef HEADER_D1_SRTP_H +# define HEADER_D1_SRTP_H + +# include + +#ifdef __cplusplus +extern "C" { +#endif + +# define SRTP_AES128_CM_SHA1_80 0x0001 +# define SRTP_AES128_CM_SHA1_32 0x0002 +# define SRTP_AES128_F8_SHA1_80 0x0003 +# define SRTP_AES128_F8_SHA1_32 0x0004 +# define SRTP_NULL_SHA1_80 0x0005 +# define SRTP_NULL_SHA1_32 0x0006 + +/* AEAD SRTP protection profiles from RFC 7714 */ +# define SRTP_AEAD_AES_128_GCM 0x0007 +# define SRTP_AEAD_AES_256_GCM 0x0008 + +# ifndef OPENSSL_NO_SRTP + +__owur int SSL_CTX_set_tlsext_use_srtp(SSL_CTX *ctx, const char *profiles); +__owur int SSL_set_tlsext_use_srtp(SSL *ssl, const char *profiles); + +__owur STACK_OF(SRTP_PROTECTION_PROFILE) *SSL_get_srtp_profiles(SSL *ssl); +__owur SRTP_PROTECTION_PROFILE *SSL_get_selected_srtp_profile(SSL *s); + +# endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h new file mode 100644 index 0000000..895f2c7 --- /dev/null +++ b/include/openssl/ssl.h @@ -0,0 +1,2413 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * Copyright 2005 Nokia. All rights reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SSL_H +# define HEADER_SSL_H + +# include +# include +# include +# include +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# include +# include +# endif +# include +# include +# include +# include + +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* OpenSSL version number for ASN.1 encoding of the session information */ +/*- + * Version 0 - initial version + * Version 1 - added the optional peer certificate + */ +# define SSL_SESSION_ASN1_VERSION 0x0001 + +# define SSL_MAX_SSL_SESSION_ID_LENGTH 32 +# define SSL_MAX_SID_CTX_LENGTH 32 + +# define SSL_MIN_RSA_MODULUS_LENGTH_IN_BYTES (512/8) +# define SSL_MAX_KEY_ARG_LENGTH 8 +# define SSL_MAX_MASTER_KEY_LENGTH 48 + +/* The maximum number of encrypt/decrypt pipelines we can support */ +# define SSL_MAX_PIPELINES 32 + +/* text strings for the ciphers */ + +/* These are used to specify which ciphers to use and not to use */ + +# define SSL_TXT_LOW "LOW" +# define SSL_TXT_MEDIUM "MEDIUM" +# define SSL_TXT_HIGH "HIGH" +# define SSL_TXT_FIPS "FIPS" + +# define SSL_TXT_aNULL "aNULL" +# define SSL_TXT_eNULL "eNULL" +# define SSL_TXT_NULL "NULL" + +# define SSL_TXT_kRSA "kRSA" +# define SSL_TXT_kDHr "kDHr"/* this cipher class has been removed */ +# define SSL_TXT_kDHd "kDHd"/* this cipher class has been removed */ +# define SSL_TXT_kDH "kDH"/* this cipher class has been removed */ +# define SSL_TXT_kEDH "kEDH"/* alias for kDHE */ +# define SSL_TXT_kDHE "kDHE" +# define SSL_TXT_kECDHr "kECDHr"/* this cipher class has been removed */ +# define SSL_TXT_kECDHe "kECDHe"/* this cipher class has been removed */ +# define SSL_TXT_kECDH "kECDH"/* this cipher class has been removed */ +# define SSL_TXT_kEECDH "kEECDH"/* alias for kECDHE */ +# define SSL_TXT_kECDHE "kECDHE" +# define SSL_TXT_kPSK "kPSK" +# define SSL_TXT_kRSAPSK "kRSAPSK" +# define SSL_TXT_kECDHEPSK "kECDHEPSK" +# define SSL_TXT_kDHEPSK "kDHEPSK" +# define SSL_TXT_kGOST "kGOST" +# define SSL_TXT_kSRP "kSRP" + +# define SSL_TXT_aRSA "aRSA" +# define SSL_TXT_aDSS "aDSS" +# define SSL_TXT_aDH "aDH"/* this cipher class has been removed */ +# define SSL_TXT_aECDH "aECDH"/* this cipher class has been removed */ +# define SSL_TXT_aECDSA "aECDSA" +# define SSL_TXT_aPSK "aPSK" +# define SSL_TXT_aGOST94 "aGOST94" +# define SSL_TXT_aGOST01 "aGOST01" +# define SSL_TXT_aGOST12 "aGOST12" +# define SSL_TXT_aGOST "aGOST" +# define SSL_TXT_aSRP "aSRP" + +# define SSL_TXT_DSS "DSS" +# define SSL_TXT_DH "DH" +# define SSL_TXT_DHE "DHE"/* same as "kDHE:-ADH" */ +# define SSL_TXT_EDH "EDH"/* alias for DHE */ +# define SSL_TXT_ADH "ADH" +# define SSL_TXT_RSA "RSA" +# define SSL_TXT_ECDH "ECDH" +# define SSL_TXT_EECDH "EECDH"/* alias for ECDHE" */ +# define SSL_TXT_ECDHE "ECDHE"/* same as "kECDHE:-AECDH" */ +# define SSL_TXT_AECDH "AECDH" +# define SSL_TXT_ECDSA "ECDSA" +# define SSL_TXT_PSK "PSK" +# define SSL_TXT_SRP "SRP" + +# define SSL_TXT_DES "DES" +# define SSL_TXT_3DES "3DES" +# define SSL_TXT_RC4 "RC4" +# define SSL_TXT_RC2 "RC2" +# define SSL_TXT_IDEA "IDEA" +# define SSL_TXT_SEED "SEED" +# define SSL_TXT_AES128 "AES128" +# define SSL_TXT_AES256 "AES256" +# define SSL_TXT_AES "AES" +# define SSL_TXT_AES_GCM "AESGCM" +# define SSL_TXT_AES_CCM "AESCCM" +# define SSL_TXT_AES_CCM_8 "AESCCM8" +# define SSL_TXT_CAMELLIA128 "CAMELLIA128" +# define SSL_TXT_CAMELLIA256 "CAMELLIA256" +# define SSL_TXT_CAMELLIA "CAMELLIA" +# define SSL_TXT_CHACHA20 "CHACHA20" +# define SSL_TXT_GOST "GOST89" +# define SSL_TXT_ARIA "ARIA" +# define SSL_TXT_ARIA_GCM "ARIAGCM" +# define SSL_TXT_ARIA128 "ARIA128" +# define SSL_TXT_ARIA256 "ARIA256" + +# define SSL_TXT_MD5 "MD5" +# define SSL_TXT_SHA1 "SHA1" +# define SSL_TXT_SHA "SHA"/* same as "SHA1" */ +# define SSL_TXT_GOST94 "GOST94" +# define SSL_TXT_GOST89MAC "GOST89MAC" +# define SSL_TXT_GOST12 "GOST12" +# define SSL_TXT_GOST89MAC12 "GOST89MAC12" +# define SSL_TXT_SHA256 "SHA256" +# define SSL_TXT_SHA384 "SHA384" + +# define SSL_TXT_SSLV3 "SSLv3" +# define SSL_TXT_TLSV1 "TLSv1" +# define SSL_TXT_TLSV1_1 "TLSv1.1" +# define SSL_TXT_TLSV1_2 "TLSv1.2" + +# define SSL_TXT_ALL "ALL" + +/*- + * COMPLEMENTOF* definitions. These identifiers are used to (de-select) + * ciphers normally not being used. + * Example: "RC4" will activate all ciphers using RC4 including ciphers + * without authentication, which would normally disabled by DEFAULT (due + * the "!ADH" being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT" + * will make sure that it is also disabled in the specific selection. + * COMPLEMENTOF* identifiers are portable between version, as adjustments + * to the default cipher setup will also be included here. + * + * COMPLEMENTOFDEFAULT does not experience the same special treatment that + * DEFAULT gets, as only selection is being done and no sorting as needed + * for DEFAULT. + */ +# define SSL_TXT_CMPALL "COMPLEMENTOFALL" +# define SSL_TXT_CMPDEF "COMPLEMENTOFDEFAULT" + +/* + * The following cipher list is used by default. It also is substituted when + * an application-defined cipher list string starts with 'DEFAULT'. + * This applies to ciphersuites for TLSv1.2 and below. + */ +# define SSL_DEFAULT_CIPHER_LIST "ALL:!COMPLEMENTOFDEFAULT:!eNULL" +/* This is the default set of TLSv1.3 ciphersuites */ +# if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) +# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \ + "TLS_CHACHA20_POLY1305_SHA256:" \ + "TLS_AES_128_GCM_SHA256" +# else +# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \ + "TLS_AES_128_GCM_SHA256" +#endif +/* + * As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always + * starts with a reasonable order, and all we have to do for DEFAULT is + * throwing out anonymous and unencrypted ciphersuites! (The latter are not + * actually enabled by ALL, but "ALL:RSA" would enable some of them.) + */ + +/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */ +# define SSL_SENT_SHUTDOWN 1 +# define SSL_RECEIVED_SHUTDOWN 2 + +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +# define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1 +# define SSL_FILETYPE_PEM X509_FILETYPE_PEM + +/* + * This is needed to stop compilers complaining about the 'struct ssl_st *' + * function parameters used to prototype callbacks in SSL_CTX. + */ +typedef struct ssl_st *ssl_crock_st; +typedef struct tls_session_ticket_ext_st TLS_SESSION_TICKET_EXT; +typedef struct ssl_method_st SSL_METHOD; +typedef struct ssl_cipher_st SSL_CIPHER; +typedef struct ssl_session_st SSL_SESSION; +typedef struct tls_sigalgs_st TLS_SIGALGS; +typedef struct ssl_conf_ctx_st SSL_CONF_CTX; +typedef struct ssl_comp_st SSL_COMP; + +STACK_OF(SSL_CIPHER); +STACK_OF(SSL_COMP); + +/* SRTP protection profiles for use with the use_srtp extension (RFC 5764)*/ +typedef struct srtp_protection_profile_st { + const char *name; + unsigned long id; +} SRTP_PROTECTION_PROFILE; + +DEFINE_STACK_OF(SRTP_PROTECTION_PROFILE) + +typedef int (*tls_session_ticket_ext_cb_fn)(SSL *s, const unsigned char *data, + int len, void *arg); +typedef int (*tls_session_secret_cb_fn)(SSL *s, void *secret, int *secret_len, + STACK_OF(SSL_CIPHER) *peer_ciphers, + const SSL_CIPHER **cipher, void *arg); + +/* Extension context codes */ +/* This extension is only allowed in TLS */ +#define SSL_EXT_TLS_ONLY 0x0001 +/* This extension is only allowed in DTLS */ +#define SSL_EXT_DTLS_ONLY 0x0002 +/* Some extensions may be allowed in DTLS but we don't implement them for it */ +#define SSL_EXT_TLS_IMPLEMENTATION_ONLY 0x0004 +/* Most extensions are not defined for SSLv3 but EXT_TYPE_renegotiate is */ +#define SSL_EXT_SSL3_ALLOWED 0x0008 +/* Extension is only defined for TLS1.2 and below */ +#define SSL_EXT_TLS1_2_AND_BELOW_ONLY 0x0010 +/* Extension is only defined for TLS1.3 and above */ +#define SSL_EXT_TLS1_3_ONLY 0x0020 +/* Ignore this extension during parsing if we are resuming */ +#define SSL_EXT_IGNORE_ON_RESUMPTION 0x0040 +#define SSL_EXT_CLIENT_HELLO 0x0080 +/* Really means TLS1.2 or below */ +#define SSL_EXT_TLS1_2_SERVER_HELLO 0x0100 +#define SSL_EXT_TLS1_3_SERVER_HELLO 0x0200 +#define SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS 0x0400 +#define SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST 0x0800 +#define SSL_EXT_TLS1_3_CERTIFICATE 0x1000 +#define SSL_EXT_TLS1_3_NEW_SESSION_TICKET 0x2000 +#define SSL_EXT_TLS1_3_CERTIFICATE_REQUEST 0x4000 + +/* Typedefs for handling custom extensions */ + +typedef int (*custom_ext_add_cb)(SSL *s, unsigned int ext_type, + const unsigned char **out, size_t *outlen, + int *al, void *add_arg); + +typedef void (*custom_ext_free_cb)(SSL *s, unsigned int ext_type, + const unsigned char *out, void *add_arg); + +typedef int (*custom_ext_parse_cb)(SSL *s, unsigned int ext_type, + const unsigned char *in, size_t inlen, + int *al, void *parse_arg); + + +typedef int (*SSL_custom_ext_add_cb_ex)(SSL *s, unsigned int ext_type, + unsigned int context, + const unsigned char **out, + size_t *outlen, X509 *x, + size_t chainidx, + int *al, void *add_arg); + +typedef void (*SSL_custom_ext_free_cb_ex)(SSL *s, unsigned int ext_type, + unsigned int context, + const unsigned char *out, + void *add_arg); + +typedef int (*SSL_custom_ext_parse_cb_ex)(SSL *s, unsigned int ext_type, + unsigned int context, + const unsigned char *in, + size_t inlen, X509 *x, + size_t chainidx, + int *al, void *parse_arg); + +/* Typedef for verification callback */ +typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx); + +/* + * Some values are reserved until OpenSSL 1.2.0 because they were previously + * included in SSL_OP_ALL in a 1.1.x release. + * + * Reserved value (until OpenSSL 1.2.0) 0x00000001U + * Reserved value (until OpenSSL 1.2.0) 0x00000002U + */ +/* Allow initial connection to servers that don't support RI */ +# define SSL_OP_LEGACY_SERVER_CONNECT 0x00000004U + +/* Reserved value (until OpenSSL 1.2.0) 0x00000008U */ +# define SSL_OP_TLSEXT_PADDING 0x00000010U +/* Reserved value (until OpenSSL 1.2.0) 0x00000020U */ +# define SSL_OP_SAFARI_ECDHE_ECDSA_BUG 0x00000040U +/* + * Reserved value (until OpenSSL 1.2.0) 0x00000080U + * Reserved value (until OpenSSL 1.2.0) 0x00000100U + * Reserved value (until OpenSSL 1.2.0) 0x00000200U + */ + +/* In TLSv1.3 allow a non-(ec)dhe based kex_mode */ +# define SSL_OP_ALLOW_NO_DHE_KEX 0x00000400U + +/* + * Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added in + * OpenSSL 0.9.6d. Usually (depending on the application protocol) the + * workaround is not needed. Unfortunately some broken SSL/TLS + * implementations cannot handle it at all, which is why we include it in + * SSL_OP_ALL. Added in 0.9.6e + */ +# define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 0x00000800U + +/* DTLS options */ +# define SSL_OP_NO_QUERY_MTU 0x00001000U +/* Turn on Cookie Exchange (on relevant for servers) */ +# define SSL_OP_COOKIE_EXCHANGE 0x00002000U +/* Don't use RFC4507 ticket extension */ +# define SSL_OP_NO_TICKET 0x00004000U +# ifndef OPENSSL_NO_DTLS1_METHOD +/* Use Cisco's "speshul" version of DTLS_BAD_VER + * (only with deprecated DTLSv1_client_method()) */ +# define SSL_OP_CISCO_ANYCONNECT 0x00008000U +# endif + +/* As server, disallow session resumption on renegotiation */ +# define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0x00010000U +/* Don't use compression even if supported */ +# define SSL_OP_NO_COMPRESSION 0x00020000U +/* Permit unsafe legacy renegotiation */ +# define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000U +/* Disable encrypt-then-mac */ +# define SSL_OP_NO_ENCRYPT_THEN_MAC 0x00080000U + +/* + * Enable TLSv1.3 Compatibility mode. This is on by default. A future version + * of OpenSSL may have this disabled by default. + */ +# define SSL_OP_ENABLE_MIDDLEBOX_COMPAT 0x00100000U + +/* Prioritize Chacha20Poly1305 when client does. + * Modifies SSL_OP_CIPHER_SERVER_PREFERENCE */ +# define SSL_OP_PRIORITIZE_CHACHA 0x00200000U + +/* + * Set on servers to choose the cipher according to the server's preferences + */ +# define SSL_OP_CIPHER_SERVER_PREFERENCE 0x00400000U +/* + * If set, a server will allow a client to issue a SSLv3.0 version number as + * latest version supported in the premaster secret, even when TLSv1.0 + * (version 3.1) was announced in the client hello. Normally this is + * forbidden to prevent version rollback attacks. + */ +# define SSL_OP_TLS_ROLLBACK_BUG 0x00800000U + +/* + * Switches off automatic TLSv1.3 anti-replay protection for early data. This + * is a server-side option only (no effect on the client). + */ +# define SSL_OP_NO_ANTI_REPLAY 0x01000000U + +# define SSL_OP_NO_SSLv3 0x02000000U +# define SSL_OP_NO_TLSv1 0x04000000U +# define SSL_OP_NO_TLSv1_2 0x08000000U +# define SSL_OP_NO_TLSv1_1 0x10000000U +# define SSL_OP_NO_TLSv1_3 0x20000000U + +# define SSL_OP_NO_DTLSv1 0x04000000U +# define SSL_OP_NO_DTLSv1_2 0x08000000U + +# define SSL_OP_NO_SSL_MASK (SSL_OP_NO_SSLv3|\ + SSL_OP_NO_TLSv1|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2|SSL_OP_NO_TLSv1_3) +# define SSL_OP_NO_DTLS_MASK (SSL_OP_NO_DTLSv1|SSL_OP_NO_DTLSv1_2) + +/* Disallow all renegotiation */ +# define SSL_OP_NO_RENEGOTIATION 0x40000000U + +/* + * Make server add server-hello extension from early version of cryptopro + * draft, when GOST ciphersuite is negotiated. Required for interoperability + * with CryptoPro CSP 3.x + */ +# define SSL_OP_CRYPTOPRO_TLSEXT_BUG 0x80000000U + +/* + * SSL_OP_ALL: various bug workarounds that should be rather harmless. + * This used to be 0x000FFFFFL before 0.9.7. + * This used to be 0x80000BFFU before 1.1.1. + */ +# define SSL_OP_ALL (SSL_OP_CRYPTOPRO_TLSEXT_BUG|\ + SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS|\ + SSL_OP_LEGACY_SERVER_CONNECT|\ + SSL_OP_TLSEXT_PADDING|\ + SSL_OP_SAFARI_ECDHE_ECDSA_BUG) + +/* OBSOLETE OPTIONS: retained for compatibility */ + +/* Removed from OpenSSL 1.1.0. Was 0x00000001L */ +/* Related to removed SSLv2. */ +# define SSL_OP_MICROSOFT_SESS_ID_BUG 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x00000002L */ +/* Related to removed SSLv2. */ +# define SSL_OP_NETSCAPE_CHALLENGE_BUG 0x0 +/* Removed from OpenSSL 0.9.8q and 1.0.0c. Was 0x00000008L */ +/* Dead forever, see CVE-2010-4180 */ +# define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0x0 +/* Removed from OpenSSL 1.0.1h and 1.0.2. Was 0x00000010L */ +/* Refers to ancient SSLREF and SSLv2. */ +# define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x00000020 */ +# define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER 0x0 +/* Removed from OpenSSL 0.9.7h and 0.9.8b. Was 0x00000040L */ +# define SSL_OP_MSIE_SSLV2_RSA_PADDING 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x00000080 */ +/* Ancient SSLeay version. */ +# define SSL_OP_SSLEAY_080_CLIENT_DH_BUG 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x00000100L */ +# define SSL_OP_TLS_D5_BUG 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x00000200L */ +# define SSL_OP_TLS_BLOCK_PADDING_BUG 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x00080000L */ +# define SSL_OP_SINGLE_ECDH_USE 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x00100000L */ +# define SSL_OP_SINGLE_DH_USE 0x0 +/* Removed from OpenSSL 1.0.1k and 1.0.2. Was 0x00200000L */ +# define SSL_OP_EPHEMERAL_RSA 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x01000000L */ +# define SSL_OP_NO_SSLv2 0x0 +/* Removed from OpenSSL 1.0.1. Was 0x08000000L */ +# define SSL_OP_PKCS1_CHECK_1 0x0 +/* Removed from OpenSSL 1.0.1. Was 0x10000000L */ +# define SSL_OP_PKCS1_CHECK_2 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x20000000L */ +# define SSL_OP_NETSCAPE_CA_DN_BUG 0x0 +/* Removed from OpenSSL 1.1.0. Was 0x40000000L */ +# define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG 0x0 + +/* + * Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success + * when just a single record has been written): + */ +# define SSL_MODE_ENABLE_PARTIAL_WRITE 0x00000001U +/* + * Make it possible to retry SSL_write() with changed buffer location (buffer + * contents must stay the same!); this is not the default to avoid the + * misconception that non-blocking SSL_write() behaves like non-blocking + * write(): + */ +# define SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002U +/* + * Never bother the application with retries if the transport is blocking: + */ +# define SSL_MODE_AUTO_RETRY 0x00000004U +/* Don't attempt to automatically build certificate chain */ +# define SSL_MODE_NO_AUTO_CHAIN 0x00000008U +/* + * Save RAM by releasing read and write buffers when they're empty. (SSL3 and + * TLS only.) Released buffers are freed. + */ +# define SSL_MODE_RELEASE_BUFFERS 0x00000010U +/* + * Send the current time in the Random fields of the ClientHello and + * ServerHello records for compatibility with hypothetical implementations + * that require it. + */ +# define SSL_MODE_SEND_CLIENTHELLO_TIME 0x00000020U +# define SSL_MODE_SEND_SERVERHELLO_TIME 0x00000040U +/* + * Send TLS_FALLBACK_SCSV in the ClientHello. To be set only by applications + * that reconnect with a downgraded protocol version; see + * draft-ietf-tls-downgrade-scsv-00 for details. DO NOT ENABLE THIS if your + * application attempts a normal handshake. Only use this in explicit + * fallback retries, following the guidance in + * draft-ietf-tls-downgrade-scsv-00. + */ +# define SSL_MODE_SEND_FALLBACK_SCSV 0x00000080U +/* + * Support Asynchronous operation + */ +# define SSL_MODE_ASYNC 0x00000100U + +/* Cert related flags */ +/* + * Many implementations ignore some aspects of the TLS standards such as + * enforcing certificate chain algorithms. When this is set we enforce them. + */ +# define SSL_CERT_FLAG_TLS_STRICT 0x00000001U + +/* Suite B modes, takes same values as certificate verify flags */ +# define SSL_CERT_FLAG_SUITEB_128_LOS_ONLY 0x10000 +/* Suite B 192 bit only mode */ +# define SSL_CERT_FLAG_SUITEB_192_LOS 0x20000 +/* Suite B 128 bit mode allowing 192 bit algorithms */ +# define SSL_CERT_FLAG_SUITEB_128_LOS 0x30000 + +/* Perform all sorts of protocol violations for testing purposes */ +# define SSL_CERT_FLAG_BROKEN_PROTOCOL 0x10000000 + +/* Flags for building certificate chains */ +/* Treat any existing certificates as untrusted CAs */ +# define SSL_BUILD_CHAIN_FLAG_UNTRUSTED 0x1 +/* Don't include root CA in chain */ +# define SSL_BUILD_CHAIN_FLAG_NO_ROOT 0x2 +/* Just check certificates already there */ +# define SSL_BUILD_CHAIN_FLAG_CHECK 0x4 +/* Ignore verification errors */ +# define SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR 0x8 +/* Clear verification errors from queue */ +# define SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR 0x10 + +/* Flags returned by SSL_check_chain */ +/* Certificate can be used with this session */ +# define CERT_PKEY_VALID 0x1 +/* Certificate can also be used for signing */ +# define CERT_PKEY_SIGN 0x2 +/* EE certificate signing algorithm OK */ +# define CERT_PKEY_EE_SIGNATURE 0x10 +/* CA signature algorithms OK */ +# define CERT_PKEY_CA_SIGNATURE 0x20 +/* EE certificate parameters OK */ +# define CERT_PKEY_EE_PARAM 0x40 +/* CA certificate parameters OK */ +# define CERT_PKEY_CA_PARAM 0x80 +/* Signing explicitly allowed as opposed to SHA1 fallback */ +# define CERT_PKEY_EXPLICIT_SIGN 0x100 +/* Client CA issuer names match (always set for server cert) */ +# define CERT_PKEY_ISSUER_NAME 0x200 +/* Cert type matches client types (always set for server cert) */ +# define CERT_PKEY_CERT_TYPE 0x400 +/* Cert chain suitable to Suite B */ +# define CERT_PKEY_SUITEB 0x800 + +# define SSL_CONF_FLAG_CMDLINE 0x1 +# define SSL_CONF_FLAG_FILE 0x2 +# define SSL_CONF_FLAG_CLIENT 0x4 +# define SSL_CONF_FLAG_SERVER 0x8 +# define SSL_CONF_FLAG_SHOW_ERRORS 0x10 +# define SSL_CONF_FLAG_CERTIFICATE 0x20 +# define SSL_CONF_FLAG_REQUIRE_PRIVATE 0x40 +/* Configuration value types */ +# define SSL_CONF_TYPE_UNKNOWN 0x0 +# define SSL_CONF_TYPE_STRING 0x1 +# define SSL_CONF_TYPE_FILE 0x2 +# define SSL_CONF_TYPE_DIR 0x3 +# define SSL_CONF_TYPE_NONE 0x4 + +/* Maximum length of the application-controlled segment of a a TLSv1.3 cookie */ +# define SSL_COOKIE_LENGTH 4096 + +/* + * Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, they + * cannot be used to clear bits. + */ + +unsigned long SSL_CTX_get_options(const SSL_CTX *ctx); +unsigned long SSL_get_options(const SSL *s); +unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op); +unsigned long SSL_clear_options(SSL *s, unsigned long op); +unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long op); +unsigned long SSL_set_options(SSL *s, unsigned long op); + +# define SSL_CTX_set_mode(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL) +# define SSL_CTX_clear_mode(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL) +# define SSL_CTX_get_mode(ctx) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,0,NULL) +# define SSL_clear_mode(ssl,op) \ + SSL_ctrl((ssl),SSL_CTRL_CLEAR_MODE,(op),NULL) +# define SSL_set_mode(ssl,op) \ + SSL_ctrl((ssl),SSL_CTRL_MODE,(op),NULL) +# define SSL_get_mode(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_MODE,0,NULL) +# define SSL_set_mtu(ssl, mtu) \ + SSL_ctrl((ssl),SSL_CTRL_SET_MTU,(mtu),NULL) +# define DTLS_set_link_mtu(ssl, mtu) \ + SSL_ctrl((ssl),DTLS_CTRL_SET_LINK_MTU,(mtu),NULL) +# define DTLS_get_link_min_mtu(ssl) \ + SSL_ctrl((ssl),DTLS_CTRL_GET_LINK_MIN_MTU,0,NULL) + +# define SSL_get_secure_renegotiation_support(ssl) \ + SSL_ctrl((ssl), SSL_CTRL_GET_RI_SUPPORT, 0, NULL) + +# ifndef OPENSSL_NO_HEARTBEATS +# define SSL_heartbeat(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_DTLS_EXT_SEND_HEARTBEAT,0,NULL) +# endif + +# define SSL_CTX_set_cert_flags(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_CERT_FLAGS,(op),NULL) +# define SSL_set_cert_flags(s,op) \ + SSL_ctrl((s),SSL_CTRL_CERT_FLAGS,(op),NULL) +# define SSL_CTX_clear_cert_flags(ctx,op) \ + SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL) +# define SSL_clear_cert_flags(s,op) \ + SSL_ctrl((s),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL) + +void SSL_CTX_set_msg_callback(SSL_CTX *ctx, + void (*cb) (int write_p, int version, + int content_type, const void *buf, + size_t len, SSL *ssl, void *arg)); +void SSL_set_msg_callback(SSL *ssl, + void (*cb) (int write_p, int version, + int content_type, const void *buf, + size_t len, SSL *ssl, void *arg)); +# define SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_CTX_ctrl((ctx), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg)) +# define SSL_set_msg_callback_arg(ssl, arg) SSL_ctrl((ssl), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg)) + +# define SSL_get_extms_support(s) \ + SSL_ctrl((s),SSL_CTRL_GET_EXTMS_SUPPORT,0,NULL) + +# ifndef OPENSSL_NO_SRP + +/* see tls_srp.c */ +__owur int SSL_SRP_CTX_init(SSL *s); +__owur int SSL_CTX_SRP_CTX_init(SSL_CTX *ctx); +int SSL_SRP_CTX_free(SSL *ctx); +int SSL_CTX_SRP_CTX_free(SSL_CTX *ctx); +__owur int SSL_srp_server_param_with_username(SSL *s, int *ad); +__owur int SRP_Calc_A_param(SSL *s); + +# endif + +/* 100k max cert list */ +# define SSL_MAX_CERT_LIST_DEFAULT 1024*100 + +# define SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (1024*20) + +/* + * This callback type is used inside SSL_CTX, SSL, and in the functions that + * set them. It is used to override the generation of SSL/TLS session IDs in + * a server. Return value should be zero on an error, non-zero to proceed. + * Also, callbacks should themselves check if the id they generate is unique + * otherwise the SSL handshake will fail with an error - callbacks can do + * this using the 'ssl' value they're passed by; + * SSL_has_matching_session_id(ssl, id, *id_len) The length value passed in + * is set at the maximum size the session ID can be. In SSLv3/TLSv1 it is 32 + * bytes. The callback can alter this length to be less if desired. It is + * also an error for the callback to set the size to zero. + */ +typedef int (*GEN_SESSION_CB) (SSL *ssl, unsigned char *id, + unsigned int *id_len); + +# define SSL_SESS_CACHE_OFF 0x0000 +# define SSL_SESS_CACHE_CLIENT 0x0001 +# define SSL_SESS_CACHE_SERVER 0x0002 +# define SSL_SESS_CACHE_BOTH (SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_SERVER) +# define SSL_SESS_CACHE_NO_AUTO_CLEAR 0x0080 +/* enough comments already ... see SSL_CTX_set_session_cache_mode(3) */ +# define SSL_SESS_CACHE_NO_INTERNAL_LOOKUP 0x0100 +# define SSL_SESS_CACHE_NO_INTERNAL_STORE 0x0200 +# define SSL_SESS_CACHE_NO_INTERNAL \ + (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP|SSL_SESS_CACHE_NO_INTERNAL_STORE) + +LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx); +# define SSL_CTX_sess_number(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_NUMBER,0,NULL) +# define SSL_CTX_sess_connect(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT,0,NULL) +# define SSL_CTX_sess_connect_good(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_GOOD,0,NULL) +# define SSL_CTX_sess_connect_renegotiate(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_RENEGOTIATE,0,NULL) +# define SSL_CTX_sess_accept(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT,0,NULL) +# define SSL_CTX_sess_accept_renegotiate(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_RENEGOTIATE,0,NULL) +# define SSL_CTX_sess_accept_good(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_GOOD,0,NULL) +# define SSL_CTX_sess_hits(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_HIT,0,NULL) +# define SSL_CTX_sess_cb_hits(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CB_HIT,0,NULL) +# define SSL_CTX_sess_misses(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_MISSES,0,NULL) +# define SSL_CTX_sess_timeouts(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_TIMEOUTS,0,NULL) +# define SSL_CTX_sess_cache_full(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CACHE_FULL,0,NULL) + +void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx, + int (*new_session_cb) (struct ssl_st *ssl, + SSL_SESSION *sess)); +int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (struct ssl_st *ssl, + SSL_SESSION *sess); +void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx, + void (*remove_session_cb) (struct ssl_ctx_st + *ctx, + SSL_SESSION *sess)); +void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (struct ssl_ctx_st *ctx, + SSL_SESSION *sess); +void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, + SSL_SESSION *(*get_session_cb) (struct ssl_st + *ssl, + const unsigned char + *data, int len, + int *copy)); +SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (struct ssl_st *ssl, + const unsigned char *data, + int len, int *copy); +void SSL_CTX_set_info_callback(SSL_CTX *ctx, + void (*cb) (const SSL *ssl, int type, int val)); +void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type, + int val); +void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, + int (*client_cert_cb) (SSL *ssl, X509 **x509, + EVP_PKEY **pkey)); +int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509, + EVP_PKEY **pkey); +# ifndef OPENSSL_NO_ENGINE +__owur int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e); +# endif +void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx, + int (*app_gen_cookie_cb) (SSL *ssl, + unsigned char + *cookie, + unsigned int + *cookie_len)); +void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx, + int (*app_verify_cookie_cb) (SSL *ssl, + const unsigned + char *cookie, + unsigned int + cookie_len)); + +void SSL_CTX_set_stateless_cookie_generate_cb( + SSL_CTX *ctx, + int (*gen_stateless_cookie_cb) (SSL *ssl, + unsigned char *cookie, + size_t *cookie_len)); +void SSL_CTX_set_stateless_cookie_verify_cb( + SSL_CTX *ctx, + int (*verify_stateless_cookie_cb) (SSL *ssl, + const unsigned char *cookie, + size_t cookie_len)); +# ifndef OPENSSL_NO_NEXTPROTONEG + +typedef int (*SSL_CTX_npn_advertised_cb_func)(SSL *ssl, + const unsigned char **out, + unsigned int *outlen, + void *arg); +void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s, + SSL_CTX_npn_advertised_cb_func cb, + void *arg); +# define SSL_CTX_set_npn_advertised_cb SSL_CTX_set_next_protos_advertised_cb + +typedef int (*SSL_CTX_npn_select_cb_func)(SSL *s, + unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg); +void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s, + SSL_CTX_npn_select_cb_func cb, + void *arg); +# define SSL_CTX_set_npn_select_cb SSL_CTX_set_next_proto_select_cb + +void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data, + unsigned *len); +# define SSL_get0_npn_negotiated SSL_get0_next_proto_negotiated +# endif + +__owur int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, + const unsigned char *client, + unsigned int client_len); + +# define OPENSSL_NPN_UNSUPPORTED 0 +# define OPENSSL_NPN_NEGOTIATED 1 +# define OPENSSL_NPN_NO_OVERLAP 2 + +__owur int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos, + unsigned int protos_len); +__owur int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos, + unsigned int protos_len); +typedef int (*SSL_CTX_alpn_select_cb_func)(SSL *ssl, + const unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg); +void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, + SSL_CTX_alpn_select_cb_func cb, + void *arg); +void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data, + unsigned int *len); + +# ifndef OPENSSL_NO_PSK +/* + * the maximum length of the buffer given to callbacks containing the + * resulting identity/psk + */ +# define PSK_MAX_IDENTITY_LEN 128 +# define PSK_MAX_PSK_LEN 256 +typedef unsigned int (*SSL_psk_client_cb_func)(SSL *ssl, + const char *hint, + char *identity, + unsigned int max_identity_len, + unsigned char *psk, + unsigned int max_psk_len); +void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb); +void SSL_set_psk_client_callback(SSL *ssl, SSL_psk_client_cb_func cb); + +typedef unsigned int (*SSL_psk_server_cb_func)(SSL *ssl, + const char *identity, + unsigned char *psk, + unsigned int max_psk_len); +void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb); +void SSL_set_psk_server_callback(SSL *ssl, SSL_psk_server_cb_func cb); + +__owur int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint); +__owur int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint); +const char *SSL_get_psk_identity_hint(const SSL *s); +const char *SSL_get_psk_identity(const SSL *s); +# endif + +typedef int (*SSL_psk_find_session_cb_func)(SSL *ssl, + const unsigned char *identity, + size_t identity_len, + SSL_SESSION **sess); +typedef int (*SSL_psk_use_session_cb_func)(SSL *ssl, const EVP_MD *md, + const unsigned char **id, + size_t *idlen, + SSL_SESSION **sess); + +void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb); +void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx, + SSL_psk_find_session_cb_func cb); +void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb); +void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx, + SSL_psk_use_session_cb_func cb); + +/* Register callbacks to handle custom TLS Extensions for client or server. */ + +__owur int SSL_CTX_has_client_custom_ext(const SSL_CTX *ctx, + unsigned int ext_type); + +__owur int SSL_CTX_add_client_custom_ext(SSL_CTX *ctx, + unsigned int ext_type, + custom_ext_add_cb add_cb, + custom_ext_free_cb free_cb, + void *add_arg, + custom_ext_parse_cb parse_cb, + void *parse_arg); + +__owur int SSL_CTX_add_server_custom_ext(SSL_CTX *ctx, + unsigned int ext_type, + custom_ext_add_cb add_cb, + custom_ext_free_cb free_cb, + void *add_arg, + custom_ext_parse_cb parse_cb, + void *parse_arg); + +__owur int SSL_CTX_add_custom_ext(SSL_CTX *ctx, unsigned int ext_type, + unsigned int context, + SSL_custom_ext_add_cb_ex add_cb, + SSL_custom_ext_free_cb_ex free_cb, + void *add_arg, + SSL_custom_ext_parse_cb_ex parse_cb, + void *parse_arg); + +__owur int SSL_extension_supported(unsigned int ext_type); + +# define SSL_NOTHING 1 +# define SSL_WRITING 2 +# define SSL_READING 3 +# define SSL_X509_LOOKUP 4 +# define SSL_ASYNC_PAUSED 5 +# define SSL_ASYNC_NO_JOBS 6 +# define SSL_CLIENT_HELLO_CB 7 + +/* These will only be used when doing non-blocking IO */ +# define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING) +# define SSL_want_read(s) (SSL_want(s) == SSL_READING) +# define SSL_want_write(s) (SSL_want(s) == SSL_WRITING) +# define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP) +# define SSL_want_async(s) (SSL_want(s) == SSL_ASYNC_PAUSED) +# define SSL_want_async_job(s) (SSL_want(s) == SSL_ASYNC_NO_JOBS) +# define SSL_want_client_hello_cb(s) (SSL_want(s) == SSL_CLIENT_HELLO_CB) + +# define SSL_MAC_FLAG_READ_MAC_STREAM 1 +# define SSL_MAC_FLAG_WRITE_MAC_STREAM 2 + +/* + * A callback for logging out TLS key material. This callback should log out + * |line| followed by a newline. + */ +typedef void (*SSL_CTX_keylog_cb_func)(const SSL *ssl, const char *line); + +/* + * SSL_CTX_set_keylog_callback configures a callback to log key material. This + * is intended for debugging use with tools like Wireshark. The cb function + * should log line followed by a newline. + */ +void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb); + +/* + * SSL_CTX_get_keylog_callback returns the callback configured by + * SSL_CTX_set_keylog_callback. + */ +SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx); + +int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data); +uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx); +int SSL_set_max_early_data(SSL *s, uint32_t max_early_data); +uint32_t SSL_get_max_early_data(const SSL *s); +int SSL_CTX_set_recv_max_early_data(SSL_CTX *ctx, uint32_t recv_max_early_data); +uint32_t SSL_CTX_get_recv_max_early_data(const SSL_CTX *ctx); +int SSL_set_recv_max_early_data(SSL *s, uint32_t recv_max_early_data); +uint32_t SSL_get_recv_max_early_data(const SSL *s); + +#ifdef __cplusplus +} +#endif + +# include +# include +# include /* This is mostly sslv3 with a few tweaks */ +# include /* Datagram TLS */ +# include /* Support for the use_srtp extension */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * These need to be after the above set of includes due to a compiler bug + * in VisualStudio 2015 + */ +DEFINE_STACK_OF_CONST(SSL_CIPHER) +DEFINE_STACK_OF(SSL_COMP) + +/* compatibility */ +# define SSL_set_app_data(s,arg) (SSL_set_ex_data(s,0,(char *)(arg))) +# define SSL_get_app_data(s) (SSL_get_ex_data(s,0)) +# define SSL_SESSION_set_app_data(s,a) (SSL_SESSION_set_ex_data(s,0, \ + (char *)(a))) +# define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s,0)) +# define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx,0)) +# define SSL_CTX_set_app_data(ctx,arg) (SSL_CTX_set_ex_data(ctx,0, \ + (char *)(arg))) +DEPRECATEDIN_1_1_0(void SSL_set_debug(SSL *s, int debug)) + +/* TLSv1.3 KeyUpdate message types */ +/* -1 used so that this is an invalid value for the on-the-wire protocol */ +#define SSL_KEY_UPDATE_NONE -1 +/* Values as defined for the on-the-wire protocol */ +#define SSL_KEY_UPDATE_NOT_REQUESTED 0 +#define SSL_KEY_UPDATE_REQUESTED 1 + +/* + * The valid handshake states (one for each type message sent and one for each + * type of message received). There are also two "special" states: + * TLS = TLS or DTLS state + * DTLS = DTLS specific state + * CR/SR = Client Read/Server Read + * CW/SW = Client Write/Server Write + * + * The "special" states are: + * TLS_ST_BEFORE = No handshake has been initiated yet + * TLS_ST_OK = A handshake has been successfully completed + */ +typedef enum { + TLS_ST_BEFORE, + TLS_ST_OK, + DTLS_ST_CR_HELLO_VERIFY_REQUEST, + TLS_ST_CR_SRVR_HELLO, + TLS_ST_CR_CERT, + TLS_ST_CR_CERT_STATUS, + TLS_ST_CR_KEY_EXCH, + TLS_ST_CR_CERT_REQ, + TLS_ST_CR_SRVR_DONE, + TLS_ST_CR_SESSION_TICKET, + TLS_ST_CR_CHANGE, + TLS_ST_CR_FINISHED, + TLS_ST_CW_CLNT_HELLO, + TLS_ST_CW_CERT, + TLS_ST_CW_KEY_EXCH, + TLS_ST_CW_CERT_VRFY, + TLS_ST_CW_CHANGE, + TLS_ST_CW_NEXT_PROTO, + TLS_ST_CW_FINISHED, + TLS_ST_SW_HELLO_REQ, + TLS_ST_SR_CLNT_HELLO, + DTLS_ST_SW_HELLO_VERIFY_REQUEST, + TLS_ST_SW_SRVR_HELLO, + TLS_ST_SW_CERT, + TLS_ST_SW_KEY_EXCH, + TLS_ST_SW_CERT_REQ, + TLS_ST_SW_SRVR_DONE, + TLS_ST_SR_CERT, + TLS_ST_SR_KEY_EXCH, + TLS_ST_SR_CERT_VRFY, + TLS_ST_SR_NEXT_PROTO, + TLS_ST_SR_CHANGE, + TLS_ST_SR_FINISHED, + TLS_ST_SW_SESSION_TICKET, + TLS_ST_SW_CERT_STATUS, + TLS_ST_SW_CHANGE, + TLS_ST_SW_FINISHED, + TLS_ST_SW_ENCRYPTED_EXTENSIONS, + TLS_ST_CR_ENCRYPTED_EXTENSIONS, + TLS_ST_CR_CERT_VRFY, + TLS_ST_SW_CERT_VRFY, + TLS_ST_CR_HELLO_REQ, + TLS_ST_SW_KEY_UPDATE, + TLS_ST_CW_KEY_UPDATE, + TLS_ST_SR_KEY_UPDATE, + TLS_ST_CR_KEY_UPDATE, + TLS_ST_EARLY_DATA, + TLS_ST_PENDING_EARLY_DATA_END, + TLS_ST_CW_END_OF_EARLY_DATA, + TLS_ST_SR_END_OF_EARLY_DATA +} OSSL_HANDSHAKE_STATE; + +/* + * Most of the following state values are no longer used and are defined to be + * the closest equivalent value in the current state machine code. Not all + * defines have an equivalent and are set to a dummy value (-1). SSL_ST_CONNECT + * and SSL_ST_ACCEPT are still in use in the definition of SSL_CB_ACCEPT_LOOP, + * SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP and SSL_CB_CONNECT_EXIT. + */ + +# define SSL_ST_CONNECT 0x1000 +# define SSL_ST_ACCEPT 0x2000 + +# define SSL_ST_MASK 0x0FFF + +# define SSL_CB_LOOP 0x01 +# define SSL_CB_EXIT 0x02 +# define SSL_CB_READ 0x04 +# define SSL_CB_WRITE 0x08 +# define SSL_CB_ALERT 0x4000/* used in callback */ +# define SSL_CB_READ_ALERT (SSL_CB_ALERT|SSL_CB_READ) +# define SSL_CB_WRITE_ALERT (SSL_CB_ALERT|SSL_CB_WRITE) +# define SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT|SSL_CB_LOOP) +# define SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT|SSL_CB_EXIT) +# define SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT|SSL_CB_LOOP) +# define SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT|SSL_CB_EXIT) +# define SSL_CB_HANDSHAKE_START 0x10 +# define SSL_CB_HANDSHAKE_DONE 0x20 + +/* Is the SSL_connection established? */ +# define SSL_in_connect_init(a) (SSL_in_init(a) && !SSL_is_server(a)) +# define SSL_in_accept_init(a) (SSL_in_init(a) && SSL_is_server(a)) +int SSL_in_init(const SSL *s); +int SSL_in_before(const SSL *s); +int SSL_is_init_finished(const SSL *s); + +/* + * The following 3 states are kept in ssl->rlayer.rstate when reads fail, you + * should not need these + */ +# define SSL_ST_READ_HEADER 0xF0 +# define SSL_ST_READ_BODY 0xF1 +# define SSL_ST_READ_DONE 0xF2 + +/*- + * Obtain latest Finished message + * -- that we sent (SSL_get_finished) + * -- that we expected from peer (SSL_get_peer_finished). + * Returns length (0 == no Finished so far), copies up to 'count' bytes. + */ +size_t SSL_get_finished(const SSL *s, void *buf, size_t count); +size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count); + +/* + * use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 3 options are + * 'ored' with SSL_VERIFY_PEER if they are desired + */ +# define SSL_VERIFY_NONE 0x00 +# define SSL_VERIFY_PEER 0x01 +# define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02 +# define SSL_VERIFY_CLIENT_ONCE 0x04 +# define SSL_VERIFY_POST_HANDSHAKE 0x08 + +# if OPENSSL_API_COMPAT < 0x10100000L +# define OpenSSL_add_ssl_algorithms() SSL_library_init() +# define SSLeay_add_ssl_algorithms() SSL_library_init() +# endif + +/* More backward compatibility */ +# define SSL_get_cipher(s) \ + SSL_CIPHER_get_name(SSL_get_current_cipher(s)) +# define SSL_get_cipher_bits(s,np) \ + SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np) +# define SSL_get_cipher_version(s) \ + SSL_CIPHER_get_version(SSL_get_current_cipher(s)) +# define SSL_get_cipher_name(s) \ + SSL_CIPHER_get_name(SSL_get_current_cipher(s)) +# define SSL_get_time(a) SSL_SESSION_get_time(a) +# define SSL_set_time(a,b) SSL_SESSION_set_time((a),(b)) +# define SSL_get_timeout(a) SSL_SESSION_get_timeout(a) +# define SSL_set_timeout(a,b) SSL_SESSION_set_timeout((a),(b)) + +# define d2i_SSL_SESSION_bio(bp,s_id) ASN1_d2i_bio_of(SSL_SESSION,SSL_SESSION_new,d2i_SSL_SESSION,bp,s_id) +# define i2d_SSL_SESSION_bio(bp,s_id) ASN1_i2d_bio_of(SSL_SESSION,i2d_SSL_SESSION,bp,s_id) + +DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION) +# define SSL_AD_REASON_OFFSET 1000/* offset to get SSL_R_... value + * from SSL_AD_... */ +/* These alert types are for SSLv3 and TLSv1 */ +# define SSL_AD_CLOSE_NOTIFY SSL3_AD_CLOSE_NOTIFY +/* fatal */ +# define SSL_AD_UNEXPECTED_MESSAGE SSL3_AD_UNEXPECTED_MESSAGE +/* fatal */ +# define SSL_AD_BAD_RECORD_MAC SSL3_AD_BAD_RECORD_MAC +# define SSL_AD_DECRYPTION_FAILED TLS1_AD_DECRYPTION_FAILED +# define SSL_AD_RECORD_OVERFLOW TLS1_AD_RECORD_OVERFLOW +/* fatal */ +# define SSL_AD_DECOMPRESSION_FAILURE SSL3_AD_DECOMPRESSION_FAILURE +/* fatal */ +# define SSL_AD_HANDSHAKE_FAILURE SSL3_AD_HANDSHAKE_FAILURE +/* Not for TLS */ +# define SSL_AD_NO_CERTIFICATE SSL3_AD_NO_CERTIFICATE +# define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE +# define SSL_AD_UNSUPPORTED_CERTIFICATE SSL3_AD_UNSUPPORTED_CERTIFICATE +# define SSL_AD_CERTIFICATE_REVOKED SSL3_AD_CERTIFICATE_REVOKED +# define SSL_AD_CERTIFICATE_EXPIRED SSL3_AD_CERTIFICATE_EXPIRED +# define SSL_AD_CERTIFICATE_UNKNOWN SSL3_AD_CERTIFICATE_UNKNOWN +/* fatal */ +# define SSL_AD_ILLEGAL_PARAMETER SSL3_AD_ILLEGAL_PARAMETER +/* fatal */ +# define SSL_AD_UNKNOWN_CA TLS1_AD_UNKNOWN_CA +/* fatal */ +# define SSL_AD_ACCESS_DENIED TLS1_AD_ACCESS_DENIED +/* fatal */ +# define SSL_AD_DECODE_ERROR TLS1_AD_DECODE_ERROR +# define SSL_AD_DECRYPT_ERROR TLS1_AD_DECRYPT_ERROR +/* fatal */ +# define SSL_AD_EXPORT_RESTRICTION TLS1_AD_EXPORT_RESTRICTION +/* fatal */ +# define SSL_AD_PROTOCOL_VERSION TLS1_AD_PROTOCOL_VERSION +/* fatal */ +# define SSL_AD_INSUFFICIENT_SECURITY TLS1_AD_INSUFFICIENT_SECURITY +/* fatal */ +# define SSL_AD_INTERNAL_ERROR TLS1_AD_INTERNAL_ERROR +# define SSL_AD_USER_CANCELLED TLS1_AD_USER_CANCELLED +# define SSL_AD_NO_RENEGOTIATION TLS1_AD_NO_RENEGOTIATION +# define SSL_AD_MISSING_EXTENSION TLS13_AD_MISSING_EXTENSION +# define SSL_AD_CERTIFICATE_REQUIRED TLS13_AD_CERTIFICATE_REQUIRED +# define SSL_AD_UNSUPPORTED_EXTENSION TLS1_AD_UNSUPPORTED_EXTENSION +# define SSL_AD_CERTIFICATE_UNOBTAINABLE TLS1_AD_CERTIFICATE_UNOBTAINABLE +# define SSL_AD_UNRECOGNIZED_NAME TLS1_AD_UNRECOGNIZED_NAME +# define SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE +# define SSL_AD_BAD_CERTIFICATE_HASH_VALUE TLS1_AD_BAD_CERTIFICATE_HASH_VALUE +/* fatal */ +# define SSL_AD_UNKNOWN_PSK_IDENTITY TLS1_AD_UNKNOWN_PSK_IDENTITY +/* fatal */ +# define SSL_AD_INAPPROPRIATE_FALLBACK TLS1_AD_INAPPROPRIATE_FALLBACK +# define SSL_AD_NO_APPLICATION_PROTOCOL TLS1_AD_NO_APPLICATION_PROTOCOL +# define SSL_ERROR_NONE 0 +# define SSL_ERROR_SSL 1 +# define SSL_ERROR_WANT_READ 2 +# define SSL_ERROR_WANT_WRITE 3 +# define SSL_ERROR_WANT_X509_LOOKUP 4 +# define SSL_ERROR_SYSCALL 5/* look at error stack/return + * value/errno */ +# define SSL_ERROR_ZERO_RETURN 6 +# define SSL_ERROR_WANT_CONNECT 7 +# define SSL_ERROR_WANT_ACCEPT 8 +# define SSL_ERROR_WANT_ASYNC 9 +# define SSL_ERROR_WANT_ASYNC_JOB 10 +# define SSL_ERROR_WANT_CLIENT_HELLO_CB 11 +# define SSL_CTRL_SET_TMP_DH 3 +# define SSL_CTRL_SET_TMP_ECDH 4 +# define SSL_CTRL_SET_TMP_DH_CB 6 +# define SSL_CTRL_GET_CLIENT_CERT_REQUEST 9 +# define SSL_CTRL_GET_NUM_RENEGOTIATIONS 10 +# define SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS 11 +# define SSL_CTRL_GET_TOTAL_RENEGOTIATIONS 12 +# define SSL_CTRL_GET_FLAGS 13 +# define SSL_CTRL_EXTRA_CHAIN_CERT 14 +# define SSL_CTRL_SET_MSG_CALLBACK 15 +# define SSL_CTRL_SET_MSG_CALLBACK_ARG 16 +/* only applies to datagram connections */ +# define SSL_CTRL_SET_MTU 17 +/* Stats */ +# define SSL_CTRL_SESS_NUMBER 20 +# define SSL_CTRL_SESS_CONNECT 21 +# define SSL_CTRL_SESS_CONNECT_GOOD 22 +# define SSL_CTRL_SESS_CONNECT_RENEGOTIATE 23 +# define SSL_CTRL_SESS_ACCEPT 24 +# define SSL_CTRL_SESS_ACCEPT_GOOD 25 +# define SSL_CTRL_SESS_ACCEPT_RENEGOTIATE 26 +# define SSL_CTRL_SESS_HIT 27 +# define SSL_CTRL_SESS_CB_HIT 28 +# define SSL_CTRL_SESS_MISSES 29 +# define SSL_CTRL_SESS_TIMEOUTS 30 +# define SSL_CTRL_SESS_CACHE_FULL 31 +# define SSL_CTRL_MODE 33 +# define SSL_CTRL_GET_READ_AHEAD 40 +# define SSL_CTRL_SET_READ_AHEAD 41 +# define SSL_CTRL_SET_SESS_CACHE_SIZE 42 +# define SSL_CTRL_GET_SESS_CACHE_SIZE 43 +# define SSL_CTRL_SET_SESS_CACHE_MODE 44 +# define SSL_CTRL_GET_SESS_CACHE_MODE 45 +# define SSL_CTRL_GET_MAX_CERT_LIST 50 +# define SSL_CTRL_SET_MAX_CERT_LIST 51 +# define SSL_CTRL_SET_MAX_SEND_FRAGMENT 52 +/* see tls1.h for macros based on these */ +# define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53 +# define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54 +# define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 +# define SSL_CTRL_SET_TLSEXT_DEBUG_CB 56 +# define SSL_CTRL_SET_TLSEXT_DEBUG_ARG 57 +# define SSL_CTRL_GET_TLSEXT_TICKET_KEYS 58 +# define SSL_CTRL_SET_TLSEXT_TICKET_KEYS 59 +/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT 60 */ +/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB 61 */ +/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG 62 */ +# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB 63 +# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG 64 +# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE 65 +# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS 66 +# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS 67 +# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS 68 +# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS 69 +# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP 70 +# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP 71 +# define SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB 72 +# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB 75 +# define SSL_CTRL_SET_SRP_VERIFY_PARAM_CB 76 +# define SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB 77 +# define SSL_CTRL_SET_SRP_ARG 78 +# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME 79 +# define SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH 80 +# define SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD 81 +# ifndef OPENSSL_NO_HEARTBEATS +# define SSL_CTRL_DTLS_EXT_SEND_HEARTBEAT 85 +# define SSL_CTRL_GET_DTLS_EXT_HEARTBEAT_PENDING 86 +# define SSL_CTRL_SET_DTLS_EXT_HEARTBEAT_NO_REQUESTS 87 +# endif +# define DTLS_CTRL_GET_TIMEOUT 73 +# define DTLS_CTRL_HANDLE_TIMEOUT 74 +# define SSL_CTRL_GET_RI_SUPPORT 76 +# define SSL_CTRL_CLEAR_MODE 78 +# define SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB 79 +# define SSL_CTRL_GET_EXTRA_CHAIN_CERTS 82 +# define SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS 83 +# define SSL_CTRL_CHAIN 88 +# define SSL_CTRL_CHAIN_CERT 89 +# define SSL_CTRL_GET_GROUPS 90 +# define SSL_CTRL_SET_GROUPS 91 +# define SSL_CTRL_SET_GROUPS_LIST 92 +# define SSL_CTRL_GET_SHARED_GROUP 93 +# define SSL_CTRL_SET_SIGALGS 97 +# define SSL_CTRL_SET_SIGALGS_LIST 98 +# define SSL_CTRL_CERT_FLAGS 99 +# define SSL_CTRL_CLEAR_CERT_FLAGS 100 +# define SSL_CTRL_SET_CLIENT_SIGALGS 101 +# define SSL_CTRL_SET_CLIENT_SIGALGS_LIST 102 +# define SSL_CTRL_GET_CLIENT_CERT_TYPES 103 +# define SSL_CTRL_SET_CLIENT_CERT_TYPES 104 +# define SSL_CTRL_BUILD_CERT_CHAIN 105 +# define SSL_CTRL_SET_VERIFY_CERT_STORE 106 +# define SSL_CTRL_SET_CHAIN_CERT_STORE 107 +# define SSL_CTRL_GET_PEER_SIGNATURE_NID 108 +# define SSL_CTRL_GET_SERVER_TMP_KEY 109 +# define SSL_CTRL_GET_RAW_CIPHERLIST 110 +# define SSL_CTRL_GET_EC_POINT_FORMATS 111 +# define SSL_CTRL_GET_CHAIN_CERTS 115 +# define SSL_CTRL_SELECT_CURRENT_CERT 116 +# define SSL_CTRL_SET_CURRENT_CERT 117 +# define SSL_CTRL_SET_DH_AUTO 118 +# define DTLS_CTRL_SET_LINK_MTU 120 +# define DTLS_CTRL_GET_LINK_MIN_MTU 121 +# define SSL_CTRL_GET_EXTMS_SUPPORT 122 +# define SSL_CTRL_SET_MIN_PROTO_VERSION 123 +# define SSL_CTRL_SET_MAX_PROTO_VERSION 124 +# define SSL_CTRL_SET_SPLIT_SEND_FRAGMENT 125 +# define SSL_CTRL_SET_MAX_PIPELINES 126 +# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE 127 +# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB 128 +# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG 129 +# define SSL_CTRL_GET_MIN_PROTO_VERSION 130 +# define SSL_CTRL_GET_MAX_PROTO_VERSION 131 +# define SSL_CERT_SET_FIRST 1 +# define SSL_CERT_SET_NEXT 2 +# define SSL_CERT_SET_SERVER 3 +# define DTLSv1_get_timeout(ssl, arg) \ + SSL_ctrl(ssl,DTLS_CTRL_GET_TIMEOUT,0, (void *)(arg)) +# define DTLSv1_handle_timeout(ssl) \ + SSL_ctrl(ssl,DTLS_CTRL_HANDLE_TIMEOUT,0, NULL) +# define SSL_num_renegotiations(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_GET_NUM_RENEGOTIATIONS,0,NULL) +# define SSL_clear_num_renegotiations(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS,0,NULL) +# define SSL_total_renegotiations(ssl) \ + SSL_ctrl((ssl),SSL_CTRL_GET_TOTAL_RENEGOTIATIONS,0,NULL) +# define SSL_CTX_set_tmp_dh(ctx,dh) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH,0,(char *)(dh)) +# define SSL_CTX_set_tmp_ecdh(ctx,ecdh) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh)) +# define SSL_CTX_set_dh_auto(ctx, onoff) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_DH_AUTO,onoff,NULL) +# define SSL_set_dh_auto(s, onoff) \ + SSL_ctrl(s,SSL_CTRL_SET_DH_AUTO,onoff,NULL) +# define SSL_set_tmp_dh(ssl,dh) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH,0,(char *)(dh)) +# define SSL_set_tmp_ecdh(ssl,ecdh) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh)) +# define SSL_CTX_add_extra_chain_cert(ctx,x509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_EXTRA_CHAIN_CERT,0,(char *)(x509)) +# define SSL_CTX_get_extra_chain_certs(ctx,px509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,0,px509) +# define SSL_CTX_get_extra_chain_certs_only(ctx,px509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,1,px509) +# define SSL_CTX_clear_extra_chain_certs(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS,0,NULL) +# define SSL_CTX_set0_chain(ctx,sk) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)(sk)) +# define SSL_CTX_set1_chain(ctx,sk) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)(sk)) +# define SSL_CTX_add0_chain_cert(ctx,x509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)(x509)) +# define SSL_CTX_add1_chain_cert(ctx,x509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)(x509)) +# define SSL_CTX_get0_chain_certs(ctx,px509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509) +# define SSL_CTX_clear_chain_certs(ctx) \ + SSL_CTX_set0_chain(ctx,NULL) +# define SSL_CTX_build_cert_chain(ctx, flags) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL) +# define SSL_CTX_select_current_cert(ctx,x509) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509)) +# define SSL_CTX_set_current_cert(ctx, op) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL) +# define SSL_CTX_set0_verify_cert_store(ctx,st) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st)) +# define SSL_CTX_set1_verify_cert_store(ctx,st) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st)) +# define SSL_CTX_set0_chain_cert_store(ctx,st) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st)) +# define SSL_CTX_set1_chain_cert_store(ctx,st) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st)) +# define SSL_set0_chain(ctx,sk) \ + SSL_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)(sk)) +# define SSL_set1_chain(ctx,sk) \ + SSL_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)(sk)) +# define SSL_add0_chain_cert(ctx,x509) \ + SSL_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)(x509)) +# define SSL_add1_chain_cert(ctx,x509) \ + SSL_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)(x509)) +# define SSL_get0_chain_certs(ctx,px509) \ + SSL_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509) +# define SSL_clear_chain_certs(ctx) \ + SSL_set0_chain(ctx,NULL) +# define SSL_build_cert_chain(s, flags) \ + SSL_ctrl(s,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL) +# define SSL_select_current_cert(ctx,x509) \ + SSL_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509)) +# define SSL_set_current_cert(ctx,op) \ + SSL_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL) +# define SSL_set0_verify_cert_store(s,st) \ + SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st)) +# define SSL_set1_verify_cert_store(s,st) \ + SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st)) +# define SSL_set0_chain_cert_store(s,st) \ + SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st)) +# define SSL_set1_chain_cert_store(s,st) \ + SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st)) +# define SSL_get1_groups(ctx, s) \ + SSL_ctrl(ctx,SSL_CTRL_GET_GROUPS,0,(char *)(s)) +# define SSL_CTX_set1_groups(ctx, glist, glistlen) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS,glistlen,(char *)(glist)) +# define SSL_CTX_set1_groups_list(ctx, s) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(s)) +# define SSL_set1_groups(ctx, glist, glistlen) \ + SSL_ctrl(ctx,SSL_CTRL_SET_GROUPS,glistlen,(char *)(glist)) +# define SSL_set1_groups_list(ctx, s) \ + SSL_ctrl(ctx,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(s)) +# define SSL_get_shared_group(s, n) \ + SSL_ctrl(s,SSL_CTRL_GET_SHARED_GROUP,n,NULL) +# define SSL_CTX_set1_sigalgs(ctx, slist, slistlen) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)(slist)) +# define SSL_CTX_set1_sigalgs_list(ctx, s) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(s)) +# define SSL_set1_sigalgs(ctx, slist, slistlen) \ + SSL_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)(slist)) +# define SSL_set1_sigalgs_list(ctx, s) \ + SSL_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(s)) +# define SSL_CTX_set1_client_sigalgs(ctx, slist, slistlen) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(int *)(slist)) +# define SSL_CTX_set1_client_sigalgs_list(ctx, s) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(s)) +# define SSL_set1_client_sigalgs(ctx, slist, slistlen) \ + SSL_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,clistlen,(int *)(slist)) +# define SSL_set1_client_sigalgs_list(ctx, s) \ + SSL_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(s)) +# define SSL_get0_certificate_types(s, clist) \ + SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, (char *)(clist)) +# define SSL_CTX_set1_client_certificate_types(ctx, clist, clistlen) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen, \ + (char *)(clist)) +# define SSL_set1_client_certificate_types(s, clist, clistlen) \ + SSL_ctrl(s,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)(clist)) +# define SSL_get_peer_signature_nid(s, pn) \ + SSL_ctrl(s,SSL_CTRL_GET_PEER_SIGNATURE_NID,0,pn) +# define SSL_get_server_tmp_key(s, pk) \ + SSL_ctrl(s,SSL_CTRL_GET_SERVER_TMP_KEY,0,pk) +# define SSL_get0_raw_cipherlist(s, plst) \ + SSL_ctrl(s,SSL_CTRL_GET_RAW_CIPHERLIST,0,plst) +# define SSL_get0_ec_point_formats(s, plst) \ + SSL_ctrl(s,SSL_CTRL_GET_EC_POINT_FORMATS,0,plst) +# define SSL_CTX_set_min_proto_version(ctx, version) \ + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL) +# define SSL_CTX_set_max_proto_version(ctx, version) \ + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL) +# define SSL_CTX_get_min_proto_version(ctx) \ + SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL) +# define SSL_CTX_get_max_proto_version(ctx) \ + SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL) +# define SSL_set_min_proto_version(s, version) \ + SSL_ctrl(s, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL) +# define SSL_set_max_proto_version(s, version) \ + SSL_ctrl(s, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL) +# define SSL_get_min_proto_version(s) \ + SSL_ctrl(s, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL) +# define SSL_get_max_proto_version(s) \ + SSL_ctrl(s, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL) + +/* + * The following symbol names are old and obsolete. They are kept + * for compatibility reasons only and should not be used anymore. + */ +# define SSL_CTRL_GET_CURVES SSL_CTRL_GET_GROUPS +# define SSL_CTRL_SET_CURVES SSL_CTRL_SET_GROUPS +# define SSL_CTRL_SET_CURVES_LIST SSL_CTRL_SET_GROUPS_LIST +# define SSL_CTRL_GET_SHARED_CURVE SSL_CTRL_GET_SHARED_GROUP + +# define SSL_get1_curves SSL_get1_groups +# define SSL_CTX_set1_curves SSL_CTX_set1_groups +# define SSL_CTX_set1_curves_list SSL_CTX_set1_groups_list +# define SSL_set1_curves SSL_set1_groups +# define SSL_set1_curves_list SSL_set1_groups_list +# define SSL_get_shared_curve SSL_get_shared_group + + +# if OPENSSL_API_COMPAT < 0x10100000L +/* Provide some compatibility macros for removed functionality. */ +# define SSL_CTX_need_tmp_RSA(ctx) 0 +# define SSL_CTX_set_tmp_rsa(ctx,rsa) 1 +# define SSL_need_tmp_RSA(ssl) 0 +# define SSL_set_tmp_rsa(ssl,rsa) 1 +# define SSL_CTX_set_ecdh_auto(dummy, onoff) ((onoff) != 0) +# define SSL_set_ecdh_auto(dummy, onoff) ((onoff) != 0) +/* + * We "pretend" to call the callback to avoid warnings about unused static + * functions. + */ +# define SSL_CTX_set_tmp_rsa_callback(ctx, cb) while(0) (cb)(NULL, 0, 0) +# define SSL_set_tmp_rsa_callback(ssl, cb) while(0) (cb)(NULL, 0, 0) +# endif +__owur const BIO_METHOD *BIO_f_ssl(void); +__owur BIO *BIO_new_ssl(SSL_CTX *ctx, int client); +__owur BIO *BIO_new_ssl_connect(SSL_CTX *ctx); +__owur BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx); +__owur int BIO_ssl_copy_session_id(BIO *to, BIO *from); +void BIO_ssl_shutdown(BIO *ssl_bio); + +__owur int SSL_CTX_set_cipher_list(SSL_CTX *, const char *str); +__owur SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth); +int SSL_CTX_up_ref(SSL_CTX *ctx); +void SSL_CTX_free(SSL_CTX *); +__owur long SSL_CTX_set_timeout(SSL_CTX *ctx, long t); +__owur long SSL_CTX_get_timeout(const SSL_CTX *ctx); +__owur X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *); +void SSL_CTX_set_cert_store(SSL_CTX *, X509_STORE *); +void SSL_CTX_set1_cert_store(SSL_CTX *, X509_STORE *); +__owur int SSL_want(const SSL *s); +__owur int SSL_clear(SSL *s); + +void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm); + +__owur const SSL_CIPHER *SSL_get_current_cipher(const SSL *s); +__owur const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s); +__owur int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits); +__owur const char *SSL_CIPHER_get_version(const SSL_CIPHER *c); +__owur const char *SSL_CIPHER_get_name(const SSL_CIPHER *c); +__owur const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c); +__owur const char *OPENSSL_cipher_name(const char *rfc_name); +__owur uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *c); +__owur uint16_t SSL_CIPHER_get_protocol_id(const SSL_CIPHER *c); +__owur int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c); +__owur int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c); +__owur const EVP_MD *SSL_CIPHER_get_handshake_digest(const SSL_CIPHER *c); +__owur int SSL_CIPHER_is_aead(const SSL_CIPHER *c); + +__owur int SSL_get_fd(const SSL *s); +__owur int SSL_get_rfd(const SSL *s); +__owur int SSL_get_wfd(const SSL *s); +__owur const char *SSL_get_cipher_list(const SSL *s, int n); +__owur char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size); +__owur int SSL_get_read_ahead(const SSL *s); +__owur int SSL_pending(const SSL *s); +__owur int SSL_has_pending(const SSL *s); +# ifndef OPENSSL_NO_SOCK +__owur int SSL_set_fd(SSL *s, int fd); +__owur int SSL_set_rfd(SSL *s, int fd); +__owur int SSL_set_wfd(SSL *s, int fd); +# endif +void SSL_set0_rbio(SSL *s, BIO *rbio); +void SSL_set0_wbio(SSL *s, BIO *wbio); +void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio); +__owur BIO *SSL_get_rbio(const SSL *s); +__owur BIO *SSL_get_wbio(const SSL *s); +__owur int SSL_set_cipher_list(SSL *s, const char *str); +__owur int SSL_CTX_set_ciphersuites(SSL_CTX *ctx, const char *str); +__owur int SSL_set_ciphersuites(SSL *s, const char *str); +void SSL_set_read_ahead(SSL *s, int yes); +__owur int SSL_get_verify_mode(const SSL *s); +__owur int SSL_get_verify_depth(const SSL *s); +__owur SSL_verify_cb SSL_get_verify_callback(const SSL *s); +void SSL_set_verify(SSL *s, int mode, SSL_verify_cb callback); +void SSL_set_verify_depth(SSL *s, int depth); +void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg); +# ifndef OPENSSL_NO_RSA +__owur int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa); +__owur int SSL_use_RSAPrivateKey_ASN1(SSL *ssl, const unsigned char *d, + long len); +# endif +__owur int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey); +__owur int SSL_use_PrivateKey_ASN1(int pk, SSL *ssl, const unsigned char *d, + long len); +__owur int SSL_use_certificate(SSL *ssl, X509 *x); +__owur int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len); +__owur int SSL_use_cert_and_key(SSL *ssl, X509 *x509, EVP_PKEY *privatekey, + STACK_OF(X509) *chain, int override); + + +/* serverinfo file format versions */ +# define SSL_SERVERINFOV1 1 +# define SSL_SERVERINFOV2 2 + +/* Set serverinfo data for the current active cert. */ +__owur int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, + size_t serverinfo_length); +__owur int SSL_CTX_use_serverinfo_ex(SSL_CTX *ctx, unsigned int version, + const unsigned char *serverinfo, + size_t serverinfo_length); +__owur int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file); + +#ifndef OPENSSL_NO_RSA +__owur int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type); +#endif + +__owur int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type); +__owur int SSL_use_certificate_file(SSL *ssl, const char *file, int type); + +#ifndef OPENSSL_NO_RSA +__owur int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, + int type); +#endif +__owur int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, + int type); +__owur int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, + int type); +/* PEM type */ +__owur int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file); +__owur int SSL_use_certificate_chain_file(SSL *ssl, const char *file); +__owur STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file); +__owur int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs, + const char *file); +int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs, + const char *dir); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define SSL_load_error_strings() \ + OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS \ + | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL) +# endif + +__owur const char *SSL_state_string(const SSL *s); +__owur const char *SSL_rstate_string(const SSL *s); +__owur const char *SSL_state_string_long(const SSL *s); +__owur const char *SSL_rstate_string_long(const SSL *s); +__owur long SSL_SESSION_get_time(const SSL_SESSION *s); +__owur long SSL_SESSION_set_time(SSL_SESSION *s, long t); +__owur long SSL_SESSION_get_timeout(const SSL_SESSION *s); +__owur long SSL_SESSION_set_timeout(SSL_SESSION *s, long t); +__owur int SSL_SESSION_get_protocol_version(const SSL_SESSION *s); +__owur int SSL_SESSION_set_protocol_version(SSL_SESSION *s, int version); + +__owur const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s); +__owur int SSL_SESSION_set1_hostname(SSL_SESSION *s, const char *hostname); +void SSL_SESSION_get0_alpn_selected(const SSL_SESSION *s, + const unsigned char **alpn, + size_t *len); +__owur int SSL_SESSION_set1_alpn_selected(SSL_SESSION *s, + const unsigned char *alpn, + size_t len); +__owur const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s); +__owur int SSL_SESSION_set_cipher(SSL_SESSION *s, const SSL_CIPHER *cipher); +__owur int SSL_SESSION_has_ticket(const SSL_SESSION *s); +__owur unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s); +void SSL_SESSION_get0_ticket(const SSL_SESSION *s, const unsigned char **tick, + size_t *len); +__owur uint32_t SSL_SESSION_get_max_early_data(const SSL_SESSION *s); +__owur int SSL_SESSION_set_max_early_data(SSL_SESSION *s, + uint32_t max_early_data); +__owur int SSL_copy_session_id(SSL *to, const SSL *from); +__owur X509 *SSL_SESSION_get0_peer(SSL_SESSION *s); +__owur int SSL_SESSION_set1_id_context(SSL_SESSION *s, + const unsigned char *sid_ctx, + unsigned int sid_ctx_len); +__owur int SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid, + unsigned int sid_len); +__owur int SSL_SESSION_is_resumable(const SSL_SESSION *s); + +__owur SSL_SESSION *SSL_SESSION_new(void); +__owur SSL_SESSION *SSL_SESSION_dup(SSL_SESSION *src); +const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, + unsigned int *len); +const unsigned char *SSL_SESSION_get0_id_context(const SSL_SESSION *s, + unsigned int *len); +__owur unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s); +# ifndef OPENSSL_NO_STDIO +int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *ses); +# endif +int SSL_SESSION_print(BIO *fp, const SSL_SESSION *ses); +int SSL_SESSION_print_keylog(BIO *bp, const SSL_SESSION *x); +int SSL_SESSION_up_ref(SSL_SESSION *ses); +void SSL_SESSION_free(SSL_SESSION *ses); +__owur int i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp); +__owur int SSL_set_session(SSL *to, SSL_SESSION *session); +int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *session); +int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *session); +__owur int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb); +__owur int SSL_set_generate_session_id(SSL *s, GEN_SESSION_CB cb); +__owur int SSL_has_matching_session_id(const SSL *s, + const unsigned char *id, + unsigned int id_len); +SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp, + long length); + +# ifdef HEADER_X509_H +__owur X509 *SSL_get_peer_certificate(const SSL *s); +# endif + +__owur STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s); + +__owur int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); +__owur int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); +__owur SSL_verify_cb SSL_CTX_get_verify_callback(const SSL_CTX *ctx); +void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb callback); +void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); +void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, + int (*cb) (X509_STORE_CTX *, void *), + void *arg); +void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg), + void *arg); +# ifndef OPENSSL_NO_RSA +__owur int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa); +__owur int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, + long len); +# endif +__owur int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); +__owur int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, + const unsigned char *d, long len); +__owur int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); +__owur int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, + const unsigned char *d); +__owur int SSL_CTX_use_cert_and_key(SSL_CTX *ctx, X509 *x509, EVP_PKEY *privatekey, + STACK_OF(X509) *chain, int override); + +void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb); +void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u); +pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx); +void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx); +void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb); +void SSL_set_default_passwd_cb_userdata(SSL *s, void *u); +pem_password_cb *SSL_get_default_passwd_cb(SSL *s); +void *SSL_get_default_passwd_cb_userdata(SSL *s); + +__owur int SSL_CTX_check_private_key(const SSL_CTX *ctx); +__owur int SSL_check_private_key(const SSL *ctx); + +__owur int SSL_CTX_set_session_id_context(SSL_CTX *ctx, + const unsigned char *sid_ctx, + unsigned int sid_ctx_len); + +SSL *SSL_new(SSL_CTX *ctx); +int SSL_up_ref(SSL *s); +int SSL_is_dtls(const SSL *s); +__owur int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx, + unsigned int sid_ctx_len); + +__owur int SSL_CTX_set_purpose(SSL_CTX *ctx, int purpose); +__owur int SSL_set_purpose(SSL *ssl, int purpose); +__owur int SSL_CTX_set_trust(SSL_CTX *ctx, int trust); +__owur int SSL_set_trust(SSL *ssl, int trust); + +__owur int SSL_set1_host(SSL *s, const char *hostname); +__owur int SSL_add1_host(SSL *s, const char *hostname); +__owur const char *SSL_get0_peername(SSL *s); +void SSL_set_hostflags(SSL *s, unsigned int flags); + +__owur int SSL_CTX_dane_enable(SSL_CTX *ctx); +__owur int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, + uint8_t mtype, uint8_t ord); +__owur int SSL_dane_enable(SSL *s, const char *basedomain); +__owur int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector, + uint8_t mtype, unsigned const char *data, size_t dlen); +__owur int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki); +__owur int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector, + uint8_t *mtype, unsigned const char **data, + size_t *dlen); +/* + * Bridge opacity barrier between libcrypt and libssl, also needed to support + * offline testing in test/danetest.c + */ +SSL_DANE *SSL_get0_dane(SSL *ssl); +/* + * DANE flags + */ +unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags); +unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags); +unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags); +unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags); + +__owur int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm); +__owur int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm); + +__owur X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx); +__owur X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl); + +# ifndef OPENSSL_NO_SRP +int SSL_CTX_set_srp_username(SSL_CTX *ctx, char *name); +int SSL_CTX_set_srp_password(SSL_CTX *ctx, char *password); +int SSL_CTX_set_srp_strength(SSL_CTX *ctx, int strength); +int SSL_CTX_set_srp_client_pwd_callback(SSL_CTX *ctx, + char *(*cb) (SSL *, void *)); +int SSL_CTX_set_srp_verify_param_callback(SSL_CTX *ctx, + int (*cb) (SSL *, void *)); +int SSL_CTX_set_srp_username_callback(SSL_CTX *ctx, + int (*cb) (SSL *, int *, void *)); +int SSL_CTX_set_srp_cb_arg(SSL_CTX *ctx, void *arg); + +int SSL_set_srp_server_param(SSL *s, const BIGNUM *N, const BIGNUM *g, + BIGNUM *sa, BIGNUM *v, char *info); +int SSL_set_srp_server_param_pw(SSL *s, const char *user, const char *pass, + const char *grp); + +__owur BIGNUM *SSL_get_srp_g(SSL *s); +__owur BIGNUM *SSL_get_srp_N(SSL *s); + +__owur char *SSL_get_srp_username(SSL *s); +__owur char *SSL_get_srp_userinfo(SSL *s); +# endif + +/* + * ClientHello callback and helpers. + */ + +# define SSL_CLIENT_HELLO_SUCCESS 1 +# define SSL_CLIENT_HELLO_ERROR 0 +# define SSL_CLIENT_HELLO_RETRY (-1) + +typedef int (*SSL_client_hello_cb_fn) (SSL *s, int *al, void *arg); +void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn cb, + void *arg); +int SSL_client_hello_isv2(SSL *s); +unsigned int SSL_client_hello_get0_legacy_version(SSL *s); +size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out); +size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out); +size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out); +size_t SSL_client_hello_get0_compression_methods(SSL *s, + const unsigned char **out); +int SSL_client_hello_get1_extensions_present(SSL *s, int **out, size_t *outlen); +int SSL_client_hello_get0_ext(SSL *s, unsigned int type, + const unsigned char **out, size_t *outlen); + +void SSL_certs_clear(SSL *s); +void SSL_free(SSL *ssl); +# ifdef OSSL_ASYNC_FD +/* + * Windows application developer has to include windows.h to use these. + */ +__owur int SSL_waiting_for_async(SSL *s); +__owur int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds); +__owur int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, + size_t *numaddfds, OSSL_ASYNC_FD *delfd, + size_t *numdelfds); +# endif +__owur int SSL_accept(SSL *ssl); +__owur int SSL_stateless(SSL *s); +__owur int SSL_connect(SSL *ssl); +__owur int SSL_read(SSL *ssl, void *buf, int num); +__owur int SSL_read_ex(SSL *ssl, void *buf, size_t num, size_t *readbytes); + +# define SSL_READ_EARLY_DATA_ERROR 0 +# define SSL_READ_EARLY_DATA_SUCCESS 1 +# define SSL_READ_EARLY_DATA_FINISH 2 + +__owur int SSL_read_early_data(SSL *s, void *buf, size_t num, + size_t *readbytes); +__owur int SSL_peek(SSL *ssl, void *buf, int num); +__owur int SSL_peek_ex(SSL *ssl, void *buf, size_t num, size_t *readbytes); +__owur int SSL_write(SSL *ssl, const void *buf, int num); +__owur int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written); +__owur int SSL_write_early_data(SSL *s, const void *buf, size_t num, + size_t *written); +long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg); +long SSL_callback_ctrl(SSL *, int, void (*)(void)); +long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg); +long SSL_CTX_callback_ctrl(SSL_CTX *, int, void (*)(void)); + +# define SSL_EARLY_DATA_NOT_SENT 0 +# define SSL_EARLY_DATA_REJECTED 1 +# define SSL_EARLY_DATA_ACCEPTED 2 + +__owur int SSL_get_early_data_status(const SSL *s); + +__owur int SSL_get_error(const SSL *s, int ret_code); +__owur const char *SSL_get_version(const SSL *s); + +/* This sets the 'default' SSL version that SSL_new() will create */ +__owur int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth); + +# ifndef OPENSSL_NO_SSL3_METHOD +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *SSLv3_method(void)) /* SSLv3 */ +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *SSLv3_server_method(void)) +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *SSLv3_client_method(void)) +# endif + +#define SSLv23_method TLS_method +#define SSLv23_server_method TLS_server_method +#define SSLv23_client_method TLS_client_method + +/* Negotiate highest available SSL/TLS version */ +__owur const SSL_METHOD *TLS_method(void); +__owur const SSL_METHOD *TLS_server_method(void); +__owur const SSL_METHOD *TLS_client_method(void); + +# ifndef OPENSSL_NO_TLS1_METHOD +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_method(void)) /* TLSv1.0 */ +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_server_method(void)) +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_client_method(void)) +# endif + +# ifndef OPENSSL_NO_TLS1_1_METHOD +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_1_method(void)) /* TLSv1.1 */ +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_1_server_method(void)) +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_1_client_method(void)) +# endif + +# ifndef OPENSSL_NO_TLS1_2_METHOD +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_2_method(void)) /* TLSv1.2 */ +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_2_server_method(void)) +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *TLSv1_2_client_method(void)) +# endif + +# ifndef OPENSSL_NO_DTLS1_METHOD +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *DTLSv1_method(void)) /* DTLSv1.0 */ +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *DTLSv1_server_method(void)) +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *DTLSv1_client_method(void)) +# endif + +# ifndef OPENSSL_NO_DTLS1_2_METHOD +/* DTLSv1.2 */ +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *DTLSv1_2_method(void)) +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *DTLSv1_2_server_method(void)) +DEPRECATEDIN_1_1_0(__owur const SSL_METHOD *DTLSv1_2_client_method(void)) +# endif + +__owur const SSL_METHOD *DTLS_method(void); /* DTLS 1.0 and 1.2 */ +__owur const SSL_METHOD *DTLS_server_method(void); /* DTLS 1.0 and 1.2 */ +__owur const SSL_METHOD *DTLS_client_method(void); /* DTLS 1.0 and 1.2 */ + +__owur size_t DTLS_get_data_mtu(const SSL *s); + +__owur STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s); +__owur STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx); +__owur STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s); +__owur STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s); + +__owur int SSL_do_handshake(SSL *s); +int SSL_key_update(SSL *s, int updatetype); +int SSL_get_key_update_type(SSL *s); +int SSL_renegotiate(SSL *s); +int SSL_renegotiate_abbreviated(SSL *s); +__owur int SSL_renegotiate_pending(SSL *s); +int SSL_shutdown(SSL *s); +__owur int SSL_verify_client_post_handshake(SSL *s); +void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val); +void SSL_set_post_handshake_auth(SSL *s, int val); + +__owur const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx); +__owur const SSL_METHOD *SSL_get_ssl_method(SSL *s); +__owur int SSL_set_ssl_method(SSL *s, const SSL_METHOD *method); +__owur const char *SSL_alert_type_string_long(int value); +__owur const char *SSL_alert_type_string(int value); +__owur const char *SSL_alert_desc_string_long(int value); +__owur const char *SSL_alert_desc_string(int value); + +void SSL_set0_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list); +void SSL_CTX_set0_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); +__owur const STACK_OF(X509_NAME) *SSL_get0_CA_list(const SSL *s); +__owur const STACK_OF(X509_NAME) *SSL_CTX_get0_CA_list(const SSL_CTX *ctx); +__owur int SSL_add1_to_CA_list(SSL *ssl, const X509 *x); +__owur int SSL_CTX_add1_to_CA_list(SSL_CTX *ctx, const X509 *x); +__owur const STACK_OF(X509_NAME) *SSL_get0_peer_CA_list(const SSL *s); + +void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list); +void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); +__owur STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s); +__owur STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *s); +__owur int SSL_add_client_CA(SSL *ssl, X509 *x); +__owur int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x); + +void SSL_set_connect_state(SSL *s); +void SSL_set_accept_state(SSL *s); + +__owur long SSL_get_default_timeout(const SSL *s); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define SSL_library_init() OPENSSL_init_ssl(0, NULL) +# endif + +__owur char *SSL_CIPHER_description(const SSL_CIPHER *, char *buf, int size); +__owur STACK_OF(X509_NAME) *SSL_dup_CA_list(const STACK_OF(X509_NAME) *sk); + +__owur SSL *SSL_dup(SSL *ssl); + +__owur X509 *SSL_get_certificate(const SSL *ssl); +/* + * EVP_PKEY + */ +struct evp_pkey_st *SSL_get_privatekey(const SSL *ssl); + +__owur X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx); +__owur EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx); + +void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode); +__owur int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx); +void SSL_set_quiet_shutdown(SSL *ssl, int mode); +__owur int SSL_get_quiet_shutdown(const SSL *ssl); +void SSL_set_shutdown(SSL *ssl, int mode); +__owur int SSL_get_shutdown(const SSL *ssl); +__owur int SSL_version(const SSL *ssl); +__owur int SSL_client_version(const SSL *s); +__owur int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx); +__owur int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx); +__owur int SSL_CTX_set_default_verify_file(SSL_CTX *ctx); +__owur int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, + const char *CApath); +# define SSL_get0_session SSL_get_session/* just peek at pointer */ +__owur SSL_SESSION *SSL_get_session(const SSL *ssl); +__owur SSL_SESSION *SSL_get1_session(SSL *ssl); /* obtain a reference count */ +__owur SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); +SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx); +void SSL_set_info_callback(SSL *ssl, + void (*cb) (const SSL *ssl, int type, int val)); +void (*SSL_get_info_callback(const SSL *ssl)) (const SSL *ssl, int type, + int val); +__owur OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl); + +void SSL_set_verify_result(SSL *ssl, long v); +__owur long SSL_get_verify_result(const SSL *ssl); +__owur STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s); + +__owur size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, + size_t outlen); +__owur size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, + size_t outlen); +__owur size_t SSL_SESSION_get_master_key(const SSL_SESSION *sess, + unsigned char *out, size_t outlen); +__owur int SSL_SESSION_set1_master_key(SSL_SESSION *sess, + const unsigned char *in, size_t len); +uint8_t SSL_SESSION_get_max_fragment_length(const SSL_SESSION *sess); + +#define SSL_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, l, p, newf, dupf, freef) +__owur int SSL_set_ex_data(SSL *ssl, int idx, void *data); +void *SSL_get_ex_data(const SSL *ssl, int idx); +#define SSL_SESSION_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION, l, p, newf, dupf, freef) +__owur int SSL_SESSION_set_ex_data(SSL_SESSION *ss, int idx, void *data); +void *SSL_SESSION_get_ex_data(const SSL_SESSION *ss, int idx); +#define SSL_CTX_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, l, p, newf, dupf, freef) +__owur int SSL_CTX_set_ex_data(SSL_CTX *ssl, int idx, void *data); +void *SSL_CTX_get_ex_data(const SSL_CTX *ssl, int idx); + +__owur int SSL_get_ex_data_X509_STORE_CTX_idx(void); + +# define SSL_CTX_sess_set_cache_size(ctx,t) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_SIZE,t,NULL) +# define SSL_CTX_sess_get_cache_size(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_SIZE,0,NULL) +# define SSL_CTX_set_session_cache_mode(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_MODE,m,NULL) +# define SSL_CTX_get_session_cache_mode(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_MODE,0,NULL) + +# define SSL_CTX_get_default_read_ahead(ctx) SSL_CTX_get_read_ahead(ctx) +# define SSL_CTX_set_default_read_ahead(ctx,m) SSL_CTX_set_read_ahead(ctx,m) +# define SSL_CTX_get_read_ahead(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_READ_AHEAD,0,NULL) +# define SSL_CTX_set_read_ahead(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_READ_AHEAD,m,NULL) +# define SSL_CTX_get_max_cert_list(ctx) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL) +# define SSL_CTX_set_max_cert_list(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL) +# define SSL_get_max_cert_list(ssl) \ + SSL_ctrl(ssl,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL) +# define SSL_set_max_cert_list(ssl,m) \ + SSL_ctrl(ssl,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL) + +# define SSL_CTX_set_max_send_fragment(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL) +# define SSL_set_max_send_fragment(ssl,m) \ + SSL_ctrl(ssl,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL) +# define SSL_CTX_set_split_send_fragment(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL) +# define SSL_set_split_send_fragment(ssl,m) \ + SSL_ctrl(ssl,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL) +# define SSL_CTX_set_max_pipelines(ctx,m) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_PIPELINES,m,NULL) +# define SSL_set_max_pipelines(ssl,m) \ + SSL_ctrl(ssl,SSL_CTRL_SET_MAX_PIPELINES,m,NULL) + +void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); +void SSL_set_default_read_buffer_len(SSL *s, size_t len); + +# ifndef OPENSSL_NO_DH +/* NB: the |keylength| is only applicable when is_export is true */ +void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, + DH *(*dh) (SSL *ssl, int is_export, + int keylength)); +void SSL_set_tmp_dh_callback(SSL *ssl, + DH *(*dh) (SSL *ssl, int is_export, + int keylength)); +# endif + +__owur const COMP_METHOD *SSL_get_current_compression(SSL *s); +__owur const COMP_METHOD *SSL_get_current_expansion(SSL *s); +__owur const char *SSL_COMP_get_name(const COMP_METHOD *comp); +__owur const char *SSL_COMP_get0_name(const SSL_COMP *comp); +__owur int SSL_COMP_get_id(const SSL_COMP *comp); +STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void); +__owur STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP) + *meths); +# if OPENSSL_API_COMPAT < 0x10100000L +# define SSL_COMP_free_compression_methods() while(0) continue +# endif +__owur int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm); + +const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr); +int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c); +int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c); +int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len, + int isv2format, STACK_OF(SSL_CIPHER) **sk, + STACK_OF(SSL_CIPHER) **scsvs); + +/* TLS extensions functions */ +__owur int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len); + +__owur int SSL_set_session_ticket_ext_cb(SSL *s, + tls_session_ticket_ext_cb_fn cb, + void *arg); + +/* Pre-shared secret session resumption functions */ +__owur int SSL_set_session_secret_cb(SSL *s, + tls_session_secret_cb_fn session_secret_cb, + void *arg); + +void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx, + int (*cb) (SSL *ssl, + int + is_forward_secure)); + +void SSL_set_not_resumable_session_callback(SSL *ssl, + int (*cb) (SSL *ssl, + int is_forward_secure)); + +void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx, + size_t (*cb) (SSL *ssl, int type, + size_t len, void *arg)); +void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg); +void *SSL_CTX_get_record_padding_callback_arg(SSL_CTX *ctx); +int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size); + +void SSL_set_record_padding_callback(SSL *ssl, + size_t (*cb) (SSL *ssl, int type, + size_t len, void *arg)); +void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg); +void *SSL_get_record_padding_callback_arg(SSL *ssl); +int SSL_set_block_padding(SSL *ssl, size_t block_size); + +int SSL_set_num_tickets(SSL *s, size_t num_tickets); +size_t SSL_get_num_tickets(SSL *s); +int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets); +size_t SSL_CTX_get_num_tickets(SSL_CTX *ctx); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define SSL_cache_hit(s) SSL_session_reused(s) +# endif + +__owur int SSL_session_reused(SSL *s); +__owur int SSL_is_server(const SSL *s); + +__owur __owur SSL_CONF_CTX *SSL_CONF_CTX_new(void); +int SSL_CONF_CTX_finish(SSL_CONF_CTX *cctx); +void SSL_CONF_CTX_free(SSL_CONF_CTX *cctx); +unsigned int SSL_CONF_CTX_set_flags(SSL_CONF_CTX *cctx, unsigned int flags); +__owur unsigned int SSL_CONF_CTX_clear_flags(SSL_CONF_CTX *cctx, + unsigned int flags); +__owur int SSL_CONF_CTX_set1_prefix(SSL_CONF_CTX *cctx, const char *pre); + +void SSL_CONF_CTX_set_ssl(SSL_CONF_CTX *cctx, SSL *ssl); +void SSL_CONF_CTX_set_ssl_ctx(SSL_CONF_CTX *cctx, SSL_CTX *ctx); + +__owur int SSL_CONF_cmd(SSL_CONF_CTX *cctx, const char *cmd, const char *value); +__owur int SSL_CONF_cmd_argv(SSL_CONF_CTX *cctx, int *pargc, char ***pargv); +__owur int SSL_CONF_cmd_value_type(SSL_CONF_CTX *cctx, const char *cmd); + +void SSL_add_ssl_module(void); +int SSL_config(SSL *s, const char *name); +int SSL_CTX_config(SSL_CTX *ctx, const char *name); + +# ifndef OPENSSL_NO_SSL_TRACE +void SSL_trace(int write_p, int version, int content_type, + const void *buf, size_t len, SSL *ssl, void *arg); +# endif + +# ifndef OPENSSL_NO_SOCK +int DTLSv1_listen(SSL *s, BIO_ADDR *client); +# endif + +# ifndef OPENSSL_NO_CT + +/* + * A callback for verifying that the received SCTs are sufficient. + * Expected to return 1 if they are sufficient, otherwise 0. + * May return a negative integer if an error occurs. + * A connection should be aborted if the SCTs are deemed insufficient. + */ +typedef int (*ssl_ct_validation_cb)(const CT_POLICY_EVAL_CTX *ctx, + const STACK_OF(SCT) *scts, void *arg); + +/* + * Sets a |callback| that is invoked upon receipt of ServerHelloDone to validate + * the received SCTs. + * If the callback returns a non-positive result, the connection is terminated. + * Call this function before beginning a handshake. + * If a NULL |callback| is provided, SCT validation is disabled. + * |arg| is arbitrary userdata that will be passed to the callback whenever it + * is invoked. Ownership of |arg| remains with the caller. + * + * NOTE: A side-effect of setting a CT callback is that an OCSP stapled response + * will be requested. + */ +int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback, + void *arg); +int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx, + ssl_ct_validation_cb callback, + void *arg); +#define SSL_disable_ct(s) \ + ((void) SSL_set_validation_callback((s), NULL, NULL)) +#define SSL_CTX_disable_ct(ctx) \ + ((void) SSL_CTX_set_validation_callback((ctx), NULL, NULL)) + +/* + * The validation type enumerates the available behaviours of the built-in SSL + * CT validation callback selected via SSL_enable_ct() and SSL_CTX_enable_ct(). + * The underlying callback is a static function in libssl. + */ +enum { + SSL_CT_VALIDATION_PERMISSIVE = 0, + SSL_CT_VALIDATION_STRICT +}; + +/* + * Enable CT by setting up a callback that implements one of the built-in + * validation variants. The SSL_CT_VALIDATION_PERMISSIVE variant always + * continues the handshake, the application can make appropriate decisions at + * handshake completion. The SSL_CT_VALIDATION_STRICT variant requires at + * least one valid SCT, or else handshake termination will be requested. The + * handshake may continue anyway if SSL_VERIFY_NONE is in effect. + */ +int SSL_enable_ct(SSL *s, int validation_mode); +int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode); + +/* + * Report whether a non-NULL callback is enabled. + */ +int SSL_ct_is_enabled(const SSL *s); +int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx); + +/* Gets the SCTs received from a connection */ +const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s); + +/* + * Loads the CT log list from the default location. + * If a CTLOG_STORE has previously been set using SSL_CTX_set_ctlog_store, + * the log information loaded from this file will be appended to the + * CTLOG_STORE. + * Returns 1 on success, 0 otherwise. + */ +int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx); + +/* + * Loads the CT log list from the specified file path. + * If a CTLOG_STORE has previously been set using SSL_CTX_set_ctlog_store, + * the log information loaded from this file will be appended to the + * CTLOG_STORE. + * Returns 1 on success, 0 otherwise. + */ +int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path); + +/* + * Sets the CT log list used by all SSL connections created from this SSL_CTX. + * Ownership of the CTLOG_STORE is transferred to the SSL_CTX. + */ +void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE *logs); + +/* + * Gets the CT log list used by all SSL connections created from this SSL_CTX. + * This will be NULL unless one of the following functions has been called: + * - SSL_CTX_set_default_ctlog_list_file + * - SSL_CTX_set_ctlog_list_file + * - SSL_CTX_set_ctlog_store + */ +const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx); + +# endif /* OPENSSL_NO_CT */ + +/* What the "other" parameter contains in security callback */ +/* Mask for type */ +# define SSL_SECOP_OTHER_TYPE 0xffff0000 +# define SSL_SECOP_OTHER_NONE 0 +# define SSL_SECOP_OTHER_CIPHER (1 << 16) +# define SSL_SECOP_OTHER_CURVE (2 << 16) +# define SSL_SECOP_OTHER_DH (3 << 16) +# define SSL_SECOP_OTHER_PKEY (4 << 16) +# define SSL_SECOP_OTHER_SIGALG (5 << 16) +# define SSL_SECOP_OTHER_CERT (6 << 16) + +/* Indicated operation refers to peer key or certificate */ +# define SSL_SECOP_PEER 0x1000 + +/* Values for "op" parameter in security callback */ + +/* Called to filter ciphers */ +/* Ciphers client supports */ +# define SSL_SECOP_CIPHER_SUPPORTED (1 | SSL_SECOP_OTHER_CIPHER) +/* Cipher shared by client/server */ +# define SSL_SECOP_CIPHER_SHARED (2 | SSL_SECOP_OTHER_CIPHER) +/* Sanity check of cipher server selects */ +# define SSL_SECOP_CIPHER_CHECK (3 | SSL_SECOP_OTHER_CIPHER) +/* Curves supported by client */ +# define SSL_SECOP_CURVE_SUPPORTED (4 | SSL_SECOP_OTHER_CURVE) +/* Curves shared by client/server */ +# define SSL_SECOP_CURVE_SHARED (5 | SSL_SECOP_OTHER_CURVE) +/* Sanity check of curve server selects */ +# define SSL_SECOP_CURVE_CHECK (6 | SSL_SECOP_OTHER_CURVE) +/* Temporary DH key */ +# define SSL_SECOP_TMP_DH (7 | SSL_SECOP_OTHER_PKEY) +/* SSL/TLS version */ +# define SSL_SECOP_VERSION (9 | SSL_SECOP_OTHER_NONE) +/* Session tickets */ +# define SSL_SECOP_TICKET (10 | SSL_SECOP_OTHER_NONE) +/* Supported signature algorithms sent to peer */ +# define SSL_SECOP_SIGALG_SUPPORTED (11 | SSL_SECOP_OTHER_SIGALG) +/* Shared signature algorithm */ +# define SSL_SECOP_SIGALG_SHARED (12 | SSL_SECOP_OTHER_SIGALG) +/* Sanity check signature algorithm allowed */ +# define SSL_SECOP_SIGALG_CHECK (13 | SSL_SECOP_OTHER_SIGALG) +/* Used to get mask of supported public key signature algorithms */ +# define SSL_SECOP_SIGALG_MASK (14 | SSL_SECOP_OTHER_SIGALG) +/* Use to see if compression is allowed */ +# define SSL_SECOP_COMPRESSION (15 | SSL_SECOP_OTHER_NONE) +/* EE key in certificate */ +# define SSL_SECOP_EE_KEY (16 | SSL_SECOP_OTHER_CERT) +/* CA key in certificate */ +# define SSL_SECOP_CA_KEY (17 | SSL_SECOP_OTHER_CERT) +/* CA digest algorithm in certificate */ +# define SSL_SECOP_CA_MD (18 | SSL_SECOP_OTHER_CERT) +/* Peer EE key in certificate */ +# define SSL_SECOP_PEER_EE_KEY (SSL_SECOP_EE_KEY | SSL_SECOP_PEER) +/* Peer CA key in certificate */ +# define SSL_SECOP_PEER_CA_KEY (SSL_SECOP_CA_KEY | SSL_SECOP_PEER) +/* Peer CA digest algorithm in certificate */ +# define SSL_SECOP_PEER_CA_MD (SSL_SECOP_CA_MD | SSL_SECOP_PEER) + +void SSL_set_security_level(SSL *s, int level); +__owur int SSL_get_security_level(const SSL *s); +void SSL_set_security_callback(SSL *s, + int (*cb) (const SSL *s, const SSL_CTX *ctx, + int op, int bits, int nid, + void *other, void *ex)); +int (*SSL_get_security_callback(const SSL *s)) (const SSL *s, + const SSL_CTX *ctx, int op, + int bits, int nid, void *other, + void *ex); +void SSL_set0_security_ex_data(SSL *s, void *ex); +__owur void *SSL_get0_security_ex_data(const SSL *s); + +void SSL_CTX_set_security_level(SSL_CTX *ctx, int level); +__owur int SSL_CTX_get_security_level(const SSL_CTX *ctx); +void SSL_CTX_set_security_callback(SSL_CTX *ctx, + int (*cb) (const SSL *s, const SSL_CTX *ctx, + int op, int bits, int nid, + void *other, void *ex)); +int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s, + const SSL_CTX *ctx, + int op, int bits, + int nid, + void *other, + void *ex); +void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex); +__owur void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx); + +/* OPENSSL_INIT flag 0x010000 reserved for internal use */ +# define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L +# define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L + +# define OPENSSL_INIT_SSL_DEFAULT \ + (OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS) + +int OPENSSL_init_ssl(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings); + +# ifndef OPENSSL_NO_UNIT_TEST +__owur const struct openssl_ssl_test_functions *SSL_test_functions(void); +# endif + +__owur int SSL_free_buffers(SSL *ssl); +__owur int SSL_alloc_buffers(SSL *ssl); + +/* Status codes passed to the decrypt session ticket callback. Some of these + * are for internal use only and are never passed to the callback. */ +typedef int SSL_TICKET_STATUS; + +/* Support for ticket appdata */ +/* fatal error, malloc failure */ +# define SSL_TICKET_FATAL_ERR_MALLOC 0 +/* fatal error, either from parsing or decrypting the ticket */ +# define SSL_TICKET_FATAL_ERR_OTHER 1 +/* No ticket present */ +# define SSL_TICKET_NONE 2 +/* Empty ticket present */ +# define SSL_TICKET_EMPTY 3 +/* the ticket couldn't be decrypted */ +# define SSL_TICKET_NO_DECRYPT 4 +/* a ticket was successfully decrypted */ +# define SSL_TICKET_SUCCESS 5 +/* same as above but the ticket needs to be renewed */ +# define SSL_TICKET_SUCCESS_RENEW 6 + +/* Return codes for the decrypt session ticket callback */ +typedef int SSL_TICKET_RETURN; + +/* An error occurred */ +#define SSL_TICKET_RETURN_ABORT 0 +/* Do not use the ticket, do not send a renewed ticket to the client */ +#define SSL_TICKET_RETURN_IGNORE 1 +/* Do not use the ticket, send a renewed ticket to the client */ +#define SSL_TICKET_RETURN_IGNORE_RENEW 2 +/* Use the ticket, do not send a renewed ticket to the client */ +#define SSL_TICKET_RETURN_USE 3 +/* Use the ticket, send a renewed ticket to the client */ +#define SSL_TICKET_RETURN_USE_RENEW 4 + +typedef int (*SSL_CTX_generate_session_ticket_fn)(SSL *s, void *arg); +typedef SSL_TICKET_RETURN (*SSL_CTX_decrypt_session_ticket_fn)(SSL *s, SSL_SESSION *ss, + const unsigned char *keyname, + size_t keyname_length, + SSL_TICKET_STATUS status, + void *arg); +int SSL_CTX_set_session_ticket_cb(SSL_CTX *ctx, + SSL_CTX_generate_session_ticket_fn gen_cb, + SSL_CTX_decrypt_session_ticket_fn dec_cb, + void *arg); +int SSL_SESSION_set1_ticket_appdata(SSL_SESSION *ss, const void *data, size_t len); +int SSL_SESSION_get0_ticket_appdata(SSL_SESSION *ss, void **data, size_t *len); + +extern const char SSL_version_str[]; + +typedef unsigned int (*DTLS_timer_cb)(SSL *s, unsigned int timer_us); + +void DTLS_set_timer_cb(SSL *s, DTLS_timer_cb cb); + + +typedef int (*SSL_allow_early_data_cb_fn)(SSL *s, void *arg); +void SSL_CTX_set_allow_early_data_cb(SSL_CTX *ctx, + SSL_allow_early_data_cb_fn cb, + void *arg); +void SSL_set_allow_early_data_cb(SSL *s, + SSL_allow_early_data_cb_fn cb, + void *arg); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/ssl2.h b/include/openssl/ssl2.h new file mode 100644 index 0000000..5321bd2 --- /dev/null +++ b/include/openssl/ssl2.h @@ -0,0 +1,24 @@ +/* + * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SSL2_H +# define HEADER_SSL2_H + +#ifdef __cplusplus +extern "C" { +#endif + +# define SSL2_VERSION 0x0002 + +# define SSL2_MT_CLIENT_HELLO 1 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/ssl3.h b/include/openssl/ssl3.h new file mode 100644 index 0000000..607277d --- /dev/null +++ b/include/openssl/ssl3.h @@ -0,0 +1,339 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SSL3_H +# define HEADER_SSL3_H + +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Signalling cipher suite value from RFC 5746 + * (TLS_EMPTY_RENEGOTIATION_INFO_SCSV) + */ +# define SSL3_CK_SCSV 0x030000FF + +/* + * Signalling cipher suite value from draft-ietf-tls-downgrade-scsv-00 + * (TLS_FALLBACK_SCSV) + */ +# define SSL3_CK_FALLBACK_SCSV 0x03005600 + +# define SSL3_CK_RSA_NULL_MD5 0x03000001 +# define SSL3_CK_RSA_NULL_SHA 0x03000002 +# define SSL3_CK_RSA_RC4_40_MD5 0x03000003 +# define SSL3_CK_RSA_RC4_128_MD5 0x03000004 +# define SSL3_CK_RSA_RC4_128_SHA 0x03000005 +# define SSL3_CK_RSA_RC2_40_MD5 0x03000006 +# define SSL3_CK_RSA_IDEA_128_SHA 0x03000007 +# define SSL3_CK_RSA_DES_40_CBC_SHA 0x03000008 +# define SSL3_CK_RSA_DES_64_CBC_SHA 0x03000009 +# define SSL3_CK_RSA_DES_192_CBC3_SHA 0x0300000A + +# define SSL3_CK_DH_DSS_DES_40_CBC_SHA 0x0300000B +# define SSL3_CK_DH_DSS_DES_64_CBC_SHA 0x0300000C +# define SSL3_CK_DH_DSS_DES_192_CBC3_SHA 0x0300000D +# define SSL3_CK_DH_RSA_DES_40_CBC_SHA 0x0300000E +# define SSL3_CK_DH_RSA_DES_64_CBC_SHA 0x0300000F +# define SSL3_CK_DH_RSA_DES_192_CBC3_SHA 0x03000010 + +# define SSL3_CK_DHE_DSS_DES_40_CBC_SHA 0x03000011 +# define SSL3_CK_EDH_DSS_DES_40_CBC_SHA SSL3_CK_DHE_DSS_DES_40_CBC_SHA +# define SSL3_CK_DHE_DSS_DES_64_CBC_SHA 0x03000012 +# define SSL3_CK_EDH_DSS_DES_64_CBC_SHA SSL3_CK_DHE_DSS_DES_64_CBC_SHA +# define SSL3_CK_DHE_DSS_DES_192_CBC3_SHA 0x03000013 +# define SSL3_CK_EDH_DSS_DES_192_CBC3_SHA SSL3_CK_DHE_DSS_DES_192_CBC3_SHA +# define SSL3_CK_DHE_RSA_DES_40_CBC_SHA 0x03000014 +# define SSL3_CK_EDH_RSA_DES_40_CBC_SHA SSL3_CK_DHE_RSA_DES_40_CBC_SHA +# define SSL3_CK_DHE_RSA_DES_64_CBC_SHA 0x03000015 +# define SSL3_CK_EDH_RSA_DES_64_CBC_SHA SSL3_CK_DHE_RSA_DES_64_CBC_SHA +# define SSL3_CK_DHE_RSA_DES_192_CBC3_SHA 0x03000016 +# define SSL3_CK_EDH_RSA_DES_192_CBC3_SHA SSL3_CK_DHE_RSA_DES_192_CBC3_SHA + +# define SSL3_CK_ADH_RC4_40_MD5 0x03000017 +# define SSL3_CK_ADH_RC4_128_MD5 0x03000018 +# define SSL3_CK_ADH_DES_40_CBC_SHA 0x03000019 +# define SSL3_CK_ADH_DES_64_CBC_SHA 0x0300001A +# define SSL3_CK_ADH_DES_192_CBC_SHA 0x0300001B + +/* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] */ +# define SSL3_RFC_RSA_NULL_MD5 "TLS_RSA_WITH_NULL_MD5" +# define SSL3_RFC_RSA_NULL_SHA "TLS_RSA_WITH_NULL_SHA" +# define SSL3_RFC_RSA_DES_192_CBC3_SHA "TLS_RSA_WITH_3DES_EDE_CBC_SHA" +# define SSL3_RFC_DHE_DSS_DES_192_CBC3_SHA "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" +# define SSL3_RFC_DHE_RSA_DES_192_CBC3_SHA "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" +# define SSL3_RFC_ADH_DES_192_CBC_SHA "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA" +# define SSL3_RFC_RSA_IDEA_128_SHA "TLS_RSA_WITH_IDEA_CBC_SHA" +# define SSL3_RFC_RSA_RC4_128_MD5 "TLS_RSA_WITH_RC4_128_MD5" +# define SSL3_RFC_RSA_RC4_128_SHA "TLS_RSA_WITH_RC4_128_SHA" +# define SSL3_RFC_ADH_RC4_128_MD5 "TLS_DH_anon_WITH_RC4_128_MD5" + +# define SSL3_TXT_RSA_NULL_MD5 "NULL-MD5" +# define SSL3_TXT_RSA_NULL_SHA "NULL-SHA" +# define SSL3_TXT_RSA_RC4_40_MD5 "EXP-RC4-MD5" +# define SSL3_TXT_RSA_RC4_128_MD5 "RC4-MD5" +# define SSL3_TXT_RSA_RC4_128_SHA "RC4-SHA" +# define SSL3_TXT_RSA_RC2_40_MD5 "EXP-RC2-CBC-MD5" +# define SSL3_TXT_RSA_IDEA_128_SHA "IDEA-CBC-SHA" +# define SSL3_TXT_RSA_DES_40_CBC_SHA "EXP-DES-CBC-SHA" +# define SSL3_TXT_RSA_DES_64_CBC_SHA "DES-CBC-SHA" +# define SSL3_TXT_RSA_DES_192_CBC3_SHA "DES-CBC3-SHA" + +# define SSL3_TXT_DH_DSS_DES_40_CBC_SHA "EXP-DH-DSS-DES-CBC-SHA" +# define SSL3_TXT_DH_DSS_DES_64_CBC_SHA "DH-DSS-DES-CBC-SHA" +# define SSL3_TXT_DH_DSS_DES_192_CBC3_SHA "DH-DSS-DES-CBC3-SHA" +# define SSL3_TXT_DH_RSA_DES_40_CBC_SHA "EXP-DH-RSA-DES-CBC-SHA" +# define SSL3_TXT_DH_RSA_DES_64_CBC_SHA "DH-RSA-DES-CBC-SHA" +# define SSL3_TXT_DH_RSA_DES_192_CBC3_SHA "DH-RSA-DES-CBC3-SHA" + +# define SSL3_TXT_DHE_DSS_DES_40_CBC_SHA "EXP-DHE-DSS-DES-CBC-SHA" +# define SSL3_TXT_DHE_DSS_DES_64_CBC_SHA "DHE-DSS-DES-CBC-SHA" +# define SSL3_TXT_DHE_DSS_DES_192_CBC3_SHA "DHE-DSS-DES-CBC3-SHA" +# define SSL3_TXT_DHE_RSA_DES_40_CBC_SHA "EXP-DHE-RSA-DES-CBC-SHA" +# define SSL3_TXT_DHE_RSA_DES_64_CBC_SHA "DHE-RSA-DES-CBC-SHA" +# define SSL3_TXT_DHE_RSA_DES_192_CBC3_SHA "DHE-RSA-DES-CBC3-SHA" + +/* + * This next block of six "EDH" labels is for backward compatibility with + * older versions of OpenSSL. New code should use the six "DHE" labels above + * instead: + */ +# define SSL3_TXT_EDH_DSS_DES_40_CBC_SHA "EXP-EDH-DSS-DES-CBC-SHA" +# define SSL3_TXT_EDH_DSS_DES_64_CBC_SHA "EDH-DSS-DES-CBC-SHA" +# define SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA "EDH-DSS-DES-CBC3-SHA" +# define SSL3_TXT_EDH_RSA_DES_40_CBC_SHA "EXP-EDH-RSA-DES-CBC-SHA" +# define SSL3_TXT_EDH_RSA_DES_64_CBC_SHA "EDH-RSA-DES-CBC-SHA" +# define SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA "EDH-RSA-DES-CBC3-SHA" + +# define SSL3_TXT_ADH_RC4_40_MD5 "EXP-ADH-RC4-MD5" +# define SSL3_TXT_ADH_RC4_128_MD5 "ADH-RC4-MD5" +# define SSL3_TXT_ADH_DES_40_CBC_SHA "EXP-ADH-DES-CBC-SHA" +# define SSL3_TXT_ADH_DES_64_CBC_SHA "ADH-DES-CBC-SHA" +# define SSL3_TXT_ADH_DES_192_CBC_SHA "ADH-DES-CBC3-SHA" + +# define SSL3_SSL_SESSION_ID_LENGTH 32 +# define SSL3_MAX_SSL_SESSION_ID_LENGTH 32 + +# define SSL3_MASTER_SECRET_SIZE 48 +# define SSL3_RANDOM_SIZE 32 +# define SSL3_SESSION_ID_SIZE 32 +# define SSL3_RT_HEADER_LENGTH 5 + +# define SSL3_HM_HEADER_LENGTH 4 + +# ifndef SSL3_ALIGN_PAYLOAD + /* + * Some will argue that this increases memory footprint, but it's not + * actually true. Point is that malloc has to return at least 64-bit aligned + * pointers, meaning that allocating 5 bytes wastes 3 bytes in either case. + * Suggested pre-gaping simply moves these wasted bytes from the end of + * allocated region to its front, but makes data payload aligned, which + * improves performance:-) + */ +# define SSL3_ALIGN_PAYLOAD 8 +# else +# if (SSL3_ALIGN_PAYLOAD&(SSL3_ALIGN_PAYLOAD-1))!=0 +# error "insane SSL3_ALIGN_PAYLOAD" +# undef SSL3_ALIGN_PAYLOAD +# endif +# endif + +/* + * This is the maximum MAC (digest) size used by the SSL library. Currently + * maximum of 20 is used by SHA1, but we reserve for future extension for + * 512-bit hashes. + */ + +# define SSL3_RT_MAX_MD_SIZE 64 + +/* + * Maximum block size used in all ciphersuites. Currently 16 for AES. + */ + +# define SSL_RT_MAX_CIPHER_BLOCK_SIZE 16 + +# define SSL3_RT_MAX_EXTRA (16384) + +/* Maximum plaintext length: defined by SSL/TLS standards */ +# define SSL3_RT_MAX_PLAIN_LENGTH 16384 +/* Maximum compression overhead: defined by SSL/TLS standards */ +# define SSL3_RT_MAX_COMPRESSED_OVERHEAD 1024 + +/* + * The standards give a maximum encryption overhead of 1024 bytes. In + * practice the value is lower than this. The overhead is the maximum number + * of padding bytes (256) plus the mac size. + */ +# define SSL3_RT_MAX_ENCRYPTED_OVERHEAD (256 + SSL3_RT_MAX_MD_SIZE) +# define SSL3_RT_MAX_TLS13_ENCRYPTED_OVERHEAD 256 + +/* + * OpenSSL currently only uses a padding length of at most one block so the + * send overhead is smaller. + */ + +# define SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \ + (SSL_RT_MAX_CIPHER_BLOCK_SIZE + SSL3_RT_MAX_MD_SIZE) + +/* If compression isn't used don't include the compression overhead */ + +# ifdef OPENSSL_NO_COMP +# define SSL3_RT_MAX_COMPRESSED_LENGTH SSL3_RT_MAX_PLAIN_LENGTH +# else +# define SSL3_RT_MAX_COMPRESSED_LENGTH \ + (SSL3_RT_MAX_PLAIN_LENGTH+SSL3_RT_MAX_COMPRESSED_OVERHEAD) +# endif +# define SSL3_RT_MAX_ENCRYPTED_LENGTH \ + (SSL3_RT_MAX_ENCRYPTED_OVERHEAD+SSL3_RT_MAX_COMPRESSED_LENGTH) +# define SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH \ + (SSL3_RT_MAX_PLAIN_LENGTH + SSL3_RT_MAX_TLS13_ENCRYPTED_OVERHEAD) +# define SSL3_RT_MAX_PACKET_SIZE \ + (SSL3_RT_MAX_ENCRYPTED_LENGTH+SSL3_RT_HEADER_LENGTH) + +# define SSL3_MD_CLIENT_FINISHED_CONST "\x43\x4C\x4E\x54" +# define SSL3_MD_SERVER_FINISHED_CONST "\x53\x52\x56\x52" + +# define SSL3_VERSION 0x0300 +# define SSL3_VERSION_MAJOR 0x03 +# define SSL3_VERSION_MINOR 0x00 + +# define SSL3_RT_CHANGE_CIPHER_SPEC 20 +# define SSL3_RT_ALERT 21 +# define SSL3_RT_HANDSHAKE 22 +# define SSL3_RT_APPLICATION_DATA 23 +# define DTLS1_RT_HEARTBEAT 24 + +/* Pseudo content types to indicate additional parameters */ +# define TLS1_RT_CRYPTO 0x1000 +# define TLS1_RT_CRYPTO_PREMASTER (TLS1_RT_CRYPTO | 0x1) +# define TLS1_RT_CRYPTO_CLIENT_RANDOM (TLS1_RT_CRYPTO | 0x2) +# define TLS1_RT_CRYPTO_SERVER_RANDOM (TLS1_RT_CRYPTO | 0x3) +# define TLS1_RT_CRYPTO_MASTER (TLS1_RT_CRYPTO | 0x4) + +# define TLS1_RT_CRYPTO_READ 0x0000 +# define TLS1_RT_CRYPTO_WRITE 0x0100 +# define TLS1_RT_CRYPTO_MAC (TLS1_RT_CRYPTO | 0x5) +# define TLS1_RT_CRYPTO_KEY (TLS1_RT_CRYPTO | 0x6) +# define TLS1_RT_CRYPTO_IV (TLS1_RT_CRYPTO | 0x7) +# define TLS1_RT_CRYPTO_FIXED_IV (TLS1_RT_CRYPTO | 0x8) + +/* Pseudo content types for SSL/TLS header info */ +# define SSL3_RT_HEADER 0x100 +# define SSL3_RT_INNER_CONTENT_TYPE 0x101 + +# define SSL3_AL_WARNING 1 +# define SSL3_AL_FATAL 2 + +# define SSL3_AD_CLOSE_NOTIFY 0 +# define SSL3_AD_UNEXPECTED_MESSAGE 10/* fatal */ +# define SSL3_AD_BAD_RECORD_MAC 20/* fatal */ +# define SSL3_AD_DECOMPRESSION_FAILURE 30/* fatal */ +# define SSL3_AD_HANDSHAKE_FAILURE 40/* fatal */ +# define SSL3_AD_NO_CERTIFICATE 41 +# define SSL3_AD_BAD_CERTIFICATE 42 +# define SSL3_AD_UNSUPPORTED_CERTIFICATE 43 +# define SSL3_AD_CERTIFICATE_REVOKED 44 +# define SSL3_AD_CERTIFICATE_EXPIRED 45 +# define SSL3_AD_CERTIFICATE_UNKNOWN 46 +# define SSL3_AD_ILLEGAL_PARAMETER 47/* fatal */ + +# define TLS1_HB_REQUEST 1 +# define TLS1_HB_RESPONSE 2 + + +# define SSL3_CT_RSA_SIGN 1 +# define SSL3_CT_DSS_SIGN 2 +# define SSL3_CT_RSA_FIXED_DH 3 +# define SSL3_CT_DSS_FIXED_DH 4 +# define SSL3_CT_RSA_EPHEMERAL_DH 5 +# define SSL3_CT_DSS_EPHEMERAL_DH 6 +# define SSL3_CT_FORTEZZA_DMS 20 +/* + * SSL3_CT_NUMBER is used to size arrays and it must be large enough to + * contain all of the cert types defined for *either* SSLv3 and TLSv1. + */ +# define SSL3_CT_NUMBER 10 + +# if defined(TLS_CT_NUMBER) +# if TLS_CT_NUMBER != SSL3_CT_NUMBER +# error "SSL/TLS CT_NUMBER values do not match" +# endif +# endif + +/* No longer used as of OpenSSL 1.1.1 */ +# define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001 + +/* Removed from OpenSSL 1.1.0 */ +# define TLS1_FLAGS_TLS_PADDING_BUG 0x0 + +# define TLS1_FLAGS_SKIP_CERT_VERIFY 0x0010 + +/* Set if we encrypt then mac instead of usual mac then encrypt */ +# define TLS1_FLAGS_ENCRYPT_THEN_MAC_READ 0x0100 +# define TLS1_FLAGS_ENCRYPT_THEN_MAC TLS1_FLAGS_ENCRYPT_THEN_MAC_READ + +/* Set if extended master secret extension received from peer */ +# define TLS1_FLAGS_RECEIVED_EXTMS 0x0200 + +# define TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE 0x0400 + +# define TLS1_FLAGS_STATELESS 0x0800 + +# define SSL3_MT_HELLO_REQUEST 0 +# define SSL3_MT_CLIENT_HELLO 1 +# define SSL3_MT_SERVER_HELLO 2 +# define SSL3_MT_NEWSESSION_TICKET 4 +# define SSL3_MT_END_OF_EARLY_DATA 5 +# define SSL3_MT_ENCRYPTED_EXTENSIONS 8 +# define SSL3_MT_CERTIFICATE 11 +# define SSL3_MT_SERVER_KEY_EXCHANGE 12 +# define SSL3_MT_CERTIFICATE_REQUEST 13 +# define SSL3_MT_SERVER_DONE 14 +# define SSL3_MT_CERTIFICATE_VERIFY 15 +# define SSL3_MT_CLIENT_KEY_EXCHANGE 16 +# define SSL3_MT_FINISHED 20 +# define SSL3_MT_CERTIFICATE_URL 21 +# define SSL3_MT_CERTIFICATE_STATUS 22 +# define SSL3_MT_SUPPLEMENTAL_DATA 23 +# define SSL3_MT_KEY_UPDATE 24 +# ifndef OPENSSL_NO_NEXTPROTONEG +# define SSL3_MT_NEXT_PROTO 67 +# endif +# define SSL3_MT_MESSAGE_HASH 254 +# define DTLS1_MT_HELLO_VERIFY_REQUEST 3 + +/* Dummy message type for handling CCS like a normal handshake message */ +# define SSL3_MT_CHANGE_CIPHER_SPEC 0x0101 + +# define SSL3_MT_CCS 1 + +/* These are used when changing over to a new cipher */ +# define SSL3_CC_READ 0x001 +# define SSL3_CC_WRITE 0x002 +# define SSL3_CC_CLIENT 0x010 +# define SSL3_CC_SERVER 0x020 +# define SSL3_CC_EARLY 0x040 +# define SSL3_CC_HANDSHAKE 0x080 +# define SSL3_CC_APPLICATION 0x100 +# define SSL3_CHANGE_CIPHER_CLIENT_WRITE (SSL3_CC_CLIENT|SSL3_CC_WRITE) +# define SSL3_CHANGE_CIPHER_SERVER_READ (SSL3_CC_SERVER|SSL3_CC_READ) +# define SSL3_CHANGE_CIPHER_CLIENT_READ (SSL3_CC_CLIENT|SSL3_CC_READ) +# define SSL3_CHANGE_CIPHER_SERVER_WRITE (SSL3_CC_SERVER|SSL3_CC_WRITE) + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/sslerr.h b/include/openssl/sslerr.h new file mode 100644 index 0000000..87b295c --- /dev/null +++ b/include/openssl/sslerr.h @@ -0,0 +1,767 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SSLERR_H +# define HEADER_SSLERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_SSL_strings(void); + +/* + * SSL function codes. + */ +# define SSL_F_ADD_CLIENT_KEY_SHARE_EXT 438 +# define SSL_F_ADD_KEY_SHARE 512 +# define SSL_F_BYTES_TO_CIPHER_LIST 519 +# define SSL_F_CHECK_SUITEB_CIPHER_LIST 331 +# define SSL_F_CIPHERSUITE_CB 622 +# define SSL_F_CONSTRUCT_CA_NAMES 552 +# define SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS 553 +# define SSL_F_CONSTRUCT_STATEFUL_TICKET 636 +# define SSL_F_CONSTRUCT_STATELESS_TICKET 637 +# define SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH 539 +# define SSL_F_CREATE_TICKET_PREQUEL 638 +# define SSL_F_CT_MOVE_SCTS 345 +# define SSL_F_CT_STRICT 349 +# define SSL_F_CUSTOM_EXT_ADD 554 +# define SSL_F_CUSTOM_EXT_PARSE 555 +# define SSL_F_D2I_SSL_SESSION 103 +# define SSL_F_DANE_CTX_ENABLE 347 +# define SSL_F_DANE_MTYPE_SET 393 +# define SSL_F_DANE_TLSA_ADD 394 +# define SSL_F_DERIVE_SECRET_KEY_AND_IV 514 +# define SSL_F_DO_DTLS1_WRITE 245 +# define SSL_F_DO_SSL3_WRITE 104 +# define SSL_F_DTLS1_BUFFER_RECORD 247 +# define SSL_F_DTLS1_CHECK_TIMEOUT_NUM 318 +# define SSL_F_DTLS1_HEARTBEAT 305 +# define SSL_F_DTLS1_HM_FRAGMENT_NEW 623 +# define SSL_F_DTLS1_PREPROCESS_FRAGMENT 288 +# define SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS 424 +# define SSL_F_DTLS1_PROCESS_RECORD 257 +# define SSL_F_DTLS1_READ_BYTES 258 +# define SSL_F_DTLS1_READ_FAILED 339 +# define SSL_F_DTLS1_RETRANSMIT_MESSAGE 390 +# define SSL_F_DTLS1_WRITE_APP_DATA_BYTES 268 +# define SSL_F_DTLS1_WRITE_BYTES 545 +# define SSL_F_DTLSV1_LISTEN 350 +# define SSL_F_DTLS_CONSTRUCT_CHANGE_CIPHER_SPEC 371 +# define SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST 385 +# define SSL_F_DTLS_GET_REASSEMBLED_MESSAGE 370 +# define SSL_F_DTLS_PROCESS_HELLO_VERIFY 386 +# define SSL_F_DTLS_RECORD_LAYER_NEW 635 +# define SSL_F_DTLS_WAIT_FOR_DRY 592 +# define SSL_F_EARLY_DATA_COUNT_OK 532 +# define SSL_F_FINAL_EARLY_DATA 556 +# define SSL_F_FINAL_EC_PT_FORMATS 485 +# define SSL_F_FINAL_EMS 486 +# define SSL_F_FINAL_KEY_SHARE 503 +# define SSL_F_FINAL_MAXFRAGMENTLEN 557 +# define SSL_F_FINAL_RENEGOTIATE 483 +# define SSL_F_FINAL_SERVER_NAME 558 +# define SSL_F_FINAL_SIG_ALGS 497 +# define SSL_F_GET_CERT_VERIFY_TBS_DATA 588 +# define SSL_F_NSS_KEYLOG_INT 500 +# define SSL_F_OPENSSL_INIT_SSL 342 +# define SSL_F_OSSL_STATEM_CLIENT13_READ_TRANSITION 436 +# define SSL_F_OSSL_STATEM_CLIENT13_WRITE_TRANSITION 598 +# define SSL_F_OSSL_STATEM_CLIENT_CONSTRUCT_MESSAGE 430 +# define SSL_F_OSSL_STATEM_CLIENT_POST_PROCESS_MESSAGE 593 +# define SSL_F_OSSL_STATEM_CLIENT_PROCESS_MESSAGE 594 +# define SSL_F_OSSL_STATEM_CLIENT_READ_TRANSITION 417 +# define SSL_F_OSSL_STATEM_CLIENT_WRITE_TRANSITION 599 +# define SSL_F_OSSL_STATEM_SERVER13_READ_TRANSITION 437 +# define SSL_F_OSSL_STATEM_SERVER13_WRITE_TRANSITION 600 +# define SSL_F_OSSL_STATEM_SERVER_CONSTRUCT_MESSAGE 431 +# define SSL_F_OSSL_STATEM_SERVER_POST_PROCESS_MESSAGE 601 +# define SSL_F_OSSL_STATEM_SERVER_POST_WORK 602 +# define SSL_F_OSSL_STATEM_SERVER_PROCESS_MESSAGE 603 +# define SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION 418 +# define SSL_F_OSSL_STATEM_SERVER_WRITE_TRANSITION 604 +# define SSL_F_PARSE_CA_NAMES 541 +# define SSL_F_PITEM_NEW 624 +# define SSL_F_PQUEUE_NEW 625 +# define SSL_F_PROCESS_KEY_SHARE_EXT 439 +# define SSL_F_READ_STATE_MACHINE 352 +# define SSL_F_SET_CLIENT_CIPHERSUITE 540 +# define SSL_F_SRP_GENERATE_CLIENT_MASTER_SECRET 595 +# define SSL_F_SRP_GENERATE_SERVER_MASTER_SECRET 589 +# define SSL_F_SRP_VERIFY_SERVER_PARAM 596 +# define SSL_F_SSL3_CHANGE_CIPHER_STATE 129 +# define SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM 130 +# define SSL_F_SSL3_CTRL 213 +# define SSL_F_SSL3_CTX_CTRL 133 +# define SSL_F_SSL3_DIGEST_CACHED_RECORDS 293 +# define SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC 292 +# define SSL_F_SSL3_ENC 608 +# define SSL_F_SSL3_FINAL_FINISH_MAC 285 +# define SSL_F_SSL3_FINISH_MAC 587 +# define SSL_F_SSL3_GENERATE_KEY_BLOCK 238 +# define SSL_F_SSL3_GENERATE_MASTER_SECRET 388 +# define SSL_F_SSL3_GET_RECORD 143 +# define SSL_F_SSL3_INIT_FINISHED_MAC 397 +# define SSL_F_SSL3_OUTPUT_CERT_CHAIN 147 +# define SSL_F_SSL3_READ_BYTES 148 +# define SSL_F_SSL3_READ_N 149 +# define SSL_F_SSL3_SETUP_KEY_BLOCK 157 +# define SSL_F_SSL3_SETUP_READ_BUFFER 156 +# define SSL_F_SSL3_SETUP_WRITE_BUFFER 291 +# define SSL_F_SSL3_WRITE_BYTES 158 +# define SSL_F_SSL3_WRITE_PENDING 159 +# define SSL_F_SSL_ADD_CERT_CHAIN 316 +# define SSL_F_SSL_ADD_CERT_TO_BUF 319 +# define SSL_F_SSL_ADD_CERT_TO_WPACKET 493 +# define SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT 298 +# define SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT 277 +# define SSL_F_SSL_ADD_CLIENTHELLO_USE_SRTP_EXT 307 +# define SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK 215 +# define SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK 216 +# define SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT 299 +# define SSL_F_SSL_ADD_SERVERHELLO_TLSEXT 278 +# define SSL_F_SSL_ADD_SERVERHELLO_USE_SRTP_EXT 308 +# define SSL_F_SSL_BAD_METHOD 160 +# define SSL_F_SSL_BUILD_CERT_CHAIN 332 +# define SSL_F_SSL_BYTES_TO_CIPHER_LIST 161 +# define SSL_F_SSL_CACHE_CIPHERLIST 520 +# define SSL_F_SSL_CERT_ADD0_CHAIN_CERT 346 +# define SSL_F_SSL_CERT_DUP 221 +# define SSL_F_SSL_CERT_NEW 162 +# define SSL_F_SSL_CERT_SET0_CHAIN 340 +# define SSL_F_SSL_CHECK_PRIVATE_KEY 163 +# define SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT 280 +# define SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO 606 +# define SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG 279 +# define SSL_F_SSL_CHOOSE_CLIENT_VERSION 607 +# define SSL_F_SSL_CIPHER_DESCRIPTION 626 +# define SSL_F_SSL_CIPHER_LIST_TO_BYTES 425 +# define SSL_F_SSL_CIPHER_PROCESS_RULESTR 230 +# define SSL_F_SSL_CIPHER_STRENGTH_SORT 231 +# define SSL_F_SSL_CLEAR 164 +# define SSL_F_SSL_CLIENT_HELLO_GET1_EXTENSIONS_PRESENT 627 +# define SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD 165 +# define SSL_F_SSL_CONF_CMD 334 +# define SSL_F_SSL_CREATE_CIPHER_LIST 166 +# define SSL_F_SSL_CTRL 232 +# define SSL_F_SSL_CTX_CHECK_PRIVATE_KEY 168 +# define SSL_F_SSL_CTX_ENABLE_CT 398 +# define SSL_F_SSL_CTX_MAKE_PROFILES 309 +# define SSL_F_SSL_CTX_NEW 169 +# define SSL_F_SSL_CTX_SET_ALPN_PROTOS 343 +# define SSL_F_SSL_CTX_SET_CIPHER_LIST 269 +# define SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE 290 +# define SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK 396 +# define SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT 219 +# define SSL_F_SSL_CTX_SET_SSL_VERSION 170 +# define SSL_F_SSL_CTX_SET_TLSEXT_MAX_FRAGMENT_LENGTH 551 +# define SSL_F_SSL_CTX_USE_CERTIFICATE 171 +# define SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1 172 +# define SSL_F_SSL_CTX_USE_CERTIFICATE_FILE 173 +# define SSL_F_SSL_CTX_USE_PRIVATEKEY 174 +# define SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1 175 +# define SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE 176 +# define SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT 272 +# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY 177 +# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1 178 +# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE 179 +# define SSL_F_SSL_CTX_USE_SERVERINFO 336 +# define SSL_F_SSL_CTX_USE_SERVERINFO_EX 543 +# define SSL_F_SSL_CTX_USE_SERVERINFO_FILE 337 +# define SSL_F_SSL_DANE_DUP 403 +# define SSL_F_SSL_DANE_ENABLE 395 +# define SSL_F_SSL_DERIVE 590 +# define SSL_F_SSL_DO_CONFIG 391 +# define SSL_F_SSL_DO_HANDSHAKE 180 +# define SSL_F_SSL_DUP_CA_LIST 408 +# define SSL_F_SSL_ENABLE_CT 402 +# define SSL_F_SSL_GENERATE_PKEY_GROUP 559 +# define SSL_F_SSL_GENERATE_SESSION_ID 547 +# define SSL_F_SSL_GET_NEW_SESSION 181 +# define SSL_F_SSL_GET_PREV_SESSION 217 +# define SSL_F_SSL_GET_SERVER_CERT_INDEX 322 +# define SSL_F_SSL_GET_SIGN_PKEY 183 +# define SSL_F_SSL_HANDSHAKE_HASH 560 +# define SSL_F_SSL_INIT_WBIO_BUFFER 184 +# define SSL_F_SSL_KEY_UPDATE 515 +# define SSL_F_SSL_LOAD_CLIENT_CA_FILE 185 +# define SSL_F_SSL_LOG_MASTER_SECRET 498 +# define SSL_F_SSL_LOG_RSA_CLIENT_KEY_EXCHANGE 499 +# define SSL_F_SSL_MODULE_INIT 392 +# define SSL_F_SSL_NEW 186 +# define SSL_F_SSL_NEXT_PROTO_VALIDATE 565 +# define SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT 300 +# define SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT 302 +# define SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT 310 +# define SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT 301 +# define SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT 303 +# define SSL_F_SSL_PARSE_SERVERHELLO_USE_SRTP_EXT 311 +# define SSL_F_SSL_PEEK 270 +# define SSL_F_SSL_PEEK_EX 432 +# define SSL_F_SSL_PEEK_INTERNAL 522 +# define SSL_F_SSL_READ 223 +# define SSL_F_SSL_READ_EARLY_DATA 529 +# define SSL_F_SSL_READ_EX 434 +# define SSL_F_SSL_READ_INTERNAL 523 +# define SSL_F_SSL_RENEGOTIATE 516 +# define SSL_F_SSL_RENEGOTIATE_ABBREVIATED 546 +# define SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT 320 +# define SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT 321 +# define SSL_F_SSL_SESSION_DUP 348 +# define SSL_F_SSL_SESSION_NEW 189 +# define SSL_F_SSL_SESSION_PRINT_FP 190 +# define SSL_F_SSL_SESSION_SET1_ID 423 +# define SSL_F_SSL_SESSION_SET1_ID_CONTEXT 312 +# define SSL_F_SSL_SET_ALPN_PROTOS 344 +# define SSL_F_SSL_SET_CERT 191 +# define SSL_F_SSL_SET_CERT_AND_KEY 621 +# define SSL_F_SSL_SET_CIPHER_LIST 271 +# define SSL_F_SSL_SET_CT_VALIDATION_CALLBACK 399 +# define SSL_F_SSL_SET_FD 192 +# define SSL_F_SSL_SET_PKEY 193 +# define SSL_F_SSL_SET_RFD 194 +# define SSL_F_SSL_SET_SESSION 195 +# define SSL_F_SSL_SET_SESSION_ID_CONTEXT 218 +# define SSL_F_SSL_SET_SESSION_TICKET_EXT 294 +# define SSL_F_SSL_SET_TLSEXT_MAX_FRAGMENT_LENGTH 550 +# define SSL_F_SSL_SET_WFD 196 +# define SSL_F_SSL_SHUTDOWN 224 +# define SSL_F_SSL_SRP_CTX_INIT 313 +# define SSL_F_SSL_START_ASYNC_JOB 389 +# define SSL_F_SSL_UNDEFINED_FUNCTION 197 +# define SSL_F_SSL_UNDEFINED_VOID_FUNCTION 244 +# define SSL_F_SSL_USE_CERTIFICATE 198 +# define SSL_F_SSL_USE_CERTIFICATE_ASN1 199 +# define SSL_F_SSL_USE_CERTIFICATE_FILE 200 +# define SSL_F_SSL_USE_PRIVATEKEY 201 +# define SSL_F_SSL_USE_PRIVATEKEY_ASN1 202 +# define SSL_F_SSL_USE_PRIVATEKEY_FILE 203 +# define SSL_F_SSL_USE_PSK_IDENTITY_HINT 273 +# define SSL_F_SSL_USE_RSAPRIVATEKEY 204 +# define SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1 205 +# define SSL_F_SSL_USE_RSAPRIVATEKEY_FILE 206 +# define SSL_F_SSL_VALIDATE_CT 400 +# define SSL_F_SSL_VERIFY_CERT_CHAIN 207 +# define SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE 616 +# define SSL_F_SSL_WRITE 208 +# define SSL_F_SSL_WRITE_EARLY_DATA 526 +# define SSL_F_SSL_WRITE_EARLY_FINISH 527 +# define SSL_F_SSL_WRITE_EX 433 +# define SSL_F_SSL_WRITE_INTERNAL 524 +# define SSL_F_STATE_MACHINE 353 +# define SSL_F_TLS12_CHECK_PEER_SIGALG 333 +# define SSL_F_TLS12_COPY_SIGALGS 533 +# define SSL_F_TLS13_CHANGE_CIPHER_STATE 440 +# define SSL_F_TLS13_ENC 609 +# define SSL_F_TLS13_FINAL_FINISH_MAC 605 +# define SSL_F_TLS13_GENERATE_SECRET 591 +# define SSL_F_TLS13_HKDF_EXPAND 561 +# define SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA 617 +# define SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA 618 +# define SSL_F_TLS13_SETUP_KEY_BLOCK 441 +# define SSL_F_TLS1_CHANGE_CIPHER_STATE 209 +# define SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS 341 +# define SSL_F_TLS1_ENC 401 +# define SSL_F_TLS1_EXPORT_KEYING_MATERIAL 314 +# define SSL_F_TLS1_GET_CURVELIST 338 +# define SSL_F_TLS1_PRF 284 +# define SSL_F_TLS1_SAVE_U16 628 +# define SSL_F_TLS1_SETUP_KEY_BLOCK 211 +# define SSL_F_TLS1_SET_GROUPS 629 +# define SSL_F_TLS1_SET_RAW_SIGALGS 630 +# define SSL_F_TLS1_SET_SERVER_SIGALGS 335 +# define SSL_F_TLS1_SET_SHARED_SIGALGS 631 +# define SSL_F_TLS1_SET_SIGALGS 632 +# define SSL_F_TLS_CHOOSE_SIGALG 513 +# define SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK 354 +# define SSL_F_TLS_COLLECT_EXTENSIONS 435 +# define SSL_F_TLS_CONSTRUCT_CERTIFICATE_AUTHORITIES 542 +# define SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST 372 +# define SSL_F_TLS_CONSTRUCT_CERT_STATUS 429 +# define SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY 494 +# define SSL_F_TLS_CONSTRUCT_CERT_VERIFY 496 +# define SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC 427 +# define SSL_F_TLS_CONSTRUCT_CKE_DHE 404 +# define SSL_F_TLS_CONSTRUCT_CKE_ECDHE 405 +# define SSL_F_TLS_CONSTRUCT_CKE_GOST 406 +# define SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE 407 +# define SSL_F_TLS_CONSTRUCT_CKE_RSA 409 +# define SSL_F_TLS_CONSTRUCT_CKE_SRP 410 +# define SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE 484 +# define SSL_F_TLS_CONSTRUCT_CLIENT_HELLO 487 +# define SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE 488 +# define SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY 489 +# define SSL_F_TLS_CONSTRUCT_CTOS_ALPN 466 +# define SSL_F_TLS_CONSTRUCT_CTOS_CERTIFICATE 355 +# define SSL_F_TLS_CONSTRUCT_CTOS_COOKIE 535 +# define SSL_F_TLS_CONSTRUCT_CTOS_EARLY_DATA 530 +# define SSL_F_TLS_CONSTRUCT_CTOS_EC_PT_FORMATS 467 +# define SSL_F_TLS_CONSTRUCT_CTOS_EMS 468 +# define SSL_F_TLS_CONSTRUCT_CTOS_ETM 469 +# define SSL_F_TLS_CONSTRUCT_CTOS_HELLO 356 +# define SSL_F_TLS_CONSTRUCT_CTOS_KEY_EXCHANGE 357 +# define SSL_F_TLS_CONSTRUCT_CTOS_KEY_SHARE 470 +# define SSL_F_TLS_CONSTRUCT_CTOS_MAXFRAGMENTLEN 549 +# define SSL_F_TLS_CONSTRUCT_CTOS_NPN 471 +# define SSL_F_TLS_CONSTRUCT_CTOS_PADDING 472 +# define SSL_F_TLS_CONSTRUCT_CTOS_POST_HANDSHAKE_AUTH 619 +# define SSL_F_TLS_CONSTRUCT_CTOS_PSK 501 +# define SSL_F_TLS_CONSTRUCT_CTOS_PSK_KEX_MODES 509 +# define SSL_F_TLS_CONSTRUCT_CTOS_RENEGOTIATE 473 +# define SSL_F_TLS_CONSTRUCT_CTOS_SCT 474 +# define SSL_F_TLS_CONSTRUCT_CTOS_SERVER_NAME 475 +# define SSL_F_TLS_CONSTRUCT_CTOS_SESSION_TICKET 476 +# define SSL_F_TLS_CONSTRUCT_CTOS_SIG_ALGS 477 +# define SSL_F_TLS_CONSTRUCT_CTOS_SRP 478 +# define SSL_F_TLS_CONSTRUCT_CTOS_STATUS_REQUEST 479 +# define SSL_F_TLS_CONSTRUCT_CTOS_SUPPORTED_GROUPS 480 +# define SSL_F_TLS_CONSTRUCT_CTOS_SUPPORTED_VERSIONS 481 +# define SSL_F_TLS_CONSTRUCT_CTOS_USE_SRTP 482 +# define SSL_F_TLS_CONSTRUCT_CTOS_VERIFY 358 +# define SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS 443 +# define SSL_F_TLS_CONSTRUCT_END_OF_EARLY_DATA 536 +# define SSL_F_TLS_CONSTRUCT_EXTENSIONS 447 +# define SSL_F_TLS_CONSTRUCT_FINISHED 359 +# define SSL_F_TLS_CONSTRUCT_HELLO_REQUEST 373 +# define SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST 510 +# define SSL_F_TLS_CONSTRUCT_KEY_UPDATE 517 +# define SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET 428 +# define SSL_F_TLS_CONSTRUCT_NEXT_PROTO 426 +# define SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE 490 +# define SSL_F_TLS_CONSTRUCT_SERVER_HELLO 491 +# define SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE 492 +# define SSL_F_TLS_CONSTRUCT_STOC_ALPN 451 +# define SSL_F_TLS_CONSTRUCT_STOC_CERTIFICATE 374 +# define SSL_F_TLS_CONSTRUCT_STOC_COOKIE 613 +# define SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG 452 +# define SSL_F_TLS_CONSTRUCT_STOC_DONE 375 +# define SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA 531 +# define SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA_INFO 525 +# define SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS 453 +# define SSL_F_TLS_CONSTRUCT_STOC_EMS 454 +# define SSL_F_TLS_CONSTRUCT_STOC_ETM 455 +# define SSL_F_TLS_CONSTRUCT_STOC_HELLO 376 +# define SSL_F_TLS_CONSTRUCT_STOC_KEY_EXCHANGE 377 +# define SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE 456 +# define SSL_F_TLS_CONSTRUCT_STOC_MAXFRAGMENTLEN 548 +# define SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG 457 +# define SSL_F_TLS_CONSTRUCT_STOC_PSK 504 +# define SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE 458 +# define SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME 459 +# define SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET 460 +# define SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST 461 +# define SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS 544 +# define SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS 611 +# define SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP 462 +# define SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO 521 +# define SSL_F_TLS_FINISH_HANDSHAKE 597 +# define SSL_F_TLS_GET_MESSAGE_BODY 351 +# define SSL_F_TLS_GET_MESSAGE_HEADER 387 +# define SSL_F_TLS_HANDLE_ALPN 562 +# define SSL_F_TLS_HANDLE_STATUS_REQUEST 563 +# define SSL_F_TLS_PARSE_CERTIFICATE_AUTHORITIES 566 +# define SSL_F_TLS_PARSE_CLIENTHELLO_TLSEXT 449 +# define SSL_F_TLS_PARSE_CTOS_ALPN 567 +# define SSL_F_TLS_PARSE_CTOS_COOKIE 614 +# define SSL_F_TLS_PARSE_CTOS_EARLY_DATA 568 +# define SSL_F_TLS_PARSE_CTOS_EC_PT_FORMATS 569 +# define SSL_F_TLS_PARSE_CTOS_EMS 570 +# define SSL_F_TLS_PARSE_CTOS_KEY_SHARE 463 +# define SSL_F_TLS_PARSE_CTOS_MAXFRAGMENTLEN 571 +# define SSL_F_TLS_PARSE_CTOS_POST_HANDSHAKE_AUTH 620 +# define SSL_F_TLS_PARSE_CTOS_PSK 505 +# define SSL_F_TLS_PARSE_CTOS_PSK_KEX_MODES 572 +# define SSL_F_TLS_PARSE_CTOS_RENEGOTIATE 464 +# define SSL_F_TLS_PARSE_CTOS_SERVER_NAME 573 +# define SSL_F_TLS_PARSE_CTOS_SESSION_TICKET 574 +# define SSL_F_TLS_PARSE_CTOS_SIG_ALGS 575 +# define SSL_F_TLS_PARSE_CTOS_SIG_ALGS_CERT 615 +# define SSL_F_TLS_PARSE_CTOS_SRP 576 +# define SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST 577 +# define SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS 578 +# define SSL_F_TLS_PARSE_CTOS_USE_SRTP 465 +# define SSL_F_TLS_PARSE_STOC_ALPN 579 +# define SSL_F_TLS_PARSE_STOC_COOKIE 534 +# define SSL_F_TLS_PARSE_STOC_EARLY_DATA 538 +# define SSL_F_TLS_PARSE_STOC_EARLY_DATA_INFO 528 +# define SSL_F_TLS_PARSE_STOC_EC_PT_FORMATS 580 +# define SSL_F_TLS_PARSE_STOC_KEY_SHARE 445 +# define SSL_F_TLS_PARSE_STOC_MAXFRAGMENTLEN 581 +# define SSL_F_TLS_PARSE_STOC_NPN 582 +# define SSL_F_TLS_PARSE_STOC_PSK 502 +# define SSL_F_TLS_PARSE_STOC_RENEGOTIATE 448 +# define SSL_F_TLS_PARSE_STOC_SCT 564 +# define SSL_F_TLS_PARSE_STOC_SERVER_NAME 583 +# define SSL_F_TLS_PARSE_STOC_SESSION_TICKET 584 +# define SSL_F_TLS_PARSE_STOC_STATUS_REQUEST 585 +# define SSL_F_TLS_PARSE_STOC_SUPPORTED_VERSIONS 612 +# define SSL_F_TLS_PARSE_STOC_USE_SRTP 446 +# define SSL_F_TLS_POST_PROCESS_CLIENT_HELLO 378 +# define SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE 384 +# define SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE 360 +# define SSL_F_TLS_PROCESS_AS_HELLO_RETRY_REQUEST 610 +# define SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST 361 +# define SSL_F_TLS_PROCESS_CERT_STATUS 362 +# define SSL_F_TLS_PROCESS_CERT_STATUS_BODY 495 +# define SSL_F_TLS_PROCESS_CERT_VERIFY 379 +# define SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC 363 +# define SSL_F_TLS_PROCESS_CKE_DHE 411 +# define SSL_F_TLS_PROCESS_CKE_ECDHE 412 +# define SSL_F_TLS_PROCESS_CKE_GOST 413 +# define SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE 414 +# define SSL_F_TLS_PROCESS_CKE_RSA 415 +# define SSL_F_TLS_PROCESS_CKE_SRP 416 +# define SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE 380 +# define SSL_F_TLS_PROCESS_CLIENT_HELLO 381 +# define SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE 382 +# define SSL_F_TLS_PROCESS_ENCRYPTED_EXTENSIONS 444 +# define SSL_F_TLS_PROCESS_END_OF_EARLY_DATA 537 +# define SSL_F_TLS_PROCESS_FINISHED 364 +# define SSL_F_TLS_PROCESS_HELLO_REQ 507 +# define SSL_F_TLS_PROCESS_HELLO_RETRY_REQUEST 511 +# define SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT 442 +# define SSL_F_TLS_PROCESS_KEY_EXCHANGE 365 +# define SSL_F_TLS_PROCESS_KEY_UPDATE 518 +# define SSL_F_TLS_PROCESS_NEW_SESSION_TICKET 366 +# define SSL_F_TLS_PROCESS_NEXT_PROTO 383 +# define SSL_F_TLS_PROCESS_SERVER_CERTIFICATE 367 +# define SSL_F_TLS_PROCESS_SERVER_DONE 368 +# define SSL_F_TLS_PROCESS_SERVER_HELLO 369 +# define SSL_F_TLS_PROCESS_SKE_DHE 419 +# define SSL_F_TLS_PROCESS_SKE_ECDHE 420 +# define SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE 421 +# define SSL_F_TLS_PROCESS_SKE_SRP 422 +# define SSL_F_TLS_PSK_DO_BINDER 506 +# define SSL_F_TLS_SCAN_CLIENTHELLO_TLSEXT 450 +# define SSL_F_TLS_SETUP_HANDSHAKE 508 +# define SSL_F_USE_CERTIFICATE_CHAIN_FILE 220 +# define SSL_F_WPACKET_INTERN_INIT_LEN 633 +# define SSL_F_WPACKET_START_SUB_PACKET_LEN__ 634 +# define SSL_F_WRITE_STATE_MACHINE 586 + +/* + * SSL reason codes. + */ +# define SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY 291 +# define SSL_R_APP_DATA_IN_HANDSHAKE 100 +# define SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT 272 +# define SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE 143 +# define SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE 158 +# define SSL_R_BAD_CHANGE_CIPHER_SPEC 103 +# define SSL_R_BAD_CIPHER 186 +# define SSL_R_BAD_DATA 390 +# define SSL_R_BAD_DATA_RETURNED_BY_CALLBACK 106 +# define SSL_R_BAD_DECOMPRESSION 107 +# define SSL_R_BAD_DH_VALUE 102 +# define SSL_R_BAD_DIGEST_LENGTH 111 +# define SSL_R_BAD_EARLY_DATA 233 +# define SSL_R_BAD_ECC_CERT 304 +# define SSL_R_BAD_ECPOINT 306 +# define SSL_R_BAD_EXTENSION 110 +# define SSL_R_BAD_HANDSHAKE_LENGTH 332 +# define SSL_R_BAD_HANDSHAKE_STATE 236 +# define SSL_R_BAD_HELLO_REQUEST 105 +# define SSL_R_BAD_HRR_VERSION 263 +# define SSL_R_BAD_KEY_SHARE 108 +# define SSL_R_BAD_KEY_UPDATE 122 +# define SSL_R_BAD_LEGACY_VERSION 292 +# define SSL_R_BAD_LENGTH 271 +# define SSL_R_BAD_PACKET 240 +# define SSL_R_BAD_PACKET_LENGTH 115 +# define SSL_R_BAD_PROTOCOL_VERSION_NUMBER 116 +# define SSL_R_BAD_PSK 219 +# define SSL_R_BAD_PSK_IDENTITY 114 +# define SSL_R_BAD_RECORD_TYPE 443 +# define SSL_R_BAD_RSA_ENCRYPT 119 +# define SSL_R_BAD_SIGNATURE 123 +# define SSL_R_BAD_SRP_A_LENGTH 347 +# define SSL_R_BAD_SRP_PARAMETERS 371 +# define SSL_R_BAD_SRTP_MKI_VALUE 352 +# define SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST 353 +# define SSL_R_BAD_SSL_FILETYPE 124 +# define SSL_R_BAD_VALUE 384 +# define SSL_R_BAD_WRITE_RETRY 127 +# define SSL_R_BINDER_DOES_NOT_VERIFY 253 +# define SSL_R_BIO_NOT_SET 128 +# define SSL_R_BLOCK_CIPHER_PAD_IS_WRONG 129 +# define SSL_R_BN_LIB 130 +# define SSL_R_CALLBACK_FAILED 234 +# define SSL_R_CANNOT_CHANGE_CIPHER 109 +# define SSL_R_CA_DN_LENGTH_MISMATCH 131 +# define SSL_R_CA_KEY_TOO_SMALL 397 +# define SSL_R_CA_MD_TOO_WEAK 398 +# define SSL_R_CCS_RECEIVED_EARLY 133 +# define SSL_R_CERTIFICATE_VERIFY_FAILED 134 +# define SSL_R_CERT_CB_ERROR 377 +# define SSL_R_CERT_LENGTH_MISMATCH 135 +# define SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED 218 +# define SSL_R_CIPHER_CODE_WRONG_LENGTH 137 +# define SSL_R_CIPHER_OR_HASH_UNAVAILABLE 138 +# define SSL_R_CLIENTHELLO_TLSEXT 226 +# define SSL_R_COMPRESSED_LENGTH_TOO_LONG 140 +# define SSL_R_COMPRESSION_DISABLED 343 +# define SSL_R_COMPRESSION_FAILURE 141 +# define SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE 307 +# define SSL_R_COMPRESSION_LIBRARY_ERROR 142 +# define SSL_R_CONNECTION_TYPE_NOT_SET 144 +# define SSL_R_CONTEXT_NOT_DANE_ENABLED 167 +# define SSL_R_COOKIE_GEN_CALLBACK_FAILURE 400 +# define SSL_R_COOKIE_MISMATCH 308 +# define SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED 206 +# define SSL_R_DANE_ALREADY_ENABLED 172 +# define SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL 173 +# define SSL_R_DANE_NOT_ENABLED 175 +# define SSL_R_DANE_TLSA_BAD_CERTIFICATE 180 +# define SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE 184 +# define SSL_R_DANE_TLSA_BAD_DATA_LENGTH 189 +# define SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH 192 +# define SSL_R_DANE_TLSA_BAD_MATCHING_TYPE 200 +# define SSL_R_DANE_TLSA_BAD_PUBLIC_KEY 201 +# define SSL_R_DANE_TLSA_BAD_SELECTOR 202 +# define SSL_R_DANE_TLSA_NULL_DATA 203 +# define SSL_R_DATA_BETWEEN_CCS_AND_FINISHED 145 +# define SSL_R_DATA_LENGTH_TOO_LONG 146 +# define SSL_R_DECRYPTION_FAILED 147 +# define SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC 281 +# define SSL_R_DH_KEY_TOO_SMALL 394 +# define SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG 148 +# define SSL_R_DIGEST_CHECK_FAILED 149 +# define SSL_R_DTLS_MESSAGE_TOO_BIG 334 +# define SSL_R_DUPLICATE_COMPRESSION_ID 309 +# define SSL_R_ECC_CERT_NOT_FOR_SIGNING 318 +# define SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE 374 +# define SSL_R_EE_KEY_TOO_SMALL 399 +# define SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST 354 +# define SSL_R_ENCRYPTED_LENGTH_TOO_LONG 150 +# define SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST 151 +# define SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN 204 +# define SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE 194 +# define SSL_R_EXCESSIVE_MESSAGE_SIZE 152 +# define SSL_R_EXTENSION_NOT_RECEIVED 279 +# define SSL_R_EXTRA_DATA_IN_MESSAGE 153 +# define SSL_R_EXT_LENGTH_MISMATCH 163 +# define SSL_R_FAILED_TO_INIT_ASYNC 405 +# define SSL_R_FRAGMENTED_CLIENT_HELLO 401 +# define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154 +# define SSL_R_HTTPS_PROXY_REQUEST 155 +# define SSL_R_HTTP_REQUEST 156 +# define SSL_R_ILLEGAL_POINT_COMPRESSION 162 +# define SSL_R_ILLEGAL_SUITEB_DIGEST 380 +# define SSL_R_INAPPROPRIATE_FALLBACK 373 +# define SSL_R_INCONSISTENT_COMPRESSION 340 +# define SSL_R_INCONSISTENT_EARLY_DATA_ALPN 222 +# define SSL_R_INCONSISTENT_EARLY_DATA_SNI 231 +# define SSL_R_INCONSISTENT_EXTMS 104 +# define SSL_R_INSUFFICIENT_SECURITY 241 +# define SSL_R_INVALID_ALERT 205 +# define SSL_R_INVALID_CCS_MESSAGE 260 +# define SSL_R_INVALID_CERTIFICATE_OR_ALG 238 +# define SSL_R_INVALID_COMMAND 280 +# define SSL_R_INVALID_COMPRESSION_ALGORITHM 341 +# define SSL_R_INVALID_CONFIG 283 +# define SSL_R_INVALID_CONFIGURATION_NAME 113 +# define SSL_R_INVALID_CONTEXT 282 +# define SSL_R_INVALID_CT_VALIDATION_TYPE 212 +# define SSL_R_INVALID_KEY_UPDATE_TYPE 120 +# define SSL_R_INVALID_MAX_EARLY_DATA 174 +# define SSL_R_INVALID_NULL_CMD_NAME 385 +# define SSL_R_INVALID_SEQUENCE_NUMBER 402 +# define SSL_R_INVALID_SERVERINFO_DATA 388 +# define SSL_R_INVALID_SESSION_ID 999 +# define SSL_R_INVALID_SRP_USERNAME 357 +# define SSL_R_INVALID_STATUS_RESPONSE 328 +# define SSL_R_INVALID_TICKET_KEYS_LENGTH 325 +# define SSL_R_LENGTH_MISMATCH 159 +# define SSL_R_LENGTH_TOO_LONG 404 +# define SSL_R_LENGTH_TOO_SHORT 160 +# define SSL_R_LIBRARY_BUG 274 +# define SSL_R_LIBRARY_HAS_NO_CIPHERS 161 +# define SSL_R_MISSING_DSA_SIGNING_CERT 165 +# define SSL_R_MISSING_ECDSA_SIGNING_CERT 381 +# define SSL_R_MISSING_FATAL 256 +# define SSL_R_MISSING_PARAMETERS 290 +# define SSL_R_MISSING_RSA_CERTIFICATE 168 +# define SSL_R_MISSING_RSA_ENCRYPTING_CERT 169 +# define SSL_R_MISSING_RSA_SIGNING_CERT 170 +# define SSL_R_MISSING_SIGALGS_EXTENSION 112 +# define SSL_R_MISSING_SIGNING_CERT 221 +# define SSL_R_MISSING_SRP_PARAM 358 +# define SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION 209 +# define SSL_R_MISSING_TMP_DH_KEY 171 +# define SSL_R_MISSING_TMP_ECDH_KEY 311 +# define SSL_R_NOT_ON_RECORD_BOUNDARY 182 +# define SSL_R_NOT_REPLACING_CERTIFICATE 289 +# define SSL_R_NOT_SERVER 284 +# define SSL_R_NO_APPLICATION_PROTOCOL 235 +# define SSL_R_NO_CERTIFICATES_RETURNED 176 +# define SSL_R_NO_CERTIFICATE_ASSIGNED 177 +# define SSL_R_NO_CERTIFICATE_SET 179 +# define SSL_R_NO_CHANGE_FOLLOWING_HRR 214 +# define SSL_R_NO_CIPHERS_AVAILABLE 181 +# define SSL_R_NO_CIPHERS_SPECIFIED 183 +# define SSL_R_NO_CIPHER_MATCH 185 +# define SSL_R_NO_CLIENT_CERT_METHOD 331 +# define SSL_R_NO_COMPRESSION_SPECIFIED 187 +# define SSL_R_NO_COOKIE_CALLBACK_SET 287 +# define SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER 330 +# define SSL_R_NO_METHOD_SPECIFIED 188 +# define SSL_R_NO_PEM_EXTENSIONS 389 +# define SSL_R_NO_PRIVATE_KEY_ASSIGNED 190 +# define SSL_R_NO_PROTOCOLS_AVAILABLE 191 +# define SSL_R_NO_RENEGOTIATION 339 +# define SSL_R_NO_REQUIRED_DIGEST 324 +# define SSL_R_NO_SHARED_CIPHER 193 +# define SSL_R_NO_SHARED_GROUPS 410 +# define SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS 376 +# define SSL_R_NO_SRTP_PROFILES 359 +# define SSL_R_NO_SUITABLE_KEY_SHARE 101 +# define SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM 118 +# define SSL_R_NO_VALID_SCTS 216 +# define SSL_R_NO_VERIFY_COOKIE_CALLBACK 403 +# define SSL_R_NULL_SSL_CTX 195 +# define SSL_R_NULL_SSL_METHOD_PASSED 196 +# define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED 197 +# define SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED 344 +# define SSL_R_OVERFLOW_ERROR 237 +# define SSL_R_PACKET_LENGTH_TOO_LONG 198 +# define SSL_R_PARSE_TLSEXT 227 +# define SSL_R_PATH_TOO_LONG 270 +# define SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE 199 +# define SSL_R_PEM_NAME_BAD_PREFIX 391 +# define SSL_R_PEM_NAME_TOO_SHORT 392 +# define SSL_R_PIPELINE_FAILURE 406 +# define SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR 278 +# define SSL_R_PRIVATE_KEY_MISMATCH 288 +# define SSL_R_PROTOCOL_IS_SHUTDOWN 207 +# define SSL_R_PSK_IDENTITY_NOT_FOUND 223 +# define SSL_R_PSK_NO_CLIENT_CB 224 +# define SSL_R_PSK_NO_SERVER_CB 225 +# define SSL_R_READ_BIO_NOT_SET 211 +# define SSL_R_READ_TIMEOUT_EXPIRED 312 +# define SSL_R_RECORD_LENGTH_MISMATCH 213 +# define SSL_R_RECORD_TOO_SMALL 298 +# define SSL_R_RENEGOTIATE_EXT_TOO_LONG 335 +# define SSL_R_RENEGOTIATION_ENCODING_ERR 336 +# define SSL_R_RENEGOTIATION_MISMATCH 337 +# define SSL_R_REQUEST_PENDING 285 +# define SSL_R_REQUEST_SENT 286 +# define SSL_R_REQUIRED_CIPHER_MISSING 215 +# define SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING 342 +# define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 345 +# define SSL_R_SCT_VERIFICATION_FAILED 208 +# define SSL_R_SERVERHELLO_TLSEXT 275 +# define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 277 +# define SSL_R_SHUTDOWN_WHILE_IN_INIT 407 +# define SSL_R_SIGNATURE_ALGORITHMS_ERROR 360 +# define SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE 220 +# define SSL_R_SRP_A_CALC 361 +# define SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES 362 +# define SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG 363 +# define SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE 364 +# define SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH 232 +# define SSL_R_SSL3_EXT_INVALID_SERVERNAME 319 +# define SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE 320 +# define SSL_R_SSL3_SESSION_ID_TOO_LONG 300 +# define SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042 +# define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020 +# define SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045 +# define SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044 +# define SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046 +# define SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030 +# define SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040 +# define SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047 +# define SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041 +# define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010 +# define SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043 +# define SSL_R_SSL_COMMAND_SECTION_EMPTY 117 +# define SSL_R_SSL_COMMAND_SECTION_NOT_FOUND 125 +# define SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION 228 +# define SSL_R_SSL_HANDSHAKE_FAILURE 229 +# define SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS 230 +# define SSL_R_SSL_NEGATIVE_LENGTH 372 +# define SSL_R_SSL_SECTION_EMPTY 126 +# define SSL_R_SSL_SECTION_NOT_FOUND 136 +# define SSL_R_SSL_SESSION_ID_CALLBACK_FAILED 301 +# define SSL_R_SSL_SESSION_ID_CONFLICT 302 +# define SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG 273 +# define SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH 303 +# define SSL_R_SSL_SESSION_ID_TOO_LONG 408 +# define SSL_R_SSL_SESSION_VERSION_MISMATCH 210 +# define SSL_R_STILL_IN_INIT 121 +# define SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED 1116 +# define SSL_R_TLSV13_ALERT_MISSING_EXTENSION 1109 +# define SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049 +# define SSL_R_TLSV1_ALERT_DECODE_ERROR 1050 +# define SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021 +# define SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051 +# define SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060 +# define SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086 +# define SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071 +# define SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080 +# define SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100 +# define SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070 +# define SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022 +# define SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048 +# define SSL_R_TLSV1_ALERT_USER_CANCELLED 1090 +# define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114 +# define SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113 +# define SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111 +# define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112 +# define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110 +# define SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT 365 +# define SSL_R_TLS_HEARTBEAT_PENDING 366 +# define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 367 +# define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157 +# define SSL_R_TOO_MANY_KEY_UPDATES 132 +# define SSL_R_TOO_MANY_WARN_ALERTS 409 +# define SSL_R_TOO_MUCH_EARLY_DATA 164 +# define SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS 314 +# define SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS 239 +# define SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES 242 +# define SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES 243 +# define SSL_R_UNEXPECTED_CCS_MESSAGE 262 +# define SSL_R_UNEXPECTED_END_OF_EARLY_DATA 178 +# define SSL_R_UNEXPECTED_MESSAGE 244 +# define SSL_R_UNEXPECTED_RECORD 245 +# define SSL_R_UNINITIALIZED 276 +# define SSL_R_UNKNOWN_ALERT_TYPE 246 +# define SSL_R_UNKNOWN_CERTIFICATE_TYPE 247 +# define SSL_R_UNKNOWN_CIPHER_RETURNED 248 +# define SSL_R_UNKNOWN_CIPHER_TYPE 249 +# define SSL_R_UNKNOWN_CMD_NAME 386 +# define SSL_R_UNKNOWN_COMMAND 139 +# define SSL_R_UNKNOWN_DIGEST 368 +# define SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE 250 +# define SSL_R_UNKNOWN_PKEY_TYPE 251 +# define SSL_R_UNKNOWN_PROTOCOL 252 +# define SSL_R_UNKNOWN_SSL_VERSION 254 +# define SSL_R_UNKNOWN_STATE 255 +# define SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED 338 +# define SSL_R_UNSOLICITED_EXTENSION 217 +# define SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM 257 +# define SSL_R_UNSUPPORTED_ELLIPTIC_CURVE 315 +# define SSL_R_UNSUPPORTED_PROTOCOL 258 +# define SSL_R_UNSUPPORTED_SSL_VERSION 259 +# define SSL_R_UNSUPPORTED_STATUS_TYPE 329 +# define SSL_R_USE_SRTP_NOT_NEGOTIATED 369 +# define SSL_R_VERSION_TOO_HIGH 166 +# define SSL_R_VERSION_TOO_LOW 396 +# define SSL_R_WRONG_CERTIFICATE_TYPE 383 +# define SSL_R_WRONG_CIPHER_RETURNED 261 +# define SSL_R_WRONG_CURVE 378 +# define SSL_R_WRONG_SIGNATURE_LENGTH 264 +# define SSL_R_WRONG_SIGNATURE_SIZE 265 +# define SSL_R_WRONG_SIGNATURE_TYPE 370 +# define SSL_R_WRONG_SSL_VERSION 266 +# define SSL_R_WRONG_VERSION_NUMBER 267 +# define SSL_R_X509_LIB 268 +# define SSL_R_X509_VERIFICATION_SETUP_PROBLEMS 269 + +#endif diff --git a/include/openssl/stack.h b/include/openssl/stack.h new file mode 100644 index 0000000..cfc0750 --- /dev/null +++ b/include/openssl/stack.h @@ -0,0 +1,83 @@ +/* + * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_STACK_H +# define HEADER_STACK_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct stack_st OPENSSL_STACK; /* Use STACK_OF(...) instead */ + +typedef int (*OPENSSL_sk_compfunc)(const void *, const void *); +typedef void (*OPENSSL_sk_freefunc)(void *); +typedef void *(*OPENSSL_sk_copyfunc)(const void *); + +int OPENSSL_sk_num(const OPENSSL_STACK *); +void *OPENSSL_sk_value(const OPENSSL_STACK *, int); + +void *OPENSSL_sk_set(OPENSSL_STACK *st, int i, const void *data); + +OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_compfunc cmp); +OPENSSL_STACK *OPENSSL_sk_new_null(void); +OPENSSL_STACK *OPENSSL_sk_new_reserve(OPENSSL_sk_compfunc c, int n); +int OPENSSL_sk_reserve(OPENSSL_STACK *st, int n); +void OPENSSL_sk_free(OPENSSL_STACK *); +void OPENSSL_sk_pop_free(OPENSSL_STACK *st, void (*func) (void *)); +OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *, + OPENSSL_sk_copyfunc c, + OPENSSL_sk_freefunc f); +int OPENSSL_sk_insert(OPENSSL_STACK *sk, const void *data, int where); +void *OPENSSL_sk_delete(OPENSSL_STACK *st, int loc); +void *OPENSSL_sk_delete_ptr(OPENSSL_STACK *st, const void *p); +int OPENSSL_sk_find(OPENSSL_STACK *st, const void *data); +int OPENSSL_sk_find_ex(OPENSSL_STACK *st, const void *data); +int OPENSSL_sk_push(OPENSSL_STACK *st, const void *data); +int OPENSSL_sk_unshift(OPENSSL_STACK *st, const void *data); +void *OPENSSL_sk_shift(OPENSSL_STACK *st); +void *OPENSSL_sk_pop(OPENSSL_STACK *st); +void OPENSSL_sk_zero(OPENSSL_STACK *st); +OPENSSL_sk_compfunc OPENSSL_sk_set_cmp_func(OPENSSL_STACK *sk, + OPENSSL_sk_compfunc cmp); +OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *st); +void OPENSSL_sk_sort(OPENSSL_STACK *st); +int OPENSSL_sk_is_sorted(const OPENSSL_STACK *st); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define _STACK OPENSSL_STACK +# define sk_num OPENSSL_sk_num +# define sk_value OPENSSL_sk_value +# define sk_set OPENSSL_sk_set +# define sk_new OPENSSL_sk_new +# define sk_new_null OPENSSL_sk_new_null +# define sk_free OPENSSL_sk_free +# define sk_pop_free OPENSSL_sk_pop_free +# define sk_deep_copy OPENSSL_sk_deep_copy +# define sk_insert OPENSSL_sk_insert +# define sk_delete OPENSSL_sk_delete +# define sk_delete_ptr OPENSSL_sk_delete_ptr +# define sk_find OPENSSL_sk_find +# define sk_find_ex OPENSSL_sk_find_ex +# define sk_push OPENSSL_sk_push +# define sk_unshift OPENSSL_sk_unshift +# define sk_shift OPENSSL_sk_shift +# define sk_pop OPENSSL_sk_pop +# define sk_zero OPENSSL_sk_zero +# define sk_set_cmp_func OPENSSL_sk_set_cmp_func +# define sk_dup OPENSSL_sk_dup +# define sk_sort OPENSSL_sk_sort +# define sk_is_sorted OPENSSL_sk_is_sorted +# endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/store.h b/include/openssl/store.h new file mode 100644 index 0000000..9f07db9 --- /dev/null +++ b/include/openssl/store.h @@ -0,0 +1,266 @@ +/* + * Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OSSL_STORE_H +# define HEADER_OSSL_STORE_H + +# include +# include +# include +# include + +# ifdef __cplusplus +extern "C" { +# endif + +/*- + * The main OSSL_STORE functions. + * ------------------------------ + * + * These allow applications to open a channel to a resource with supported + * data (keys, certs, crls, ...), read the data a piece at a time and decide + * what to do with it, and finally close. + */ + +typedef struct ossl_store_ctx_st OSSL_STORE_CTX; + +/* + * Typedef for the OSSL_STORE_INFO post processing callback. This can be used + * to massage the given OSSL_STORE_INFO, or to drop it entirely (by returning + * NULL). + */ +typedef OSSL_STORE_INFO *(*OSSL_STORE_post_process_info_fn)(OSSL_STORE_INFO *, + void *); + +/* + * Open a channel given a URI. The given UI method will be used any time the + * loader needs extra input, for example when a password or pin is needed, and + * will be passed the same user data every time it's needed in this context. + * + * Returns a context reference which represents the channel to communicate + * through. + */ +OSSL_STORE_CTX *OSSL_STORE_open(const char *uri, const UI_METHOD *ui_method, + void *ui_data, + OSSL_STORE_post_process_info_fn post_process, + void *post_process_data); + +/* + * Control / fine tune the OSSL_STORE channel. |cmd| determines what is to be + * done, and depends on the underlying loader (use OSSL_STORE_get0_scheme to + * determine which loader is used), except for common commands (see below). + * Each command takes different arguments. + */ +int OSSL_STORE_ctrl(OSSL_STORE_CTX *ctx, int cmd, ... /* args */); +int OSSL_STORE_vctrl(OSSL_STORE_CTX *ctx, int cmd, va_list args); + +/* + * Common ctrl commands that different loaders may choose to support. + */ +/* int on = 0 or 1; STORE_ctrl(ctx, STORE_C_USE_SECMEM, &on); */ +# define OSSL_STORE_C_USE_SECMEM 1 +/* Where custom commands start */ +# define OSSL_STORE_C_CUSTOM_START 100 + +/* + * Read one data item (a key, a cert, a CRL) that is supported by the OSSL_STORE + * functionality, given a context. + * Returns a OSSL_STORE_INFO pointer, from which OpenSSL typed data can be + * extracted with OSSL_STORE_INFO_get0_PKEY(), OSSL_STORE_INFO_get0_CERT(), ... + * NULL is returned on error, which may include that the data found at the URI + * can't be figured out for certain or is ambiguous. + */ +OSSL_STORE_INFO *OSSL_STORE_load(OSSL_STORE_CTX *ctx); + +/* + * Check if end of data (end of file) is reached + * Returns 1 on end, 0 otherwise. + */ +int OSSL_STORE_eof(OSSL_STORE_CTX *ctx); + +/* + * Check if an error occured + * Returns 1 if it did, 0 otherwise. + */ +int OSSL_STORE_error(OSSL_STORE_CTX *ctx); + +/* + * Close the channel + * Returns 1 on success, 0 on error. + */ +int OSSL_STORE_close(OSSL_STORE_CTX *ctx); + + +/*- + * Extracting OpenSSL types from and creating new OSSL_STORE_INFOs + * --------------------------------------------------------------- + */ + +/* + * Types of data that can be ossl_stored in a OSSL_STORE_INFO. + * OSSL_STORE_INFO_NAME is typically found when getting a listing of + * available "files" / "tokens" / what have you. + */ +# define OSSL_STORE_INFO_NAME 1 /* char * */ +# define OSSL_STORE_INFO_PARAMS 2 /* EVP_PKEY * */ +# define OSSL_STORE_INFO_PKEY 3 /* EVP_PKEY * */ +# define OSSL_STORE_INFO_CERT 4 /* X509 * */ +# define OSSL_STORE_INFO_CRL 5 /* X509_CRL * */ + +/* + * Functions to generate OSSL_STORE_INFOs, one function for each type we + * support having in them, as well as a generic constructor. + * + * In all cases, ownership of the object is transfered to the OSSL_STORE_INFO + * and will therefore be freed when the OSSL_STORE_INFO is freed. + */ +OSSL_STORE_INFO *OSSL_STORE_INFO_new_NAME(char *name); +int OSSL_STORE_INFO_set0_NAME_description(OSSL_STORE_INFO *info, char *desc); +OSSL_STORE_INFO *OSSL_STORE_INFO_new_PARAMS(EVP_PKEY *params); +OSSL_STORE_INFO *OSSL_STORE_INFO_new_PKEY(EVP_PKEY *pkey); +OSSL_STORE_INFO *OSSL_STORE_INFO_new_CERT(X509 *x509); +OSSL_STORE_INFO *OSSL_STORE_INFO_new_CRL(X509_CRL *crl); + +/* + * Functions to try to extract data from a OSSL_STORE_INFO. + */ +int OSSL_STORE_INFO_get_type(const OSSL_STORE_INFO *info); +const char *OSSL_STORE_INFO_get0_NAME(const OSSL_STORE_INFO *info); +char *OSSL_STORE_INFO_get1_NAME(const OSSL_STORE_INFO *info); +const char *OSSL_STORE_INFO_get0_NAME_description(const OSSL_STORE_INFO *info); +char *OSSL_STORE_INFO_get1_NAME_description(const OSSL_STORE_INFO *info); +EVP_PKEY *OSSL_STORE_INFO_get0_PARAMS(const OSSL_STORE_INFO *info); +EVP_PKEY *OSSL_STORE_INFO_get1_PARAMS(const OSSL_STORE_INFO *info); +EVP_PKEY *OSSL_STORE_INFO_get0_PKEY(const OSSL_STORE_INFO *info); +EVP_PKEY *OSSL_STORE_INFO_get1_PKEY(const OSSL_STORE_INFO *info); +X509 *OSSL_STORE_INFO_get0_CERT(const OSSL_STORE_INFO *info); +X509 *OSSL_STORE_INFO_get1_CERT(const OSSL_STORE_INFO *info); +X509_CRL *OSSL_STORE_INFO_get0_CRL(const OSSL_STORE_INFO *info); +X509_CRL *OSSL_STORE_INFO_get1_CRL(const OSSL_STORE_INFO *info); + +const char *OSSL_STORE_INFO_type_string(int type); + +/* + * Free the OSSL_STORE_INFO + */ +void OSSL_STORE_INFO_free(OSSL_STORE_INFO *info); + + +/*- + * Functions to construct a search URI from a base URI and search criteria + * ----------------------------------------------------------------------- + */ + +/* OSSL_STORE search types */ +# define OSSL_STORE_SEARCH_BY_NAME 1 /* subject in certs, issuer in CRLs */ +# define OSSL_STORE_SEARCH_BY_ISSUER_SERIAL 2 +# define OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT 3 +# define OSSL_STORE_SEARCH_BY_ALIAS 4 + +/* To check what search types the scheme handler supports */ +int OSSL_STORE_supports_search(OSSL_STORE_CTX *ctx, int search_type); + +/* Search term constructors */ +/* + * The input is considered to be owned by the caller, and must therefore + * remain present throughout the lifetime of the returned OSSL_STORE_SEARCH + */ +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_name(X509_NAME *name); +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_issuer_serial(X509_NAME *name, + const ASN1_INTEGER + *serial); +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_key_fingerprint(const EVP_MD *digest, + const unsigned char + *bytes, size_t len); +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_alias(const char *alias); + +/* Search term destructor */ +void OSSL_STORE_SEARCH_free(OSSL_STORE_SEARCH *search); + +/* Search term accessors */ +int OSSL_STORE_SEARCH_get_type(const OSSL_STORE_SEARCH *criterion); +X509_NAME *OSSL_STORE_SEARCH_get0_name(OSSL_STORE_SEARCH *criterion); +const ASN1_INTEGER *OSSL_STORE_SEARCH_get0_serial(const OSSL_STORE_SEARCH + *criterion); +const unsigned char *OSSL_STORE_SEARCH_get0_bytes(const OSSL_STORE_SEARCH + *criterion, size_t *length); +const char *OSSL_STORE_SEARCH_get0_string(const OSSL_STORE_SEARCH *criterion); +const EVP_MD *OSSL_STORE_SEARCH_get0_digest(const OSSL_STORE_SEARCH *criterion); + +/* + * Add search criterion and expected return type (which can be unspecified) + * to the loading channel. This MUST happen before the first OSSL_STORE_load(). + */ +int OSSL_STORE_expect(OSSL_STORE_CTX *ctx, int expected_type); +int OSSL_STORE_find(OSSL_STORE_CTX *ctx, OSSL_STORE_SEARCH *search); + + +/*- + * Function to register a loader for the given URI scheme. + * ------------------------------------------------------- + * + * The loader receives all the main components of an URI except for the + * scheme. + */ + +typedef struct ossl_store_loader_st OSSL_STORE_LOADER; +OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme); +const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER *loader); +const char *OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER *loader); +/* struct ossl_store_loader_ctx_st is defined differently by each loader */ +typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX; +typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_fn)(const OSSL_STORE_LOADER + *loader, + const char *uri, + const UI_METHOD *ui_method, + void *ui_data); +int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *loader, + OSSL_STORE_open_fn open_function); +typedef int (*OSSL_STORE_ctrl_fn)(OSSL_STORE_LOADER_CTX *ctx, int cmd, + va_list args); +int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *loader, + OSSL_STORE_ctrl_fn ctrl_function); +typedef int (*OSSL_STORE_expect_fn)(OSSL_STORE_LOADER_CTX *ctx, int expected); +int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader, + OSSL_STORE_expect_fn expect_function); +typedef int (*OSSL_STORE_find_fn)(OSSL_STORE_LOADER_CTX *ctx, + OSSL_STORE_SEARCH *criteria); +int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader, + OSSL_STORE_find_fn find_function); +typedef OSSL_STORE_INFO *(*OSSL_STORE_load_fn)(OSSL_STORE_LOADER_CTX *ctx, + const UI_METHOD *ui_method, + void *ui_data); +int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *loader, + OSSL_STORE_load_fn load_function); +typedef int (*OSSL_STORE_eof_fn)(OSSL_STORE_LOADER_CTX *ctx); +int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *loader, + OSSL_STORE_eof_fn eof_function); +typedef int (*OSSL_STORE_error_fn)(OSSL_STORE_LOADER_CTX *ctx); +int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *loader, + OSSL_STORE_error_fn error_function); +typedef int (*OSSL_STORE_close_fn)(OSSL_STORE_LOADER_CTX *ctx); +int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *loader, + OSSL_STORE_close_fn close_function); +void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *loader); + +int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader); +OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme); + +/*- + * Functions to list STORE loaders + * ------------------------------- + */ +int OSSL_STORE_do_all_loaders(void (*do_function) (const OSSL_STORE_LOADER + *loader, void *do_arg), + void *do_arg); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/storeerr.h b/include/openssl/storeerr.h new file mode 100644 index 0000000..33d0ab7 --- /dev/null +++ b/include/openssl/storeerr.h @@ -0,0 +1,87 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_OSSL_STOREERR_H +# define HEADER_OSSL_STOREERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_OSSL_STORE_strings(void); + +/* + * OSSL_STORE function codes. + */ +# define OSSL_STORE_F_FILE_CTRL 129 +# define OSSL_STORE_F_FILE_FIND 138 +# define OSSL_STORE_F_FILE_GET_PASS 118 +# define OSSL_STORE_F_FILE_LOAD 119 +# define OSSL_STORE_F_FILE_LOAD_TRY_DECODE 124 +# define OSSL_STORE_F_FILE_NAME_TO_URI 126 +# define OSSL_STORE_F_FILE_OPEN 120 +# define OSSL_STORE_F_OSSL_STORE_ATTACH_PEM_BIO 127 +# define OSSL_STORE_F_OSSL_STORE_EXPECT 130 +# define OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT 128 +# define OSSL_STORE_F_OSSL_STORE_FIND 131 +# define OSSL_STORE_F_OSSL_STORE_GET0_LOADER_INT 100 +# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_CERT 101 +# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_CRL 102 +# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME 103 +# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME_DESCRIPTION 135 +# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_PARAMS 104 +# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_PKEY 105 +# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_CERT 106 +# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_CRL 107 +# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_EMBEDDED 123 +# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_NAME 109 +# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_PARAMS 110 +# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_PKEY 111 +# define OSSL_STORE_F_OSSL_STORE_INFO_SET0_NAME_DESCRIPTION 134 +# define OSSL_STORE_F_OSSL_STORE_INIT_ONCE 112 +# define OSSL_STORE_F_OSSL_STORE_LOADER_NEW 113 +# define OSSL_STORE_F_OSSL_STORE_OPEN 114 +# define OSSL_STORE_F_OSSL_STORE_OPEN_INT 115 +# define OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT 117 +# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ALIAS 132 +# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ISSUER_SERIAL 133 +# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT 136 +# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_NAME 137 +# define OSSL_STORE_F_OSSL_STORE_UNREGISTER_LOADER_INT 116 +# define OSSL_STORE_F_TRY_DECODE_PARAMS 121 +# define OSSL_STORE_F_TRY_DECODE_PKCS12 122 +# define OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED 125 + +/* + * OSSL_STORE reason codes. + */ +# define OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE 107 +# define OSSL_STORE_R_BAD_PASSWORD_READ 115 +# define OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC 113 +# define OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST 121 +# define OSSL_STORE_R_INVALID_SCHEME 106 +# define OSSL_STORE_R_IS_NOT_A 112 +# define OSSL_STORE_R_LOADER_INCOMPLETE 116 +# define OSSL_STORE_R_LOADING_STARTED 117 +# define OSSL_STORE_R_NOT_A_CERTIFICATE 100 +# define OSSL_STORE_R_NOT_A_CRL 101 +# define OSSL_STORE_R_NOT_A_KEY 102 +# define OSSL_STORE_R_NOT_A_NAME 103 +# define OSSL_STORE_R_NOT_PARAMETERS 104 +# define OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR 114 +# define OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE 108 +# define OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES 119 +# define OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED 109 +# define OSSL_STORE_R_UNREGISTERED_SCHEME 105 +# define OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE 110 +# define OSSL_STORE_R_UNSUPPORTED_OPERATION 118 +# define OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE 120 +# define OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED 111 + +#endif diff --git a/include/openssl/symhacks.h b/include/openssl/symhacks.h new file mode 100644 index 0000000..57fedc4 --- /dev/null +++ b/include/openssl/symhacks.h @@ -0,0 +1,52 @@ +/* + * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_SYMHACKS_H +# define HEADER_SYMHACKS_H + +# include + +/* Case insensitive linking causes problems.... */ +# if defined(OPENSSL_SYS_VMS) +# undef ERR_load_CRYPTO_strings +# define ERR_load_CRYPTO_strings ERR_load_CRYPTOlib_strings +# undef OCSP_crlID_new +# define OCSP_crlID_new OCSP_crlID2_new + +# undef d2i_ECPARAMETERS +# define d2i_ECPARAMETERS d2i_UC_ECPARAMETERS +# undef i2d_ECPARAMETERS +# define i2d_ECPARAMETERS i2d_UC_ECPARAMETERS +# undef d2i_ECPKPARAMETERS +# define d2i_ECPKPARAMETERS d2i_UC_ECPKPARAMETERS +# undef i2d_ECPKPARAMETERS +# define i2d_ECPKPARAMETERS i2d_UC_ECPKPARAMETERS + +/* + * These functions do not seem to exist! However, I'm paranoid... Original + * command in x509v3.h: These functions are being redefined in another + * directory, and clash when the linker is case-insensitive, so let's hide + * them a little, by giving them an extra 'o' at the beginning of the name... + */ +# undef X509v3_cleanup_extensions +# define X509v3_cleanup_extensions oX509v3_cleanup_extensions +# undef X509v3_add_extension +# define X509v3_add_extension oX509v3_add_extension +# undef X509v3_add_netscape_extensions +# define X509v3_add_netscape_extensions oX509v3_add_netscape_extensions +# undef X509v3_add_standard_extensions +# define X509v3_add_standard_extensions oX509v3_add_standard_extensions + +/* This one clashes with CMS_data_create */ +# undef cms_Data_create +# define cms_Data_create priv_cms_Data_create + +# endif + +#endif /* ! defined HEADER_VMS_IDHACKS_H */ diff --git a/include/openssl/tls1.h b/include/openssl/tls1.h new file mode 100644 index 0000000..8f5da0c --- /dev/null +++ b/include/openssl/tls1.h @@ -0,0 +1,1236 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * Copyright 2005 Nokia. All rights reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_TLS1_H +# define HEADER_TLS1_H + +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Default security level if not overridden at config time */ +# ifndef OPENSSL_TLS_SECURITY_LEVEL +# define OPENSSL_TLS_SECURITY_LEVEL 1 +# endif + +# define TLS1_VERSION 0x0301 +# define TLS1_1_VERSION 0x0302 +# define TLS1_2_VERSION 0x0303 +# define TLS1_3_VERSION 0x0304 +# define TLS_MAX_VERSION TLS1_3_VERSION + +/* Special value for method supporting multiple versions */ +# define TLS_ANY_VERSION 0x10000 + +# define TLS1_VERSION_MAJOR 0x03 +# define TLS1_VERSION_MINOR 0x01 + +# define TLS1_1_VERSION_MAJOR 0x03 +# define TLS1_1_VERSION_MINOR 0x02 + +# define TLS1_2_VERSION_MAJOR 0x03 +# define TLS1_2_VERSION_MINOR 0x03 + +# define TLS1_get_version(s) \ + ((SSL_version(s) >> 8) == TLS1_VERSION_MAJOR ? SSL_version(s) : 0) + +# define TLS1_get_client_version(s) \ + ((SSL_client_version(s) >> 8) == TLS1_VERSION_MAJOR ? SSL_client_version(s) : 0) + +# define TLS1_AD_DECRYPTION_FAILED 21 +# define TLS1_AD_RECORD_OVERFLOW 22 +# define TLS1_AD_UNKNOWN_CA 48/* fatal */ +# define TLS1_AD_ACCESS_DENIED 49/* fatal */ +# define TLS1_AD_DECODE_ERROR 50/* fatal */ +# define TLS1_AD_DECRYPT_ERROR 51 +# define TLS1_AD_EXPORT_RESTRICTION 60/* fatal */ +# define TLS1_AD_PROTOCOL_VERSION 70/* fatal */ +# define TLS1_AD_INSUFFICIENT_SECURITY 71/* fatal */ +# define TLS1_AD_INTERNAL_ERROR 80/* fatal */ +# define TLS1_AD_INAPPROPRIATE_FALLBACK 86/* fatal */ +# define TLS1_AD_USER_CANCELLED 90 +# define TLS1_AD_NO_RENEGOTIATION 100 +/* TLSv1.3 alerts */ +# define TLS13_AD_MISSING_EXTENSION 109 /* fatal */ +# define TLS13_AD_CERTIFICATE_REQUIRED 116 /* fatal */ +/* codes 110-114 are from RFC3546 */ +# define TLS1_AD_UNSUPPORTED_EXTENSION 110 +# define TLS1_AD_CERTIFICATE_UNOBTAINABLE 111 +# define TLS1_AD_UNRECOGNIZED_NAME 112 +# define TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE 113 +# define TLS1_AD_BAD_CERTIFICATE_HASH_VALUE 114 +# define TLS1_AD_UNKNOWN_PSK_IDENTITY 115/* fatal */ +# define TLS1_AD_NO_APPLICATION_PROTOCOL 120 /* fatal */ + +/* ExtensionType values from RFC3546 / RFC4366 / RFC6066 */ +# define TLSEXT_TYPE_server_name 0 +# define TLSEXT_TYPE_max_fragment_length 1 +# define TLSEXT_TYPE_client_certificate_url 2 +# define TLSEXT_TYPE_trusted_ca_keys 3 +# define TLSEXT_TYPE_truncated_hmac 4 +# define TLSEXT_TYPE_status_request 5 +/* ExtensionType values from RFC4681 */ +# define TLSEXT_TYPE_user_mapping 6 +/* ExtensionType values from RFC5878 */ +# define TLSEXT_TYPE_client_authz 7 +# define TLSEXT_TYPE_server_authz 8 +/* ExtensionType values from RFC6091 */ +# define TLSEXT_TYPE_cert_type 9 + +/* ExtensionType values from RFC4492 */ +/* + * Prior to TLSv1.3 the supported_groups extension was known as + * elliptic_curves + */ +# define TLSEXT_TYPE_supported_groups 10 +# define TLSEXT_TYPE_elliptic_curves TLSEXT_TYPE_supported_groups +# define TLSEXT_TYPE_ec_point_formats 11 + + +/* ExtensionType value from RFC5054 */ +# define TLSEXT_TYPE_srp 12 + +/* ExtensionType values from RFC5246 */ +# define TLSEXT_TYPE_signature_algorithms 13 + +/* ExtensionType value from RFC5764 */ +# define TLSEXT_TYPE_use_srtp 14 + +/* ExtensionType value from RFC5620 */ +# define TLSEXT_TYPE_heartbeat 15 + +/* ExtensionType value from RFC7301 */ +# define TLSEXT_TYPE_application_layer_protocol_negotiation 16 + +/* + * Extension type for Certificate Transparency + * https://tools.ietf.org/html/rfc6962#section-3.3.1 + */ +# define TLSEXT_TYPE_signed_certificate_timestamp 18 + +/* + * ExtensionType value for TLS padding extension. + * http://tools.ietf.org/html/draft-agl-tls-padding + */ +# define TLSEXT_TYPE_padding 21 + +/* ExtensionType value from RFC7366 */ +# define TLSEXT_TYPE_encrypt_then_mac 22 + +/* ExtensionType value from RFC7627 */ +# define TLSEXT_TYPE_extended_master_secret 23 + +/* ExtensionType value from RFC4507 */ +# define TLSEXT_TYPE_session_ticket 35 + +/* As defined for TLS1.3 */ +# define TLSEXT_TYPE_psk 41 +# define TLSEXT_TYPE_early_data 42 +# define TLSEXT_TYPE_supported_versions 43 +# define TLSEXT_TYPE_cookie 44 +# define TLSEXT_TYPE_psk_kex_modes 45 +# define TLSEXT_TYPE_certificate_authorities 47 +# define TLSEXT_TYPE_post_handshake_auth 49 +# define TLSEXT_TYPE_signature_algorithms_cert 50 +# define TLSEXT_TYPE_key_share 51 + +/* Temporary extension type */ +# define TLSEXT_TYPE_renegotiate 0xff01 + +# ifndef OPENSSL_NO_NEXTPROTONEG +/* This is not an IANA defined extension number */ +# define TLSEXT_TYPE_next_proto_neg 13172 +# endif + +/* NameType value from RFC3546 */ +# define TLSEXT_NAMETYPE_host_name 0 +/* status request value from RFC3546 */ +# define TLSEXT_STATUSTYPE_ocsp 1 + +/* ECPointFormat values from RFC4492 */ +# define TLSEXT_ECPOINTFORMAT_first 0 +# define TLSEXT_ECPOINTFORMAT_uncompressed 0 +# define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime 1 +# define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2 2 +# define TLSEXT_ECPOINTFORMAT_last 2 + +/* Signature and hash algorithms from RFC5246 */ +# define TLSEXT_signature_anonymous 0 +# define TLSEXT_signature_rsa 1 +# define TLSEXT_signature_dsa 2 +# define TLSEXT_signature_ecdsa 3 +# define TLSEXT_signature_gostr34102001 237 +# define TLSEXT_signature_gostr34102012_256 238 +# define TLSEXT_signature_gostr34102012_512 239 + +/* Total number of different signature algorithms */ +# define TLSEXT_signature_num 7 + +# define TLSEXT_hash_none 0 +# define TLSEXT_hash_md5 1 +# define TLSEXT_hash_sha1 2 +# define TLSEXT_hash_sha224 3 +# define TLSEXT_hash_sha256 4 +# define TLSEXT_hash_sha384 5 +# define TLSEXT_hash_sha512 6 +# define TLSEXT_hash_gostr3411 237 +# define TLSEXT_hash_gostr34112012_256 238 +# define TLSEXT_hash_gostr34112012_512 239 + +/* Total number of different digest algorithms */ + +# define TLSEXT_hash_num 10 + +/* Flag set for unrecognised algorithms */ +# define TLSEXT_nid_unknown 0x1000000 + +/* ECC curves */ + +# define TLSEXT_curve_P_256 23 +# define TLSEXT_curve_P_384 24 + +/* OpenSSL value to disable maximum fragment length extension */ +# define TLSEXT_max_fragment_length_DISABLED 0 +/* Allowed values for max fragment length extension */ +# define TLSEXT_max_fragment_length_512 1 +# define TLSEXT_max_fragment_length_1024 2 +# define TLSEXT_max_fragment_length_2048 3 +# define TLSEXT_max_fragment_length_4096 4 + +int SSL_CTX_set_tlsext_max_fragment_length(SSL_CTX *ctx, uint8_t mode); +int SSL_set_tlsext_max_fragment_length(SSL *ssl, uint8_t mode); + +# define TLSEXT_MAXLEN_host_name 255 + +__owur const char *SSL_get_servername(const SSL *s, const int type); +__owur int SSL_get_servername_type(const SSL *s); +/* + * SSL_export_keying_material exports a value derived from the master secret, + * as specified in RFC 5705. It writes |olen| bytes to |out| given a label and + * optional context. (Since a zero length context is allowed, the |use_context| + * flag controls whether a context is included.) It returns 1 on success and + * 0 or -1 otherwise. + */ +__owur int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen, + const char *label, size_t llen, + const unsigned char *context, + size_t contextlen, int use_context); + +/* + * SSL_export_keying_material_early exports a value derived from the + * early exporter master secret, as specified in + * https://tools.ietf.org/html/draft-ietf-tls-tls13-23. It writes + * |olen| bytes to |out| given a label and optional context. It + * returns 1 on success and 0 otherwise. + */ +__owur int SSL_export_keying_material_early(SSL *s, unsigned char *out, + size_t olen, const char *label, + size_t llen, + const unsigned char *context, + size_t contextlen); + +int SSL_get_peer_signature_type_nid(const SSL *s, int *pnid); + +int SSL_get_sigalgs(SSL *s, int idx, + int *psign, int *phash, int *psignandhash, + unsigned char *rsig, unsigned char *rhash); + +int SSL_get_shared_sigalgs(SSL *s, int idx, + int *psign, int *phash, int *psignandhash, + unsigned char *rsig, unsigned char *rhash); + +__owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain); + +# define SSL_set_tlsext_host_name(s,name) \ + SSL_ctrl(s,SSL_CTRL_SET_TLSEXT_HOSTNAME,TLSEXT_NAMETYPE_host_name,\ + (void *)name) + +# define SSL_set_tlsext_debug_callback(ssl, cb) \ + SSL_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_CB,\ + (void (*)(void))cb) + +# define SSL_set_tlsext_debug_arg(ssl, arg) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_ARG,0,arg) + +# define SSL_get_tlsext_status_type(ssl) \ + SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE,0,NULL) + +# define SSL_set_tlsext_status_type(ssl, type) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE,type,NULL) + +# define SSL_get_tlsext_status_exts(ssl, arg) \ + SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS,0,arg) + +# define SSL_set_tlsext_status_exts(ssl, arg) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS,0,arg) + +# define SSL_get_tlsext_status_ids(ssl, arg) \ + SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS,0,arg) + +# define SSL_set_tlsext_status_ids(ssl, arg) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS,0,arg) + +# define SSL_get_tlsext_status_ocsp_resp(ssl, arg) \ + SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP,0,arg) + +# define SSL_set_tlsext_status_ocsp_resp(ssl, arg, arglen) \ + SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP,arglen,arg) + +# define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \ + SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_CB,\ + (void (*)(void))cb) + +# define SSL_TLSEXT_ERR_OK 0 +# define SSL_TLSEXT_ERR_ALERT_WARNING 1 +# define SSL_TLSEXT_ERR_ALERT_FATAL 2 +# define SSL_TLSEXT_ERR_NOACK 3 + +# define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG,0,arg) + +# define SSL_CTX_get_tlsext_ticket_keys(ctx, keys, keylen) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_GET_TLSEXT_TICKET_KEYS,keylen,keys) +# define SSL_CTX_set_tlsext_ticket_keys(ctx, keys, keylen) \ + SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_TICKET_KEYS,keylen,keys) + +# define SSL_CTX_get_tlsext_status_cb(ssl, cb) \ + SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB,0,(void *)cb) +# define SSL_CTX_set_tlsext_status_cb(ssl, cb) \ + SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB,\ + (void (*)(void))cb) + +# define SSL_CTX_get_tlsext_status_arg(ssl, arg) \ + SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG,0,arg) +# define SSL_CTX_set_tlsext_status_arg(ssl, arg) \ + SSL_CTX_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG,0,arg) + +# define SSL_CTX_set_tlsext_status_type(ssl, type) \ + SSL_CTX_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE,type,NULL) + +# define SSL_CTX_get_tlsext_status_type(ssl) \ + SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE,0,NULL) + +# define SSL_CTX_set_tlsext_ticket_key_cb(ssl, cb) \ + SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,\ + (void (*)(void))cb) + +# ifndef OPENSSL_NO_HEARTBEATS +# define SSL_DTLSEXT_HB_ENABLED 0x01 +# define SSL_DTLSEXT_HB_DONT_SEND_REQUESTS 0x02 +# define SSL_DTLSEXT_HB_DONT_RECV_REQUESTS 0x04 +# define SSL_get_dtlsext_heartbeat_pending(ssl) \ + SSL_ctrl(ssl,SSL_CTRL_GET_DTLS_EXT_HEARTBEAT_PENDING,0,NULL) +# define SSL_set_dtlsext_heartbeat_no_requests(ssl, arg) \ + SSL_ctrl(ssl,SSL_CTRL_SET_DTLS_EXT_HEARTBEAT_NO_REQUESTS,arg,NULL) + +# if OPENSSL_API_COMPAT < 0x10100000L +# define SSL_CTRL_TLS_EXT_SEND_HEARTBEAT \ + SSL_CTRL_DTLS_EXT_SEND_HEARTBEAT +# define SSL_CTRL_GET_TLS_EXT_HEARTBEAT_PENDING \ + SSL_CTRL_GET_DTLS_EXT_HEARTBEAT_PENDING +# define SSL_CTRL_SET_TLS_EXT_HEARTBEAT_NO_REQUESTS \ + SSL_CTRL_SET_DTLS_EXT_HEARTBEAT_NO_REQUESTS +# define SSL_TLSEXT_HB_ENABLED \ + SSL_DTLSEXT_HB_ENABLED +# define SSL_TLSEXT_HB_DONT_SEND_REQUESTS \ + SSL_DTLSEXT_HB_DONT_SEND_REQUESTS +# define SSL_TLSEXT_HB_DONT_RECV_REQUESTS \ + SSL_DTLSEXT_HB_DONT_RECV_REQUESTS +# define SSL_get_tlsext_heartbeat_pending(ssl) \ + SSL_get_dtlsext_heartbeat_pending(ssl) +# define SSL_set_tlsext_heartbeat_no_requests(ssl, arg) \ + SSL_set_dtlsext_heartbeat_no_requests(ssl,arg) +# endif +# endif + +/* PSK ciphersuites from 4279 */ +# define TLS1_CK_PSK_WITH_RC4_128_SHA 0x0300008A +# define TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008B +# define TLS1_CK_PSK_WITH_AES_128_CBC_SHA 0x0300008C +# define TLS1_CK_PSK_WITH_AES_256_CBC_SHA 0x0300008D +# define TLS1_CK_DHE_PSK_WITH_RC4_128_SHA 0x0300008E +# define TLS1_CK_DHE_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008F +# define TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA 0x03000090 +# define TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA 0x03000091 +# define TLS1_CK_RSA_PSK_WITH_RC4_128_SHA 0x03000092 +# define TLS1_CK_RSA_PSK_WITH_3DES_EDE_CBC_SHA 0x03000093 +# define TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA 0x03000094 +# define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA 0x03000095 + +/* PSK ciphersuites from 5487 */ +# define TLS1_CK_PSK_WITH_AES_128_GCM_SHA256 0x030000A8 +# define TLS1_CK_PSK_WITH_AES_256_GCM_SHA384 0x030000A9 +# define TLS1_CK_DHE_PSK_WITH_AES_128_GCM_SHA256 0x030000AA +# define TLS1_CK_DHE_PSK_WITH_AES_256_GCM_SHA384 0x030000AB +# define TLS1_CK_RSA_PSK_WITH_AES_128_GCM_SHA256 0x030000AC +# define TLS1_CK_RSA_PSK_WITH_AES_256_GCM_SHA384 0x030000AD +# define TLS1_CK_PSK_WITH_AES_128_CBC_SHA256 0x030000AE +# define TLS1_CK_PSK_WITH_AES_256_CBC_SHA384 0x030000AF +# define TLS1_CK_PSK_WITH_NULL_SHA256 0x030000B0 +# define TLS1_CK_PSK_WITH_NULL_SHA384 0x030000B1 +# define TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA256 0x030000B2 +# define TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA384 0x030000B3 +# define TLS1_CK_DHE_PSK_WITH_NULL_SHA256 0x030000B4 +# define TLS1_CK_DHE_PSK_WITH_NULL_SHA384 0x030000B5 +# define TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA256 0x030000B6 +# define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA384 0x030000B7 +# define TLS1_CK_RSA_PSK_WITH_NULL_SHA256 0x030000B8 +# define TLS1_CK_RSA_PSK_WITH_NULL_SHA384 0x030000B9 + +/* NULL PSK ciphersuites from RFC4785 */ +# define TLS1_CK_PSK_WITH_NULL_SHA 0x0300002C +# define TLS1_CK_DHE_PSK_WITH_NULL_SHA 0x0300002D +# define TLS1_CK_RSA_PSK_WITH_NULL_SHA 0x0300002E + +/* AES ciphersuites from RFC3268 */ +# define TLS1_CK_RSA_WITH_AES_128_SHA 0x0300002F +# define TLS1_CK_DH_DSS_WITH_AES_128_SHA 0x03000030 +# define TLS1_CK_DH_RSA_WITH_AES_128_SHA 0x03000031 +# define TLS1_CK_DHE_DSS_WITH_AES_128_SHA 0x03000032 +# define TLS1_CK_DHE_RSA_WITH_AES_128_SHA 0x03000033 +# define TLS1_CK_ADH_WITH_AES_128_SHA 0x03000034 +# define TLS1_CK_RSA_WITH_AES_256_SHA 0x03000035 +# define TLS1_CK_DH_DSS_WITH_AES_256_SHA 0x03000036 +# define TLS1_CK_DH_RSA_WITH_AES_256_SHA 0x03000037 +# define TLS1_CK_DHE_DSS_WITH_AES_256_SHA 0x03000038 +# define TLS1_CK_DHE_RSA_WITH_AES_256_SHA 0x03000039 +# define TLS1_CK_ADH_WITH_AES_256_SHA 0x0300003A + +/* TLS v1.2 ciphersuites */ +# define TLS1_CK_RSA_WITH_NULL_SHA256 0x0300003B +# define TLS1_CK_RSA_WITH_AES_128_SHA256 0x0300003C +# define TLS1_CK_RSA_WITH_AES_256_SHA256 0x0300003D +# define TLS1_CK_DH_DSS_WITH_AES_128_SHA256 0x0300003E +# define TLS1_CK_DH_RSA_WITH_AES_128_SHA256 0x0300003F +# define TLS1_CK_DHE_DSS_WITH_AES_128_SHA256 0x03000040 + +/* Camellia ciphersuites from RFC4132 */ +# define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000041 +# define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000042 +# define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000043 +# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000044 +# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000045 +# define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA 0x03000046 + +/* TLS v1.2 ciphersuites */ +# define TLS1_CK_DHE_RSA_WITH_AES_128_SHA256 0x03000067 +# define TLS1_CK_DH_DSS_WITH_AES_256_SHA256 0x03000068 +# define TLS1_CK_DH_RSA_WITH_AES_256_SHA256 0x03000069 +# define TLS1_CK_DHE_DSS_WITH_AES_256_SHA256 0x0300006A +# define TLS1_CK_DHE_RSA_WITH_AES_256_SHA256 0x0300006B +# define TLS1_CK_ADH_WITH_AES_128_SHA256 0x0300006C +# define TLS1_CK_ADH_WITH_AES_256_SHA256 0x0300006D + +/* Camellia ciphersuites from RFC4132 */ +# define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000084 +# define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000085 +# define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000086 +# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000087 +# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000088 +# define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA 0x03000089 + +/* SEED ciphersuites from RFC4162 */ +# define TLS1_CK_RSA_WITH_SEED_SHA 0x03000096 +# define TLS1_CK_DH_DSS_WITH_SEED_SHA 0x03000097 +# define TLS1_CK_DH_RSA_WITH_SEED_SHA 0x03000098 +# define TLS1_CK_DHE_DSS_WITH_SEED_SHA 0x03000099 +# define TLS1_CK_DHE_RSA_WITH_SEED_SHA 0x0300009A +# define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B + +/* TLS v1.2 GCM ciphersuites from RFC5288 */ +# define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C +# define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D +# define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E +# define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F +# define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 +# define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 +# define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 +# define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 +# define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 +# define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 +# define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 +# define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 + +/* CCM ciphersuites from RFC6655 */ +# define TLS1_CK_RSA_WITH_AES_128_CCM 0x0300C09C +# define TLS1_CK_RSA_WITH_AES_256_CCM 0x0300C09D +# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM 0x0300C09E +# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM 0x0300C09F +# define TLS1_CK_RSA_WITH_AES_128_CCM_8 0x0300C0A0 +# define TLS1_CK_RSA_WITH_AES_256_CCM_8 0x0300C0A1 +# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM_8 0x0300C0A2 +# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM_8 0x0300C0A3 +# define TLS1_CK_PSK_WITH_AES_128_CCM 0x0300C0A4 +# define TLS1_CK_PSK_WITH_AES_256_CCM 0x0300C0A5 +# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM 0x0300C0A6 +# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM 0x0300C0A7 +# define TLS1_CK_PSK_WITH_AES_128_CCM_8 0x0300C0A8 +# define TLS1_CK_PSK_WITH_AES_256_CCM_8 0x0300C0A9 +# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM_8 0x0300C0AA +# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM_8 0x0300C0AB + +/* CCM ciphersuites from RFC7251 */ +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM 0x0300C0AC +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM 0x0300C0AD +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM_8 0x0300C0AE +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM_8 0x0300C0AF + +/* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */ +# define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BA +# define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 0x030000BB +# define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BC +# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 0x030000BD +# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BE +# define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA256 0x030000BF + +# define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C0 +# define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 0x030000C1 +# define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C2 +# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 0x030000C3 +# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C4 +# define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA256 0x030000C5 + +/* ECC ciphersuites from RFC4492 */ +# define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 +# define TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA 0x0300C002 +# define TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C003 +# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0x0300C004 +# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0x0300C005 + +# define TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA 0x0300C006 +# define TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA 0x0300C007 +# define TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C008 +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0x0300C009 +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0x0300C00A + +# define TLS1_CK_ECDH_RSA_WITH_NULL_SHA 0x0300C00B +# define TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA 0x0300C00C +# define TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA 0x0300C00D +# define TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA 0x0300C00E +# define TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA 0x0300C00F + +# define TLS1_CK_ECDHE_RSA_WITH_NULL_SHA 0x0300C010 +# define TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA 0x0300C011 +# define TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA 0x0300C012 +# define TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA 0x0300C013 +# define TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA 0x0300C014 + +# define TLS1_CK_ECDH_anon_WITH_NULL_SHA 0x0300C015 +# define TLS1_CK_ECDH_anon_WITH_RC4_128_SHA 0x0300C016 +# define TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA 0x0300C017 +# define TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA 0x0300C018 +# define TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA 0x0300C019 + +/* SRP ciphersuites from RFC 5054 */ +# define TLS1_CK_SRP_SHA_WITH_3DES_EDE_CBC_SHA 0x0300C01A +# define TLS1_CK_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA 0x0300C01B +# define TLS1_CK_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA 0x0300C01C +# define TLS1_CK_SRP_SHA_WITH_AES_128_CBC_SHA 0x0300C01D +# define TLS1_CK_SRP_SHA_RSA_WITH_AES_128_CBC_SHA 0x0300C01E +# define TLS1_CK_SRP_SHA_DSS_WITH_AES_128_CBC_SHA 0x0300C01F +# define TLS1_CK_SRP_SHA_WITH_AES_256_CBC_SHA 0x0300C020 +# define TLS1_CK_SRP_SHA_RSA_WITH_AES_256_CBC_SHA 0x0300C021 +# define TLS1_CK_SRP_SHA_DSS_WITH_AES_256_CBC_SHA 0x0300C022 + +/* ECDH HMAC based ciphersuites from RFC5289 */ +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256 0x0300C023 +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384 0x0300C024 +# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256 0x0300C025 +# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384 0x0300C026 +# define TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256 0x0300C027 +# define TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384 0x0300C028 +# define TLS1_CK_ECDH_RSA_WITH_AES_128_SHA256 0x0300C029 +# define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A + +/* ECDH GCM based ciphersuites from RFC5289 */ +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C +# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D +# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E +# define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F +# define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 +# define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 +# define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 + +/* ECDHE PSK ciphersuites from RFC5489 */ +# define TLS1_CK_ECDHE_PSK_WITH_RC4_128_SHA 0x0300C033 +# define TLS1_CK_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA 0x0300C034 +# define TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA 0x0300C035 +# define TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA 0x0300C036 + +# define TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0x0300C037 +# define TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA384 0x0300C038 + +/* NULL PSK ciphersuites from RFC4785 */ +# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA 0x0300C039 +# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA256 0x0300C03A +# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA384 0x0300C03B + +/* Camellia-CBC ciphersuites from RFC6367 */ +# define TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C072 +# define TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C073 +# define TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C074 +# define TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C075 +# define TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C076 +# define TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C077 +# define TLS1_CK_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C078 +# define TLS1_CK_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C079 + +# define TLS1_CK_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C094 +# define TLS1_CK_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C095 +# define TLS1_CK_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C096 +# define TLS1_CK_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C097 +# define TLS1_CK_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C098 +# define TLS1_CK_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C099 +# define TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C09A +# define TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C09B + +/* draft-ietf-tls-chacha20-poly1305-03 */ +# define TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305 0x0300CCA8 +# define TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 0x0300CCA9 +# define TLS1_CK_DHE_RSA_WITH_CHACHA20_POLY1305 0x0300CCAA +# define TLS1_CK_PSK_WITH_CHACHA20_POLY1305 0x0300CCAB +# define TLS1_CK_ECDHE_PSK_WITH_CHACHA20_POLY1305 0x0300CCAC +# define TLS1_CK_DHE_PSK_WITH_CHACHA20_POLY1305 0x0300CCAD +# define TLS1_CK_RSA_PSK_WITH_CHACHA20_POLY1305 0x0300CCAE + +/* TLS v1.3 ciphersuites */ +# define TLS1_3_CK_AES_128_GCM_SHA256 0x03001301 +# define TLS1_3_CK_AES_256_GCM_SHA384 0x03001302 +# define TLS1_3_CK_CHACHA20_POLY1305_SHA256 0x03001303 +# define TLS1_3_CK_AES_128_CCM_SHA256 0x03001304 +# define TLS1_3_CK_AES_128_CCM_8_SHA256 0x03001305 + +/* Aria ciphersuites from RFC6209 */ +# define TLS1_CK_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C050 +# define TLS1_CK_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C051 +# define TLS1_CK_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C052 +# define TLS1_CK_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C053 +# define TLS1_CK_DH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C054 +# define TLS1_CK_DH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C055 +# define TLS1_CK_DHE_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C056 +# define TLS1_CK_DHE_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C057 +# define TLS1_CK_DH_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C058 +# define TLS1_CK_DH_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C059 +# define TLS1_CK_DH_anon_WITH_ARIA_128_GCM_SHA256 0x0300C05A +# define TLS1_CK_DH_anon_WITH_ARIA_256_GCM_SHA384 0x0300C05B +# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05C +# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05D +# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05E +# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05F +# define TLS1_CK_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C060 +# define TLS1_CK_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C061 +# define TLS1_CK_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C062 +# define TLS1_CK_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C063 +# define TLS1_CK_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06A +# define TLS1_CK_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06B +# define TLS1_CK_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06C +# define TLS1_CK_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06D +# define TLS1_CK_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06E +# define TLS1_CK_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06F + +/* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] */ +# define TLS1_RFC_RSA_WITH_AES_128_SHA "TLS_RSA_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_DHE_DSS_WITH_AES_128_SHA "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_SHA "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_ADH_WITH_AES_128_SHA "TLS_DH_anon_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_RSA_WITH_AES_256_SHA "TLS_RSA_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_DHE_DSS_WITH_AES_256_SHA "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_ADH_WITH_AES_256_SHA "TLS_DH_anon_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_RSA_WITH_NULL_SHA256 "TLS_RSA_WITH_NULL_SHA256" +# define TLS1_RFC_RSA_WITH_AES_128_SHA256 "TLS_RSA_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_RSA_WITH_AES_256_SHA256 "TLS_RSA_WITH_AES_256_CBC_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_AES_128_SHA256 "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_SHA256 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_AES_256_SHA256 "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA256 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" +# define TLS1_RFC_ADH_WITH_AES_128_SHA256 "TLS_DH_anon_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_ADH_WITH_AES_256_SHA256 "TLS_DH_anon_WITH_AES_256_CBC_SHA256" +# define TLS1_RFC_RSA_WITH_AES_128_GCM_SHA256 "TLS_RSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_RSA_WITH_AES_256_GCM_SHA384 "TLS_RSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_DHE_DSS_WITH_AES_128_GCM_SHA256 "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_AES_256_GCM_SHA384 "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_ADH_WITH_AES_128_GCM_SHA256 "TLS_DH_anon_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_ADH_WITH_AES_256_GCM_SHA384 "TLS_DH_anon_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_RSA_WITH_AES_128_CCM "TLS_RSA_WITH_AES_128_CCM" +# define TLS1_RFC_RSA_WITH_AES_256_CCM "TLS_RSA_WITH_AES_256_CCM" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM "TLS_DHE_RSA_WITH_AES_128_CCM" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM "TLS_DHE_RSA_WITH_AES_256_CCM" +# define TLS1_RFC_RSA_WITH_AES_128_CCM_8 "TLS_RSA_WITH_AES_128_CCM_8" +# define TLS1_RFC_RSA_WITH_AES_256_CCM_8 "TLS_RSA_WITH_AES_256_CCM_8" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM_8 "TLS_DHE_RSA_WITH_AES_128_CCM_8" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM_8 "TLS_DHE_RSA_WITH_AES_256_CCM_8" +# define TLS1_RFC_PSK_WITH_AES_128_CCM "TLS_PSK_WITH_AES_128_CCM" +# define TLS1_RFC_PSK_WITH_AES_256_CCM "TLS_PSK_WITH_AES_256_CCM" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM "TLS_DHE_PSK_WITH_AES_128_CCM" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM "TLS_DHE_PSK_WITH_AES_256_CCM" +# define TLS1_RFC_PSK_WITH_AES_128_CCM_8 "TLS_PSK_WITH_AES_128_CCM_8" +# define TLS1_RFC_PSK_WITH_AES_256_CCM_8 "TLS_PSK_WITH_AES_256_CCM_8" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM_8 "TLS_PSK_DHE_WITH_AES_128_CCM_8" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM_8 "TLS_PSK_DHE_WITH_AES_256_CCM_8" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM "TLS_ECDHE_ECDSA_WITH_AES_128_CCM" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM "TLS_ECDHE_ECDSA_WITH_AES_256_CCM" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8" +# define TLS1_3_RFC_AES_128_GCM_SHA256 "TLS_AES_128_GCM_SHA256" +# define TLS1_3_RFC_AES_256_GCM_SHA384 "TLS_AES_256_GCM_SHA384" +# define TLS1_3_RFC_CHACHA20_POLY1305_SHA256 "TLS_CHACHA20_POLY1305_SHA256" +# define TLS1_3_RFC_AES_128_CCM_SHA256 "TLS_AES_128_CCM_SHA256" +# define TLS1_3_RFC_AES_128_CCM_8_SHA256 "TLS_AES_128_CCM_8_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_NULL_SHA "TLS_ECDHE_ECDSA_WITH_NULL_SHA" +# define TLS1_RFC_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_ECDHE_RSA_WITH_NULL_SHA "TLS_ECDHE_RSA_WITH_NULL_SHA" +# define TLS1_RFC_ECDHE_RSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_CBC_SHA "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_ECDH_anon_WITH_NULL_SHA "TLS_ECDH_anon_WITH_NULL_SHA" +# define TLS1_RFC_ECDH_anon_WITH_DES_192_CBC3_SHA "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_ECDH_anon_WITH_AES_128_CBC_SHA "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_ECDH_anon_WITH_AES_256_CBC_SHA "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_PSK_WITH_NULL_SHA "TLS_PSK_WITH_NULL_SHA" +# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA "TLS_DHE_PSK_WITH_NULL_SHA" +# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA "TLS_RSA_PSK_WITH_NULL_SHA" +# define TLS1_RFC_PSK_WITH_3DES_EDE_CBC_SHA "TLS_PSK_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA "TLS_PSK_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA "TLS_PSK_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_DHE_PSK_WITH_3DES_EDE_CBC_SHA "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_CBC_SHA "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_CBC_SHA "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_RSA_PSK_WITH_3DES_EDE_CBC_SHA "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_PSK_WITH_AES_128_GCM_SHA256 "TLS_PSK_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_PSK_WITH_AES_256_GCM_SHA384 "TLS_PSK_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_GCM_SHA256 "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_GCM_SHA384 "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_AES_128_GCM_SHA256 "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_AES_256_GCM_SHA384 "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA256 "TLS_PSK_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA384 "TLS_PSK_WITH_AES_256_CBC_SHA384" +# define TLS1_RFC_PSK_WITH_NULL_SHA256 "TLS_PSK_WITH_NULL_SHA256" +# define TLS1_RFC_PSK_WITH_NULL_SHA384 "TLS_PSK_WITH_NULL_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_CBC_SHA256 "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_CBC_SHA384 "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA256 "TLS_DHE_PSK_WITH_NULL_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA384 "TLS_DHE_PSK_WITH_NULL_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA256 "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA384 "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA256 "TLS_RSA_PSK_WITH_NULL_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA384 "TLS_RSA_PSK_WITH_NULL_SHA384" +# define TLS1_RFC_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_ECDHE_PSK_WITH_AES_128_CBC_SHA "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_ECDHE_PSK_WITH_AES_256_CBC_SHA "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_ECDHE_PSK_WITH_AES_128_CBC_SHA256 "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256" +# define TLS1_RFC_ECDHE_PSK_WITH_AES_256_CBC_SHA384 "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384" +# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA "TLS_ECDHE_PSK_WITH_NULL_SHA" +# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA256 "TLS_ECDHE_PSK_WITH_NULL_SHA256" +# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA384 "TLS_ECDHE_PSK_WITH_NULL_SHA384" +# define TLS1_RFC_SRP_SHA_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" +# define TLS1_RFC_SRP_SHA_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_SRP_SHA_RSA_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_SRP_SHA_DSS_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" +# define TLS1_RFC_SRP_SHA_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_SRP_SHA_RSA_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_SRP_SHA_DSS_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" +# define TLS1_RFC_DHE_RSA_WITH_CHACHA20_POLY1305 "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_CHACHA20_POLY1305 "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" +# define TLS1_RFC_PSK_WITH_CHACHA20_POLY1305 "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256" +# define TLS1_RFC_ECDHE_PSK_WITH_CHACHA20_POLY1305 "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_CHACHA20_POLY1305 "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_CHACHA20_POLY1305 "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256" +# define TLS1_RFC_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_ADH_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_RSA_WITH_CAMELLIA_256_CBC_SHA256 "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256" +# define TLS1_RFC_ADH_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256" +# define TLS1_RFC_RSA_WITH_CAMELLIA_256_CBC_SHA "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" +# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" +# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" +# define TLS1_RFC_ADH_WITH_CAMELLIA_256_CBC_SHA "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" +# define TLS1_RFC_RSA_WITH_CAMELLIA_128_CBC_SHA "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" +# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" +# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" +# define TLS1_RFC_ADH_WITH_CAMELLIA_128_CBC_SHA "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" +# define TLS1_RFC_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384" +# define TLS1_RFC_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384" +# define TLS1_RFC_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256" +# define TLS1_RFC_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384" +# define TLS1_RFC_RSA_WITH_SEED_SHA "TLS_RSA_WITH_SEED_CBC_SHA" +# define TLS1_RFC_DHE_DSS_WITH_SEED_SHA "TLS_DHE_DSS_WITH_SEED_CBC_SHA" +# define TLS1_RFC_DHE_RSA_WITH_SEED_SHA "TLS_DHE_RSA_WITH_SEED_CBC_SHA" +# define TLS1_RFC_ADH_WITH_SEED_SHA "TLS_DH_anon_WITH_SEED_CBC_SHA" +# define TLS1_RFC_ECDHE_PSK_WITH_RC4_128_SHA "TLS_ECDHE_PSK_WITH_RC4_128_SHA" +# define TLS1_RFC_ECDH_anon_WITH_RC4_128_SHA "TLS_ECDH_anon_WITH_RC4_128_SHA" +# define TLS1_RFC_ECDHE_ECDSA_WITH_RC4_128_SHA "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" +# define TLS1_RFC_ECDHE_RSA_WITH_RC4_128_SHA "TLS_ECDHE_RSA_WITH_RC4_128_SHA" +# define TLS1_RFC_PSK_WITH_RC4_128_SHA "TLS_PSK_WITH_RC4_128_SHA" +# define TLS1_RFC_RSA_PSK_WITH_RC4_128_SHA "TLS_RSA_PSK_WITH_RC4_128_SHA" +# define TLS1_RFC_DHE_PSK_WITH_RC4_128_SHA "TLS_DHE_PSK_WITH_RC4_128_SHA" +# define TLS1_RFC_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DH_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DH_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DH_anon_WITH_ARIA_128_GCM_SHA256 "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DH_anon_WITH_ARIA_256_GCM_SHA384 "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_PSK_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_PSK_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384" + + +/* + * XXX Backward compatibility alert: Older versions of OpenSSL gave some DHE + * ciphers names with "EDH" instead of "DHE". Going forward, we should be + * using DHE everywhere, though we may indefinitely maintain aliases for + * users or configurations that used "EDH" + */ +# define TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA "DHE-DSS-RC4-SHA" + +# define TLS1_TXT_PSK_WITH_NULL_SHA "PSK-NULL-SHA" +# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA "DHE-PSK-NULL-SHA" +# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA "RSA-PSK-NULL-SHA" + +/* AES ciphersuites from RFC3268 */ +# define TLS1_TXT_RSA_WITH_AES_128_SHA "AES128-SHA" +# define TLS1_TXT_DH_DSS_WITH_AES_128_SHA "DH-DSS-AES128-SHA" +# define TLS1_TXT_DH_RSA_WITH_AES_128_SHA "DH-RSA-AES128-SHA" +# define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA "DHE-DSS-AES128-SHA" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA "DHE-RSA-AES128-SHA" +# define TLS1_TXT_ADH_WITH_AES_128_SHA "ADH-AES128-SHA" + +# define TLS1_TXT_RSA_WITH_AES_256_SHA "AES256-SHA" +# define TLS1_TXT_DH_DSS_WITH_AES_256_SHA "DH-DSS-AES256-SHA" +# define TLS1_TXT_DH_RSA_WITH_AES_256_SHA "DH-RSA-AES256-SHA" +# define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA "DHE-DSS-AES256-SHA" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA "DHE-RSA-AES256-SHA" +# define TLS1_TXT_ADH_WITH_AES_256_SHA "ADH-AES256-SHA" + +/* ECC ciphersuites from RFC4492 */ +# define TLS1_TXT_ECDH_ECDSA_WITH_NULL_SHA "ECDH-ECDSA-NULL-SHA" +# define TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA "ECDH-ECDSA-RC4-SHA" +# define TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA "ECDH-ECDSA-DES-CBC3-SHA" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA "ECDH-ECDSA-AES128-SHA" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA "ECDH-ECDSA-AES256-SHA" + +# define TLS1_TXT_ECDHE_ECDSA_WITH_NULL_SHA "ECDHE-ECDSA-NULL-SHA" +# define TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA "ECDHE-ECDSA-RC4-SHA" +# define TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "ECDHE-ECDSA-DES-CBC3-SHA" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "ECDHE-ECDSA-AES128-SHA" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "ECDHE-ECDSA-AES256-SHA" + +# define TLS1_TXT_ECDH_RSA_WITH_NULL_SHA "ECDH-RSA-NULL-SHA" +# define TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA "ECDH-RSA-RC4-SHA" +# define TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA "ECDH-RSA-DES-CBC3-SHA" +# define TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA "ECDH-RSA-AES128-SHA" +# define TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA "ECDH-RSA-AES256-SHA" + +# define TLS1_TXT_ECDHE_RSA_WITH_NULL_SHA "ECDHE-RSA-NULL-SHA" +# define TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA "ECDHE-RSA-RC4-SHA" +# define TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA "ECDHE-RSA-DES-CBC3-SHA" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA "ECDHE-RSA-AES128-SHA" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA "ECDHE-RSA-AES256-SHA" + +# define TLS1_TXT_ECDH_anon_WITH_NULL_SHA "AECDH-NULL-SHA" +# define TLS1_TXT_ECDH_anon_WITH_RC4_128_SHA "AECDH-RC4-SHA" +# define TLS1_TXT_ECDH_anon_WITH_DES_192_CBC3_SHA "AECDH-DES-CBC3-SHA" +# define TLS1_TXT_ECDH_anon_WITH_AES_128_CBC_SHA "AECDH-AES128-SHA" +# define TLS1_TXT_ECDH_anon_WITH_AES_256_CBC_SHA "AECDH-AES256-SHA" + +/* PSK ciphersuites from RFC 4279 */ +# define TLS1_TXT_PSK_WITH_RC4_128_SHA "PSK-RC4-SHA" +# define TLS1_TXT_PSK_WITH_3DES_EDE_CBC_SHA "PSK-3DES-EDE-CBC-SHA" +# define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA "PSK-AES128-CBC-SHA" +# define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA "PSK-AES256-CBC-SHA" + +# define TLS1_TXT_DHE_PSK_WITH_RC4_128_SHA "DHE-PSK-RC4-SHA" +# define TLS1_TXT_DHE_PSK_WITH_3DES_EDE_CBC_SHA "DHE-PSK-3DES-EDE-CBC-SHA" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_CBC_SHA "DHE-PSK-AES128-CBC-SHA" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_CBC_SHA "DHE-PSK-AES256-CBC-SHA" +# define TLS1_TXT_RSA_PSK_WITH_RC4_128_SHA "RSA-PSK-RC4-SHA" +# define TLS1_TXT_RSA_PSK_WITH_3DES_EDE_CBC_SHA "RSA-PSK-3DES-EDE-CBC-SHA" +# define TLS1_TXT_RSA_PSK_WITH_AES_128_CBC_SHA "RSA-PSK-AES128-CBC-SHA" +# define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA "RSA-PSK-AES256-CBC-SHA" + +/* PSK ciphersuites from RFC 5487 */ +# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_GCM_SHA256 "DHE-PSK-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_GCM_SHA384 "DHE-PSK-AES256-GCM-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_AES_128_GCM_SHA256 "RSA-PSK-AES128-GCM-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_AES_256_GCM_SHA384 "RSA-PSK-AES256-GCM-SHA384" + +# define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA256 "PSK-AES128-CBC-SHA256" +# define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA384 "PSK-AES256-CBC-SHA384" +# define TLS1_TXT_PSK_WITH_NULL_SHA256 "PSK-NULL-SHA256" +# define TLS1_TXT_PSK_WITH_NULL_SHA384 "PSK-NULL-SHA384" + +# define TLS1_TXT_DHE_PSK_WITH_AES_128_CBC_SHA256 "DHE-PSK-AES128-CBC-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_CBC_SHA384 "DHE-PSK-AES256-CBC-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA256 "DHE-PSK-NULL-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA384 "DHE-PSK-NULL-SHA384" + +# define TLS1_TXT_RSA_PSK_WITH_AES_128_CBC_SHA256 "RSA-PSK-AES128-CBC-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA384 "RSA-PSK-AES256-CBC-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA256 "RSA-PSK-NULL-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA384 "RSA-PSK-NULL-SHA384" + +/* SRP ciphersuite from RFC 5054 */ +# define TLS1_TXT_SRP_SHA_WITH_3DES_EDE_CBC_SHA "SRP-3DES-EDE-CBC-SHA" +# define TLS1_TXT_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA "SRP-RSA-3DES-EDE-CBC-SHA" +# define TLS1_TXT_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA "SRP-DSS-3DES-EDE-CBC-SHA" +# define TLS1_TXT_SRP_SHA_WITH_AES_128_CBC_SHA "SRP-AES-128-CBC-SHA" +# define TLS1_TXT_SRP_SHA_RSA_WITH_AES_128_CBC_SHA "SRP-RSA-AES-128-CBC-SHA" +# define TLS1_TXT_SRP_SHA_DSS_WITH_AES_128_CBC_SHA "SRP-DSS-AES-128-CBC-SHA" +# define TLS1_TXT_SRP_SHA_WITH_AES_256_CBC_SHA "SRP-AES-256-CBC-SHA" +# define TLS1_TXT_SRP_SHA_RSA_WITH_AES_256_CBC_SHA "SRP-RSA-AES-256-CBC-SHA" +# define TLS1_TXT_SRP_SHA_DSS_WITH_AES_256_CBC_SHA "SRP-DSS-AES-256-CBC-SHA" + +/* Camellia ciphersuites from RFC4132 */ +# define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA "CAMELLIA128-SHA" +# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA "DH-DSS-CAMELLIA128-SHA" +# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA "DH-RSA-CAMELLIA128-SHA" +# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "DHE-DSS-CAMELLIA128-SHA" +# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "DHE-RSA-CAMELLIA128-SHA" +# define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA "ADH-CAMELLIA128-SHA" + +# define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA "CAMELLIA256-SHA" +# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA "DH-DSS-CAMELLIA256-SHA" +# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA "DH-RSA-CAMELLIA256-SHA" +# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "DHE-DSS-CAMELLIA256-SHA" +# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "DHE-RSA-CAMELLIA256-SHA" +# define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA "ADH-CAMELLIA256-SHA" + +/* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */ +# define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA256 "CAMELLIA128-SHA256" +# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 "DH-DSS-CAMELLIA128-SHA256" +# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 "DH-RSA-CAMELLIA128-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 "DHE-DSS-CAMELLIA128-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "DHE-RSA-CAMELLIA128-SHA256" +# define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA256 "ADH-CAMELLIA128-SHA256" + +# define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA256 "CAMELLIA256-SHA256" +# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 "DH-DSS-CAMELLIA256-SHA256" +# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 "DH-RSA-CAMELLIA256-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 "DHE-DSS-CAMELLIA256-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 "DHE-RSA-CAMELLIA256-SHA256" +# define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA256 "ADH-CAMELLIA256-SHA256" + +# define TLS1_TXT_PSK_WITH_CAMELLIA_128_CBC_SHA256 "PSK-CAMELLIA128-SHA256" +# define TLS1_TXT_PSK_WITH_CAMELLIA_256_CBC_SHA384 "PSK-CAMELLIA256-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "DHE-PSK-CAMELLIA128-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "DHE-PSK-CAMELLIA256-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 "RSA-PSK-CAMELLIA128-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 "RSA-PSK-CAMELLIA256-SHA384" +# define TLS1_TXT_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-PSK-CAMELLIA128-SHA256" +# define TLS1_TXT_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-PSK-CAMELLIA256-SHA384" + +/* SEED ciphersuites from RFC4162 */ +# define TLS1_TXT_RSA_WITH_SEED_SHA "SEED-SHA" +# define TLS1_TXT_DH_DSS_WITH_SEED_SHA "DH-DSS-SEED-SHA" +# define TLS1_TXT_DH_RSA_WITH_SEED_SHA "DH-RSA-SEED-SHA" +# define TLS1_TXT_DHE_DSS_WITH_SEED_SHA "DHE-DSS-SEED-SHA" +# define TLS1_TXT_DHE_RSA_WITH_SEED_SHA "DHE-RSA-SEED-SHA" +# define TLS1_TXT_ADH_WITH_SEED_SHA "ADH-SEED-SHA" + +/* TLS v1.2 ciphersuites */ +# define TLS1_TXT_RSA_WITH_NULL_SHA256 "NULL-SHA256" +# define TLS1_TXT_RSA_WITH_AES_128_SHA256 "AES128-SHA256" +# define TLS1_TXT_RSA_WITH_AES_256_SHA256 "AES256-SHA256" +# define TLS1_TXT_DH_DSS_WITH_AES_128_SHA256 "DH-DSS-AES128-SHA256" +# define TLS1_TXT_DH_RSA_WITH_AES_128_SHA256 "DH-RSA-AES128-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA256 "DHE-DSS-AES128-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 "DHE-RSA-AES128-SHA256" +# define TLS1_TXT_DH_DSS_WITH_AES_256_SHA256 "DH-DSS-AES256-SHA256" +# define TLS1_TXT_DH_RSA_WITH_AES_256_SHA256 "DH-RSA-AES256-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA256 "DHE-DSS-AES256-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 "DHE-RSA-AES256-SHA256" +# define TLS1_TXT_ADH_WITH_AES_128_SHA256 "ADH-AES128-SHA256" +# define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" + +/* TLS v1.2 GCM ciphersuites from RFC5288 */ +# define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" +# define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +# define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" +# define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" +# define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" +# define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" + +/* CCM ciphersuites from RFC6655 */ +# define TLS1_TXT_RSA_WITH_AES_128_CCM "AES128-CCM" +# define TLS1_TXT_RSA_WITH_AES_256_CCM "AES256-CCM" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM "DHE-RSA-AES128-CCM" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM "DHE-RSA-AES256-CCM" + +# define TLS1_TXT_RSA_WITH_AES_128_CCM_8 "AES128-CCM8" +# define TLS1_TXT_RSA_WITH_AES_256_CCM_8 "AES256-CCM8" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM_8 "DHE-RSA-AES128-CCM8" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM_8 "DHE-RSA-AES256-CCM8" + +# define TLS1_TXT_PSK_WITH_AES_128_CCM "PSK-AES128-CCM" +# define TLS1_TXT_PSK_WITH_AES_256_CCM "PSK-AES256-CCM" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM "DHE-PSK-AES128-CCM" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM "DHE-PSK-AES256-CCM" + +# define TLS1_TXT_PSK_WITH_AES_128_CCM_8 "PSK-AES128-CCM8" +# define TLS1_TXT_PSK_WITH_AES_256_CCM_8 "PSK-AES256-CCM8" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM_8 "DHE-PSK-AES128-CCM8" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM_8 "DHE-PSK-AES256-CCM8" + +/* CCM ciphersuites from RFC7251 */ +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM "ECDHE-ECDSA-AES128-CCM" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM "ECDHE-ECDSA-AES256-CCM" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM_8 "ECDHE-ECDSA-AES128-CCM8" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM_8 "ECDHE-ECDSA-AES256-CCM8" + +/* ECDH HMAC based ciphersuites from RFC5289 */ +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_SHA256 "ECDHE-ECDSA-AES128-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_SHA384 "ECDHE-ECDSA-AES256-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_SHA256 "ECDH-ECDSA-AES128-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_SHA384 "ECDH-ECDSA-AES256-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 "ECDHE-RSA-AES128-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 "ECDHE-RSA-AES256-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_AES_128_SHA256 "ECDH-RSA-AES128-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" + +/* ECDH GCM based ciphersuites from RFC5289 */ +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" + +/* TLS v1.2 PSK GCM ciphersuites from RFC5487 */ +# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384" + +/* ECDHE PSK ciphersuites from RFC 5489 */ +# define TLS1_TXT_ECDHE_PSK_WITH_RC4_128_SHA "ECDHE-PSK-RC4-SHA" +# define TLS1_TXT_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA "ECDHE-PSK-3DES-EDE-CBC-SHA" +# define TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA "ECDHE-PSK-AES128-CBC-SHA" +# define TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA "ECDHE-PSK-AES256-CBC-SHA" + +# define TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA256 "ECDHE-PSK-AES128-CBC-SHA256" +# define TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA384 "ECDHE-PSK-AES256-CBC-SHA384" + +# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA "ECDHE-PSK-NULL-SHA" +# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA256 "ECDHE-PSK-NULL-SHA256" +# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA384 "ECDHE-PSK-NULL-SHA384" + +/* Camellia-CBC ciphersuites from RFC6367 */ +# define TLS1_TXT_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-ECDSA-CAMELLIA128-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-ECDSA-CAMELLIA256-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDH-ECDSA-CAMELLIA128-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDH-ECDSA-CAMELLIA256-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-RSA-CAMELLIA128-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-RSA-CAMELLIA256-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDH-RSA-CAMELLIA128-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDH-RSA-CAMELLIA256-SHA384" + +/* draft-ietf-tls-chacha20-poly1305-03 */ +# define TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 "ECDHE-RSA-CHACHA20-POLY1305" +# define TLS1_TXT_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 "ECDHE-ECDSA-CHACHA20-POLY1305" +# define TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305 "DHE-RSA-CHACHA20-POLY1305" +# define TLS1_TXT_PSK_WITH_CHACHA20_POLY1305 "PSK-CHACHA20-POLY1305" +# define TLS1_TXT_ECDHE_PSK_WITH_CHACHA20_POLY1305 "ECDHE-PSK-CHACHA20-POLY1305" +# define TLS1_TXT_DHE_PSK_WITH_CHACHA20_POLY1305 "DHE-PSK-CHACHA20-POLY1305" +# define TLS1_TXT_RSA_PSK_WITH_CHACHA20_POLY1305 "RSA-PSK-CHACHA20-POLY1305" + +/* Aria ciphersuites from RFC6209 */ +# define TLS1_TXT_RSA_WITH_ARIA_128_GCM_SHA256 "ARIA128-GCM-SHA256" +# define TLS1_TXT_RSA_WITH_ARIA_256_GCM_SHA384 "ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "DHE-RSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "DHE-RSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_RSA_WITH_ARIA_128_GCM_SHA256 "DH-RSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_RSA_WITH_ARIA_256_GCM_SHA384 "DH-RSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "DHE-DSS-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "DHE-DSS-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_DSS_WITH_ARIA_128_GCM_SHA256 "DH-DSS-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_DSS_WITH_ARIA_256_GCM_SHA384 "DH-DSS-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_anon_WITH_ARIA_128_GCM_SHA256 "ADH-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_anon_WITH_ARIA_256_GCM_SHA384 "ADH-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ECDSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ECDSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ECDSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ECDSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ARIA256-GCM-SHA384" +# define TLS1_TXT_PSK_WITH_ARIA_128_GCM_SHA256 "PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_ARIA_256_GCM_SHA384 "PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "DHE-PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "DHE-PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "RSA-PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "RSA-PSK-ARIA256-GCM-SHA384" + +# define TLS_CT_RSA_SIGN 1 +# define TLS_CT_DSS_SIGN 2 +# define TLS_CT_RSA_FIXED_DH 3 +# define TLS_CT_DSS_FIXED_DH 4 +# define TLS_CT_ECDSA_SIGN 64 +# define TLS_CT_RSA_FIXED_ECDH 65 +# define TLS_CT_ECDSA_FIXED_ECDH 66 +# define TLS_CT_GOST01_SIGN 22 +# define TLS_CT_GOST12_SIGN 238 +# define TLS_CT_GOST12_512_SIGN 239 + +/* + * when correcting this number, correct also SSL3_CT_NUMBER in ssl3.h (see + * comment there) + */ +# define TLS_CT_NUMBER 10 + +# if defined(SSL3_CT_NUMBER) +# if TLS_CT_NUMBER != SSL3_CT_NUMBER +# error "SSL/TLS CT_NUMBER values do not match" +# endif +# endif + +# define TLS1_FINISH_MAC_LENGTH 12 + +# define TLS_MD_MAX_CONST_SIZE 22 +# define TLS_MD_CLIENT_FINISH_CONST "client finished" +# define TLS_MD_CLIENT_FINISH_CONST_SIZE 15 +# define TLS_MD_SERVER_FINISH_CONST "server finished" +# define TLS_MD_SERVER_FINISH_CONST_SIZE 15 +# define TLS_MD_KEY_EXPANSION_CONST "key expansion" +# define TLS_MD_KEY_EXPANSION_CONST_SIZE 13 +# define TLS_MD_CLIENT_WRITE_KEY_CONST "client write key" +# define TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE 16 +# define TLS_MD_SERVER_WRITE_KEY_CONST "server write key" +# define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16 +# define TLS_MD_IV_BLOCK_CONST "IV block" +# define TLS_MD_IV_BLOCK_CONST_SIZE 8 +# define TLS_MD_MASTER_SECRET_CONST "master secret" +# define TLS_MD_MASTER_SECRET_CONST_SIZE 13 +# define TLS_MD_EXTENDED_MASTER_SECRET_CONST "extended master secret" +# define TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE 22 + +# ifdef CHARSET_EBCDIC +# undef TLS_MD_CLIENT_FINISH_CONST +/* + * client finished + */ +# define TLS_MD_CLIENT_FINISH_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x66\x69\x6e\x69\x73\x68\x65\x64" + +# undef TLS_MD_SERVER_FINISH_CONST +/* + * server finished + */ +# define TLS_MD_SERVER_FINISH_CONST "\x73\x65\x72\x76\x65\x72\x20\x66\x69\x6e\x69\x73\x68\x65\x64" + +# undef TLS_MD_SERVER_WRITE_KEY_CONST +/* + * server write key + */ +# define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" + +# undef TLS_MD_KEY_EXPANSION_CONST +/* + * key expansion + */ +# define TLS_MD_KEY_EXPANSION_CONST "\x6b\x65\x79\x20\x65\x78\x70\x61\x6e\x73\x69\x6f\x6e" + +# undef TLS_MD_CLIENT_WRITE_KEY_CONST +/* + * client write key + */ +# define TLS_MD_CLIENT_WRITE_KEY_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" + +# undef TLS_MD_SERVER_WRITE_KEY_CONST +/* + * server write key + */ +# define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" + +# undef TLS_MD_IV_BLOCK_CONST +/* + * IV block + */ +# define TLS_MD_IV_BLOCK_CONST "\x49\x56\x20\x62\x6c\x6f\x63\x6b" + +# undef TLS_MD_MASTER_SECRET_CONST +/* + * master secret + */ +# define TLS_MD_MASTER_SECRET_CONST "\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74" +# undef TLS_MD_EXTENDED_MASTER_SECRET_CONST +/* + * extended master secret + */ +# define TLS_MD_EXTENDED_MASTER_SECRET_CONST "\x65\x78\x74\x65\x63\x64\x65\x64\x20\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74" +# endif + +/* TLS Session Ticket extension struct */ +struct tls_session_ticket_ext_st { + unsigned short length; + void *data; +}; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/ts.h b/include/openssl/ts.h new file mode 100644 index 0000000..1b0d101 --- /dev/null +++ b/include/openssl/ts.h @@ -0,0 +1,559 @@ +/* + * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_TS_H +# define HEADER_TS_H + +# include + +# ifndef OPENSSL_NO_TS +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +# include +# include + +typedef struct TS_msg_imprint_st TS_MSG_IMPRINT; +typedef struct TS_req_st TS_REQ; +typedef struct TS_accuracy_st TS_ACCURACY; +typedef struct TS_tst_info_st TS_TST_INFO; + +/* Possible values for status. */ +# define TS_STATUS_GRANTED 0 +# define TS_STATUS_GRANTED_WITH_MODS 1 +# define TS_STATUS_REJECTION 2 +# define TS_STATUS_WAITING 3 +# define TS_STATUS_REVOCATION_WARNING 4 +# define TS_STATUS_REVOCATION_NOTIFICATION 5 + +/* Possible values for failure_info. */ +# define TS_INFO_BAD_ALG 0 +# define TS_INFO_BAD_REQUEST 2 +# define TS_INFO_BAD_DATA_FORMAT 5 +# define TS_INFO_TIME_NOT_AVAILABLE 14 +# define TS_INFO_UNACCEPTED_POLICY 15 +# define TS_INFO_UNACCEPTED_EXTENSION 16 +# define TS_INFO_ADD_INFO_NOT_AVAILABLE 17 +# define TS_INFO_SYSTEM_FAILURE 25 + + +typedef struct TS_status_info_st TS_STATUS_INFO; +typedef struct ESS_issuer_serial ESS_ISSUER_SERIAL; +typedef struct ESS_cert_id ESS_CERT_ID; +typedef struct ESS_signing_cert ESS_SIGNING_CERT; + +DEFINE_STACK_OF(ESS_CERT_ID) + +typedef struct ESS_cert_id_v2_st ESS_CERT_ID_V2; +typedef struct ESS_signing_cert_v2_st ESS_SIGNING_CERT_V2; + +DEFINE_STACK_OF(ESS_CERT_ID_V2) + +typedef struct TS_resp_st TS_RESP; + +TS_REQ *TS_REQ_new(void); +void TS_REQ_free(TS_REQ *a); +int i2d_TS_REQ(const TS_REQ *a, unsigned char **pp); +TS_REQ *d2i_TS_REQ(TS_REQ **a, const unsigned char **pp, long length); + +TS_REQ *TS_REQ_dup(TS_REQ *a); + +#ifndef OPENSSL_NO_STDIO +TS_REQ *d2i_TS_REQ_fp(FILE *fp, TS_REQ **a); +int i2d_TS_REQ_fp(FILE *fp, TS_REQ *a); +#endif +TS_REQ *d2i_TS_REQ_bio(BIO *fp, TS_REQ **a); +int i2d_TS_REQ_bio(BIO *fp, TS_REQ *a); + +TS_MSG_IMPRINT *TS_MSG_IMPRINT_new(void); +void TS_MSG_IMPRINT_free(TS_MSG_IMPRINT *a); +int i2d_TS_MSG_IMPRINT(const TS_MSG_IMPRINT *a, unsigned char **pp); +TS_MSG_IMPRINT *d2i_TS_MSG_IMPRINT(TS_MSG_IMPRINT **a, + const unsigned char **pp, long length); + +TS_MSG_IMPRINT *TS_MSG_IMPRINT_dup(TS_MSG_IMPRINT *a); + +#ifndef OPENSSL_NO_STDIO +TS_MSG_IMPRINT *d2i_TS_MSG_IMPRINT_fp(FILE *fp, TS_MSG_IMPRINT **a); +int i2d_TS_MSG_IMPRINT_fp(FILE *fp, TS_MSG_IMPRINT *a); +#endif +TS_MSG_IMPRINT *d2i_TS_MSG_IMPRINT_bio(BIO *bio, TS_MSG_IMPRINT **a); +int i2d_TS_MSG_IMPRINT_bio(BIO *bio, TS_MSG_IMPRINT *a); + +TS_RESP *TS_RESP_new(void); +void TS_RESP_free(TS_RESP *a); +int i2d_TS_RESP(const TS_RESP *a, unsigned char **pp); +TS_RESP *d2i_TS_RESP(TS_RESP **a, const unsigned char **pp, long length); +TS_TST_INFO *PKCS7_to_TS_TST_INFO(PKCS7 *token); +TS_RESP *TS_RESP_dup(TS_RESP *a); + +#ifndef OPENSSL_NO_STDIO +TS_RESP *d2i_TS_RESP_fp(FILE *fp, TS_RESP **a); +int i2d_TS_RESP_fp(FILE *fp, TS_RESP *a); +#endif +TS_RESP *d2i_TS_RESP_bio(BIO *bio, TS_RESP **a); +int i2d_TS_RESP_bio(BIO *bio, TS_RESP *a); + +TS_STATUS_INFO *TS_STATUS_INFO_new(void); +void TS_STATUS_INFO_free(TS_STATUS_INFO *a); +int i2d_TS_STATUS_INFO(const TS_STATUS_INFO *a, unsigned char **pp); +TS_STATUS_INFO *d2i_TS_STATUS_INFO(TS_STATUS_INFO **a, + const unsigned char **pp, long length); +TS_STATUS_INFO *TS_STATUS_INFO_dup(TS_STATUS_INFO *a); + +TS_TST_INFO *TS_TST_INFO_new(void); +void TS_TST_INFO_free(TS_TST_INFO *a); +int i2d_TS_TST_INFO(const TS_TST_INFO *a, unsigned char **pp); +TS_TST_INFO *d2i_TS_TST_INFO(TS_TST_INFO **a, const unsigned char **pp, + long length); +TS_TST_INFO *TS_TST_INFO_dup(TS_TST_INFO *a); + +#ifndef OPENSSL_NO_STDIO +TS_TST_INFO *d2i_TS_TST_INFO_fp(FILE *fp, TS_TST_INFO **a); +int i2d_TS_TST_INFO_fp(FILE *fp, TS_TST_INFO *a); +#endif +TS_TST_INFO *d2i_TS_TST_INFO_bio(BIO *bio, TS_TST_INFO **a); +int i2d_TS_TST_INFO_bio(BIO *bio, TS_TST_INFO *a); + +TS_ACCURACY *TS_ACCURACY_new(void); +void TS_ACCURACY_free(TS_ACCURACY *a); +int i2d_TS_ACCURACY(const TS_ACCURACY *a, unsigned char **pp); +TS_ACCURACY *d2i_TS_ACCURACY(TS_ACCURACY **a, const unsigned char **pp, + long length); +TS_ACCURACY *TS_ACCURACY_dup(TS_ACCURACY *a); + +ESS_ISSUER_SERIAL *ESS_ISSUER_SERIAL_new(void); +void ESS_ISSUER_SERIAL_free(ESS_ISSUER_SERIAL *a); +int i2d_ESS_ISSUER_SERIAL(const ESS_ISSUER_SERIAL *a, unsigned char **pp); +ESS_ISSUER_SERIAL *d2i_ESS_ISSUER_SERIAL(ESS_ISSUER_SERIAL **a, + const unsigned char **pp, + long length); +ESS_ISSUER_SERIAL *ESS_ISSUER_SERIAL_dup(ESS_ISSUER_SERIAL *a); + +ESS_CERT_ID *ESS_CERT_ID_new(void); +void ESS_CERT_ID_free(ESS_CERT_ID *a); +int i2d_ESS_CERT_ID(const ESS_CERT_ID *a, unsigned char **pp); +ESS_CERT_ID *d2i_ESS_CERT_ID(ESS_CERT_ID **a, const unsigned char **pp, + long length); +ESS_CERT_ID *ESS_CERT_ID_dup(ESS_CERT_ID *a); + +ESS_SIGNING_CERT *ESS_SIGNING_CERT_new(void); +void ESS_SIGNING_CERT_free(ESS_SIGNING_CERT *a); +int i2d_ESS_SIGNING_CERT(const ESS_SIGNING_CERT *a, unsigned char **pp); +ESS_SIGNING_CERT *d2i_ESS_SIGNING_CERT(ESS_SIGNING_CERT **a, + const unsigned char **pp, long length); +ESS_SIGNING_CERT *ESS_SIGNING_CERT_dup(ESS_SIGNING_CERT *a); + +ESS_CERT_ID_V2 *ESS_CERT_ID_V2_new(void); +void ESS_CERT_ID_V2_free(ESS_CERT_ID_V2 *a); +int i2d_ESS_CERT_ID_V2(const ESS_CERT_ID_V2 *a, unsigned char **pp); +ESS_CERT_ID_V2 *d2i_ESS_CERT_ID_V2(ESS_CERT_ID_V2 **a, + const unsigned char **pp, long length); +ESS_CERT_ID_V2 *ESS_CERT_ID_V2_dup(ESS_CERT_ID_V2 *a); + +ESS_SIGNING_CERT_V2 *ESS_SIGNING_CERT_V2_new(void); +void ESS_SIGNING_CERT_V2_free(ESS_SIGNING_CERT_V2 *a); +int i2d_ESS_SIGNING_CERT_V2(const ESS_SIGNING_CERT_V2 *a, unsigned char **pp); +ESS_SIGNING_CERT_V2 *d2i_ESS_SIGNING_CERT_V2(ESS_SIGNING_CERT_V2 **a, + const unsigned char **pp, + long length); +ESS_SIGNING_CERT_V2 *ESS_SIGNING_CERT_V2_dup(ESS_SIGNING_CERT_V2 *a); + +int TS_REQ_set_version(TS_REQ *a, long version); +long TS_REQ_get_version(const TS_REQ *a); + +int TS_STATUS_INFO_set_status(TS_STATUS_INFO *a, int i); +const ASN1_INTEGER *TS_STATUS_INFO_get0_status(const TS_STATUS_INFO *a); + +const STACK_OF(ASN1_UTF8STRING) * +TS_STATUS_INFO_get0_text(const TS_STATUS_INFO *a); + +const ASN1_BIT_STRING * +TS_STATUS_INFO_get0_failure_info(const TS_STATUS_INFO *a); + +int TS_REQ_set_msg_imprint(TS_REQ *a, TS_MSG_IMPRINT *msg_imprint); +TS_MSG_IMPRINT *TS_REQ_get_msg_imprint(TS_REQ *a); + +int TS_MSG_IMPRINT_set_algo(TS_MSG_IMPRINT *a, X509_ALGOR *alg); +X509_ALGOR *TS_MSG_IMPRINT_get_algo(TS_MSG_IMPRINT *a); + +int TS_MSG_IMPRINT_set_msg(TS_MSG_IMPRINT *a, unsigned char *d, int len); +ASN1_OCTET_STRING *TS_MSG_IMPRINT_get_msg(TS_MSG_IMPRINT *a); + +int TS_REQ_set_policy_id(TS_REQ *a, const ASN1_OBJECT *policy); +ASN1_OBJECT *TS_REQ_get_policy_id(TS_REQ *a); + +int TS_REQ_set_nonce(TS_REQ *a, const ASN1_INTEGER *nonce); +const ASN1_INTEGER *TS_REQ_get_nonce(const TS_REQ *a); + +int TS_REQ_set_cert_req(TS_REQ *a, int cert_req); +int TS_REQ_get_cert_req(const TS_REQ *a); + +STACK_OF(X509_EXTENSION) *TS_REQ_get_exts(TS_REQ *a); +void TS_REQ_ext_free(TS_REQ *a); +int TS_REQ_get_ext_count(TS_REQ *a); +int TS_REQ_get_ext_by_NID(TS_REQ *a, int nid, int lastpos); +int TS_REQ_get_ext_by_OBJ(TS_REQ *a, const ASN1_OBJECT *obj, int lastpos); +int TS_REQ_get_ext_by_critical(TS_REQ *a, int crit, int lastpos); +X509_EXTENSION *TS_REQ_get_ext(TS_REQ *a, int loc); +X509_EXTENSION *TS_REQ_delete_ext(TS_REQ *a, int loc); +int TS_REQ_add_ext(TS_REQ *a, X509_EXTENSION *ex, int loc); +void *TS_REQ_get_ext_d2i(TS_REQ *a, int nid, int *crit, int *idx); + +/* Function declarations for TS_REQ defined in ts/ts_req_print.c */ + +int TS_REQ_print_bio(BIO *bio, TS_REQ *a); + +/* Function declarations for TS_RESP defined in ts/ts_resp_utils.c */ + +int TS_RESP_set_status_info(TS_RESP *a, TS_STATUS_INFO *info); +TS_STATUS_INFO *TS_RESP_get_status_info(TS_RESP *a); + +/* Caller loses ownership of PKCS7 and TS_TST_INFO objects. */ +void TS_RESP_set_tst_info(TS_RESP *a, PKCS7 *p7, TS_TST_INFO *tst_info); +PKCS7 *TS_RESP_get_token(TS_RESP *a); +TS_TST_INFO *TS_RESP_get_tst_info(TS_RESP *a); + +int TS_TST_INFO_set_version(TS_TST_INFO *a, long version); +long TS_TST_INFO_get_version(const TS_TST_INFO *a); + +int TS_TST_INFO_set_policy_id(TS_TST_INFO *a, ASN1_OBJECT *policy_id); +ASN1_OBJECT *TS_TST_INFO_get_policy_id(TS_TST_INFO *a); + +int TS_TST_INFO_set_msg_imprint(TS_TST_INFO *a, TS_MSG_IMPRINT *msg_imprint); +TS_MSG_IMPRINT *TS_TST_INFO_get_msg_imprint(TS_TST_INFO *a); + +int TS_TST_INFO_set_serial(TS_TST_INFO *a, const ASN1_INTEGER *serial); +const ASN1_INTEGER *TS_TST_INFO_get_serial(const TS_TST_INFO *a); + +int TS_TST_INFO_set_time(TS_TST_INFO *a, const ASN1_GENERALIZEDTIME *gtime); +const ASN1_GENERALIZEDTIME *TS_TST_INFO_get_time(const TS_TST_INFO *a); + +int TS_TST_INFO_set_accuracy(TS_TST_INFO *a, TS_ACCURACY *accuracy); +TS_ACCURACY *TS_TST_INFO_get_accuracy(TS_TST_INFO *a); + +int TS_ACCURACY_set_seconds(TS_ACCURACY *a, const ASN1_INTEGER *seconds); +const ASN1_INTEGER *TS_ACCURACY_get_seconds(const TS_ACCURACY *a); + +int TS_ACCURACY_set_millis(TS_ACCURACY *a, const ASN1_INTEGER *millis); +const ASN1_INTEGER *TS_ACCURACY_get_millis(const TS_ACCURACY *a); + +int TS_ACCURACY_set_micros(TS_ACCURACY *a, const ASN1_INTEGER *micros); +const ASN1_INTEGER *TS_ACCURACY_get_micros(const TS_ACCURACY *a); + +int TS_TST_INFO_set_ordering(TS_TST_INFO *a, int ordering); +int TS_TST_INFO_get_ordering(const TS_TST_INFO *a); + +int TS_TST_INFO_set_nonce(TS_TST_INFO *a, const ASN1_INTEGER *nonce); +const ASN1_INTEGER *TS_TST_INFO_get_nonce(const TS_TST_INFO *a); + +int TS_TST_INFO_set_tsa(TS_TST_INFO *a, GENERAL_NAME *tsa); +GENERAL_NAME *TS_TST_INFO_get_tsa(TS_TST_INFO *a); + +STACK_OF(X509_EXTENSION) *TS_TST_INFO_get_exts(TS_TST_INFO *a); +void TS_TST_INFO_ext_free(TS_TST_INFO *a); +int TS_TST_INFO_get_ext_count(TS_TST_INFO *a); +int TS_TST_INFO_get_ext_by_NID(TS_TST_INFO *a, int nid, int lastpos); +int TS_TST_INFO_get_ext_by_OBJ(TS_TST_INFO *a, const ASN1_OBJECT *obj, + int lastpos); +int TS_TST_INFO_get_ext_by_critical(TS_TST_INFO *a, int crit, int lastpos); +X509_EXTENSION *TS_TST_INFO_get_ext(TS_TST_INFO *a, int loc); +X509_EXTENSION *TS_TST_INFO_delete_ext(TS_TST_INFO *a, int loc); +int TS_TST_INFO_add_ext(TS_TST_INFO *a, X509_EXTENSION *ex, int loc); +void *TS_TST_INFO_get_ext_d2i(TS_TST_INFO *a, int nid, int *crit, int *idx); + +/* + * Declarations related to response generation, defined in ts/ts_resp_sign.c. + */ + +/* Optional flags for response generation. */ + +/* Don't include the TSA name in response. */ +# define TS_TSA_NAME 0x01 + +/* Set ordering to true in response. */ +# define TS_ORDERING 0x02 + +/* + * Include the signer certificate and the other specified certificates in + * the ESS signing certificate attribute beside the PKCS7 signed data. + * Only the signer certificates is included by default. + */ +# define TS_ESS_CERT_ID_CHAIN 0x04 + +/* Forward declaration. */ +struct TS_resp_ctx; + +/* This must return a unique number less than 160 bits long. */ +typedef ASN1_INTEGER *(*TS_serial_cb) (struct TS_resp_ctx *, void *); + +/* + * This must return the seconds and microseconds since Jan 1, 1970 in the sec + * and usec variables allocated by the caller. Return non-zero for success + * and zero for failure. + */ +typedef int (*TS_time_cb) (struct TS_resp_ctx *, void *, long *sec, + long *usec); + +/* + * This must process the given extension. It can modify the TS_TST_INFO + * object of the context. Return values: !0 (processed), 0 (error, it must + * set the status info/failure info of the response). + */ +typedef int (*TS_extension_cb) (struct TS_resp_ctx *, X509_EXTENSION *, + void *); + +typedef struct TS_resp_ctx TS_RESP_CTX; + +DEFINE_STACK_OF_CONST(EVP_MD) + +/* Creates a response context that can be used for generating responses. */ +TS_RESP_CTX *TS_RESP_CTX_new(void); +void TS_RESP_CTX_free(TS_RESP_CTX *ctx); + +/* This parameter must be set. */ +int TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer); + +/* This parameter must be set. */ +int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key); + +int TS_RESP_CTX_set_signer_digest(TS_RESP_CTX *ctx, + const EVP_MD *signer_digest); +int TS_RESP_CTX_set_ess_cert_id_digest(TS_RESP_CTX *ctx, const EVP_MD *md); + +/* This parameter must be set. */ +int TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *def_policy); + +/* No additional certs are included in the response by default. */ +int TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs); + +/* + * Adds a new acceptable policy, only the default policy is accepted by + * default. + */ +int TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *policy); + +/* + * Adds a new acceptable message digest. Note that no message digests are + * accepted by default. The md argument is shared with the caller. + */ +int TS_RESP_CTX_add_md(TS_RESP_CTX *ctx, const EVP_MD *md); + +/* Accuracy is not included by default. */ +int TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx, + int secs, int millis, int micros); + +/* + * Clock precision digits, i.e. the number of decimal digits: '0' means sec, + * '3' msec, '6' usec, and so on. Default is 0. + */ +int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx, + unsigned clock_precision_digits); +/* At most we accept usec precision. */ +# define TS_MAX_CLOCK_PRECISION_DIGITS 6 + +/* Maximum status message length */ +# define TS_MAX_STATUS_LENGTH (1024 * 1024) + +/* No flags are set by default. */ +void TS_RESP_CTX_add_flags(TS_RESP_CTX *ctx, int flags); + +/* Default callback always returns a constant. */ +void TS_RESP_CTX_set_serial_cb(TS_RESP_CTX *ctx, TS_serial_cb cb, void *data); + +/* Default callback uses the gettimeofday() and gmtime() system calls. */ +void TS_RESP_CTX_set_time_cb(TS_RESP_CTX *ctx, TS_time_cb cb, void *data); + +/* + * Default callback rejects all extensions. The extension callback is called + * when the TS_TST_INFO object is already set up and not signed yet. + */ +/* FIXME: extension handling is not tested yet. */ +void TS_RESP_CTX_set_extension_cb(TS_RESP_CTX *ctx, + TS_extension_cb cb, void *data); + +/* The following methods can be used in the callbacks. */ +int TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx, + int status, const char *text); + +/* Sets the status info only if it is still TS_STATUS_GRANTED. */ +int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx, + int status, const char *text); + +int TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure); + +/* The get methods below can be used in the extension callback. */ +TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx); + +TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx); + +/* + * Creates the signed TS_TST_INFO and puts it in TS_RESP. + * In case of errors it sets the status info properly. + * Returns NULL only in case of memory allocation/fatal error. + */ +TS_RESP *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio); + +/* + * Declarations related to response verification, + * they are defined in ts/ts_resp_verify.c. + */ + +int TS_RESP_verify_signature(PKCS7 *token, STACK_OF(X509) *certs, + X509_STORE *store, X509 **signer_out); + +/* Context structure for the generic verify method. */ + +/* Verify the signer's certificate and the signature of the response. */ +# define TS_VFY_SIGNATURE (1u << 0) +/* Verify the version number of the response. */ +# define TS_VFY_VERSION (1u << 1) +/* Verify if the policy supplied by the user matches the policy of the TSA. */ +# define TS_VFY_POLICY (1u << 2) +/* + * Verify the message imprint provided by the user. This flag should not be + * specified with TS_VFY_DATA. + */ +# define TS_VFY_IMPRINT (1u << 3) +/* + * Verify the message imprint computed by the verify method from the user + * provided data and the MD algorithm of the response. This flag should not + * be specified with TS_VFY_IMPRINT. + */ +# define TS_VFY_DATA (1u << 4) +/* Verify the nonce value. */ +# define TS_VFY_NONCE (1u << 5) +/* Verify if the TSA name field matches the signer certificate. */ +# define TS_VFY_SIGNER (1u << 6) +/* Verify if the TSA name field equals to the user provided name. */ +# define TS_VFY_TSA_NAME (1u << 7) + +/* You can use the following convenience constants. */ +# define TS_VFY_ALL_IMPRINT (TS_VFY_SIGNATURE \ + | TS_VFY_VERSION \ + | TS_VFY_POLICY \ + | TS_VFY_IMPRINT \ + | TS_VFY_NONCE \ + | TS_VFY_SIGNER \ + | TS_VFY_TSA_NAME) +# define TS_VFY_ALL_DATA (TS_VFY_SIGNATURE \ + | TS_VFY_VERSION \ + | TS_VFY_POLICY \ + | TS_VFY_DATA \ + | TS_VFY_NONCE \ + | TS_VFY_SIGNER \ + | TS_VFY_TSA_NAME) + +typedef struct TS_verify_ctx TS_VERIFY_CTX; + +int TS_RESP_verify_response(TS_VERIFY_CTX *ctx, TS_RESP *response); +int TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token); + +/* + * Declarations related to response verification context, + */ +TS_VERIFY_CTX *TS_VERIFY_CTX_new(void); +void TS_VERIFY_CTX_init(TS_VERIFY_CTX *ctx); +void TS_VERIFY_CTX_free(TS_VERIFY_CTX *ctx); +void TS_VERIFY_CTX_cleanup(TS_VERIFY_CTX *ctx); +int TS_VERIFY_CTX_set_flags(TS_VERIFY_CTX *ctx, int f); +int TS_VERIFY_CTX_add_flags(TS_VERIFY_CTX *ctx, int f); +BIO *TS_VERIFY_CTX_set_data(TS_VERIFY_CTX *ctx, BIO *b); +unsigned char *TS_VERIFY_CTX_set_imprint(TS_VERIFY_CTX *ctx, + unsigned char *hexstr, long len); +X509_STORE *TS_VERIFY_CTX_set_store(TS_VERIFY_CTX *ctx, X509_STORE *s); +STACK_OF(X509) *TS_VERIFY_CTS_set_certs(TS_VERIFY_CTX *ctx, STACK_OF(X509) *certs); + +/*- + * If ctx is NULL, it allocates and returns a new object, otherwise + * it returns ctx. It initialises all the members as follows: + * flags = TS_VFY_ALL_IMPRINT & ~(TS_VFY_TSA_NAME | TS_VFY_SIGNATURE) + * certs = NULL + * store = NULL + * policy = policy from the request or NULL if absent (in this case + * TS_VFY_POLICY is cleared from flags as well) + * md_alg = MD algorithm from request + * imprint, imprint_len = imprint from request + * data = NULL + * nonce, nonce_len = nonce from the request or NULL if absent (in this case + * TS_VFY_NONCE is cleared from flags as well) + * tsa_name = NULL + * Important: after calling this method TS_VFY_SIGNATURE should be added! + */ +TS_VERIFY_CTX *TS_REQ_to_TS_VERIFY_CTX(TS_REQ *req, TS_VERIFY_CTX *ctx); + +/* Function declarations for TS_RESP defined in ts/ts_resp_print.c */ + +int TS_RESP_print_bio(BIO *bio, TS_RESP *a); +int TS_STATUS_INFO_print_bio(BIO *bio, TS_STATUS_INFO *a); +int TS_TST_INFO_print_bio(BIO *bio, TS_TST_INFO *a); + +/* Common utility functions defined in ts/ts_lib.c */ + +int TS_ASN1_INTEGER_print_bio(BIO *bio, const ASN1_INTEGER *num); +int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj); +int TS_ext_print_bio(BIO *bio, const STACK_OF(X509_EXTENSION) *extensions); +int TS_X509_ALGOR_print_bio(BIO *bio, const X509_ALGOR *alg); +int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *msg); + +/* + * Function declarations for handling configuration options, defined in + * ts/ts_conf.c + */ + +X509 *TS_CONF_load_cert(const char *file); +STACK_OF(X509) *TS_CONF_load_certs(const char *file); +EVP_PKEY *TS_CONF_load_key(const char *file, const char *pass); +const char *TS_CONF_get_tsa_section(CONF *conf, const char *section); +int TS_CONF_set_serial(CONF *conf, const char *section, TS_serial_cb cb, + TS_RESP_CTX *ctx); +#ifndef OPENSSL_NO_ENGINE +int TS_CONF_set_crypto_device(CONF *conf, const char *section, + const char *device); +int TS_CONF_set_default_engine(const char *name); +#endif +int TS_CONF_set_signer_cert(CONF *conf, const char *section, + const char *cert, TS_RESP_CTX *ctx); +int TS_CONF_set_certs(CONF *conf, const char *section, const char *certs, + TS_RESP_CTX *ctx); +int TS_CONF_set_signer_key(CONF *conf, const char *section, + const char *key, const char *pass, + TS_RESP_CTX *ctx); +int TS_CONF_set_signer_digest(CONF *conf, const char *section, + const char *md, TS_RESP_CTX *ctx); +int TS_CONF_set_def_policy(CONF *conf, const char *section, + const char *policy, TS_RESP_CTX *ctx); +int TS_CONF_set_policies(CONF *conf, const char *section, TS_RESP_CTX *ctx); +int TS_CONF_set_digests(CONF *conf, const char *section, TS_RESP_CTX *ctx); +int TS_CONF_set_accuracy(CONF *conf, const char *section, TS_RESP_CTX *ctx); +int TS_CONF_set_clock_precision_digits(CONF *conf, const char *section, + TS_RESP_CTX *ctx); +int TS_CONF_set_ordering(CONF *conf, const char *section, TS_RESP_CTX *ctx); +int TS_CONF_set_tsa_name(CONF *conf, const char *section, TS_RESP_CTX *ctx); +int TS_CONF_set_ess_cert_id_chain(CONF *conf, const char *section, + TS_RESP_CTX *ctx); +int TS_CONF_set_ess_cert_id_digest(CONF *conf, const char *section, + TS_RESP_CTX *ctx); + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/include/openssl/tserr.h b/include/openssl/tserr.h new file mode 100644 index 0000000..144ef41 --- /dev/null +++ b/include/openssl/tserr.h @@ -0,0 +1,128 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_TSERR_H +# define HEADER_TSERR_H + +# include + +# ifndef OPENSSL_NO_TS + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_TS_strings(void); + +/* + * TS function codes. + */ +# define TS_F_DEF_SERIAL_CB 110 +# define TS_F_DEF_TIME_CB 111 +# define TS_F_ESS_ADD_SIGNING_CERT 112 +# define TS_F_ESS_ADD_SIGNING_CERT_V2 147 +# define TS_F_ESS_CERT_ID_NEW_INIT 113 +# define TS_F_ESS_CERT_ID_V2_NEW_INIT 156 +# define TS_F_ESS_SIGNING_CERT_NEW_INIT 114 +# define TS_F_ESS_SIGNING_CERT_V2_NEW_INIT 157 +# define TS_F_INT_TS_RESP_VERIFY_TOKEN 149 +# define TS_F_PKCS7_TO_TS_TST_INFO 148 +# define TS_F_TS_ACCURACY_SET_MICROS 115 +# define TS_F_TS_ACCURACY_SET_MILLIS 116 +# define TS_F_TS_ACCURACY_SET_SECONDS 117 +# define TS_F_TS_CHECK_IMPRINTS 100 +# define TS_F_TS_CHECK_NONCES 101 +# define TS_F_TS_CHECK_POLICY 102 +# define TS_F_TS_CHECK_SIGNING_CERTS 103 +# define TS_F_TS_CHECK_STATUS_INFO 104 +# define TS_F_TS_COMPUTE_IMPRINT 145 +# define TS_F_TS_CONF_INVALID 151 +# define TS_F_TS_CONF_LOAD_CERT 153 +# define TS_F_TS_CONF_LOAD_CERTS 154 +# define TS_F_TS_CONF_LOAD_KEY 155 +# define TS_F_TS_CONF_LOOKUP_FAIL 152 +# define TS_F_TS_CONF_SET_DEFAULT_ENGINE 146 +# define TS_F_TS_GET_STATUS_TEXT 105 +# define TS_F_TS_MSG_IMPRINT_SET_ALGO 118 +# define TS_F_TS_REQ_SET_MSG_IMPRINT 119 +# define TS_F_TS_REQ_SET_NONCE 120 +# define TS_F_TS_REQ_SET_POLICY_ID 121 +# define TS_F_TS_RESP_CREATE_RESPONSE 122 +# define TS_F_TS_RESP_CREATE_TST_INFO 123 +# define TS_F_TS_RESP_CTX_ADD_FAILURE_INFO 124 +# define TS_F_TS_RESP_CTX_ADD_MD 125 +# define TS_F_TS_RESP_CTX_ADD_POLICY 126 +# define TS_F_TS_RESP_CTX_NEW 127 +# define TS_F_TS_RESP_CTX_SET_ACCURACY 128 +# define TS_F_TS_RESP_CTX_SET_CERTS 129 +# define TS_F_TS_RESP_CTX_SET_DEF_POLICY 130 +# define TS_F_TS_RESP_CTX_SET_SIGNER_CERT 131 +# define TS_F_TS_RESP_CTX_SET_STATUS_INFO 132 +# define TS_F_TS_RESP_GET_POLICY 133 +# define TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION 134 +# define TS_F_TS_RESP_SET_STATUS_INFO 135 +# define TS_F_TS_RESP_SET_TST_INFO 150 +# define TS_F_TS_RESP_SIGN 136 +# define TS_F_TS_RESP_VERIFY_SIGNATURE 106 +# define TS_F_TS_TST_INFO_SET_ACCURACY 137 +# define TS_F_TS_TST_INFO_SET_MSG_IMPRINT 138 +# define TS_F_TS_TST_INFO_SET_NONCE 139 +# define TS_F_TS_TST_INFO_SET_POLICY_ID 140 +# define TS_F_TS_TST_INFO_SET_SERIAL 141 +# define TS_F_TS_TST_INFO_SET_TIME 142 +# define TS_F_TS_TST_INFO_SET_TSA 143 +# define TS_F_TS_VERIFY 108 +# define TS_F_TS_VERIFY_CERT 109 +# define TS_F_TS_VERIFY_CTX_NEW 144 + +/* + * TS reason codes. + */ +# define TS_R_BAD_PKCS7_TYPE 132 +# define TS_R_BAD_TYPE 133 +# define TS_R_CANNOT_LOAD_CERT 137 +# define TS_R_CANNOT_LOAD_KEY 138 +# define TS_R_CERTIFICATE_VERIFY_ERROR 100 +# define TS_R_COULD_NOT_SET_ENGINE 127 +# define TS_R_COULD_NOT_SET_TIME 115 +# define TS_R_DETACHED_CONTENT 134 +# define TS_R_ESS_ADD_SIGNING_CERT_ERROR 116 +# define TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR 139 +# define TS_R_ESS_SIGNING_CERTIFICATE_ERROR 101 +# define TS_R_INVALID_NULL_POINTER 102 +# define TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE 117 +# define TS_R_MESSAGE_IMPRINT_MISMATCH 103 +# define TS_R_NONCE_MISMATCH 104 +# define TS_R_NONCE_NOT_RETURNED 105 +# define TS_R_NO_CONTENT 106 +# define TS_R_NO_TIME_STAMP_TOKEN 107 +# define TS_R_PKCS7_ADD_SIGNATURE_ERROR 118 +# define TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR 119 +# define TS_R_PKCS7_TO_TS_TST_INFO_FAILED 129 +# define TS_R_POLICY_MISMATCH 108 +# define TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 120 +# define TS_R_RESPONSE_SETUP_ERROR 121 +# define TS_R_SIGNATURE_FAILURE 109 +# define TS_R_THERE_MUST_BE_ONE_SIGNER 110 +# define TS_R_TIME_SYSCALL_ERROR 122 +# define TS_R_TOKEN_NOT_PRESENT 130 +# define TS_R_TOKEN_PRESENT 131 +# define TS_R_TSA_NAME_MISMATCH 111 +# define TS_R_TSA_UNTRUSTED 112 +# define TS_R_TST_INFO_SETUP_ERROR 123 +# define TS_R_TS_DATASIGN 124 +# define TS_R_UNACCEPTABLE_POLICY 125 +# define TS_R_UNSUPPORTED_MD_ALGORITHM 126 +# define TS_R_UNSUPPORTED_VERSION 113 +# define TS_R_VAR_BAD_VALUE 135 +# define TS_R_VAR_LOOKUP_FAILURE 136 +# define TS_R_WRONG_CONTENT_TYPE 114 + +# endif +#endif diff --git a/include/openssl/txt_db.h b/include/openssl/txt_db.h new file mode 100644 index 0000000..c26eb1c --- /dev/null +++ b/include/openssl/txt_db.h @@ -0,0 +1,57 @@ +/* + * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_TXT_DB_H +# define HEADER_TXT_DB_H + +# include +# include +# include +# include + +# define DB_ERROR_OK 0 +# define DB_ERROR_MALLOC 1 +# define DB_ERROR_INDEX_CLASH 2 +# define DB_ERROR_INDEX_OUT_OF_RANGE 3 +# define DB_ERROR_NO_INDEX 4 +# define DB_ERROR_INSERT_INDEX_CLASH 5 +# define DB_ERROR_WRONG_NUM_FIELDS 6 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef OPENSSL_STRING *OPENSSL_PSTRING; +DEFINE_SPECIAL_STACK_OF(OPENSSL_PSTRING, OPENSSL_STRING) + +typedef struct txt_db_st { + int num_fields; + STACK_OF(OPENSSL_PSTRING) *data; + LHASH_OF(OPENSSL_STRING) **index; + int (**qual) (OPENSSL_STRING *); + long error; + long arg1; + long arg2; + OPENSSL_STRING *arg_row; +} TXT_DB; + +TXT_DB *TXT_DB_read(BIO *in, int num); +long TXT_DB_write(BIO *out, TXT_DB *db); +int TXT_DB_create_index(TXT_DB *db, int field, int (*qual) (OPENSSL_STRING *), + OPENSSL_LH_HASHFUNC hash, OPENSSL_LH_COMPFUNC cmp); +void TXT_DB_free(TXT_DB *db); +OPENSSL_STRING *TXT_DB_get_by_index(TXT_DB *db, int idx, + OPENSSL_STRING *value); +int TXT_DB_insert(TXT_DB *db, OPENSSL_STRING *value); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/openssl/ui.h b/include/openssl/ui.h new file mode 100644 index 0000000..6d0f74f --- /dev/null +++ b/include/openssl/ui.h @@ -0,0 +1,368 @@ +/* + * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_UI_H +# define HEADER_UI_H + +# include + +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# endif +# include +# include +# include +# include + +/* For compatibility reasons, the macro OPENSSL_NO_UI is currently retained */ +# if OPENSSL_API_COMPAT < 0x10200000L +# ifdef OPENSSL_NO_UI_CONSOLE +# define OPENSSL_NO_UI +# endif +# endif + +# ifdef __cplusplus +extern "C" { +# endif + +/* + * All the following functions return -1 or NULL on error and in some cases + * (UI_process()) -2 if interrupted or in some other way cancelled. When + * everything is fine, they return 0, a positive value or a non-NULL pointer, + * all depending on their purpose. + */ + +/* Creators and destructor. */ +UI *UI_new(void); +UI *UI_new_method(const UI_METHOD *method); +void UI_free(UI *ui); + +/*- + The following functions are used to add strings to be printed and prompt + strings to prompt for data. The names are UI_{add,dup}__string + and UI_{add,dup}_input_boolean. + + UI_{add,dup}__string have the following meanings: + add add a text or prompt string. The pointers given to these + functions are used verbatim, no copying is done. + dup make a copy of the text or prompt string, then add the copy + to the collection of strings in the user interface. + + The function is a name for the functionality that the given + string shall be used for. It can be one of: + input use the string as data prompt. + verify use the string as verification prompt. This + is used to verify a previous input. + info use the string for informational output. + error use the string for error output. + Honestly, there's currently no difference between info and error for the + moment. + + UI_{add,dup}_input_boolean have the same semantics for "add" and "dup", + and are typically used when one wants to prompt for a yes/no response. + + All of the functions in this group take a UI and a prompt string. + The string input and verify addition functions also take a flag argument, + a buffer for the result to end up with, a minimum input size and a maximum + input size (the result buffer MUST be large enough to be able to contain + the maximum number of characters). Additionally, the verify addition + functions takes another buffer to compare the result against. + The boolean input functions take an action description string (which should + be safe to ignore if the expected user action is obvious, for example with + a dialog box with an OK button and a Cancel button), a string of acceptable + characters to mean OK and to mean Cancel. The two last strings are checked + to make sure they don't have common characters. Additionally, the same + flag argument as for the string input is taken, as well as a result buffer. + The result buffer is required to be at least one byte long. Depending on + the answer, the first character from the OK or the Cancel character strings + will be stored in the first byte of the result buffer. No NUL will be + added, so the result is *not* a string. + + On success, the all return an index of the added information. That index + is useful when retrieving results with UI_get0_result(). */ +int UI_add_input_string(UI *ui, const char *prompt, int flags, + char *result_buf, int minsize, int maxsize); +int UI_dup_input_string(UI *ui, const char *prompt, int flags, + char *result_buf, int minsize, int maxsize); +int UI_add_verify_string(UI *ui, const char *prompt, int flags, + char *result_buf, int minsize, int maxsize, + const char *test_buf); +int UI_dup_verify_string(UI *ui, const char *prompt, int flags, + char *result_buf, int minsize, int maxsize, + const char *test_buf); +int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc, + const char *ok_chars, const char *cancel_chars, + int flags, char *result_buf); +int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc, + const char *ok_chars, const char *cancel_chars, + int flags, char *result_buf); +int UI_add_info_string(UI *ui, const char *text); +int UI_dup_info_string(UI *ui, const char *text); +int UI_add_error_string(UI *ui, const char *text); +int UI_dup_error_string(UI *ui, const char *text); + +/* These are the possible flags. They can be or'ed together. */ +/* Use to have echoing of input */ +# define UI_INPUT_FLAG_ECHO 0x01 +/* + * Use a default password. Where that password is found is completely up to + * the application, it might for example be in the user data set with + * UI_add_user_data(). It is not recommended to have more than one input in + * each UI being marked with this flag, or the application might get + * confused. + */ +# define UI_INPUT_FLAG_DEFAULT_PWD 0x02 + +/*- + * The user of these routines may want to define flags of their own. The core + * UI won't look at those, but will pass them on to the method routines. They + * must use higher bits so they don't get confused with the UI bits above. + * UI_INPUT_FLAG_USER_BASE tells which is the lowest bit to use. A good + * example of use is this: + * + * #define MY_UI_FLAG1 (0x01 << UI_INPUT_FLAG_USER_BASE) + * +*/ +# define UI_INPUT_FLAG_USER_BASE 16 + +/*- + * The following function helps construct a prompt. object_desc is a + * textual short description of the object, for example "pass phrase", + * and object_name is the name of the object (might be a card name or + * a file name. + * The returned string shall always be allocated on the heap with + * OPENSSL_malloc(), and need to be free'd with OPENSSL_free(). + * + * If the ui_method doesn't contain a pointer to a user-defined prompt + * constructor, a default string is built, looking like this: + * + * "Enter {object_desc} for {object_name}:" + * + * So, if object_desc has the value "pass phrase" and object_name has + * the value "foo.key", the resulting string is: + * + * "Enter pass phrase for foo.key:" +*/ +char *UI_construct_prompt(UI *ui_method, + const char *object_desc, const char *object_name); + +/* + * The following function is used to store a pointer to user-specific data. + * Any previous such pointer will be returned and replaced. + * + * For callback purposes, this function makes a lot more sense than using + * ex_data, since the latter requires that different parts of OpenSSL or + * applications share the same ex_data index. + * + * Note that the UI_OpenSSL() method completely ignores the user data. Other + * methods may not, however. + */ +void *UI_add_user_data(UI *ui, void *user_data); +/* + * Alternatively, this function is used to duplicate the user data. + * This uses the duplicator method function. The destroy function will + * be used to free the user data in this case. + */ +int UI_dup_user_data(UI *ui, void *user_data); +/* We need a user data retrieving function as well. */ +void *UI_get0_user_data(UI *ui); + +/* Return the result associated with a prompt given with the index i. */ +const char *UI_get0_result(UI *ui, int i); +int UI_get_result_length(UI *ui, int i); + +/* When all strings have been added, process the whole thing. */ +int UI_process(UI *ui); + +/* + * Give a user interface parameterised control commands. This can be used to + * send down an integer, a data pointer or a function pointer, as well as be + * used to get information from a UI. + */ +int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f) (void)); + +/* The commands */ +/* + * Use UI_CONTROL_PRINT_ERRORS with the value 1 to have UI_process print the + * OpenSSL error stack before printing any info or added error messages and + * before any prompting. + */ +# define UI_CTRL_PRINT_ERRORS 1 +/* + * Check if a UI_process() is possible to do again with the same instance of + * a user interface. This makes UI_ctrl() return 1 if it is redoable, and 0 + * if not. + */ +# define UI_CTRL_IS_REDOABLE 2 + +/* Some methods may use extra data */ +# define UI_set_app_data(s,arg) UI_set_ex_data(s,0,arg) +# define UI_get_app_data(s) UI_get_ex_data(s,0) + +# define UI_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, l, p, newf, dupf, freef) +int UI_set_ex_data(UI *r, int idx, void *arg); +void *UI_get_ex_data(UI *r, int idx); + +/* Use specific methods instead of the built-in one */ +void UI_set_default_method(const UI_METHOD *meth); +const UI_METHOD *UI_get_default_method(void); +const UI_METHOD *UI_get_method(UI *ui); +const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth); + +# ifndef OPENSSL_NO_UI_CONSOLE + +/* The method with all the built-in thingies */ +UI_METHOD *UI_OpenSSL(void); + +# endif + +/* + * NULL method. Literally does nothing, but may serve as a placeholder + * to avoid internal default. + */ +const UI_METHOD *UI_null(void); + +/* ---------- For method writers ---------- */ +/*- + A method contains a number of functions that implement the low level + of the User Interface. The functions are: + + an opener This function starts a session, maybe by opening + a channel to a tty, or by opening a window. + a writer This function is called to write a given string, + maybe to the tty, maybe as a field label in a + window. + a flusher This function is called to flush everything that + has been output so far. It can be used to actually + display a dialog box after it has been built. + a reader This function is called to read a given prompt, + maybe from the tty, maybe from a field in a + window. Note that it's called with all string + structures, not only the prompt ones, so it must + check such things itself. + a closer This function closes the session, maybe by closing + the channel to the tty, or closing the window. + + All these functions are expected to return: + + 0 on error. + 1 on success. + -1 on out-of-band events, for example if some prompting has + been canceled (by pressing Ctrl-C, for example). This is + only checked when returned by the flusher or the reader. + + The way this is used, the opener is first called, then the writer for all + strings, then the flusher, then the reader for all strings and finally the + closer. Note that if you want to prompt from a terminal or other command + line interface, the best is to have the reader also write the prompts + instead of having the writer do it. If you want to prompt from a dialog + box, the writer can be used to build up the contents of the box, and the + flusher to actually display the box and run the event loop until all data + has been given, after which the reader only grabs the given data and puts + them back into the UI strings. + + All method functions take a UI as argument. Additionally, the writer and + the reader take a UI_STRING. +*/ + +/* + * The UI_STRING type is the data structure that contains all the needed info + * about a string or a prompt, including test data for a verification prompt. + */ +typedef struct ui_string_st UI_STRING; +DEFINE_STACK_OF(UI_STRING) + +/* + * The different types of strings that are currently supported. This is only + * needed by method authors. + */ +enum UI_string_types { + UIT_NONE = 0, + UIT_PROMPT, /* Prompt for a string */ + UIT_VERIFY, /* Prompt for a string and verify */ + UIT_BOOLEAN, /* Prompt for a yes/no response */ + UIT_INFO, /* Send info to the user */ + UIT_ERROR /* Send an error message to the user */ +}; + +/* Create and manipulate methods */ +UI_METHOD *UI_create_method(const char *name); +void UI_destroy_method(UI_METHOD *ui_method); +int UI_method_set_opener(UI_METHOD *method, int (*opener) (UI *ui)); +int UI_method_set_writer(UI_METHOD *method, + int (*writer) (UI *ui, UI_STRING *uis)); +int UI_method_set_flusher(UI_METHOD *method, int (*flusher) (UI *ui)); +int UI_method_set_reader(UI_METHOD *method, + int (*reader) (UI *ui, UI_STRING *uis)); +int UI_method_set_closer(UI_METHOD *method, int (*closer) (UI *ui)); +int UI_method_set_data_duplicator(UI_METHOD *method, + void *(*duplicator) (UI *ui, void *ui_data), + void (*destructor)(UI *ui, void *ui_data)); +int UI_method_set_prompt_constructor(UI_METHOD *method, + char *(*prompt_constructor) (UI *ui, + const char + *object_desc, + const char + *object_name)); +int UI_method_set_ex_data(UI_METHOD *method, int idx, void *data); +int (*UI_method_get_opener(const UI_METHOD *method)) (UI *); +int (*UI_method_get_writer(const UI_METHOD *method)) (UI *, UI_STRING *); +int (*UI_method_get_flusher(const UI_METHOD *method)) (UI *); +int (*UI_method_get_reader(const UI_METHOD *method)) (UI *, UI_STRING *); +int (*UI_method_get_closer(const UI_METHOD *method)) (UI *); +char *(*UI_method_get_prompt_constructor(const UI_METHOD *method)) + (UI *, const char *, const char *); +void *(*UI_method_get_data_duplicator(const UI_METHOD *method)) (UI *, void *); +void (*UI_method_get_data_destructor(const UI_METHOD *method)) (UI *, void *); +const void *UI_method_get_ex_data(const UI_METHOD *method, int idx); + +/* + * The following functions are helpers for method writers to access relevant + * data from a UI_STRING. + */ + +/* Return type of the UI_STRING */ +enum UI_string_types UI_get_string_type(UI_STRING *uis); +/* Return input flags of the UI_STRING */ +int UI_get_input_flags(UI_STRING *uis); +/* Return the actual string to output (the prompt, info or error) */ +const char *UI_get0_output_string(UI_STRING *uis); +/* + * Return the optional action string to output (the boolean prompt + * instruction) + */ +const char *UI_get0_action_string(UI_STRING *uis); +/* Return the result of a prompt */ +const char *UI_get0_result_string(UI_STRING *uis); +int UI_get_result_string_length(UI_STRING *uis); +/* + * Return the string to test the result against. Only useful with verifies. + */ +const char *UI_get0_test_string(UI_STRING *uis); +/* Return the required minimum size of the result */ +int UI_get_result_minsize(UI_STRING *uis); +/* Return the required maximum size of the result */ +int UI_get_result_maxsize(UI_STRING *uis); +/* Set the result of a UI_STRING. */ +int UI_set_result(UI *ui, UI_STRING *uis, const char *result); +int UI_set_result_ex(UI *ui, UI_STRING *uis, const char *result, int len); + +/* A couple of popular utility functions */ +int UI_UTIL_read_pw_string(char *buf, int length, const char *prompt, + int verify); +int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt, + int verify); +UI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag); + + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/uierr.h b/include/openssl/uierr.h new file mode 100644 index 0000000..72fd9a9 --- /dev/null +++ b/include/openssl/uierr.h @@ -0,0 +1,61 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_UIERR_H +# define HEADER_UIERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_UI_strings(void); + +/* + * UI function codes. + */ +# define UI_F_CLOSE_CONSOLE 115 +# define UI_F_ECHO_CONSOLE 116 +# define UI_F_GENERAL_ALLOCATE_BOOLEAN 108 +# define UI_F_GENERAL_ALLOCATE_PROMPT 109 +# define UI_F_NOECHO_CONSOLE 117 +# define UI_F_OPEN_CONSOLE 114 +# define UI_F_UI_CONSTRUCT_PROMPT 121 +# define UI_F_UI_CREATE_METHOD 112 +# define UI_F_UI_CTRL 111 +# define UI_F_UI_DUP_ERROR_STRING 101 +# define UI_F_UI_DUP_INFO_STRING 102 +# define UI_F_UI_DUP_INPUT_BOOLEAN 110 +# define UI_F_UI_DUP_INPUT_STRING 103 +# define UI_F_UI_DUP_USER_DATA 118 +# define UI_F_UI_DUP_VERIFY_STRING 106 +# define UI_F_UI_GET0_RESULT 107 +# define UI_F_UI_GET_RESULT_LENGTH 119 +# define UI_F_UI_NEW_METHOD 104 +# define UI_F_UI_PROCESS 113 +# define UI_F_UI_SET_RESULT 105 +# define UI_F_UI_SET_RESULT_EX 120 + +/* + * UI reason codes. + */ +# define UI_R_COMMON_OK_AND_CANCEL_CHARACTERS 104 +# define UI_R_INDEX_TOO_LARGE 102 +# define UI_R_INDEX_TOO_SMALL 103 +# define UI_R_NO_RESULT_BUFFER 105 +# define UI_R_PROCESSING_ERROR 107 +# define UI_R_RESULT_TOO_LARGE 100 +# define UI_R_RESULT_TOO_SMALL 101 +# define UI_R_SYSASSIGN_ERROR 109 +# define UI_R_SYSDASSGN_ERROR 110 +# define UI_R_SYSQIOW_ERROR 111 +# define UI_R_UNKNOWN_CONTROL_COMMAND 106 +# define UI_R_UNKNOWN_TTYGET_ERRNO_VALUE 108 +# define UI_R_USER_DATA_DUPLICATION_UNSUPPORTED 112 + +#endif diff --git a/include/openssl/whrlpool.h b/include/openssl/whrlpool.h new file mode 100644 index 0000000..cde6664 --- /dev/null +++ b/include/openssl/whrlpool.h @@ -0,0 +1,48 @@ +/* + * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_WHRLPOOL_H +# define HEADER_WHRLPOOL_H + +#include + +# ifndef OPENSSL_NO_WHIRLPOOL +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +# define WHIRLPOOL_DIGEST_LENGTH (512/8) +# define WHIRLPOOL_BBLOCK 512 +# define WHIRLPOOL_COUNTER (256/8) + +typedef struct { + union { + unsigned char c[WHIRLPOOL_DIGEST_LENGTH]; + /* double q is here to ensure 64-bit alignment */ + double q[WHIRLPOOL_DIGEST_LENGTH / sizeof(double)]; + } H; + unsigned char data[WHIRLPOOL_BBLOCK / 8]; + unsigned int bitoff; + size_t bitlen[WHIRLPOOL_COUNTER / sizeof(size_t)]; +} WHIRLPOOL_CTX; + +int WHIRLPOOL_Init(WHIRLPOOL_CTX *c); +int WHIRLPOOL_Update(WHIRLPOOL_CTX *c, const void *inp, size_t bytes); +void WHIRLPOOL_BitUpdate(WHIRLPOOL_CTX *c, const void *inp, size_t bits); +int WHIRLPOOL_Final(unsigned char *md, WHIRLPOOL_CTX *c); +unsigned char *WHIRLPOOL(const void *inp, size_t bytes, unsigned char *md); + +# ifdef __cplusplus +} +# endif +# endif + +#endif diff --git a/include/openssl/x509.h b/include/openssl/x509.h new file mode 100644 index 0000000..07f22d7 --- /dev/null +++ b/include/openssl/x509.h @@ -0,0 +1,1047 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_X509_H +# define HEADER_X509_H + +# include +# include +# include +# include +# include +# include +# include +# include +# include + +# if OPENSSL_API_COMPAT < 0x10100000L +# include +# include +# include +# endif + +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Flags for X509_get_signature_info() */ +/* Signature info is valid */ +# define X509_SIG_INFO_VALID 0x1 +/* Signature is suitable for TLS use */ +# define X509_SIG_INFO_TLS 0x2 + +# define X509_FILETYPE_PEM 1 +# define X509_FILETYPE_ASN1 2 +# define X509_FILETYPE_DEFAULT 3 + +# define X509v3_KU_DIGITAL_SIGNATURE 0x0080 +# define X509v3_KU_NON_REPUDIATION 0x0040 +# define X509v3_KU_KEY_ENCIPHERMENT 0x0020 +# define X509v3_KU_DATA_ENCIPHERMENT 0x0010 +# define X509v3_KU_KEY_AGREEMENT 0x0008 +# define X509v3_KU_KEY_CERT_SIGN 0x0004 +# define X509v3_KU_CRL_SIGN 0x0002 +# define X509v3_KU_ENCIPHER_ONLY 0x0001 +# define X509v3_KU_DECIPHER_ONLY 0x8000 +# define X509v3_KU_UNDEF 0xffff + +struct X509_algor_st { + ASN1_OBJECT *algorithm; + ASN1_TYPE *parameter; +} /* X509_ALGOR */ ; + +typedef STACK_OF(X509_ALGOR) X509_ALGORS; + +typedef struct X509_val_st { + ASN1_TIME *notBefore; + ASN1_TIME *notAfter; +} X509_VAL; + +typedef struct X509_sig_st X509_SIG; + +typedef struct X509_name_entry_st X509_NAME_ENTRY; + +DEFINE_STACK_OF(X509_NAME_ENTRY) + +DEFINE_STACK_OF(X509_NAME) + +# define X509_EX_V_NETSCAPE_HACK 0x8000 +# define X509_EX_V_INIT 0x0001 +typedef struct X509_extension_st X509_EXTENSION; + +typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS; + +DEFINE_STACK_OF(X509_EXTENSION) + +typedef struct x509_attributes_st X509_ATTRIBUTE; + +DEFINE_STACK_OF(X509_ATTRIBUTE) + +typedef struct X509_req_info_st X509_REQ_INFO; + +typedef struct X509_req_st X509_REQ; + +typedef struct x509_cert_aux_st X509_CERT_AUX; + +typedef struct x509_cinf_st X509_CINF; + +DEFINE_STACK_OF(X509) + +/* This is used for a table of trust checking functions */ + +typedef struct x509_trust_st { + int trust; + int flags; + int (*check_trust) (struct x509_trust_st *, X509 *, int); + char *name; + int arg1; + void *arg2; +} X509_TRUST; + +DEFINE_STACK_OF(X509_TRUST) + +/* standard trust ids */ + +# define X509_TRUST_DEFAULT 0 /* Only valid in purpose settings */ + +# define X509_TRUST_COMPAT 1 +# define X509_TRUST_SSL_CLIENT 2 +# define X509_TRUST_SSL_SERVER 3 +# define X509_TRUST_EMAIL 4 +# define X509_TRUST_OBJECT_SIGN 5 +# define X509_TRUST_OCSP_SIGN 6 +# define X509_TRUST_OCSP_REQUEST 7 +# define X509_TRUST_TSA 8 + +/* Keep these up to date! */ +# define X509_TRUST_MIN 1 +# define X509_TRUST_MAX 8 + +/* trust_flags values */ +# define X509_TRUST_DYNAMIC (1U << 0) +# define X509_TRUST_DYNAMIC_NAME (1U << 1) +/* No compat trust if self-signed, preempts "DO_SS" */ +# define X509_TRUST_NO_SS_COMPAT (1U << 2) +/* Compat trust if no explicit accepted trust EKUs */ +# define X509_TRUST_DO_SS_COMPAT (1U << 3) +/* Accept "anyEKU" as a wildcard trust OID */ +# define X509_TRUST_OK_ANY_EKU (1U << 4) + +/* check_trust return codes */ + +# define X509_TRUST_TRUSTED 1 +# define X509_TRUST_REJECTED 2 +# define X509_TRUST_UNTRUSTED 3 + +/* Flags for X509_print_ex() */ + +# define X509_FLAG_COMPAT 0 +# define X509_FLAG_NO_HEADER 1L +# define X509_FLAG_NO_VERSION (1L << 1) +# define X509_FLAG_NO_SERIAL (1L << 2) +# define X509_FLAG_NO_SIGNAME (1L << 3) +# define X509_FLAG_NO_ISSUER (1L << 4) +# define X509_FLAG_NO_VALIDITY (1L << 5) +# define X509_FLAG_NO_SUBJECT (1L << 6) +# define X509_FLAG_NO_PUBKEY (1L << 7) +# define X509_FLAG_NO_EXTENSIONS (1L << 8) +# define X509_FLAG_NO_SIGDUMP (1L << 9) +# define X509_FLAG_NO_AUX (1L << 10) +# define X509_FLAG_NO_ATTRIBUTES (1L << 11) +# define X509_FLAG_NO_IDS (1L << 12) + +/* Flags specific to X509_NAME_print_ex() */ + +/* The field separator information */ + +# define XN_FLAG_SEP_MASK (0xf << 16) + +# define XN_FLAG_COMPAT 0/* Traditional; use old X509_NAME_print */ +# define XN_FLAG_SEP_COMMA_PLUS (1 << 16)/* RFC2253 ,+ */ +# define XN_FLAG_SEP_CPLUS_SPC (2 << 16)/* ,+ spaced: more readable */ +# define XN_FLAG_SEP_SPLUS_SPC (3 << 16)/* ;+ spaced */ +# define XN_FLAG_SEP_MULTILINE (4 << 16)/* One line per field */ + +# define XN_FLAG_DN_REV (1 << 20)/* Reverse DN order */ + +/* How the field name is shown */ + +# define XN_FLAG_FN_MASK (0x3 << 21) + +# define XN_FLAG_FN_SN 0/* Object short name */ +# define XN_FLAG_FN_LN (1 << 21)/* Object long name */ +# define XN_FLAG_FN_OID (2 << 21)/* Always use OIDs */ +# define XN_FLAG_FN_NONE (3 << 21)/* No field names */ + +# define XN_FLAG_SPC_EQ (1 << 23)/* Put spaces round '=' */ + +/* + * This determines if we dump fields we don't recognise: RFC2253 requires + * this. + */ + +# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24) + +# define XN_FLAG_FN_ALIGN (1 << 25)/* Align field names to 20 + * characters */ + +/* Complete set of RFC2253 flags */ + +# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \ + XN_FLAG_SEP_COMMA_PLUS | \ + XN_FLAG_DN_REV | \ + XN_FLAG_FN_SN | \ + XN_FLAG_DUMP_UNKNOWN_FIELDS) + +/* readable oneline form */ + +# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \ + ASN1_STRFLGS_ESC_QUOTE | \ + XN_FLAG_SEP_CPLUS_SPC | \ + XN_FLAG_SPC_EQ | \ + XN_FLAG_FN_SN) + +/* readable multiline form */ + +# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \ + ASN1_STRFLGS_ESC_MSB | \ + XN_FLAG_SEP_MULTILINE | \ + XN_FLAG_SPC_EQ | \ + XN_FLAG_FN_LN | \ + XN_FLAG_FN_ALIGN) + +DEFINE_STACK_OF(X509_REVOKED) + +typedef struct X509_crl_info_st X509_CRL_INFO; + +DEFINE_STACK_OF(X509_CRL) + +typedef struct private_key_st { + int version; + /* The PKCS#8 data types */ + X509_ALGOR *enc_algor; + ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */ + /* When decrypted, the following will not be NULL */ + EVP_PKEY *dec_pkey; + /* used to encrypt and decrypt */ + int key_length; + char *key_data; + int key_free; /* true if we should auto free key_data */ + /* expanded version of 'enc_algor' */ + EVP_CIPHER_INFO cipher; +} X509_PKEY; + +typedef struct X509_info_st { + X509 *x509; + X509_CRL *crl; + X509_PKEY *x_pkey; + EVP_CIPHER_INFO enc_cipher; + int enc_len; + char *enc_data; +} X509_INFO; + +DEFINE_STACK_OF(X509_INFO) + +/* + * The next 2 structures and their 8 routines are used to manipulate Netscape's + * spki structures - useful if you are writing a CA web page + */ +typedef struct Netscape_spkac_st { + X509_PUBKEY *pubkey; + ASN1_IA5STRING *challenge; /* challenge sent in atlas >= PR2 */ +} NETSCAPE_SPKAC; + +typedef struct Netscape_spki_st { + NETSCAPE_SPKAC *spkac; /* signed public key and challenge */ + X509_ALGOR sig_algor; + ASN1_BIT_STRING *signature; +} NETSCAPE_SPKI; + +/* Netscape certificate sequence structure */ +typedef struct Netscape_certificate_sequence { + ASN1_OBJECT *type; + STACK_OF(X509) *certs; +} NETSCAPE_CERT_SEQUENCE; + +/*- Unused (and iv length is wrong) +typedef struct CBCParameter_st + { + unsigned char iv[8]; + } CBC_PARAM; +*/ + +/* Password based encryption structure */ + +typedef struct PBEPARAM_st { + ASN1_OCTET_STRING *salt; + ASN1_INTEGER *iter; +} PBEPARAM; + +/* Password based encryption V2 structures */ + +typedef struct PBE2PARAM_st { + X509_ALGOR *keyfunc; + X509_ALGOR *encryption; +} PBE2PARAM; + +typedef struct PBKDF2PARAM_st { +/* Usually OCTET STRING but could be anything */ + ASN1_TYPE *salt; + ASN1_INTEGER *iter; + ASN1_INTEGER *keylength; + X509_ALGOR *prf; +} PBKDF2PARAM; + +#ifndef OPENSSL_NO_SCRYPT +typedef struct SCRYPT_PARAMS_st { + ASN1_OCTET_STRING *salt; + ASN1_INTEGER *costParameter; + ASN1_INTEGER *blockSize; + ASN1_INTEGER *parallelizationParameter; + ASN1_INTEGER *keyLength; +} SCRYPT_PARAMS; +#endif + +#ifdef __cplusplus +} +#endif + +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +# define X509_EXT_PACK_UNKNOWN 1 +# define X509_EXT_PACK_STRING 2 + +# define X509_extract_key(x) X509_get_pubkey(x)/*****/ +# define X509_REQ_extract_key(a) X509_REQ_get_pubkey(a) +# define X509_name_cmp(a,b) X509_NAME_cmp((a),(b)) + +void X509_CRL_set_default_method(const X509_CRL_METHOD *meth); +X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl), + int (*crl_free) (X509_CRL *crl), + int (*crl_lookup) (X509_CRL *crl, + X509_REVOKED **ret, + ASN1_INTEGER *ser, + X509_NAME *issuer), + int (*crl_verify) (X509_CRL *crl, + EVP_PKEY *pk)); +void X509_CRL_METHOD_free(X509_CRL_METHOD *m); + +void X509_CRL_set_meth_data(X509_CRL *crl, void *dat); +void *X509_CRL_get_meth_data(X509_CRL *crl); + +const char *X509_verify_cert_error_string(long n); + +int X509_verify(X509 *a, EVP_PKEY *r); + +int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r); +int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r); +int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r); + +NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len); +char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x); +EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x); +int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey); + +int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki); + +int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent); +int X509_signature_print(BIO *bp, const X509_ALGOR *alg, + const ASN1_STRING *sig); + +int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md); +int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx); +# ifndef OPENSSL_NO_OCSP +int X509_http_nbio(OCSP_REQ_CTX *rctx, X509 **pcert); +# endif +int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md); +int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx); +int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md); +int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx); +# ifndef OPENSSL_NO_OCSP +int X509_CRL_http_nbio(OCSP_REQ_CTX *rctx, X509_CRL **pcrl); +# endif +int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md); + +int X509_pubkey_digest(const X509 *data, const EVP_MD *type, + unsigned char *md, unsigned int *len); +int X509_digest(const X509 *data, const EVP_MD *type, + unsigned char *md, unsigned int *len); +int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type, + unsigned char *md, unsigned int *len); +int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type, + unsigned char *md, unsigned int *len); +int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type, + unsigned char *md, unsigned int *len); + +# ifndef OPENSSL_NO_STDIO +X509 *d2i_X509_fp(FILE *fp, X509 **x509); +int i2d_X509_fp(FILE *fp, X509 *x509); +X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl); +int i2d_X509_CRL_fp(FILE *fp, X509_CRL *crl); +X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req); +int i2d_X509_REQ_fp(FILE *fp, X509_REQ *req); +# ifndef OPENSSL_NO_RSA +RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa); +int i2d_RSAPrivateKey_fp(FILE *fp, RSA *rsa); +RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa); +int i2d_RSAPublicKey_fp(FILE *fp, RSA *rsa); +RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa); +int i2d_RSA_PUBKEY_fp(FILE *fp, RSA *rsa); +# endif +# ifndef OPENSSL_NO_DSA +DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa); +int i2d_DSA_PUBKEY_fp(FILE *fp, DSA *dsa); +DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa); +int i2d_DSAPrivateKey_fp(FILE *fp, DSA *dsa); +# endif +# ifndef OPENSSL_NO_EC +EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey); +int i2d_EC_PUBKEY_fp(FILE *fp, EC_KEY *eckey); +EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey); +int i2d_ECPrivateKey_fp(FILE *fp, EC_KEY *eckey); +# endif +X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8); +int i2d_PKCS8_fp(FILE *fp, X509_SIG *p8); +PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, + PKCS8_PRIV_KEY_INFO **p8inf); +int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, PKCS8_PRIV_KEY_INFO *p8inf); +int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, EVP_PKEY *key); +int i2d_PrivateKey_fp(FILE *fp, EVP_PKEY *pkey); +EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a); +int i2d_PUBKEY_fp(FILE *fp, EVP_PKEY *pkey); +EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a); +# endif + +X509 *d2i_X509_bio(BIO *bp, X509 **x509); +int i2d_X509_bio(BIO *bp, X509 *x509); +X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl); +int i2d_X509_CRL_bio(BIO *bp, X509_CRL *crl); +X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req); +int i2d_X509_REQ_bio(BIO *bp, X509_REQ *req); +# ifndef OPENSSL_NO_RSA +RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa); +int i2d_RSAPrivateKey_bio(BIO *bp, RSA *rsa); +RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa); +int i2d_RSAPublicKey_bio(BIO *bp, RSA *rsa); +RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa); +int i2d_RSA_PUBKEY_bio(BIO *bp, RSA *rsa); +# endif +# ifndef OPENSSL_NO_DSA +DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa); +int i2d_DSA_PUBKEY_bio(BIO *bp, DSA *dsa); +DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa); +int i2d_DSAPrivateKey_bio(BIO *bp, DSA *dsa); +# endif +# ifndef OPENSSL_NO_EC +EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey); +int i2d_EC_PUBKEY_bio(BIO *bp, EC_KEY *eckey); +EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey); +int i2d_ECPrivateKey_bio(BIO *bp, EC_KEY *eckey); +# endif +X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8); +int i2d_PKCS8_bio(BIO *bp, X509_SIG *p8); +PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, + PKCS8_PRIV_KEY_INFO **p8inf); +int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, PKCS8_PRIV_KEY_INFO *p8inf); +int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, EVP_PKEY *key); +int i2d_PrivateKey_bio(BIO *bp, EVP_PKEY *pkey); +EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a); +int i2d_PUBKEY_bio(BIO *bp, EVP_PKEY *pkey); +EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a); + +X509 *X509_dup(X509 *x509); +X509_ATTRIBUTE *X509_ATTRIBUTE_dup(X509_ATTRIBUTE *xa); +X509_EXTENSION *X509_EXTENSION_dup(X509_EXTENSION *ex); +X509_CRL *X509_CRL_dup(X509_CRL *crl); +X509_REVOKED *X509_REVOKED_dup(X509_REVOKED *rev); +X509_REQ *X509_REQ_dup(X509_REQ *req); +X509_ALGOR *X509_ALGOR_dup(X509_ALGOR *xn); +int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype, + void *pval); +void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype, + const void **ppval, const X509_ALGOR *algor); +void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md); +int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b); + +X509_NAME *X509_NAME_dup(X509_NAME *xn); +X509_NAME_ENTRY *X509_NAME_ENTRY_dup(X509_NAME_ENTRY *ne); + +int X509_cmp_time(const ASN1_TIME *s, time_t *t); +int X509_cmp_current_time(const ASN1_TIME *s); +ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t); +ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s, + int offset_day, long offset_sec, time_t *t); +ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj); + +const char *X509_get_default_cert_area(void); +const char *X509_get_default_cert_dir(void); +const char *X509_get_default_cert_file(void); +const char *X509_get_default_cert_dir_env(void); +const char *X509_get_default_cert_file_env(void); +const char *X509_get_default_private_dir(void); + +X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md); +X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey); + +DECLARE_ASN1_FUNCTIONS(X509_ALGOR) +DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS) +DECLARE_ASN1_FUNCTIONS(X509_VAL) + +DECLARE_ASN1_FUNCTIONS(X509_PUBKEY) + +int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey); +EVP_PKEY *X509_PUBKEY_get0(X509_PUBKEY *key); +EVP_PKEY *X509_PUBKEY_get(X509_PUBKEY *key); +int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain); +long X509_get_pathlen(X509 *x); +int i2d_PUBKEY(EVP_PKEY *a, unsigned char **pp); +EVP_PKEY *d2i_PUBKEY(EVP_PKEY **a, const unsigned char **pp, long length); +# ifndef OPENSSL_NO_RSA +int i2d_RSA_PUBKEY(RSA *a, unsigned char **pp); +RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length); +# endif +# ifndef OPENSSL_NO_DSA +int i2d_DSA_PUBKEY(DSA *a, unsigned char **pp); +DSA *d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length); +# endif +# ifndef OPENSSL_NO_EC +int i2d_EC_PUBKEY(EC_KEY *a, unsigned char **pp); +EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length); +# endif + +DECLARE_ASN1_FUNCTIONS(X509_SIG) +void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg, + const ASN1_OCTET_STRING **pdigest); +void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg, + ASN1_OCTET_STRING **pdigest); + +DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO) +DECLARE_ASN1_FUNCTIONS(X509_REQ) + +DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE) +X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value); + +DECLARE_ASN1_FUNCTIONS(X509_EXTENSION) +DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS) + +DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY) + +DECLARE_ASN1_FUNCTIONS(X509_NAME) + +int X509_NAME_set(X509_NAME **xn, X509_NAME *name); + +DECLARE_ASN1_FUNCTIONS(X509_CINF) + +DECLARE_ASN1_FUNCTIONS(X509) +DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX) + +#define X509_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef) +int X509_set_ex_data(X509 *r, int idx, void *arg); +void *X509_get_ex_data(X509 *r, int idx); +int i2d_X509_AUX(X509 *a, unsigned char **pp); +X509 *d2i_X509_AUX(X509 **a, const unsigned char **pp, long length); + +int i2d_re_X509_tbs(X509 *x, unsigned char **pp); + +int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid, + int *secbits, uint32_t *flags); +void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid, + int secbits, uint32_t flags); + +int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits, + uint32_t *flags); + +void X509_get0_signature(const ASN1_BIT_STRING **psig, + const X509_ALGOR **palg, const X509 *x); +int X509_get_signature_nid(const X509 *x); + +int X509_trusted(const X509 *x); +int X509_alias_set1(X509 *x, const unsigned char *name, int len); +int X509_keyid_set1(X509 *x, const unsigned char *id, int len); +unsigned char *X509_alias_get0(X509 *x, int *len); +unsigned char *X509_keyid_get0(X509 *x, int *len); +int (*X509_TRUST_set_default(int (*trust) (int, X509 *, int))) (int, X509 *, + int); +int X509_TRUST_set(int *t, int trust); +int X509_add1_trust_object(X509 *x, const ASN1_OBJECT *obj); +int X509_add1_reject_object(X509 *x, const ASN1_OBJECT *obj); +void X509_trust_clear(X509 *x); +void X509_reject_clear(X509 *x); + +STACK_OF(ASN1_OBJECT) *X509_get0_trust_objects(X509 *x); +STACK_OF(ASN1_OBJECT) *X509_get0_reject_objects(X509 *x); + +DECLARE_ASN1_FUNCTIONS(X509_REVOKED) +DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO) +DECLARE_ASN1_FUNCTIONS(X509_CRL) + +int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev); +int X509_CRL_get0_by_serial(X509_CRL *crl, + X509_REVOKED **ret, ASN1_INTEGER *serial); +int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x); + +X509_PKEY *X509_PKEY_new(void); +void X509_PKEY_free(X509_PKEY *a); + +DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI) +DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC) +DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE) + +X509_INFO *X509_INFO_new(void); +void X509_INFO_free(X509_INFO *a); +char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size); + +int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1, + ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey); + +int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data, + unsigned char *md, unsigned int *len); + +int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, + X509_ALGOR *algor2, ASN1_BIT_STRING *signature, + char *data, EVP_PKEY *pkey, const EVP_MD *type); + +int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data, + unsigned char *md, unsigned int *len); + +int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *algor1, + ASN1_BIT_STRING *signature, void *data, EVP_PKEY *pkey); + +int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, + X509_ALGOR *algor2, ASN1_BIT_STRING *signature, void *data, + EVP_PKEY *pkey, const EVP_MD *type); +int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1, + X509_ALGOR *algor2, ASN1_BIT_STRING *signature, + void *asn, EVP_MD_CTX *ctx); + +long X509_get_version(const X509 *x); +int X509_set_version(X509 *x, long version); +int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial); +ASN1_INTEGER *X509_get_serialNumber(X509 *x); +const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x); +int X509_set_issuer_name(X509 *x, X509_NAME *name); +X509_NAME *X509_get_issuer_name(const X509 *a); +int X509_set_subject_name(X509 *x, X509_NAME *name); +X509_NAME *X509_get_subject_name(const X509 *a); +const ASN1_TIME * X509_get0_notBefore(const X509 *x); +ASN1_TIME *X509_getm_notBefore(const X509 *x); +int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm); +const ASN1_TIME *X509_get0_notAfter(const X509 *x); +ASN1_TIME *X509_getm_notAfter(const X509 *x); +int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm); +int X509_set_pubkey(X509 *x, EVP_PKEY *pkey); +int X509_up_ref(X509 *x); +int X509_get_signature_type(const X509 *x); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define X509_get_notBefore X509_getm_notBefore +# define X509_get_notAfter X509_getm_notAfter +# define X509_set_notBefore X509_set1_notBefore +# define X509_set_notAfter X509_set1_notAfter +#endif + + +/* + * This one is only used so that a binary form can output, as in + * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf) + */ +X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x); +const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x); +void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid, + const ASN1_BIT_STRING **psuid); +const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x); + +EVP_PKEY *X509_get0_pubkey(const X509 *x); +EVP_PKEY *X509_get_pubkey(X509 *x); +ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x); +int X509_certificate_type(const X509 *x, const EVP_PKEY *pubkey); + +long X509_REQ_get_version(const X509_REQ *req); +int X509_REQ_set_version(X509_REQ *x, long version); +X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req); +int X509_REQ_set_subject_name(X509_REQ *req, X509_NAME *name); +void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig, + const X509_ALGOR **palg); +int X509_REQ_get_signature_nid(const X509_REQ *req); +int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp); +int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey); +EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req); +EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req); +X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req); +int X509_REQ_extension_nid(int nid); +int *X509_REQ_get_extension_nids(void); +void X509_REQ_set_extension_nids(int *nids); +STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req); +int X509_REQ_add_extensions_nid(X509_REQ *req, STACK_OF(X509_EXTENSION) *exts, + int nid); +int X509_REQ_add_extensions(X509_REQ *req, STACK_OF(X509_EXTENSION) *exts); +int X509_REQ_get_attr_count(const X509_REQ *req); +int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos); +int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc); +X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc); +int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr); +int X509_REQ_add1_attr_by_OBJ(X509_REQ *req, + const ASN1_OBJECT *obj, int type, + const unsigned char *bytes, int len); +int X509_REQ_add1_attr_by_NID(X509_REQ *req, + int nid, int type, + const unsigned char *bytes, int len); +int X509_REQ_add1_attr_by_txt(X509_REQ *req, + const char *attrname, int type, + const unsigned char *bytes, int len); + +int X509_CRL_set_version(X509_CRL *x, long version); +int X509_CRL_set_issuer_name(X509_CRL *x, X509_NAME *name); +int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm); +int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm); +int X509_CRL_sort(X509_CRL *crl); +int X509_CRL_up_ref(X509_CRL *crl); + +# if OPENSSL_API_COMPAT < 0x10100000L +# define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate +# define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate +#endif + +long X509_CRL_get_version(const X509_CRL *crl); +const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl); +const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl); +DEPRECATEDIN_1_1_0(ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl)) +DEPRECATEDIN_1_1_0(ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl)) +X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl); +const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl); +STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl); +void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig, + const X509_ALGOR **palg); +int X509_CRL_get_signature_nid(const X509_CRL *crl); +int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp); + +const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x); +int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial); +const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x); +int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm); +const STACK_OF(X509_EXTENSION) * +X509_REVOKED_get0_extensions(const X509_REVOKED *r); + +X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer, + EVP_PKEY *skey, const EVP_MD *md, unsigned int flags); + +int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey); + +int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey); +int X509_chain_check_suiteb(int *perror_depth, + X509 *x, STACK_OF(X509) *chain, + unsigned long flags); +int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags); +STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain); + +int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b); +unsigned long X509_issuer_and_serial_hash(X509 *a); + +int X509_issuer_name_cmp(const X509 *a, const X509 *b); +unsigned long X509_issuer_name_hash(X509 *a); + +int X509_subject_name_cmp(const X509 *a, const X509 *b); +unsigned long X509_subject_name_hash(X509 *x); + +# ifndef OPENSSL_NO_MD5 +unsigned long X509_issuer_name_hash_old(X509 *a); +unsigned long X509_subject_name_hash_old(X509 *x); +# endif + +int X509_cmp(const X509 *a, const X509 *b); +int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b); +unsigned long X509_NAME_hash(X509_NAME *x); +unsigned long X509_NAME_hash_old(X509_NAME *x); + +int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b); +int X509_CRL_match(const X509_CRL *a, const X509_CRL *b); +int X509_aux_print(BIO *out, X509 *x, int indent); +# ifndef OPENSSL_NO_STDIO +int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag, + unsigned long cflag); +int X509_print_fp(FILE *bp, X509 *x); +int X509_CRL_print_fp(FILE *bp, X509_CRL *x); +int X509_REQ_print_fp(FILE *bp, X509_REQ *req); +int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent, + unsigned long flags); +# endif + +int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase); +int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent, + unsigned long flags); +int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag, + unsigned long cflag); +int X509_print(BIO *bp, X509 *x); +int X509_ocspid_print(BIO *bp, X509 *x); +int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag); +int X509_CRL_print(BIO *bp, X509_CRL *x); +int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag, + unsigned long cflag); +int X509_REQ_print(BIO *bp, X509_REQ *req); + +int X509_NAME_entry_count(const X509_NAME *name); +int X509_NAME_get_text_by_NID(X509_NAME *name, int nid, char *buf, int len); +int X509_NAME_get_text_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, + char *buf, int len); + +/* + * NOTE: you should be passing -1, not 0 as lastpos. The functions that use + * lastpos, search after that position on. + */ +int X509_NAME_get_index_by_NID(X509_NAME *name, int nid, int lastpos); +int X509_NAME_get_index_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, + int lastpos); +X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc); +X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc); +int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne, + int loc, int set); +int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type, + const unsigned char *bytes, int len, int loc, + int set); +int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type, + const unsigned char *bytes, int len, int loc, + int set); +X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, + const char *field, int type, + const unsigned char *bytes, + int len); +X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid, + int type, + const unsigned char *bytes, + int len); +int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type, + const unsigned char *bytes, int len, int loc, + int set); +X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, + const ASN1_OBJECT *obj, int type, + const unsigned char *bytes, + int len); +int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj); +int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, + const unsigned char *bytes, int len); +ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne); +ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne); +int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne); + +int X509_NAME_get0_der(X509_NAME *nm, const unsigned char **pder, + size_t *pderlen); + +int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x); +int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x, + int nid, int lastpos); +int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x, + const ASN1_OBJECT *obj, int lastpos); +int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x, + int crit, int lastpos); +X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc); +X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc); +STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x, + X509_EXTENSION *ex, int loc); + +int X509_get_ext_count(const X509 *x); +int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos); +int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos); +int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos); +X509_EXTENSION *X509_get_ext(const X509 *x, int loc); +X509_EXTENSION *X509_delete_ext(X509 *x, int loc); +int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc); +void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx); +int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit, + unsigned long flags); + +int X509_CRL_get_ext_count(const X509_CRL *x); +int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos); +int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj, + int lastpos); +int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos); +X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc); +X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc); +int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc); +void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx); +int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit, + unsigned long flags); + +int X509_REVOKED_get_ext_count(const X509_REVOKED *x); +int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos); +int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj, + int lastpos); +int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit, + int lastpos); +X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc); +X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc); +int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc); +void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit, + int *idx); +int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit, + unsigned long flags); + +X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, + int nid, int crit, + ASN1_OCTET_STRING *data); +X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex, + const ASN1_OBJECT *obj, int crit, + ASN1_OCTET_STRING *data); +int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj); +int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit); +int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data); +ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex); +ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne); +int X509_EXTENSION_get_critical(const X509_EXTENSION *ex); + +int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x); +int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid, + int lastpos); +int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk, + const ASN1_OBJECT *obj, int lastpos); +X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc); +X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc); +STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x, + X509_ATTRIBUTE *attr); +STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE) + **x, const ASN1_OBJECT *obj, + int type, + const unsigned char *bytes, + int len); +STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE) + **x, int nid, int type, + const unsigned char *bytes, + int len); +STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE) + **x, const char *attrname, + int type, + const unsigned char *bytes, + int len); +void *X509at_get0_data_by_OBJ(STACK_OF(X509_ATTRIBUTE) *x, + const ASN1_OBJECT *obj, int lastpos, int type); +X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid, + int atrtype, const void *data, + int len); +X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr, + const ASN1_OBJECT *obj, + int atrtype, const void *data, + int len); +X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr, + const char *atrname, int type, + const unsigned char *bytes, + int len); +int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj); +int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype, + const void *data, int len); +void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype, + void *data); +int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr); +ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr); +ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx); + +int EVP_PKEY_get_attr_count(const EVP_PKEY *key); +int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos); +int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc); +X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc); +int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr); +int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key, + const ASN1_OBJECT *obj, int type, + const unsigned char *bytes, int len); +int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key, + int nid, int type, + const unsigned char *bytes, int len); +int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key, + const char *attrname, int type, + const unsigned char *bytes, int len); + +int X509_verify_cert(X509_STORE_CTX *ctx); + +/* lookup a cert from a X509 STACK */ +X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, X509_NAME *name, + ASN1_INTEGER *serial); +X509 *X509_find_by_subject(STACK_OF(X509) *sk, X509_NAME *name); + +DECLARE_ASN1_FUNCTIONS(PBEPARAM) +DECLARE_ASN1_FUNCTIONS(PBE2PARAM) +DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM) +#ifndef OPENSSL_NO_SCRYPT +DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS) +#endif + +int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter, + const unsigned char *salt, int saltlen); + +X509_ALGOR *PKCS5_pbe_set(int alg, int iter, + const unsigned char *salt, int saltlen); +X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter, + unsigned char *salt, int saltlen); +X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter, + unsigned char *salt, int saltlen, + unsigned char *aiv, int prf_nid); + +#ifndef OPENSSL_NO_SCRYPT +X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher, + const unsigned char *salt, int saltlen, + unsigned char *aiv, uint64_t N, uint64_t r, + uint64_t p); +#endif + +X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen, + int prf_nid, int keylen); + +/* PKCS#8 utilities */ + +DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO) + +EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8); +PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey); + +int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj, + int version, int ptype, void *pval, + unsigned char *penc, int penclen); +int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg, + const unsigned char **pk, int *ppklen, + const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8); + +const STACK_OF(X509_ATTRIBUTE) * +PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8); +int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type, + const unsigned char *bytes, int len); + +int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj, + int ptype, void *pval, + unsigned char *penc, int penclen); +int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg, + const unsigned char **pk, int *ppklen, + X509_ALGOR **pa, X509_PUBKEY *pub); + +int X509_check_trust(X509 *x, int id, int flags); +int X509_TRUST_get_count(void); +X509_TRUST *X509_TRUST_get0(int idx); +int X509_TRUST_get_by_id(int id); +int X509_TRUST_add(int id, int flags, int (*ck) (X509_TRUST *, X509 *, int), + const char *name, int arg1, void *arg2); +void X509_TRUST_cleanup(void); +int X509_TRUST_get_flags(const X509_TRUST *xp); +char *X509_TRUST_get0_name(const X509_TRUST *xp); +int X509_TRUST_get_trust(const X509_TRUST *xp); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/x509_vfy.h b/include/openssl/x509_vfy.h new file mode 100644 index 0000000..0ce72c5 --- /dev/null +++ b/include/openssl/x509_vfy.h @@ -0,0 +1,624 @@ +/* + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_X509_VFY_H +# define HEADER_X509_VFY_H + +/* + * Protect against recursion, x509.h and x509_vfy.h each include the other. + */ +# ifndef HEADER_X509_H +# include +# endif + +# include +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/*- +SSL_CTX -> X509_STORE + -> X509_LOOKUP + ->X509_LOOKUP_METHOD + -> X509_LOOKUP + ->X509_LOOKUP_METHOD + +SSL -> X509_STORE_CTX + ->X509_STORE + +The X509_STORE holds the tables etc for verification stuff. +A X509_STORE_CTX is used while validating a single certificate. +The X509_STORE has X509_LOOKUPs for looking up certs. +The X509_STORE then calls a function to actually verify the +certificate chain. +*/ + +typedef enum { + X509_LU_NONE = 0, + X509_LU_X509, X509_LU_CRL +} X509_LOOKUP_TYPE; + +#if OPENSSL_API_COMPAT < 0x10100000L +#define X509_LU_RETRY -1 +#define X509_LU_FAIL 0 +#endif + +DEFINE_STACK_OF(X509_LOOKUP) +DEFINE_STACK_OF(X509_OBJECT) +DEFINE_STACK_OF(X509_VERIFY_PARAM) + +int X509_STORE_set_depth(X509_STORE *store, int depth); + +typedef int (*X509_STORE_CTX_verify_cb)(int, X509_STORE_CTX *); +typedef int (*X509_STORE_CTX_verify_fn)(X509_STORE_CTX *); +typedef int (*X509_STORE_CTX_get_issuer_fn)(X509 **issuer, + X509_STORE_CTX *ctx, X509 *x); +typedef int (*X509_STORE_CTX_check_issued_fn)(X509_STORE_CTX *ctx, + X509 *x, X509 *issuer); +typedef int (*X509_STORE_CTX_check_revocation_fn)(X509_STORE_CTX *ctx); +typedef int (*X509_STORE_CTX_get_crl_fn)(X509_STORE_CTX *ctx, + X509_CRL **crl, X509 *x); +typedef int (*X509_STORE_CTX_check_crl_fn)(X509_STORE_CTX *ctx, X509_CRL *crl); +typedef int (*X509_STORE_CTX_cert_crl_fn)(X509_STORE_CTX *ctx, + X509_CRL *crl, X509 *x); +typedef int (*X509_STORE_CTX_check_policy_fn)(X509_STORE_CTX *ctx); +typedef STACK_OF(X509) *(*X509_STORE_CTX_lookup_certs_fn)(X509_STORE_CTX *ctx, + X509_NAME *nm); +typedef STACK_OF(X509_CRL) *(*X509_STORE_CTX_lookup_crls_fn)(X509_STORE_CTX *ctx, + X509_NAME *nm); +typedef int (*X509_STORE_CTX_cleanup_fn)(X509_STORE_CTX *ctx); + + +void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth); + +# define X509_STORE_CTX_set_app_data(ctx,data) \ + X509_STORE_CTX_set_ex_data(ctx,0,data) +# define X509_STORE_CTX_get_app_data(ctx) \ + X509_STORE_CTX_get_ex_data(ctx,0) + +# define X509_L_FILE_LOAD 1 +# define X509_L_ADD_DIR 2 + +# define X509_LOOKUP_load_file(x,name,type) \ + X509_LOOKUP_ctrl((x),X509_L_FILE_LOAD,(name),(long)(type),NULL) + +# define X509_LOOKUP_add_dir(x,name,type) \ + X509_LOOKUP_ctrl((x),X509_L_ADD_DIR,(name),(long)(type),NULL) + +# define X509_V_OK 0 +# define X509_V_ERR_UNSPECIFIED 1 +# define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 +# define X509_V_ERR_UNABLE_TO_GET_CRL 3 +# define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 +# define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 +# define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 +# define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 +# define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 +# define X509_V_ERR_CERT_NOT_YET_VALID 9 +# define X509_V_ERR_CERT_HAS_EXPIRED 10 +# define X509_V_ERR_CRL_NOT_YET_VALID 11 +# define X509_V_ERR_CRL_HAS_EXPIRED 12 +# define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 +# define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 +# define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 +# define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 +# define X509_V_ERR_OUT_OF_MEM 17 +# define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 +# define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 +# define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 +# define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 +# define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 +# define X509_V_ERR_CERT_REVOKED 23 +# define X509_V_ERR_INVALID_CA 24 +# define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 +# define X509_V_ERR_INVALID_PURPOSE 26 +# define X509_V_ERR_CERT_UNTRUSTED 27 +# define X509_V_ERR_CERT_REJECTED 28 +/* These are 'informational' when looking for issuer cert */ +# define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 +# define X509_V_ERR_AKID_SKID_MISMATCH 30 +# define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 +# define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 +# define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 +# define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 +# define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 +# define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 +# define X509_V_ERR_INVALID_NON_CA 37 +# define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 +# define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 +# define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 +# define X509_V_ERR_INVALID_EXTENSION 41 +# define X509_V_ERR_INVALID_POLICY_EXTENSION 42 +# define X509_V_ERR_NO_EXPLICIT_POLICY 43 +# define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 +# define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 +# define X509_V_ERR_UNNESTED_RESOURCE 46 +# define X509_V_ERR_PERMITTED_VIOLATION 47 +# define X509_V_ERR_EXCLUDED_VIOLATION 48 +# define X509_V_ERR_SUBTREE_MINMAX 49 +/* The application is not happy */ +# define X509_V_ERR_APPLICATION_VERIFICATION 50 +# define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 +# define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 +# define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 +# define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 +/* Another issuer check debug option */ +# define X509_V_ERR_PATH_LOOP 55 +/* Suite B mode algorithm violation */ +# define X509_V_ERR_SUITE_B_INVALID_VERSION 56 +# define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 +# define X509_V_ERR_SUITE_B_INVALID_CURVE 58 +# define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 +# define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 +# define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 +/* Host, email and IP check errors */ +# define X509_V_ERR_HOSTNAME_MISMATCH 62 +# define X509_V_ERR_EMAIL_MISMATCH 63 +# define X509_V_ERR_IP_ADDRESS_MISMATCH 64 +/* DANE TLSA errors */ +# define X509_V_ERR_DANE_NO_MATCH 65 +/* security level errors */ +# define X509_V_ERR_EE_KEY_TOO_SMALL 66 +# define X509_V_ERR_CA_KEY_TOO_SMALL 67 +# define X509_V_ERR_CA_MD_TOO_WEAK 68 +/* Caller error */ +# define X509_V_ERR_INVALID_CALL 69 +/* Issuer lookup error */ +# define X509_V_ERR_STORE_LOOKUP 70 +/* Certificate transparency */ +# define X509_V_ERR_NO_VALID_SCTS 71 + +# define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 +/* OCSP status errors */ +# define X509_V_ERR_OCSP_VERIFY_NEEDED 73 /* Need OCSP verification */ +# define X509_V_ERR_OCSP_VERIFY_FAILED 74 /* Couldn't verify cert through OCSP */ +# define X509_V_ERR_OCSP_CERT_UNKNOWN 75 /* Certificate wasn't recognized by the OCSP responder */ + +/* Certificate verify flags */ + +# if OPENSSL_API_COMPAT < 0x10100000L +# define X509_V_FLAG_CB_ISSUER_CHECK 0x0 /* Deprecated */ +# endif +/* Use check time instead of current time */ +# define X509_V_FLAG_USE_CHECK_TIME 0x2 +/* Lookup CRLs */ +# define X509_V_FLAG_CRL_CHECK 0x4 +/* Lookup CRLs for whole chain */ +# define X509_V_FLAG_CRL_CHECK_ALL 0x8 +/* Ignore unhandled critical extensions */ +# define X509_V_FLAG_IGNORE_CRITICAL 0x10 +/* Disable workarounds for broken certificates */ +# define X509_V_FLAG_X509_STRICT 0x20 +/* Enable proxy certificate validation */ +# define X509_V_FLAG_ALLOW_PROXY_CERTS 0x40 +/* Enable policy checking */ +# define X509_V_FLAG_POLICY_CHECK 0x80 +/* Policy variable require-explicit-policy */ +# define X509_V_FLAG_EXPLICIT_POLICY 0x100 +/* Policy variable inhibit-any-policy */ +# define X509_V_FLAG_INHIBIT_ANY 0x200 +/* Policy variable inhibit-policy-mapping */ +# define X509_V_FLAG_INHIBIT_MAP 0x400 +/* Notify callback that policy is OK */ +# define X509_V_FLAG_NOTIFY_POLICY 0x800 +/* Extended CRL features such as indirect CRLs, alternate CRL signing keys */ +# define X509_V_FLAG_EXTENDED_CRL_SUPPORT 0x1000 +/* Delta CRL support */ +# define X509_V_FLAG_USE_DELTAS 0x2000 +/* Check self-signed CA signature */ +# define X509_V_FLAG_CHECK_SS_SIGNATURE 0x4000 +/* Use trusted store first */ +# define X509_V_FLAG_TRUSTED_FIRST 0x8000 +/* Suite B 128 bit only mode: not normally used */ +# define X509_V_FLAG_SUITEB_128_LOS_ONLY 0x10000 +/* Suite B 192 bit only mode */ +# define X509_V_FLAG_SUITEB_192_LOS 0x20000 +/* Suite B 128 bit mode allowing 192 bit algorithms */ +# define X509_V_FLAG_SUITEB_128_LOS 0x30000 +/* Allow partial chains if at least one certificate is in trusted store */ +# define X509_V_FLAG_PARTIAL_CHAIN 0x80000 +/* + * If the initial chain is not trusted, do not attempt to build an alternative + * chain. Alternate chain checking was introduced in 1.1.0. Setting this flag + * will force the behaviour to match that of previous versions. + */ +# define X509_V_FLAG_NO_ALT_CHAINS 0x100000 +/* Do not check certificate/CRL validity against current time */ +# define X509_V_FLAG_NO_CHECK_TIME 0x200000 + +# define X509_VP_FLAG_DEFAULT 0x1 +# define X509_VP_FLAG_OVERWRITE 0x2 +# define X509_VP_FLAG_RESET_FLAGS 0x4 +# define X509_VP_FLAG_LOCKED 0x8 +# define X509_VP_FLAG_ONCE 0x10 + +/* Internal use: mask of policy related options */ +# define X509_V_FLAG_POLICY_MASK (X509_V_FLAG_POLICY_CHECK \ + | X509_V_FLAG_EXPLICIT_POLICY \ + | X509_V_FLAG_INHIBIT_ANY \ + | X509_V_FLAG_INHIBIT_MAP) + +int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, + X509_NAME *name); +X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h, + X509_LOOKUP_TYPE type, + X509_NAME *name); +X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, + X509_OBJECT *x); +int X509_OBJECT_up_ref_count(X509_OBJECT *a); +X509_OBJECT *X509_OBJECT_new(void); +void X509_OBJECT_free(X509_OBJECT *a); +X509_LOOKUP_TYPE X509_OBJECT_get_type(const X509_OBJECT *a); +X509 *X509_OBJECT_get0_X509(const X509_OBJECT *a); +int X509_OBJECT_set1_X509(X509_OBJECT *a, X509 *obj); +X509_CRL *X509_OBJECT_get0_X509_CRL(X509_OBJECT *a); +int X509_OBJECT_set1_X509_CRL(X509_OBJECT *a, X509_CRL *obj); +X509_STORE *X509_STORE_new(void); +void X509_STORE_free(X509_STORE *v); +int X509_STORE_lock(X509_STORE *ctx); +int X509_STORE_unlock(X509_STORE *ctx); +int X509_STORE_up_ref(X509_STORE *v); +STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *v); + +STACK_OF(X509) *X509_STORE_CTX_get1_certs(X509_STORE_CTX *st, X509_NAME *nm); +STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(X509_STORE_CTX *st, X509_NAME *nm); +int X509_STORE_set_flags(X509_STORE *ctx, unsigned long flags); +int X509_STORE_set_purpose(X509_STORE *ctx, int purpose); +int X509_STORE_set_trust(X509_STORE *ctx, int trust); +int X509_STORE_set1_param(X509_STORE *ctx, X509_VERIFY_PARAM *pm); +X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *ctx); + +void X509_STORE_set_verify(X509_STORE *ctx, X509_STORE_CTX_verify_fn verify); +#define X509_STORE_set_verify_func(ctx, func) \ + X509_STORE_set_verify((ctx),(func)) +void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx, + X509_STORE_CTX_verify_fn verify); +X509_STORE_CTX_verify_fn X509_STORE_get_verify(X509_STORE *ctx); +void X509_STORE_set_verify_cb(X509_STORE *ctx, + X509_STORE_CTX_verify_cb verify_cb); +# define X509_STORE_set_verify_cb_func(ctx,func) \ + X509_STORE_set_verify_cb((ctx),(func)) +X509_STORE_CTX_verify_cb X509_STORE_get_verify_cb(X509_STORE *ctx); +void X509_STORE_set_get_issuer(X509_STORE *ctx, + X509_STORE_CTX_get_issuer_fn get_issuer); +X509_STORE_CTX_get_issuer_fn X509_STORE_get_get_issuer(X509_STORE *ctx); +void X509_STORE_set_check_issued(X509_STORE *ctx, + X509_STORE_CTX_check_issued_fn check_issued); +X509_STORE_CTX_check_issued_fn X509_STORE_get_check_issued(X509_STORE *ctx); +void X509_STORE_set_check_revocation(X509_STORE *ctx, + X509_STORE_CTX_check_revocation_fn check_revocation); +X509_STORE_CTX_check_revocation_fn X509_STORE_get_check_revocation(X509_STORE *ctx); +void X509_STORE_set_get_crl(X509_STORE *ctx, + X509_STORE_CTX_get_crl_fn get_crl); +X509_STORE_CTX_get_crl_fn X509_STORE_get_get_crl(X509_STORE *ctx); +void X509_STORE_set_check_crl(X509_STORE *ctx, + X509_STORE_CTX_check_crl_fn check_crl); +X509_STORE_CTX_check_crl_fn X509_STORE_get_check_crl(X509_STORE *ctx); +void X509_STORE_set_cert_crl(X509_STORE *ctx, + X509_STORE_CTX_cert_crl_fn cert_crl); +X509_STORE_CTX_cert_crl_fn X509_STORE_get_cert_crl(X509_STORE *ctx); +void X509_STORE_set_check_policy(X509_STORE *ctx, + X509_STORE_CTX_check_policy_fn check_policy); +X509_STORE_CTX_check_policy_fn X509_STORE_get_check_policy(X509_STORE *ctx); +void X509_STORE_set_lookup_certs(X509_STORE *ctx, + X509_STORE_CTX_lookup_certs_fn lookup_certs); +X509_STORE_CTX_lookup_certs_fn X509_STORE_get_lookup_certs(X509_STORE *ctx); +void X509_STORE_set_lookup_crls(X509_STORE *ctx, + X509_STORE_CTX_lookup_crls_fn lookup_crls); +#define X509_STORE_set_lookup_crls_cb(ctx, func) \ + X509_STORE_set_lookup_crls((ctx), (func)) +X509_STORE_CTX_lookup_crls_fn X509_STORE_get_lookup_crls(X509_STORE *ctx); +void X509_STORE_set_cleanup(X509_STORE *ctx, + X509_STORE_CTX_cleanup_fn cleanup); +X509_STORE_CTX_cleanup_fn X509_STORE_get_cleanup(X509_STORE *ctx); + +#define X509_STORE_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE, l, p, newf, dupf, freef) +int X509_STORE_set_ex_data(X509_STORE *ctx, int idx, void *data); +void *X509_STORE_get_ex_data(X509_STORE *ctx, int idx); + +X509_STORE_CTX *X509_STORE_CTX_new(void); + +int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *x); + +void X509_STORE_CTX_free(X509_STORE_CTX *ctx); +int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, + X509 *x509, STACK_OF(X509) *chain); +void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk); +void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx); + +X509_STORE *X509_STORE_CTX_get0_store(X509_STORE_CTX *ctx); +X509 *X509_STORE_CTX_get0_cert(X509_STORE_CTX *ctx); +STACK_OF(X509)* X509_STORE_CTX_get0_untrusted(X509_STORE_CTX *ctx); +void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk); +void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx, + X509_STORE_CTX_verify_cb verify); +X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(X509_STORE_CTX *ctx); +X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(X509_STORE_CTX *ctx); +X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(X509_STORE_CTX *ctx); +X509_STORE_CTX_check_issued_fn X509_STORE_CTX_get_check_issued(X509_STORE_CTX *ctx); +X509_STORE_CTX_check_revocation_fn X509_STORE_CTX_get_check_revocation(X509_STORE_CTX *ctx); +X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(X509_STORE_CTX *ctx); +X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(X509_STORE_CTX *ctx); +X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(X509_STORE_CTX *ctx); +X509_STORE_CTX_check_policy_fn X509_STORE_CTX_get_check_policy(X509_STORE_CTX *ctx); +X509_STORE_CTX_lookup_certs_fn X509_STORE_CTX_get_lookup_certs(X509_STORE_CTX *ctx); +X509_STORE_CTX_lookup_crls_fn X509_STORE_CTX_get_lookup_crls(X509_STORE_CTX *ctx); +X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(X509_STORE_CTX *ctx); + +#if OPENSSL_API_COMPAT < 0x10100000L +# define X509_STORE_CTX_get_chain X509_STORE_CTX_get0_chain +# define X509_STORE_CTX_set_chain X509_STORE_CTX_set0_untrusted +# define X509_STORE_CTX_trusted_stack X509_STORE_CTX_set0_trusted_stack +# define X509_STORE_get_by_subject X509_STORE_CTX_get_by_subject +# define X509_STORE_get1_cert X509_STORE_CTX_get1_certs +# define X509_STORE_get1_crl X509_STORE_CTX_get1_crls +#endif + +X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m); +X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void); +X509_LOOKUP_METHOD *X509_LOOKUP_file(void); + +typedef int (*X509_LOOKUP_ctrl_fn)(X509_LOOKUP *ctx, int cmd, const char *argc, + long argl, char **ret); +typedef int (*X509_LOOKUP_get_by_subject_fn)(X509_LOOKUP *ctx, + X509_LOOKUP_TYPE type, + X509_NAME *name, + X509_OBJECT *ret); +typedef int (*X509_LOOKUP_get_by_issuer_serial_fn)(X509_LOOKUP *ctx, + X509_LOOKUP_TYPE type, + X509_NAME *name, + ASN1_INTEGER *serial, + X509_OBJECT *ret); +typedef int (*X509_LOOKUP_get_by_fingerprint_fn)(X509_LOOKUP *ctx, + X509_LOOKUP_TYPE type, + const unsigned char* bytes, + int len, + X509_OBJECT *ret); +typedef int (*X509_LOOKUP_get_by_alias_fn)(X509_LOOKUP *ctx, + X509_LOOKUP_TYPE type, + const char *str, + int len, + X509_OBJECT *ret); + +X509_LOOKUP_METHOD *X509_LOOKUP_meth_new(const char *name); +void X509_LOOKUP_meth_free(X509_LOOKUP_METHOD *method); + +int X509_LOOKUP_meth_set_new_item(X509_LOOKUP_METHOD *method, + int (*new_item) (X509_LOOKUP *ctx)); +int (*X509_LOOKUP_meth_get_new_item(const X509_LOOKUP_METHOD* method)) + (X509_LOOKUP *ctx); + +int X509_LOOKUP_meth_set_free(X509_LOOKUP_METHOD *method, + void (*free_fn) (X509_LOOKUP *ctx)); +void (*X509_LOOKUP_meth_get_free(const X509_LOOKUP_METHOD* method)) + (X509_LOOKUP *ctx); + +int X509_LOOKUP_meth_set_init(X509_LOOKUP_METHOD *method, + int (*init) (X509_LOOKUP *ctx)); +int (*X509_LOOKUP_meth_get_init(const X509_LOOKUP_METHOD* method)) + (X509_LOOKUP *ctx); + +int X509_LOOKUP_meth_set_shutdown(X509_LOOKUP_METHOD *method, + int (*shutdown) (X509_LOOKUP *ctx)); +int (*X509_LOOKUP_meth_get_shutdown(const X509_LOOKUP_METHOD* method)) + (X509_LOOKUP *ctx); + +int X509_LOOKUP_meth_set_ctrl(X509_LOOKUP_METHOD *method, + X509_LOOKUP_ctrl_fn ctrl_fn); +X509_LOOKUP_ctrl_fn X509_LOOKUP_meth_get_ctrl(const X509_LOOKUP_METHOD *method); + +int X509_LOOKUP_meth_set_get_by_subject(X509_LOOKUP_METHOD *method, + X509_LOOKUP_get_by_subject_fn fn); +X509_LOOKUP_get_by_subject_fn X509_LOOKUP_meth_get_get_by_subject( + const X509_LOOKUP_METHOD *method); + +int X509_LOOKUP_meth_set_get_by_issuer_serial(X509_LOOKUP_METHOD *method, + X509_LOOKUP_get_by_issuer_serial_fn fn); +X509_LOOKUP_get_by_issuer_serial_fn X509_LOOKUP_meth_get_get_by_issuer_serial( + const X509_LOOKUP_METHOD *method); + +int X509_LOOKUP_meth_set_get_by_fingerprint(X509_LOOKUP_METHOD *method, + X509_LOOKUP_get_by_fingerprint_fn fn); +X509_LOOKUP_get_by_fingerprint_fn X509_LOOKUP_meth_get_get_by_fingerprint( + const X509_LOOKUP_METHOD *method); + +int X509_LOOKUP_meth_set_get_by_alias(X509_LOOKUP_METHOD *method, + X509_LOOKUP_get_by_alias_fn fn); +X509_LOOKUP_get_by_alias_fn X509_LOOKUP_meth_get_get_by_alias( + const X509_LOOKUP_METHOD *method); + + +int X509_STORE_add_cert(X509_STORE *ctx, X509 *x); +int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x); + +int X509_STORE_CTX_get_by_subject(X509_STORE_CTX *vs, X509_LOOKUP_TYPE type, + X509_NAME *name, X509_OBJECT *ret); +X509_OBJECT *X509_STORE_CTX_get_obj_by_subject(X509_STORE_CTX *vs, + X509_LOOKUP_TYPE type, + X509_NAME *name); + +int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, + long argl, char **ret); + +int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type); +int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type); +int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type); + +X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method); +void X509_LOOKUP_free(X509_LOOKUP *ctx); +int X509_LOOKUP_init(X509_LOOKUP *ctx); +int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, + X509_NAME *name, X509_OBJECT *ret); +int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, + X509_NAME *name, ASN1_INTEGER *serial, + X509_OBJECT *ret); +int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, + const unsigned char *bytes, int len, + X509_OBJECT *ret); +int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type, + const char *str, int len, X509_OBJECT *ret); +int X509_LOOKUP_set_method_data(X509_LOOKUP *ctx, void *data); +void *X509_LOOKUP_get_method_data(const X509_LOOKUP *ctx); +X509_STORE *X509_LOOKUP_get_store(const X509_LOOKUP *ctx); +int X509_LOOKUP_shutdown(X509_LOOKUP *ctx); + +int X509_STORE_load_locations(X509_STORE *ctx, + const char *file, const char *dir); +int X509_STORE_set_default_paths(X509_STORE *ctx); + +#define X509_STORE_CTX_get_ex_new_index(l, p, newf, dupf, freef) \ + CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX, l, p, newf, dupf, freef) +int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data); +void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx); +int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx); +void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int s); +int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx); +void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth); +X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx); +void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x); +X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx); +X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx); +X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx); +STACK_OF(X509) *X509_STORE_CTX_get0_chain(X509_STORE_CTX *ctx); +STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx); +void X509_STORE_CTX_set_cert(X509_STORE_CTX *c, X509 *x); +void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *c, STACK_OF(X509) *sk); +void X509_STORE_CTX_set0_crls(X509_STORE_CTX *c, STACK_OF(X509_CRL) *sk); +int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose); +int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust); +int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose, + int purpose, int trust); +void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags); +void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags, + time_t t); + +X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx); +int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx); +int X509_STORE_CTX_get_num_untrusted(X509_STORE_CTX *ctx); + +X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx); +void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param); +int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name); + +/* + * Bridge opacity barrier between libcrypt and libssl, also needed to support + * offline testing in test/danetest.c + */ +void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane); +#define DANE_FLAG_NO_DANE_EE_NAMECHECKS (1L << 0) + +/* X509_VERIFY_PARAM functions */ + +X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void); +void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param); +int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *to, + const X509_VERIFY_PARAM *from); +int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, + const X509_VERIFY_PARAM *from); +int X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name); +int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, + unsigned long flags); +int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param, + unsigned long flags); +unsigned long X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *param); +int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose); +int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust); +void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth); +void X509_VERIFY_PARAM_set_auth_level(X509_VERIFY_PARAM *param, int auth_level); +time_t X509_VERIFY_PARAM_get_time(const X509_VERIFY_PARAM *param); +void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t); +int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param, + ASN1_OBJECT *policy); +int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param, + STACK_OF(ASN1_OBJECT) *policies); + +int X509_VERIFY_PARAM_set_inh_flags(X509_VERIFY_PARAM *param, + uint32_t flags); +uint32_t X509_VERIFY_PARAM_get_inh_flags(const X509_VERIFY_PARAM *param); + +int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, + const char *name, size_t namelen); +int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param, + const char *name, size_t namelen); +void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, + unsigned int flags); +unsigned int X509_VERIFY_PARAM_get_hostflags(const X509_VERIFY_PARAM *param); +char *X509_VERIFY_PARAM_get0_peername(X509_VERIFY_PARAM *); +void X509_VERIFY_PARAM_move_peername(X509_VERIFY_PARAM *, X509_VERIFY_PARAM *); +int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param, + const char *email, size_t emaillen); +int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param, + const unsigned char *ip, size_t iplen); +int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, + const char *ipasc); + +int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param); +int X509_VERIFY_PARAM_get_auth_level(const X509_VERIFY_PARAM *param); +const char *X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param); + +int X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param); +int X509_VERIFY_PARAM_get_count(void); +const X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id); +const X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name); +void X509_VERIFY_PARAM_table_cleanup(void); + +/* Non positive return values are errors */ +#define X509_PCY_TREE_FAILURE -2 /* Failure to satisfy explicit policy */ +#define X509_PCY_TREE_INVALID -1 /* Inconsistent or invalid extensions */ +#define X509_PCY_TREE_INTERNAL 0 /* Internal error, most likely malloc */ + +/* + * Positive return values form a bit mask, all but the first are internal to + * the library and don't appear in results from X509_policy_check(). + */ +#define X509_PCY_TREE_VALID 1 /* The policy tree is valid */ +#define X509_PCY_TREE_EMPTY 2 /* The policy tree is empty */ +#define X509_PCY_TREE_EXPLICIT 4 /* Explicit policy required */ + +int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy, + STACK_OF(X509) *certs, + STACK_OF(ASN1_OBJECT) *policy_oids, unsigned int flags); + +void X509_policy_tree_free(X509_POLICY_TREE *tree); + +int X509_policy_tree_level_count(const X509_POLICY_TREE *tree); +X509_POLICY_LEVEL *X509_policy_tree_get0_level(const X509_POLICY_TREE *tree, + int i); + +STACK_OF(X509_POLICY_NODE) *X509_policy_tree_get0_policies(const + X509_POLICY_TREE + *tree); + +STACK_OF(X509_POLICY_NODE) *X509_policy_tree_get0_user_policies(const + X509_POLICY_TREE + *tree); + +int X509_policy_level_node_count(X509_POLICY_LEVEL *level); + +X509_POLICY_NODE *X509_policy_level_get0_node(X509_POLICY_LEVEL *level, + int i); + +const ASN1_OBJECT *X509_policy_node_get0_policy(const X509_POLICY_NODE *node); + +STACK_OF(POLICYQUALINFO) *X509_policy_node_get0_qualifiers(const + X509_POLICY_NODE + *node); +const X509_POLICY_NODE *X509_policy_node_get0_parent(const X509_POLICY_NODE + *node); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/include/openssl/x509err.h b/include/openssl/x509err.h new file mode 100644 index 0000000..b1d6a87 --- /dev/null +++ b/include/openssl/x509err.h @@ -0,0 +1,125 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_X509ERR_H +# define HEADER_X509ERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_X509_strings(void); + +/* + * X509 function codes. + */ +# define X509_F_ADD_CERT_DIR 100 +# define X509_F_BUILD_CHAIN 106 +# define X509_F_BY_FILE_CTRL 101 +# define X509_F_CHECK_NAME_CONSTRAINTS 149 +# define X509_F_CHECK_POLICY 145 +# define X509_F_DANE_I2D 107 +# define X509_F_DIR_CTRL 102 +# define X509_F_GET_CERT_BY_SUBJECT 103 +# define X509_F_I2D_X509_AUX 151 +# define X509_F_LOOKUP_CERTS_SK 152 +# define X509_F_NETSCAPE_SPKI_B64_DECODE 129 +# define X509_F_NETSCAPE_SPKI_B64_ENCODE 130 +# define X509_F_NEW_DIR 153 +# define X509_F_X509AT_ADD1_ATTR 135 +# define X509_F_X509V3_ADD_EXT 104 +# define X509_F_X509_ATTRIBUTE_CREATE_BY_NID 136 +# define X509_F_X509_ATTRIBUTE_CREATE_BY_OBJ 137 +# define X509_F_X509_ATTRIBUTE_CREATE_BY_TXT 140 +# define X509_F_X509_ATTRIBUTE_GET0_DATA 139 +# define X509_F_X509_ATTRIBUTE_SET1_DATA 138 +# define X509_F_X509_CHECK_PRIVATE_KEY 128 +# define X509_F_X509_CRL_DIFF 105 +# define X509_F_X509_CRL_METHOD_NEW 154 +# define X509_F_X509_CRL_PRINT_FP 147 +# define X509_F_X509_EXTENSION_CREATE_BY_NID 108 +# define X509_F_X509_EXTENSION_CREATE_BY_OBJ 109 +# define X509_F_X509_GET_PUBKEY_PARAMETERS 110 +# define X509_F_X509_LOAD_CERT_CRL_FILE 132 +# define X509_F_X509_LOAD_CERT_FILE 111 +# define X509_F_X509_LOAD_CRL_FILE 112 +# define X509_F_X509_LOOKUP_METH_NEW 160 +# define X509_F_X509_LOOKUP_NEW 155 +# define X509_F_X509_NAME_ADD_ENTRY 113 +# define X509_F_X509_NAME_CANON 156 +# define X509_F_X509_NAME_ENTRY_CREATE_BY_NID 114 +# define X509_F_X509_NAME_ENTRY_CREATE_BY_TXT 131 +# define X509_F_X509_NAME_ENTRY_SET_OBJECT 115 +# define X509_F_X509_NAME_ONELINE 116 +# define X509_F_X509_NAME_PRINT 117 +# define X509_F_X509_OBJECT_NEW 150 +# define X509_F_X509_PRINT_EX_FP 118 +# define X509_F_X509_PUBKEY_DECODE 148 +# define X509_F_X509_PUBKEY_GET0 119 +# define X509_F_X509_PUBKEY_SET 120 +# define X509_F_X509_REQ_CHECK_PRIVATE_KEY 144 +# define X509_F_X509_REQ_PRINT_EX 121 +# define X509_F_X509_REQ_PRINT_FP 122 +# define X509_F_X509_REQ_TO_X509 123 +# define X509_F_X509_STORE_ADD_CERT 124 +# define X509_F_X509_STORE_ADD_CRL 125 +# define X509_F_X509_STORE_ADD_LOOKUP 157 +# define X509_F_X509_STORE_CTX_GET1_ISSUER 146 +# define X509_F_X509_STORE_CTX_INIT 143 +# define X509_F_X509_STORE_CTX_NEW 142 +# define X509_F_X509_STORE_CTX_PURPOSE_INHERIT 134 +# define X509_F_X509_STORE_NEW 158 +# define X509_F_X509_TO_X509_REQ 126 +# define X509_F_X509_TRUST_ADD 133 +# define X509_F_X509_TRUST_SET 141 +# define X509_F_X509_VERIFY_CERT 127 +# define X509_F_X509_VERIFY_PARAM_NEW 159 + +/* + * X509 reason codes. + */ +# define X509_R_AKID_MISMATCH 110 +# define X509_R_BAD_SELECTOR 133 +# define X509_R_BAD_X509_FILETYPE 100 +# define X509_R_BASE64_DECODE_ERROR 118 +# define X509_R_CANT_CHECK_DH_KEY 114 +# define X509_R_CERT_ALREADY_IN_HASH_TABLE 101 +# define X509_R_CRL_ALREADY_DELTA 127 +# define X509_R_CRL_VERIFY_FAILURE 131 +# define X509_R_IDP_MISMATCH 128 +# define X509_R_INVALID_DIRECTORY 113 +# define X509_R_INVALID_FIELD_NAME 119 +# define X509_R_INVALID_TRUST 123 +# define X509_R_ISSUER_MISMATCH 129 +# define X509_R_KEY_TYPE_MISMATCH 115 +# define X509_R_KEY_VALUES_MISMATCH 116 +# define X509_R_LOADING_CERT_DIR 103 +# define X509_R_LOADING_DEFAULTS 104 +# define X509_R_METHOD_NOT_SUPPORTED 124 +# define X509_R_NAME_TOO_LONG 134 +# define X509_R_NEWER_CRL_NOT_NEWER 132 +# define X509_R_NO_CERTIFICATE_FOUND 135 +# define X509_R_NO_CERTIFICATE_OR_CRL_FOUND 136 +# define X509_R_NO_CERT_SET_FOR_US_TO_VERIFY 105 +# define X509_R_NO_CRL_FOUND 137 +# define X509_R_NO_CRL_NUMBER 130 +# define X509_R_PUBLIC_KEY_DECODE_ERROR 125 +# define X509_R_PUBLIC_KEY_ENCODE_ERROR 126 +# define X509_R_SHOULD_RETRY 106 +# define X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN 107 +# define X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY 108 +# define X509_R_UNKNOWN_KEY_TYPE 117 +# define X509_R_UNKNOWN_NID 109 +# define X509_R_UNKNOWN_PURPOSE_ID 121 +# define X509_R_UNKNOWN_TRUST_ID 120 +# define X509_R_UNSUPPORTED_ALGORITHM 111 +# define X509_R_WRONG_LOOKUP_TYPE 112 +# define X509_R_WRONG_TYPE 122 + +#endif diff --git a/include/openssl/x509v3.h b/include/openssl/x509v3.h new file mode 100644 index 0000000..659b556 --- /dev/null +++ b/include/openssl/x509v3.h @@ -0,0 +1,935 @@ +/* + * Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_X509V3_H +# define HEADER_X509V3_H + +# include +# include +# include +# include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Forward reference */ +struct v3_ext_method; +struct v3_ext_ctx; + +/* Useful typedefs */ + +typedef void *(*X509V3_EXT_NEW)(void); +typedef void (*X509V3_EXT_FREE) (void *); +typedef void *(*X509V3_EXT_D2I)(void *, const unsigned char **, long); +typedef int (*X509V3_EXT_I2D) (void *, unsigned char **); +typedef STACK_OF(CONF_VALUE) * + (*X509V3_EXT_I2V) (const struct v3_ext_method *method, void *ext, + STACK_OF(CONF_VALUE) *extlist); +typedef void *(*X509V3_EXT_V2I)(const struct v3_ext_method *method, + struct v3_ext_ctx *ctx, + STACK_OF(CONF_VALUE) *values); +typedef char *(*X509V3_EXT_I2S)(const struct v3_ext_method *method, + void *ext); +typedef void *(*X509V3_EXT_S2I)(const struct v3_ext_method *method, + struct v3_ext_ctx *ctx, const char *str); +typedef int (*X509V3_EXT_I2R) (const struct v3_ext_method *method, void *ext, + BIO *out, int indent); +typedef void *(*X509V3_EXT_R2I)(const struct v3_ext_method *method, + struct v3_ext_ctx *ctx, const char *str); + +/* V3 extension structure */ + +struct v3_ext_method { + int ext_nid; + int ext_flags; +/* If this is set the following four fields are ignored */ + ASN1_ITEM_EXP *it; +/* Old style ASN1 calls */ + X509V3_EXT_NEW ext_new; + X509V3_EXT_FREE ext_free; + X509V3_EXT_D2I d2i; + X509V3_EXT_I2D i2d; +/* The following pair is used for string extensions */ + X509V3_EXT_I2S i2s; + X509V3_EXT_S2I s2i; +/* The following pair is used for multi-valued extensions */ + X509V3_EXT_I2V i2v; + X509V3_EXT_V2I v2i; +/* The following are used for raw extensions */ + X509V3_EXT_I2R i2r; + X509V3_EXT_R2I r2i; + void *usr_data; /* Any extension specific data */ +}; + +typedef struct X509V3_CONF_METHOD_st { + char *(*get_string) (void *db, const char *section, const char *value); + STACK_OF(CONF_VALUE) *(*get_section) (void *db, const char *section); + void (*free_string) (void *db, char *string); + void (*free_section) (void *db, STACK_OF(CONF_VALUE) *section); +} X509V3_CONF_METHOD; + +/* Context specific info */ +struct v3_ext_ctx { +# define CTX_TEST 0x1 +# define X509V3_CTX_REPLACE 0x2 + int flags; + X509 *issuer_cert; + X509 *subject_cert; + X509_REQ *subject_req; + X509_CRL *crl; + X509V3_CONF_METHOD *db_meth; + void *db; +/* Maybe more here */ +}; + +typedef struct v3_ext_method X509V3_EXT_METHOD; + +DEFINE_STACK_OF(X509V3_EXT_METHOD) + +/* ext_flags values */ +# define X509V3_EXT_DYNAMIC 0x1 +# define X509V3_EXT_CTX_DEP 0x2 +# define X509V3_EXT_MULTILINE 0x4 + +typedef BIT_STRING_BITNAME ENUMERATED_NAMES; + +typedef struct BASIC_CONSTRAINTS_st { + int ca; + ASN1_INTEGER *pathlen; +} BASIC_CONSTRAINTS; + +typedef struct PKEY_USAGE_PERIOD_st { + ASN1_GENERALIZEDTIME *notBefore; + ASN1_GENERALIZEDTIME *notAfter; +} PKEY_USAGE_PERIOD; + +typedef struct otherName_st { + ASN1_OBJECT *type_id; + ASN1_TYPE *value; +} OTHERNAME; + +typedef struct EDIPartyName_st { + ASN1_STRING *nameAssigner; + ASN1_STRING *partyName; +} EDIPARTYNAME; + +typedef struct GENERAL_NAME_st { +# define GEN_OTHERNAME 0 +# define GEN_EMAIL 1 +# define GEN_DNS 2 +# define GEN_X400 3 +# define GEN_DIRNAME 4 +# define GEN_EDIPARTY 5 +# define GEN_URI 6 +# define GEN_IPADD 7 +# define GEN_RID 8 + int type; + union { + char *ptr; + OTHERNAME *otherName; /* otherName */ + ASN1_IA5STRING *rfc822Name; + ASN1_IA5STRING *dNSName; + ASN1_TYPE *x400Address; + X509_NAME *directoryName; + EDIPARTYNAME *ediPartyName; + ASN1_IA5STRING *uniformResourceIdentifier; + ASN1_OCTET_STRING *iPAddress; + ASN1_OBJECT *registeredID; + /* Old names */ + ASN1_OCTET_STRING *ip; /* iPAddress */ + X509_NAME *dirn; /* dirn */ + ASN1_IA5STRING *ia5; /* rfc822Name, dNSName, + * uniformResourceIdentifier */ + ASN1_OBJECT *rid; /* registeredID */ + ASN1_TYPE *other; /* x400Address */ + } d; +} GENERAL_NAME; + +typedef struct ACCESS_DESCRIPTION_st { + ASN1_OBJECT *method; + GENERAL_NAME *location; +} ACCESS_DESCRIPTION; + +typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS; + +typedef STACK_OF(ASN1_OBJECT) EXTENDED_KEY_USAGE; + +typedef STACK_OF(ASN1_INTEGER) TLS_FEATURE; + +DEFINE_STACK_OF(GENERAL_NAME) +typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES; +DEFINE_STACK_OF(GENERAL_NAMES) + +DEFINE_STACK_OF(ACCESS_DESCRIPTION) + +typedef struct DIST_POINT_NAME_st { + int type; + union { + GENERAL_NAMES *fullname; + STACK_OF(X509_NAME_ENTRY) *relativename; + } name; +/* If relativename then this contains the full distribution point name */ + X509_NAME *dpname; +} DIST_POINT_NAME; +/* All existing reasons */ +# define CRLDP_ALL_REASONS 0x807f + +# define CRL_REASON_NONE -1 +# define CRL_REASON_UNSPECIFIED 0 +# define CRL_REASON_KEY_COMPROMISE 1 +# define CRL_REASON_CA_COMPROMISE 2 +# define CRL_REASON_AFFILIATION_CHANGED 3 +# define CRL_REASON_SUPERSEDED 4 +# define CRL_REASON_CESSATION_OF_OPERATION 5 +# define CRL_REASON_CERTIFICATE_HOLD 6 +# define CRL_REASON_REMOVE_FROM_CRL 8 +# define CRL_REASON_PRIVILEGE_WITHDRAWN 9 +# define CRL_REASON_AA_COMPROMISE 10 + +struct DIST_POINT_st { + DIST_POINT_NAME *distpoint; + ASN1_BIT_STRING *reasons; + GENERAL_NAMES *CRLissuer; + int dp_reasons; +}; + +typedef STACK_OF(DIST_POINT) CRL_DIST_POINTS; + +DEFINE_STACK_OF(DIST_POINT) + +struct AUTHORITY_KEYID_st { + ASN1_OCTET_STRING *keyid; + GENERAL_NAMES *issuer; + ASN1_INTEGER *serial; +}; + +/* Strong extranet structures */ + +typedef struct SXNET_ID_st { + ASN1_INTEGER *zone; + ASN1_OCTET_STRING *user; +} SXNETID; + +DEFINE_STACK_OF(SXNETID) + +typedef struct SXNET_st { + ASN1_INTEGER *version; + STACK_OF(SXNETID) *ids; +} SXNET; + +typedef struct NOTICEREF_st { + ASN1_STRING *organization; + STACK_OF(ASN1_INTEGER) *noticenos; +} NOTICEREF; + +typedef struct USERNOTICE_st { + NOTICEREF *noticeref; + ASN1_STRING *exptext; +} USERNOTICE; + +typedef struct POLICYQUALINFO_st { + ASN1_OBJECT *pqualid; + union { + ASN1_IA5STRING *cpsuri; + USERNOTICE *usernotice; + ASN1_TYPE *other; + } d; +} POLICYQUALINFO; + +DEFINE_STACK_OF(POLICYQUALINFO) + +typedef struct POLICYINFO_st { + ASN1_OBJECT *policyid; + STACK_OF(POLICYQUALINFO) *qualifiers; +} POLICYINFO; + +typedef STACK_OF(POLICYINFO) CERTIFICATEPOLICIES; + +DEFINE_STACK_OF(POLICYINFO) + +typedef struct POLICY_MAPPING_st { + ASN1_OBJECT *issuerDomainPolicy; + ASN1_OBJECT *subjectDomainPolicy; +} POLICY_MAPPING; + +DEFINE_STACK_OF(POLICY_MAPPING) + +typedef STACK_OF(POLICY_MAPPING) POLICY_MAPPINGS; + +typedef struct GENERAL_SUBTREE_st { + GENERAL_NAME *base; + ASN1_INTEGER *minimum; + ASN1_INTEGER *maximum; +} GENERAL_SUBTREE; + +DEFINE_STACK_OF(GENERAL_SUBTREE) + +struct NAME_CONSTRAINTS_st { + STACK_OF(GENERAL_SUBTREE) *permittedSubtrees; + STACK_OF(GENERAL_SUBTREE) *excludedSubtrees; +}; + +typedef struct POLICY_CONSTRAINTS_st { + ASN1_INTEGER *requireExplicitPolicy; + ASN1_INTEGER *inhibitPolicyMapping; +} POLICY_CONSTRAINTS; + +/* Proxy certificate structures, see RFC 3820 */ +typedef struct PROXY_POLICY_st { + ASN1_OBJECT *policyLanguage; + ASN1_OCTET_STRING *policy; +} PROXY_POLICY; + +typedef struct PROXY_CERT_INFO_EXTENSION_st { + ASN1_INTEGER *pcPathLengthConstraint; + PROXY_POLICY *proxyPolicy; +} PROXY_CERT_INFO_EXTENSION; + +DECLARE_ASN1_FUNCTIONS(PROXY_POLICY) +DECLARE_ASN1_FUNCTIONS(PROXY_CERT_INFO_EXTENSION) + +struct ISSUING_DIST_POINT_st { + DIST_POINT_NAME *distpoint; + int onlyuser; + int onlyCA; + ASN1_BIT_STRING *onlysomereasons; + int indirectCRL; + int onlyattr; +}; + +/* Values in idp_flags field */ +/* IDP present */ +# define IDP_PRESENT 0x1 +/* IDP values inconsistent */ +# define IDP_INVALID 0x2 +/* onlyuser true */ +# define IDP_ONLYUSER 0x4 +/* onlyCA true */ +# define IDP_ONLYCA 0x8 +/* onlyattr true */ +# define IDP_ONLYATTR 0x10 +/* indirectCRL true */ +# define IDP_INDIRECT 0x20 +/* onlysomereasons present */ +# define IDP_REASONS 0x40 + +# define X509V3_conf_err(val) ERR_add_error_data(6, \ + "section:", (val)->section, \ + ",name:", (val)->name, ",value:", (val)->value) + +# define X509V3_set_ctx_test(ctx) \ + X509V3_set_ctx(ctx, NULL, NULL, NULL, NULL, CTX_TEST) +# define X509V3_set_ctx_nodb(ctx) (ctx)->db = NULL; + +# define EXT_BITSTRING(nid, table) { nid, 0, ASN1_ITEM_ref(ASN1_BIT_STRING), \ + 0,0,0,0, \ + 0,0, \ + (X509V3_EXT_I2V)i2v_ASN1_BIT_STRING, \ + (X509V3_EXT_V2I)v2i_ASN1_BIT_STRING, \ + NULL, NULL, \ + table} + +# define EXT_IA5STRING(nid) { nid, 0, ASN1_ITEM_ref(ASN1_IA5STRING), \ + 0,0,0,0, \ + (X509V3_EXT_I2S)i2s_ASN1_IA5STRING, \ + (X509V3_EXT_S2I)s2i_ASN1_IA5STRING, \ + 0,0,0,0, \ + NULL} + +# define EXT_END { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + +/* X509_PURPOSE stuff */ + +# define EXFLAG_BCONS 0x1 +# define EXFLAG_KUSAGE 0x2 +# define EXFLAG_XKUSAGE 0x4 +# define EXFLAG_NSCERT 0x8 + +# define EXFLAG_CA 0x10 +/* Really self issued not necessarily self signed */ +# define EXFLAG_SI 0x20 +# define EXFLAG_V1 0x40 +# define EXFLAG_INVALID 0x80 +/* EXFLAG_SET is set to indicate that some values have been precomputed */ +# define EXFLAG_SET 0x100 +# define EXFLAG_CRITICAL 0x200 +# define EXFLAG_PROXY 0x400 + +# define EXFLAG_INVALID_POLICY 0x800 +# define EXFLAG_FRESHEST 0x1000 +/* Self signed */ +# define EXFLAG_SS 0x2000 + +# define KU_DIGITAL_SIGNATURE 0x0080 +# define KU_NON_REPUDIATION 0x0040 +# define KU_KEY_ENCIPHERMENT 0x0020 +# define KU_DATA_ENCIPHERMENT 0x0010 +# define KU_KEY_AGREEMENT 0x0008 +# define KU_KEY_CERT_SIGN 0x0004 +# define KU_CRL_SIGN 0x0002 +# define KU_ENCIPHER_ONLY 0x0001 +# define KU_DECIPHER_ONLY 0x8000 + +# define NS_SSL_CLIENT 0x80 +# define NS_SSL_SERVER 0x40 +# define NS_SMIME 0x20 +# define NS_OBJSIGN 0x10 +# define NS_SSL_CA 0x04 +# define NS_SMIME_CA 0x02 +# define NS_OBJSIGN_CA 0x01 +# define NS_ANY_CA (NS_SSL_CA|NS_SMIME_CA|NS_OBJSIGN_CA) + +# define XKU_SSL_SERVER 0x1 +# define XKU_SSL_CLIENT 0x2 +# define XKU_SMIME 0x4 +# define XKU_CODE_SIGN 0x8 +# define XKU_SGC 0x10 +# define XKU_OCSP_SIGN 0x20 +# define XKU_TIMESTAMP 0x40 +# define XKU_DVCS 0x80 +# define XKU_ANYEKU 0x100 + +# define X509_PURPOSE_DYNAMIC 0x1 +# define X509_PURPOSE_DYNAMIC_NAME 0x2 + +typedef struct x509_purpose_st { + int purpose; + int trust; /* Default trust ID */ + int flags; + int (*check_purpose) (const struct x509_purpose_st *, const X509 *, int); + char *name; + char *sname; + void *usr_data; +} X509_PURPOSE; + +# define X509_PURPOSE_SSL_CLIENT 1 +# define X509_PURPOSE_SSL_SERVER 2 +# define X509_PURPOSE_NS_SSL_SERVER 3 +# define X509_PURPOSE_SMIME_SIGN 4 +# define X509_PURPOSE_SMIME_ENCRYPT 5 +# define X509_PURPOSE_CRL_SIGN 6 +# define X509_PURPOSE_ANY 7 +# define X509_PURPOSE_OCSP_HELPER 8 +# define X509_PURPOSE_TIMESTAMP_SIGN 9 + +# define X509_PURPOSE_MIN 1 +# define X509_PURPOSE_MAX 9 + +/* Flags for X509V3_EXT_print() */ + +# define X509V3_EXT_UNKNOWN_MASK (0xfL << 16) +/* Return error for unknown extensions */ +# define X509V3_EXT_DEFAULT 0 +/* Print error for unknown extensions */ +# define X509V3_EXT_ERROR_UNKNOWN (1L << 16) +/* ASN1 parse unknown extensions */ +# define X509V3_EXT_PARSE_UNKNOWN (2L << 16) +/* BIO_dump unknown extensions */ +# define X509V3_EXT_DUMP_UNKNOWN (3L << 16) + +/* Flags for X509V3_add1_i2d */ + +# define X509V3_ADD_OP_MASK 0xfL +# define X509V3_ADD_DEFAULT 0L +# define X509V3_ADD_APPEND 1L +# define X509V3_ADD_REPLACE 2L +# define X509V3_ADD_REPLACE_EXISTING 3L +# define X509V3_ADD_KEEP_EXISTING 4L +# define X509V3_ADD_DELETE 5L +# define X509V3_ADD_SILENT 0x10 + +DEFINE_STACK_OF(X509_PURPOSE) + +DECLARE_ASN1_FUNCTIONS(BASIC_CONSTRAINTS) + +DECLARE_ASN1_FUNCTIONS(SXNET) +DECLARE_ASN1_FUNCTIONS(SXNETID) + +int SXNET_add_id_asc(SXNET **psx, const char *zone, const char *user, int userlen); +int SXNET_add_id_ulong(SXNET **psx, unsigned long lzone, const char *user, + int userlen); +int SXNET_add_id_INTEGER(SXNET **psx, ASN1_INTEGER *izone, const char *user, + int userlen); + +ASN1_OCTET_STRING *SXNET_get_id_asc(SXNET *sx, const char *zone); +ASN1_OCTET_STRING *SXNET_get_id_ulong(SXNET *sx, unsigned long lzone); +ASN1_OCTET_STRING *SXNET_get_id_INTEGER(SXNET *sx, ASN1_INTEGER *zone); + +DECLARE_ASN1_FUNCTIONS(AUTHORITY_KEYID) + +DECLARE_ASN1_FUNCTIONS(PKEY_USAGE_PERIOD) + +DECLARE_ASN1_FUNCTIONS(GENERAL_NAME) +GENERAL_NAME *GENERAL_NAME_dup(GENERAL_NAME *a); +int GENERAL_NAME_cmp(GENERAL_NAME *a, GENERAL_NAME *b); + +ASN1_BIT_STRING *v2i_ASN1_BIT_STRING(X509V3_EXT_METHOD *method, + X509V3_CTX *ctx, + STACK_OF(CONF_VALUE) *nval); +STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(X509V3_EXT_METHOD *method, + ASN1_BIT_STRING *bits, + STACK_OF(CONF_VALUE) *extlist); +char *i2s_ASN1_IA5STRING(X509V3_EXT_METHOD *method, ASN1_IA5STRING *ia5); +ASN1_IA5STRING *s2i_ASN1_IA5STRING(X509V3_EXT_METHOD *method, + X509V3_CTX *ctx, const char *str); + +STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method, + GENERAL_NAME *gen, + STACK_OF(CONF_VALUE) *ret); +int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen); + +DECLARE_ASN1_FUNCTIONS(GENERAL_NAMES) + +STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method, + GENERAL_NAMES *gen, + STACK_OF(CONF_VALUE) *extlist); +GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method, + X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); + +DECLARE_ASN1_FUNCTIONS(OTHERNAME) +DECLARE_ASN1_FUNCTIONS(EDIPARTYNAME) +int OTHERNAME_cmp(OTHERNAME *a, OTHERNAME *b); +void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value); +void *GENERAL_NAME_get0_value(GENERAL_NAME *a, int *ptype); +int GENERAL_NAME_set0_othername(GENERAL_NAME *gen, + ASN1_OBJECT *oid, ASN1_TYPE *value); +int GENERAL_NAME_get0_otherName(GENERAL_NAME *gen, + ASN1_OBJECT **poid, ASN1_TYPE **pvalue); + +char *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, + const ASN1_OCTET_STRING *ia5); +ASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, + X509V3_CTX *ctx, const char *str); + +DECLARE_ASN1_FUNCTIONS(EXTENDED_KEY_USAGE) +int i2a_ACCESS_DESCRIPTION(BIO *bp, const ACCESS_DESCRIPTION *a); + +DECLARE_ASN1_ALLOC_FUNCTIONS(TLS_FEATURE) + +DECLARE_ASN1_FUNCTIONS(CERTIFICATEPOLICIES) +DECLARE_ASN1_FUNCTIONS(POLICYINFO) +DECLARE_ASN1_FUNCTIONS(POLICYQUALINFO) +DECLARE_ASN1_FUNCTIONS(USERNOTICE) +DECLARE_ASN1_FUNCTIONS(NOTICEREF) + +DECLARE_ASN1_FUNCTIONS(CRL_DIST_POINTS) +DECLARE_ASN1_FUNCTIONS(DIST_POINT) +DECLARE_ASN1_FUNCTIONS(DIST_POINT_NAME) +DECLARE_ASN1_FUNCTIONS(ISSUING_DIST_POINT) + +int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, X509_NAME *iname); + +int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc); +int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc); + +DECLARE_ASN1_FUNCTIONS(ACCESS_DESCRIPTION) +DECLARE_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS) + +DECLARE_ASN1_ITEM(POLICY_MAPPING) +DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_MAPPING) +DECLARE_ASN1_ITEM(POLICY_MAPPINGS) + +DECLARE_ASN1_ITEM(GENERAL_SUBTREE) +DECLARE_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE) + +DECLARE_ASN1_ITEM(NAME_CONSTRAINTS) +DECLARE_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS) + +DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS) +DECLARE_ASN1_ITEM(POLICY_CONSTRAINTS) + +GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out, + const X509V3_EXT_METHOD *method, + X509V3_CTX *ctx, int gen_type, + const char *value, int is_nc); + +# ifdef HEADER_CONF_H +GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method, + X509V3_CTX *ctx, CONF_VALUE *cnf); +GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out, + const X509V3_EXT_METHOD *method, + X509V3_CTX *ctx, CONF_VALUE *cnf, + int is_nc); +void X509V3_conf_free(CONF_VALUE *val); + +X509_EXTENSION *X509V3_EXT_nconf_nid(CONF *conf, X509V3_CTX *ctx, int ext_nid, + const char *value); +X509_EXTENSION *X509V3_EXT_nconf(CONF *conf, X509V3_CTX *ctx, const char *name, + const char *value); +int X509V3_EXT_add_nconf_sk(CONF *conf, X509V3_CTX *ctx, const char *section, + STACK_OF(X509_EXTENSION) **sk); +int X509V3_EXT_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section, + X509 *cert); +int X509V3_EXT_REQ_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section, + X509_REQ *req); +int X509V3_EXT_CRL_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section, + X509_CRL *crl); + +X509_EXTENSION *X509V3_EXT_conf_nid(LHASH_OF(CONF_VALUE) *conf, + X509V3_CTX *ctx, int ext_nid, + const char *value); +X509_EXTENSION *X509V3_EXT_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx, + const char *name, const char *value); +int X509V3_EXT_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx, + const char *section, X509 *cert); +int X509V3_EXT_REQ_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx, + const char *section, X509_REQ *req); +int X509V3_EXT_CRL_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx, + const char *section, X509_CRL *crl); + +int X509V3_add_value_bool_nf(const char *name, int asn1_bool, + STACK_OF(CONF_VALUE) **extlist); +int X509V3_get_value_bool(const CONF_VALUE *value, int *asn1_bool); +int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint); +void X509V3_set_nconf(X509V3_CTX *ctx, CONF *conf); +void X509V3_set_conf_lhash(X509V3_CTX *ctx, LHASH_OF(CONF_VALUE) *lhash); +# endif + +char *X509V3_get_string(X509V3_CTX *ctx, const char *name, const char *section); +STACK_OF(CONF_VALUE) *X509V3_get_section(X509V3_CTX *ctx, const char *section); +void X509V3_string_free(X509V3_CTX *ctx, char *str); +void X509V3_section_free(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *section); +void X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subject, + X509_REQ *req, X509_CRL *crl, int flags); + +int X509V3_add_value(const char *name, const char *value, + STACK_OF(CONF_VALUE) **extlist); +int X509V3_add_value_uchar(const char *name, const unsigned char *value, + STACK_OF(CONF_VALUE) **extlist); +int X509V3_add_value_bool(const char *name, int asn1_bool, + STACK_OF(CONF_VALUE) **extlist); +int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint, + STACK_OF(CONF_VALUE) **extlist); +char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *meth, const ASN1_INTEGER *aint); +ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *meth, const char *value); +char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *meth, const ASN1_ENUMERATED *aint); +char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *meth, + const ASN1_ENUMERATED *aint); +int X509V3_EXT_add(X509V3_EXT_METHOD *ext); +int X509V3_EXT_add_list(X509V3_EXT_METHOD *extlist); +int X509V3_EXT_add_alias(int nid_to, int nid_from); +void X509V3_EXT_cleanup(void); + +const X509V3_EXT_METHOD *X509V3_EXT_get(X509_EXTENSION *ext); +const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid); +int X509V3_add_standard_extensions(void); +STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line); +void *X509V3_EXT_d2i(X509_EXTENSION *ext); +void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *x, int nid, int *crit, + int *idx); + +X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc); +int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value, + int crit, unsigned long flags); + +#if OPENSSL_API_COMPAT < 0x10100000L +/* The new declarations are in crypto.h, but the old ones were here. */ +# define hex_to_string OPENSSL_buf2hexstr +# define string_to_hex OPENSSL_hexstr2buf +#endif + +void X509V3_EXT_val_prn(BIO *out, STACK_OF(CONF_VALUE) *val, int indent, + int ml); +int X509V3_EXT_print(BIO *out, X509_EXTENSION *ext, unsigned long flag, + int indent); +#ifndef OPENSSL_NO_STDIO +int X509V3_EXT_print_fp(FILE *out, X509_EXTENSION *ext, int flag, int indent); +#endif +int X509V3_extensions_print(BIO *out, const char *title, + const STACK_OF(X509_EXTENSION) *exts, + unsigned long flag, int indent); + +int X509_check_ca(X509 *x); +int X509_check_purpose(X509 *x, int id, int ca); +int X509_supported_extension(X509_EXTENSION *ex); +int X509_PURPOSE_set(int *p, int purpose); +int X509_check_issued(X509 *issuer, X509 *subject); +int X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid); +void X509_set_proxy_flag(X509 *x); +void X509_set_proxy_pathlen(X509 *x, long l); +long X509_get_proxy_pathlen(X509 *x); + +uint32_t X509_get_extension_flags(X509 *x); +uint32_t X509_get_key_usage(X509 *x); +uint32_t X509_get_extended_key_usage(X509 *x); +const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x); +const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x); + +int X509_PURPOSE_get_count(void); +X509_PURPOSE *X509_PURPOSE_get0(int idx); +int X509_PURPOSE_get_by_sname(const char *sname); +int X509_PURPOSE_get_by_id(int id); +int X509_PURPOSE_add(int id, int trust, int flags, + int (*ck) (const X509_PURPOSE *, const X509 *, int), + const char *name, const char *sname, void *arg); +char *X509_PURPOSE_get0_name(const X509_PURPOSE *xp); +char *X509_PURPOSE_get0_sname(const X509_PURPOSE *xp); +int X509_PURPOSE_get_trust(const X509_PURPOSE *xp); +void X509_PURPOSE_cleanup(void); +int X509_PURPOSE_get_id(const X509_PURPOSE *); + +STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x); +STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x); +void X509_email_free(STACK_OF(OPENSSL_STRING) *sk); +STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x); +/* Flags for X509_check_* functions */ + +/* + * Always check subject name for host match even if subject alt names present + */ +# define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT 0x1 +/* Disable wildcard matching for dnsName fields and common name. */ +# define X509_CHECK_FLAG_NO_WILDCARDS 0x2 +/* Wildcards must not match a partial label. */ +# define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0x4 +/* Allow (non-partial) wildcards to match multiple labels. */ +# define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS 0x8 +/* Constraint verifier subdomain patterns to match a single labels. */ +# define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0x10 +/* Never check the subject CN */ +# define X509_CHECK_FLAG_NEVER_CHECK_SUBJECT 0x20 +/* + * Match reference identifiers starting with "." to any sub-domain. + * This is a non-public flag, turned on implicitly when the subject + * reference identity is a DNS name. + */ +# define _X509_CHECK_FLAG_DOT_SUBDOMAINS 0x8000 + +int X509_check_host(X509 *x, const char *chk, size_t chklen, + unsigned int flags, char **peername); +int X509_check_email(X509 *x, const char *chk, size_t chklen, + unsigned int flags); +int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen, + unsigned int flags); +int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags); + +ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc); +ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc); +int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk, + unsigned long chtype); + +void X509_POLICY_NODE_print(BIO *out, X509_POLICY_NODE *node, int indent); +DEFINE_STACK_OF(X509_POLICY_NODE) + +#ifndef OPENSSL_NO_RFC3779 +typedef struct ASRange_st { + ASN1_INTEGER *min, *max; +} ASRange; + +# define ASIdOrRange_id 0 +# define ASIdOrRange_range 1 + +typedef struct ASIdOrRange_st { + int type; + union { + ASN1_INTEGER *id; + ASRange *range; + } u; +} ASIdOrRange; + +typedef STACK_OF(ASIdOrRange) ASIdOrRanges; +DEFINE_STACK_OF(ASIdOrRange) + +# define ASIdentifierChoice_inherit 0 +# define ASIdentifierChoice_asIdsOrRanges 1 + +typedef struct ASIdentifierChoice_st { + int type; + union { + ASN1_NULL *inherit; + ASIdOrRanges *asIdsOrRanges; + } u; +} ASIdentifierChoice; + +typedef struct ASIdentifiers_st { + ASIdentifierChoice *asnum, *rdi; +} ASIdentifiers; + +DECLARE_ASN1_FUNCTIONS(ASRange) +DECLARE_ASN1_FUNCTIONS(ASIdOrRange) +DECLARE_ASN1_FUNCTIONS(ASIdentifierChoice) +DECLARE_ASN1_FUNCTIONS(ASIdentifiers) + +typedef struct IPAddressRange_st { + ASN1_BIT_STRING *min, *max; +} IPAddressRange; + +# define IPAddressOrRange_addressPrefix 0 +# define IPAddressOrRange_addressRange 1 + +typedef struct IPAddressOrRange_st { + int type; + union { + ASN1_BIT_STRING *addressPrefix; + IPAddressRange *addressRange; + } u; +} IPAddressOrRange; + +typedef STACK_OF(IPAddressOrRange) IPAddressOrRanges; +DEFINE_STACK_OF(IPAddressOrRange) + +# define IPAddressChoice_inherit 0 +# define IPAddressChoice_addressesOrRanges 1 + +typedef struct IPAddressChoice_st { + int type; + union { + ASN1_NULL *inherit; + IPAddressOrRanges *addressesOrRanges; + } u; +} IPAddressChoice; + +typedef struct IPAddressFamily_st { + ASN1_OCTET_STRING *addressFamily; + IPAddressChoice *ipAddressChoice; +} IPAddressFamily; + +typedef STACK_OF(IPAddressFamily) IPAddrBlocks; +DEFINE_STACK_OF(IPAddressFamily) + +DECLARE_ASN1_FUNCTIONS(IPAddressRange) +DECLARE_ASN1_FUNCTIONS(IPAddressOrRange) +DECLARE_ASN1_FUNCTIONS(IPAddressChoice) +DECLARE_ASN1_FUNCTIONS(IPAddressFamily) + +/* + * API tag for elements of the ASIdentifer SEQUENCE. + */ +# define V3_ASID_ASNUM 0 +# define V3_ASID_RDI 1 + +/* + * AFI values, assigned by IANA. It'd be nice to make the AFI + * handling code totally generic, but there are too many little things + * that would need to be defined for other address families for it to + * be worth the trouble. + */ +# define IANA_AFI_IPV4 1 +# define IANA_AFI_IPV6 2 + +/* + * Utilities to construct and extract values from RFC3779 extensions, + * since some of the encodings (particularly for IP address prefixes + * and ranges) are a bit tedious to work with directly. + */ +int X509v3_asid_add_inherit(ASIdentifiers *asid, int which); +int X509v3_asid_add_id_or_range(ASIdentifiers *asid, int which, + ASN1_INTEGER *min, ASN1_INTEGER *max); +int X509v3_addr_add_inherit(IPAddrBlocks *addr, + const unsigned afi, const unsigned *safi); +int X509v3_addr_add_prefix(IPAddrBlocks *addr, + const unsigned afi, const unsigned *safi, + unsigned char *a, const int prefixlen); +int X509v3_addr_add_range(IPAddrBlocks *addr, + const unsigned afi, const unsigned *safi, + unsigned char *min, unsigned char *max); +unsigned X509v3_addr_get_afi(const IPAddressFamily *f); +int X509v3_addr_get_range(IPAddressOrRange *aor, const unsigned afi, + unsigned char *min, unsigned char *max, + const int length); + +/* + * Canonical forms. + */ +int X509v3_asid_is_canonical(ASIdentifiers *asid); +int X509v3_addr_is_canonical(IPAddrBlocks *addr); +int X509v3_asid_canonize(ASIdentifiers *asid); +int X509v3_addr_canonize(IPAddrBlocks *addr); + +/* + * Tests for inheritance and containment. + */ +int X509v3_asid_inherits(ASIdentifiers *asid); +int X509v3_addr_inherits(IPAddrBlocks *addr); +int X509v3_asid_subset(ASIdentifiers *a, ASIdentifiers *b); +int X509v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b); + +/* + * Check whether RFC 3779 extensions nest properly in chains. + */ +int X509v3_asid_validate_path(X509_STORE_CTX *); +int X509v3_addr_validate_path(X509_STORE_CTX *); +int X509v3_asid_validate_resource_set(STACK_OF(X509) *chain, + ASIdentifiers *ext, + int allow_inheritance); +int X509v3_addr_validate_resource_set(STACK_OF(X509) *chain, + IPAddrBlocks *ext, int allow_inheritance); + +#endif /* OPENSSL_NO_RFC3779 */ + +DEFINE_STACK_OF(ASN1_STRING) + +/* + * Admission Syntax + */ +typedef struct NamingAuthority_st NAMING_AUTHORITY; +typedef struct ProfessionInfo_st PROFESSION_INFO; +typedef struct Admissions_st ADMISSIONS; +typedef struct AdmissionSyntax_st ADMISSION_SYNTAX; +DECLARE_ASN1_FUNCTIONS(NAMING_AUTHORITY) +DECLARE_ASN1_FUNCTIONS(PROFESSION_INFO) +DECLARE_ASN1_FUNCTIONS(ADMISSIONS) +DECLARE_ASN1_FUNCTIONS(ADMISSION_SYNTAX) +DEFINE_STACK_OF(ADMISSIONS) +DEFINE_STACK_OF(PROFESSION_INFO) +typedef STACK_OF(PROFESSION_INFO) PROFESSION_INFOS; + +const ASN1_OBJECT *NAMING_AUTHORITY_get0_authorityId( + const NAMING_AUTHORITY *n); +const ASN1_IA5STRING *NAMING_AUTHORITY_get0_authorityURL( + const NAMING_AUTHORITY *n); +const ASN1_STRING *NAMING_AUTHORITY_get0_authorityText( + const NAMING_AUTHORITY *n); +void NAMING_AUTHORITY_set0_authorityId(NAMING_AUTHORITY *n, + ASN1_OBJECT* namingAuthorityId); +void NAMING_AUTHORITY_set0_authorityURL(NAMING_AUTHORITY *n, + ASN1_IA5STRING* namingAuthorityUrl); +void NAMING_AUTHORITY_set0_authorityText(NAMING_AUTHORITY *n, + ASN1_STRING* namingAuthorityText); + +const GENERAL_NAME *ADMISSION_SYNTAX_get0_admissionAuthority( + const ADMISSION_SYNTAX *as); +void ADMISSION_SYNTAX_set0_admissionAuthority( + ADMISSION_SYNTAX *as, GENERAL_NAME *aa); +const STACK_OF(ADMISSIONS) *ADMISSION_SYNTAX_get0_contentsOfAdmissions( + const ADMISSION_SYNTAX *as); +void ADMISSION_SYNTAX_set0_contentsOfAdmissions( + ADMISSION_SYNTAX *as, STACK_OF(ADMISSIONS) *a); +const GENERAL_NAME *ADMISSIONS_get0_admissionAuthority(const ADMISSIONS *a); +void ADMISSIONS_set0_admissionAuthority(ADMISSIONS *a, GENERAL_NAME *aa); +const NAMING_AUTHORITY *ADMISSIONS_get0_namingAuthority(const ADMISSIONS *a); +void ADMISSIONS_set0_namingAuthority(ADMISSIONS *a, NAMING_AUTHORITY *na); +const PROFESSION_INFOS *ADMISSIONS_get0_professionInfos(const ADMISSIONS *a); +void ADMISSIONS_set0_professionInfos(ADMISSIONS *a, PROFESSION_INFOS *pi); +const ASN1_OCTET_STRING *PROFESSION_INFO_get0_addProfessionInfo( + const PROFESSION_INFO *pi); +void PROFESSION_INFO_set0_addProfessionInfo( + PROFESSION_INFO *pi, ASN1_OCTET_STRING *aos); +const NAMING_AUTHORITY *PROFESSION_INFO_get0_namingAuthority( + const PROFESSION_INFO *pi); +void PROFESSION_INFO_set0_namingAuthority( + PROFESSION_INFO *pi, NAMING_AUTHORITY *na); +const STACK_OF(ASN1_STRING) *PROFESSION_INFO_get0_professionItems( + const PROFESSION_INFO *pi); +void PROFESSION_INFO_set0_professionItems( + PROFESSION_INFO *pi, STACK_OF(ASN1_STRING) *as); +const STACK_OF(ASN1_OBJECT) *PROFESSION_INFO_get0_professionOIDs( + const PROFESSION_INFO *pi); +void PROFESSION_INFO_set0_professionOIDs( + PROFESSION_INFO *pi, STACK_OF(ASN1_OBJECT) *po); +const ASN1_PRINTABLESTRING *PROFESSION_INFO_get0_registrationNumber( + const PROFESSION_INFO *pi); +void PROFESSION_INFO_set0_registrationNumber( + PROFESSION_INFO *pi, ASN1_PRINTABLESTRING *rn); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/include/openssl/x509v3err.h b/include/openssl/x509v3err.h new file mode 100644 index 0000000..6b3df12 --- /dev/null +++ b/include/openssl/x509v3err.h @@ -0,0 +1,158 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_X509V3ERR_H +# define HEADER_X509V3ERR_H + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_X509V3_strings(void); + +/* + * X509V3 function codes. + */ +# define X509V3_F_A2I_GENERAL_NAME 164 +# define X509V3_F_ADDR_VALIDATE_PATH_INTERNAL 166 +# define X509V3_F_ASIDENTIFIERCHOICE_CANONIZE 161 +# define X509V3_F_ASIDENTIFIERCHOICE_IS_CANONICAL 162 +# define X509V3_F_BIGNUM_TO_STRING 167 +# define X509V3_F_COPY_EMAIL 122 +# define X509V3_F_COPY_ISSUER 123 +# define X509V3_F_DO_DIRNAME 144 +# define X509V3_F_DO_EXT_I2D 135 +# define X509V3_F_DO_EXT_NCONF 151 +# define X509V3_F_GNAMES_FROM_SECTNAME 156 +# define X509V3_F_I2S_ASN1_ENUMERATED 121 +# define X509V3_F_I2S_ASN1_IA5STRING 149 +# define X509V3_F_I2S_ASN1_INTEGER 120 +# define X509V3_F_I2V_AUTHORITY_INFO_ACCESS 138 +# define X509V3_F_LEVEL_ADD_NODE 168 +# define X509V3_F_NOTICE_SECTION 132 +# define X509V3_F_NREF_NOS 133 +# define X509V3_F_POLICY_CACHE_CREATE 169 +# define X509V3_F_POLICY_CACHE_NEW 170 +# define X509V3_F_POLICY_DATA_NEW 171 +# define X509V3_F_POLICY_SECTION 131 +# define X509V3_F_PROCESS_PCI_VALUE 150 +# define X509V3_F_R2I_CERTPOL 130 +# define X509V3_F_R2I_PCI 155 +# define X509V3_F_S2I_ASN1_IA5STRING 100 +# define X509V3_F_S2I_ASN1_INTEGER 108 +# define X509V3_F_S2I_ASN1_OCTET_STRING 112 +# define X509V3_F_S2I_SKEY_ID 115 +# define X509V3_F_SET_DIST_POINT_NAME 158 +# define X509V3_F_SXNET_ADD_ID_ASC 125 +# define X509V3_F_SXNET_ADD_ID_INTEGER 126 +# define X509V3_F_SXNET_ADD_ID_ULONG 127 +# define X509V3_F_SXNET_GET_ID_ASC 128 +# define X509V3_F_SXNET_GET_ID_ULONG 129 +# define X509V3_F_TREE_INIT 172 +# define X509V3_F_V2I_ASIDENTIFIERS 163 +# define X509V3_F_V2I_ASN1_BIT_STRING 101 +# define X509V3_F_V2I_AUTHORITY_INFO_ACCESS 139 +# define X509V3_F_V2I_AUTHORITY_KEYID 119 +# define X509V3_F_V2I_BASIC_CONSTRAINTS 102 +# define X509V3_F_V2I_CRLD 134 +# define X509V3_F_V2I_EXTENDED_KEY_USAGE 103 +# define X509V3_F_V2I_GENERAL_NAMES 118 +# define X509V3_F_V2I_GENERAL_NAME_EX 117 +# define X509V3_F_V2I_IDP 157 +# define X509V3_F_V2I_IPADDRBLOCKS 159 +# define X509V3_F_V2I_ISSUER_ALT 153 +# define X509V3_F_V2I_NAME_CONSTRAINTS 147 +# define X509V3_F_V2I_POLICY_CONSTRAINTS 146 +# define X509V3_F_V2I_POLICY_MAPPINGS 145 +# define X509V3_F_V2I_SUBJECT_ALT 154 +# define X509V3_F_V2I_TLS_FEATURE 165 +# define X509V3_F_V3_GENERIC_EXTENSION 116 +# define X509V3_F_X509V3_ADD1_I2D 140 +# define X509V3_F_X509V3_ADD_VALUE 105 +# define X509V3_F_X509V3_EXT_ADD 104 +# define X509V3_F_X509V3_EXT_ADD_ALIAS 106 +# define X509V3_F_X509V3_EXT_I2D 136 +# define X509V3_F_X509V3_EXT_NCONF 152 +# define X509V3_F_X509V3_GET_SECTION 142 +# define X509V3_F_X509V3_GET_STRING 143 +# define X509V3_F_X509V3_GET_VALUE_BOOL 110 +# define X509V3_F_X509V3_PARSE_LIST 109 +# define X509V3_F_X509_PURPOSE_ADD 137 +# define X509V3_F_X509_PURPOSE_SET 141 + +/* + * X509V3 reason codes. + */ +# define X509V3_R_BAD_IP_ADDRESS 118 +# define X509V3_R_BAD_OBJECT 119 +# define X509V3_R_BN_DEC2BN_ERROR 100 +# define X509V3_R_BN_TO_ASN1_INTEGER_ERROR 101 +# define X509V3_R_DIRNAME_ERROR 149 +# define X509V3_R_DISTPOINT_ALREADY_SET 160 +# define X509V3_R_DUPLICATE_ZONE_ID 133 +# define X509V3_R_ERROR_CONVERTING_ZONE 131 +# define X509V3_R_ERROR_CREATING_EXTENSION 144 +# define X509V3_R_ERROR_IN_EXTENSION 128 +# define X509V3_R_EXPECTED_A_SECTION_NAME 137 +# define X509V3_R_EXTENSION_EXISTS 145 +# define X509V3_R_EXTENSION_NAME_ERROR 115 +# define X509V3_R_EXTENSION_NOT_FOUND 102 +# define X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED 103 +# define X509V3_R_EXTENSION_VALUE_ERROR 116 +# define X509V3_R_ILLEGAL_EMPTY_EXTENSION 151 +# define X509V3_R_INCORRECT_POLICY_SYNTAX_TAG 152 +# define X509V3_R_INVALID_ASNUMBER 162 +# define X509V3_R_INVALID_ASRANGE 163 +# define X509V3_R_INVALID_BOOLEAN_STRING 104 +# define X509V3_R_INVALID_EXTENSION_STRING 105 +# define X509V3_R_INVALID_INHERITANCE 165 +# define X509V3_R_INVALID_IPADDRESS 166 +# define X509V3_R_INVALID_MULTIPLE_RDNS 161 +# define X509V3_R_INVALID_NAME 106 +# define X509V3_R_INVALID_NULL_ARGUMENT 107 +# define X509V3_R_INVALID_NULL_NAME 108 +# define X509V3_R_INVALID_NULL_VALUE 109 +# define X509V3_R_INVALID_NUMBER 140 +# define X509V3_R_INVALID_NUMBERS 141 +# define X509V3_R_INVALID_OBJECT_IDENTIFIER 110 +# define X509V3_R_INVALID_OPTION 138 +# define X509V3_R_INVALID_POLICY_IDENTIFIER 134 +# define X509V3_R_INVALID_PROXY_POLICY_SETTING 153 +# define X509V3_R_INVALID_PURPOSE 146 +# define X509V3_R_INVALID_SAFI 164 +# define X509V3_R_INVALID_SECTION 135 +# define X509V3_R_INVALID_SYNTAX 143 +# define X509V3_R_ISSUER_DECODE_ERROR 126 +# define X509V3_R_MISSING_VALUE 124 +# define X509V3_R_NEED_ORGANIZATION_AND_NUMBERS 142 +# define X509V3_R_NO_CONFIG_DATABASE 136 +# define X509V3_R_NO_ISSUER_CERTIFICATE 121 +# define X509V3_R_NO_ISSUER_DETAILS 127 +# define X509V3_R_NO_POLICY_IDENTIFIER 139 +# define X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED 154 +# define X509V3_R_NO_PUBLIC_KEY 114 +# define X509V3_R_NO_SUBJECT_DETAILS 125 +# define X509V3_R_OPERATION_NOT_DEFINED 148 +# define X509V3_R_OTHERNAME_ERROR 147 +# define X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED 155 +# define X509V3_R_POLICY_PATH_LENGTH 156 +# define X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED 157 +# define X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY 159 +# define X509V3_R_SECTION_NOT_FOUND 150 +# define X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS 122 +# define X509V3_R_UNABLE_TO_GET_ISSUER_KEYID 123 +# define X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT 111 +# define X509V3_R_UNKNOWN_EXTENSION 129 +# define X509V3_R_UNKNOWN_EXTENSION_NAME 130 +# define X509V3_R_UNKNOWN_OPTION 120 +# define X509V3_R_UNSUPPORTED_OPTION 117 +# define X509V3_R_UNSUPPORTED_TYPE 167 +# define X509V3_R_USER_TOO_LONG 132 + +#endif diff --git a/include/png/IDATDecoder.hpp b/include/png/IDATDecoder.hpp new file mode 100644 index 0000000..a2a5761 --- /dev/null +++ b/include/png/IDATDecoder.hpp @@ -0,0 +1,19 @@ +#ifndef IDATDECODER_HPP +#define IDATDECODER_HPP + +#include "include/array/GrowableObjectArray.hpp" +#include "include/array/GrowableByteArray.hpp" +#include "include/png/PNGChunkIDAT.hpp" +#include "include/png/PNGChunkIHDR.hpp" + +class IDATDecoder{ + + public: + + static unsigned char* decompressIDATChunks(GrowableObjectArray* idatchunks, unsigned long* resultLength); + + static unsigned char** decodeIDATChunks(GrowableObjectArray* idatchunks ,unsigned long* resultLength, PNGChunkIHDR* imgInfo); + +}; + +#endif // IDATDECODER_HPP diff --git a/include/png/PNGChunk.hpp b/include/png/PNGChunk.hpp new file mode 100644 index 0000000..888ca5d --- /dev/null +++ b/include/png/PNGChunk.hpp @@ -0,0 +1,48 @@ +#ifndef PNGCHUNK_HPP +#define PNGCHUNK_HPP + +#include "include/array/GrowableObjectArray.hpp" + +class PNGChunk{ + + protected: + + unsigned int chunkLength; + unsigned int chunkTypeInt; + unsigned char* chunkData; + unsigned int crc32; + + PNGChunk(unsigned int chunkLength ,unsigned int type, const unsigned char* chunkData, unsigned int crc32); + + public: + + static const char* CHUNKTYPE_IHDR; + static const char* CHUNKTYPE_PHYS; + static const char* CHUNKTYPE_TEXT; + static const char* CHUNKTYPE_ZTXT; + static const char* CHUNKTYPE_TRNS; + static const char* CHUNKTYPE_IDAT; + static const char* CHUNKTYPE_PLTE; + static const char* CHUNKTYPE_ITXT; + static const char* CHUNKTYPE_TIME; + static const char* CHUNKTYPE_IEND; + + static unsigned int chunkTypeToInt(const char* type); + + static GrowableObjectArray* readChunks(const unsigned char* pngdata, const char* type); + + unsigned int getChunkLength(); + + unsigned int getChunkType(); + + const unsigned char* getChunkData(); + + unsigned int getCRC32(); + + unsigned int isCRC32Matched(); + + ~PNGChunk(); + +}; + +#endif // PNGCHUNK_HPP diff --git a/include/png/PNGChunkIDAT.hpp b/include/png/PNGChunkIDAT.hpp new file mode 100644 index 0000000..212ed2b --- /dev/null +++ b/include/png/PNGChunkIDAT.hpp @@ -0,0 +1,14 @@ +#ifndef PNGCHUNKIDAT_HPP +#define PNGCHUNKIDAT_HPP + +#include "include/png/PNGChunk.hpp" + +class PNGChunkIDAT : public PNGChunk{ + + public: + + PNGChunkIDAT(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + +}; + +#endif // PNGCHUNKIDAT_HPP diff --git a/include/png/PNGChunkIHDR.hpp b/include/png/PNGChunkIHDR.hpp new file mode 100644 index 0000000..2472cd2 --- /dev/null +++ b/include/png/PNGChunkIHDR.hpp @@ -0,0 +1,61 @@ +#ifndef PNGCHUNKIDHR_HPP +#define PNGCHUNKIDHR_HPP + +#include "include/png/PNGChunk.hpp" + +class PNGChunkIHDR : public PNGChunk{ + + private: + + unsigned int imgHeight; + unsigned int imgWidth; + unsigned int imgColorType; + unsigned int imgBitDepth; + unsigned int imgCompressMethod; + unsigned int imgFilterMethod; + unsigned int imgInterlaceMethod; + + public: + + static const unsigned char IMG_COLORTYPE_GRAYSCALE; + static const unsigned char IMG_COLORTYPE_GRAYSCALE_CHANNEL; + static const unsigned char IMG_COLORTYPE_TRUECOLOR; + static const unsigned char IMG_COLORTYPE_TRUECOLOR_CHANNEL; + static const unsigned char IMG_COLORTYPE_INDEXEDCOLOR; + static const unsigned char IMG_COLORTYPE_INDEXEDCOLOR_CHANNEL; + static const unsigned char IMG_COLORTYPE_ALPHA_GRAYSCALE; + static const unsigned char IMG_COLORTYPE_ALPHA_GRAYSCALE_CHANNEL; + static const unsigned char IMG_COLORTYPE_ALPHA_TRUECOLOR; + static const unsigned char IMG_COLORTYPE_ALPHA_TRUECOLOR_CHANNEL; + + static const unsigned char IMG_COMPRESS_METHOD_DEFAULT; + + static const unsigned char IMG_SCAN_METHOD_SCANLINE; + static const unsigned char IMG_SCAN_METHOD_ADAM7; + + PNGChunkIHDR(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + + unsigned int getImageHeight(); + + unsigned int getImageWidth(); + + unsigned int getImageColorType(); + + unsigned int getImageBitBepth(); + + unsigned int getImageCompressMethod(); + + unsigned int getImageFilterMethod(); + + unsigned int getImageInterlaceMethod(); + + unsigned int getCRC32(); + + unsigned int getColorChannelCount(); + + unsigned int getBitsPerPixel(); + + +}; + +#endif // PNGCHUNKIDHR_HPP diff --git a/include/png/PNGChunkITXT.hpp b/include/png/PNGChunkITXT.hpp new file mode 100644 index 0000000..b29dd15 --- /dev/null +++ b/include/png/PNGChunkITXT.hpp @@ -0,0 +1,39 @@ +#ifndef PNGCHUNKITXT_HPP +#define PNGCHUNKITXT_HPP + +#include "include/png/PNGChunk.hpp" + +class PNGChunkITXT : public PNGChunk{ + + private: + + unsigned char* keyword=0; + unsigned char compressFlag; + unsigned char compressMethod; + unsigned char* label=0; + unsigned char* translatedKeyword=0; + unsigned char* content=0; + + + public: + + PNGChunkITXT(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + + unsigned char isCompressed(); + + unsigned char getCompressMethod(); + + const unsigned char* getKeyword(); + + const unsigned char* getLabel(); + + const unsigned char* getTranslatedKeyword(); + + const unsigned char* getText(); + + ~PNGChunkITXT(); + + +}; + +#endif // PNGCHUNKITXT_HPP diff --git a/include/png/PNGChunkPHYS.hpp b/include/png/PNGChunkPHYS.hpp new file mode 100644 index 0000000..110daca --- /dev/null +++ b/include/png/PNGChunkPHYS.hpp @@ -0,0 +1,28 @@ +#ifndef PNGCHUNKPHYS_H +#define PNGCHUNKPHYS_H +#include "include/png/PNGChunk.hpp" + +class PNGChunkPHYS : public PNGChunk{ + + private: + + unsigned int pixelsPerUnitX; + unsigned int pixelsPerUnitY; + unsigned int unitToken; + + public: + + static const unsigned char UNIT_METER=1; + static const unsigned char UNIT_UNKNOWN=0; + + PNGChunkPHYS(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + + unsigned int getPixelsPerUnitX(); + + unsigned int getPixelsPerUnitY(); + + unsigned int getUnit(); + +}; + +#endif // PNGCHUNKPHYS_H diff --git a/include/png/PNGChunkPLTE.hpp b/include/png/PNGChunkPLTE.hpp new file mode 100644 index 0000000..c3a0773 --- /dev/null +++ b/include/png/PNGChunkPLTE.hpp @@ -0,0 +1,13 @@ +#ifndef PNGCHUNKPLTE_H +#define PNGCHUNKPLTE_H +#include "include/png/PNGChunk.hpp" + +class PNGChunkPLTE : public PNGChunk{ + + public: + + PNGChunkPLTE(unsigned int chunkLength, unsigned int type, const unsigned char* chunkData, unsigned int crc32); + +}; + +#endif // PNGCHUNKPLTE_H diff --git a/include/png/PNGChunkTEXT.hpp b/include/png/PNGChunkTEXT.hpp new file mode 100644 index 0000000..2df4489 --- /dev/null +++ b/include/png/PNGChunkTEXT.hpp @@ -0,0 +1,25 @@ +#ifndef PNGCHUNKTEXT_H +#define PNGCHUNKTEXT_H + +#include "include/png/PNGChunk.hpp" + +class PNGChunkTEXT : public PNGChunk{ + + private: + + unsigned char* keyword=0; + unsigned char* text=0; + + public: + + PNGChunkTEXT(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + + const unsigned char* getKeyword(); + + const unsigned char* getText(); + + ~PNGChunkTEXT(); + +}; + +#endif // PNGCHUNKTEXT_H diff --git a/include/png/PNGChunkTIME.hpp b/include/png/PNGChunkTIME.hpp new file mode 100644 index 0000000..59ad897 --- /dev/null +++ b/include/png/PNGChunkTIME.hpp @@ -0,0 +1,40 @@ +#ifndef PNGCHUNKTIME_HPP +#define PNGCHUNKTIME_HPP + +#include "include/png/PNGChunk.hpp" + +class PNGChunkTIME : public PNGChunk{ + + private: + + unsigned short year; + unsigned char month; + unsigned char day; + unsigned char hour; + unsigned char minute; + unsigned char seconds; + unsigned char* timeString=0; + + public: + + PNGChunkTIME(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + + unsigned short getYear(); + + unsigned char getMonth(); + + unsigned char getDay(); + + unsigned char getHour(); + + unsigned char getMinute(); + + unsigned char getSecond(); + + const unsigned char* getTimeString(); + + ~PNGChunkTIME(); + +}; + +#endif // PNGCHUNKTIME_HPP diff --git a/include/png/PNGChunkTRNS.hpp b/include/png/PNGChunkTRNS.hpp new file mode 100644 index 0000000..220bf7d --- /dev/null +++ b/include/png/PNGChunkTRNS.hpp @@ -0,0 +1,13 @@ +#ifndef PNGCHUNKTRNS_H +#define PNGCHUNKTRNS_H +#include "include/png/PNGChunk.hpp" + +class PNGChunkTRNS : public PNGChunk{ + + public: + + PNGChunkTRNS(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + +}; + +#endif // PNGCHUNKTRNS_H diff --git a/include/png/PNGChunkZTXT.hpp b/include/png/PNGChunkZTXT.hpp new file mode 100644 index 0000000..d30b1c6 --- /dev/null +++ b/include/png/PNGChunkZTXT.hpp @@ -0,0 +1,25 @@ +#ifndef PNGCHUNKZTXT_HPP +#define PNGCHUNKZTXT_HPP + +#include "include/png/PNGChunk.hpp" + +class PNGChunkZTXT : public PNGChunk{ + + private: + + unsigned char* keyword=0; + unsigned char* content=0; + + public: + + PNGChunkZTXT(unsigned int chunkLength, unsigned int chunkType, const unsigned char* chunkData, unsigned int crc32); + + const unsigned char* getKeyword(); + + const unsigned char* getText(); + + ~PNGChunkZTXT(); + +}; + +#endif // PNGCHUNKZTXT_HPP diff --git a/include/png/UnfilterAverage.hpp b/include/png/UnfilterAverage.hpp new file mode 100644 index 0000000..181e265 --- /dev/null +++ b/include/png/UnfilterAverage.hpp @@ -0,0 +1,18 @@ +#ifndef UNFILTERAVERAGE_H +#define UNFILTERAVERAGE_H + +class UnfilterAverage{ + + private: + + unsigned int bytesPerPixel=0; + + public: + + UnfilterAverage(unsigned int bitsPerPixel); + + unsigned char* unfilter(unsigned char* upperLine,unsigned char* currentLine,unsigned int dataLength); + +}; + +#endif // UNFILTERAVERAGE_H diff --git a/include/png/UnfilterNone.hpp b/include/png/UnfilterNone.hpp new file mode 100644 index 0000000..4aabdc8 --- /dev/null +++ b/include/png/UnfilterNone.hpp @@ -0,0 +1,12 @@ +#ifndef UNFILTERNONE_H +#define UNFILTERNONE_H + +class UnfilterNone{ + + public: + + unsigned char* unfilter(unsigned char* currentLine, unsigned int dataLength); + +}; + +#endif // UNFILTERNONE_H diff --git a/include/png/UnfilterPaeth.hpp b/include/png/UnfilterPaeth.hpp new file mode 100644 index 0000000..51848be --- /dev/null +++ b/include/png/UnfilterPaeth.hpp @@ -0,0 +1,18 @@ +#ifndef UNFILTERPAETH_H +#define UNFILTERPAETH_H + +class UnfilterPaeth{ + + private: + + unsigned int bytesPerPixel=0; + + public: + + UnfilterPaeth(unsigned int bitsPerPixel); + + unsigned char* unfilter(unsigned char* upperLine, unsigned char* currentLine, unsigned int dataLength); + +}; + +#endif // UNFILTERPAETH_H diff --git a/include/png/UnfilterSub.hpp b/include/png/UnfilterSub.hpp new file mode 100644 index 0000000..ff4c2f5 --- /dev/null +++ b/include/png/UnfilterSub.hpp @@ -0,0 +1,18 @@ +#ifndef UNFILTERSUB_HPP +#define UNFILTERSUB_HPP + +class UnfilterSub{ + + public: + + UnfilterSub(unsigned int bitsPerPixel); + + unsigned char* unfilter(const unsigned char* currentLine, unsigned int dataLength); + + private: + + unsigned int bytesPerPixel; + +}; + +#endif // UNFILTERSUB_HPP diff --git a/include/png/UnfilterUp.hpp b/include/png/UnfilterUp.hpp new file mode 100644 index 0000000..2b724a5 --- /dev/null +++ b/include/png/UnfilterUp.hpp @@ -0,0 +1,12 @@ +#ifndef UNFILTERUP_H +#define UNFILTERUP_H + +class UnfilterUp{ + + public: + + unsigned char* unfilter(unsigned char* upperLine, unsigned char* currentLine, unsigned int dataLength); + +}; + +#endif // UNFILTERUP_H diff --git a/include/raknet/AutopatcherPatchContext.hpp b/include/raknet/AutopatcherPatchContext.hpp new file mode 100644 index 0000000..36f1091 --- /dev/null +++ b/include/raknet/AutopatcherPatchContext.hpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __AUTOPATCHER_PATCH_CONTEXT_H +#define __AUTOPATCHER_PATCH_CONTEXT_H + +enum PatchContext +{ + PC_HASH_1_WITH_PATCH, + PC_HASH_2_WITH_PATCH, + PC_WRITE_FILE, + PC_ERROR_FILE_WRITE_FAILURE, + PC_ERROR_PATCH_TARGET_MISSING, + PC_ERROR_PATCH_APPLICATION_FAILURE, + PC_ERROR_PATCH_RESULT_CHECKSUM_FAILURE, + PC_NOTICE_WILL_COPY_ON_RESTART, + PC_NOTICE_FILE_DOWNLOADED, + PC_NOTICE_FILE_DOWNLOADED_PATCH, +}; + +#endif diff --git a/include/raknet/AutopatcherRepositoryInterface.hpp b/include/raknet/AutopatcherRepositoryInterface.hpp new file mode 100644 index 0000000..d2783a4 --- /dev/null +++ b/include/raknet/AutopatcherRepositoryInterface.hpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// +/// \file AutopatcherRepositoryInterface.h +/// \brief An interface used by AutopatcherServer to get the data necessary to run an autopatcher. +/// + + +#ifndef __AUTOPATCHER_REPOSITORY_INTERFACE_H +#define __AUTOPATCHER_REPOSITORY_INTERFACE_H + +#include "IncrementalReadInterface.hpp" +#include "SimpleMutex.hpp" + +namespace RakNet +{ +/// Forward declarations +class FileList; +class BitStream; + +/// An interface used by AutopatcherServer to get the data necessary to run an autopatcher. This is up to you to implement for custom repository solutions. +class AutopatcherRepositoryInterface : public IncrementalReadInterface +{ +public: + /// Get list of files added and deleted since a certain date. This is used by AutopatcherServer and not usually explicitly called. + /// \param[in] applicationName A null terminated string identifying the application + /// \param[out] addedFiles A list of the current versions of filenames with hashes as their data that were created after \a sinceData + /// \param[out] deletedFiles A list of the current versions of filenames that were deleted after \a sinceData + /// \param[in] An input date, in whatever format your repository uses + /// \param[out] currentDate The current server date, in whatever format your repository uses + /// \return True on success, false on failure. + virtual bool GetChangelistSinceDate(const char *applicationName, FileList *addedOrModifiedFilesWithHashData, FileList *deletedFiles, double sinceDate)=0; + + /// Get patches (or files) for every file in input, assuming that input has a hash for each of those files. + /// \param[in] applicationName A null terminated string identifying the application + /// \param[in] input A list of files with SHA1_LENGTH byte hashes to get from the database. + /// \param[out] patchList You should return list of files with either the filedata or the patch. This is a subset of \a input. The context data for each file will be either PC_WRITE_FILE (to just write the file) or PC_HASH_WITH_PATCH (to patch). If PC_HASH_WITH_PATCH, then the file contains a SHA1_LENGTH byte patch followed by the hash. The datalength is patchlength + SHA1_LENGTH + /// \param[out] currentDate The current server date, in whatever format your repository uses + /// \return 1 on success, 0 on database failure, -1 on tried to download original unmodified file + virtual int GetPatches(const char *applicationName, FileList *input, bool allowDownloadOfOriginalUnmodifiedFiles, FileList *patchList)=0; + + /// For the most recent update, return files that were patched, added, or deleted. For files that were patched, return both the patch in \a patchedFiles and the current version in \a updatedFiles + /// \param[in,out] applicationName Name of the application to get patches for. If empty, uses the most recently updated application, and the string will be updated to reflect this name. + /// \param[out] patchedFiles A list of patched files with op PC_HASH_2_WITH_PATCH. It has 2 hashes, the priorHash and the currentHash. The currentHash is checked on the client after patching for patch success. The priorHash is checked in AutopatcherServer::OnGetPatch() to see if the client is able to hash with the version they currently have + /// \param[out] patchedFiles A list of new files. It contains the actual data in addition to the filename + /// \param[out] addedOrModifiedFileHashes A list of file hashes that were either modified or new. This is returned to the client when replying to ID_AUTOPATCHER_CREATION_LIST, which tells the client what files have changed on the server since a certain date + /// \param[out] deletedFiles A list of the current versions of filenames that were deleted in the most recent patch + /// \param[out] whenPatched time in seconds since epoch when patched. Use time() function to get this in C + /// \return true on success, false on failure + virtual bool GetMostRecentChangelistWithPatches( + RakNet::RakString &applicationName, + FileList *patchedFiles, + FileList *updatedFiles, + FileList *addedOrModifiedFileHashes, + FileList *deletedFiles, + double *priorRowPatchTime, + double *mostRecentRowPatchTime)=0; + + /// \return Whatever this function returns is sent from the AutopatcherServer to the AutopatcherClient when one of the above functions returns false. + virtual const char *GetLastError(void) const=0; + + /// \return Passed to FileListTransfer::Send() as the _chunkSize parameter. + virtual const int GetIncrementalReadChunkSize(void) const=0; +}; + +} // namespace RakNet + +#endif + diff --git a/include/raknet/Base64Encoder.hpp b/include/raknet/Base64Encoder.hpp new file mode 100644 index 0000000..cdc610f --- /dev/null +++ b/include/raknet/Base64Encoder.hpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __BASE_64_ENCODER_H +#define __BASE_64_ENCODER_H + +#include "Export.hpp" + +extern "C" { +/// \brief Returns how many bytes were written. +// outputData should be at least the size of inputData * 2 + 6 +int Base64Encoding(const unsigned char *inputData, int dataLength, char *outputData); +} + +extern "C" { +const char *Base64Map(void); +} + +#endif diff --git a/include/raknet/BitStream.hpp b/include/raknet/BitStream.hpp new file mode 100644 index 0000000..a7863be --- /dev/null +++ b/include/raknet/BitStream.hpp @@ -0,0 +1,2048 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file BitStream.h +/// \brief This class allows you to write and read native types as a string of bits. +/// \details BitStream is used extensively throughout RakNet and is designed to be used by users as well. +/// + + +#if defined(_MSC_VER) && _MSC_VER < 1299 // VC6 doesn't support template specialization +#include "BitStream_NoTemplate.hpp" +#else + +#ifndef __BITSTREAM_H +#define __BITSTREAM_H + +#include "RakMemoryOverride.hpp" +#include "RakNetDefines.hpp" +#include "Export.hpp" +#include "RakNetTypes.hpp" +#include "RakString.hpp" +#include "RakWString.hpp" +#include "RakAssert.hpp" +#include +#include + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +// MSWin uses _copysign, others use copysign... +#ifndef _WIN32 +#define _copysign copysign +#endif + +namespace RakNet +{ + /// This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well. + /// \sa BitStreamSample.txt + class RAK_DLL_EXPORT BitStream + { + + public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(BitStream) + + /// Default Constructor + BitStream(); + + /// \brief Create the bitstream, with some number of bytes to immediately allocate. + /// \details There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE. + /// In that case all it does is save you one or more realloc calls. + /// \param[in] initialBytesToAllocate the number of bytes to pre-allocate. + BitStream( const unsigned int initialBytesToAllocate ); + + /// \brief Initialize the BitStream, immediately setting the data it contains to a predefined pointer. + /// \details Set \a _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data. + /// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory + /// 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows: + /// \code + /// RakNet::BitStream bs(packet->data, packet->length, false); + /// \endcode + /// \param[in] _data An array of bytes. + /// \param[in] lengthInBytes Size of the \a _data. + /// \param[in] _copyData true or false to make a copy of \a _data or not. + BitStream( unsigned char* _data, const unsigned int lengthInBytes, bool _copyData ); + + // Destructor + ~BitStream(); + + /// Resets the bitstream for reuse. + void Reset( void ); + + /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutTemplateVar The value to write + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template + bool Serialize(bool writeToBitstream, templateType &inOutTemplateVar); + + /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. + /// \details If the current value is different from the last value + /// the current value will be written. Otherwise, a single bit will be written + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutCurrentValue The current value to write + /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template + bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue); + + /// \brief Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value. + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutCurrentValue The current value to write + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template + bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue); + + /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutTemplateVar The value to write + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template + bool SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar); + + /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. + /// \details If the current value is different from the last value + /// the current value will be written. Otherwise, a single bit will be written + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutCurrentValue The current value to write + /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template + bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue); + + /// \brief Save as SerializeCompressedDelta(templateType ¤tValue, const templateType &lastValue) when we have an unknown second parameter + /// \return true on data read. False on insufficient data in bitstream + template + bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutTemplateVar); + + /// \brief Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping. + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutByteArray a byte buffer + /// \param[in] numberOfBytes the size of \a input in bytes + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + bool Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes ); + + /// \brief Serialize a float into 2 bytes, spanning the range between \a floatMin and \a floatMax + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutFloat The float to write + /// \param[in] floatMin Predetermined minimum value of f + /// \param[in] floatMax Predetermined maximum value of f + bool SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax); + + /// Serialize one type casted to another (smaller) type, to save bandwidth + /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t + /// Example: int num=53; SerializeCasted(true, num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes) + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] value The value to serialize + template + bool SerializeCasted( bool writeToBitstream, sourceType &value ); + + /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range + /// Then serialize only those bits + /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum + /// \param[in] minimum Minimum value of \a value + /// \param[in] maximum Maximum value of \a value + /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates + template + bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); + /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum + template + bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); + + /// \brief Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. + /// \details Will further compress y or z axis aligned vectors. + /// Accurate to 1/32767.5. + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template // templateType for this function must be a float or double + bool SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); + + /// \brief Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12. + /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important. + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template // templateType for this function must be a float or double + bool SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); + + /// \brief Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] w w + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + template // templateType for this function must be a float or double + bool SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z); + + /// \brief Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. + /// \details Use 6 bytes instead of 36 + /// Lossy, although the result is renormalized + /// \return true on success, false on failure. + template // templateType for this function must be a float or double + bool SerializeOrthMatrix( + bool writeToBitstream, + templateType &m00, templateType &m01, templateType &m02, + templateType &m10, templateType &m11, templateType &m12, + templateType &m20, templateType &m21, templateType &m22 ); + + /// \brief Bidirectional serialize/deserialize numberToSerialize bits to/from the input. + /// \details Right aligned data means in the case of a partial byte, the bits are aligned + /// from the right (bit 0) rather than the left (as in the normal + /// internal representation) You would set this to true when + /// writing user data, and false when copying bitstream data, such + /// as writing one bitstream to another + /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data + /// \param[in] inOutByteArray The data + /// \param[in] numberOfBitsToSerialize The number of bits to write + /// \param[in] rightAlignedBits if true data will be right aligned + /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. + bool SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits = true ); + + /// \brief Write any integral type to a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// \param[in] inTemplateVar The value to write + template + void Write(const templateType &inTemplateVar); + + /// \brief Write the dereferenced pointer to any integral type to a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// \param[in] inTemplateVar The value to write + template + void WritePtr(templateType *inTemplateVar); + + /// \brief Write any integral type to a bitstream. + /// \details If the current value is different from the last value + /// the current value will be written. Otherwise, a single bit will be written + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template + void WriteDelta(const templateType ¤tValue, const templateType &lastValue); + + /// \brief WriteDelta when you don't know what the last value is, or there is no last value. + /// \param[in] currentValue The current value to write + template + void WriteDelta(const templateType ¤tValue); + + /// \brief Write any integral type to a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// \param[in] inTemplateVar The value to write + template + void WriteCompressed(const templateType &inTemplateVar); + + /// \brief Write any integral type to a bitstream. + /// \details If the current value is different from the last value + /// the current value will be written. Otherwise, a single bit will be written + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template + void WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue); + + /// \brief Save as WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) when we have an unknown second parameter + template + void WriteCompressedDelta(const templateType ¤tValue); + + /// \brief Read any integral type from a bitstream. + /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping. + /// \param[in] outTemplateVar The value to read + /// \return true on success, false on failure. + template + bool Read(templateType &outTemplateVar); + + /// \brief Read any integral type from a bitstream. + /// \details If the written value differed from the value compared against in the write function, + /// var will be updated. Otherwise it will retain the current value. + /// ReadDelta is only valid from a previous call to WriteDelta + /// \param[in] outTemplateVar The value to read + /// \return true on success, false on failure. + template + bool ReadDelta(templateType &outTemplateVar); + + /// \brief Read any integral type from a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// \param[in] outTemplateVar The value to read + /// \return true on success, false on failure. + template + bool ReadCompressed(templateType &outTemplateVar); + + /// \brief Read any integral type from a bitstream. + /// \details If the written value differed from the value compared against in the write function, + /// var will be updated. Otherwise it will retain the current value. + /// the current value will be updated. + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// ReadCompressedDelta is only valid from a previous call to WriteDelta + /// \param[in] outTemplateVar The value to read + /// \return true on success, false on failure. + template + bool ReadCompressedDelta(templateType &outTemplateVar); + + /// \brief Read one bitstream to another. + /// \param[in] numberOfBits bits to read + /// \param bitStream the bitstream to read into from + /// \return true on success, false on failure. + bool Read( BitStream *bitStream, BitSize_t numberOfBits ); + bool Read( BitStream *bitStream ); + bool Read( BitStream &bitStream, BitSize_t numberOfBits ); + bool Read( BitStream &bitStream ); + + /// \brief Write an array or casted stream or raw data. This does NOT do endian swapping. + /// \param[in] inputByteArray a byte buffer + /// \param[in] numberOfBytes the size of \a input in bytes + void Write( const char* inputByteArray, const unsigned int numberOfBytes ); + + /// \brief Write one bitstream to another. + /// \param[in] numberOfBits bits to write + /// \param bitStream the bitstream to copy from + void Write( BitStream *bitStream, BitSize_t numberOfBits ); + void Write( BitStream *bitStream ); + void Write( BitStream &bitStream, BitSize_t numberOfBits ); + void Write( BitStream &bitStream );\ + + /// \brief Write a float into 2 bytes, spanning the range between \a floatMin and \a floatMax + /// \param[in] x The float to write + /// \param[in] floatMin Predetermined minimum value of f + /// \param[in] floatMax Predetermined maximum value of f + void WriteFloat16( float x, float floatMin, float floatMax ); + + /// Write one type serialized as another (smaller) type, to save bandwidth + /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t + /// Example: int num=53; WriteCasted(num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes) + /// \param[in] value The value to write + template + void WriteCasted( const sourceType &value ); + + /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range + /// Then write only those bits + /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program + /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum + /// \param[in] minimum Minimum value of \a value + /// \param[in] maximum Maximum value of \a value + /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Read(). + template + void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); + /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum + template + void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); + + /// \brief Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. + /// \details Will further compress y or z axis aligned vectors. + /// Accurate to 1/32767.5. + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + template // templateType for this function must be a float or double + void WriteNormVector( templateType x, templateType y, templateType z ); + + /// \brief Write a vector, using 10 bytes instead of 12. + /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, + /// so only use if accuracy is not important. + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + template // templateType for this function must be a float or double + void WriteVector( templateType x, templateType y, templateType z ); + + /// \brief Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. + /// \param[in] w w + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + template // templateType for this function must be a float or double + void WriteNormQuat( templateType w, templateType x, templateType y, templateType z); + + /// \brief Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. + /// \details Use 6 bytes instead of 36 + /// Lossy, although the result is renormalized + template // templateType for this function must be a float or double + void WriteOrthMatrix( + templateType m00, templateType m01, templateType m02, + templateType m10, templateType m11, templateType m12, + templateType m20, templateType m21, templateType m22 ); + + /// \brief Read an array or casted stream of byte. + /// \details The array is raw data. There is no automatic endian conversion with this function + /// \param[in] output The result byte array. It should be larger than @em numberOfBytes. + /// \param[in] numberOfBytes The number of byte to read + /// \return true on success false if there is some missing bytes. + bool Read( char* output, const unsigned int numberOfBytes ); + + /// \brief Read a float into 2 bytes, spanning the range between \a floatMin and \a floatMax + /// \param[in] outFloat The float to read + /// \param[in] floatMin Predetermined minimum value of f + /// \param[in] floatMax Predetermined maximum value of f + bool ReadFloat16( float &outFloat, float floatMin, float floatMax ); + + /// Read one type serialized to another (smaller) type, to save bandwidth + /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t + /// Example: int num; ReadCasted(num); would read 1 bytefrom the stream, and put the value in an integer + /// \param[in] value The value to write + template + bool ReadCasted( sourceType &value ); + + /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range + /// Then read only those bits + /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program + /// \param[in] value Integer value to read, which should be between \a minimum and \a maximum + /// \param[in] minimum Minimum value of \a value + /// \param[in] maximum Maximum value of \a value + /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Write(). + template + bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false ); + /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum + template + bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false ); + + /// \brief Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. + /// \details Will further compress y or z axis aligned vectors. + /// Accurate to 1/32767.5. + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + /// \return true on success, false on failure. + template // templateType for this function must be a float or double + bool ReadNormVector( templateType &x, templateType &y, templateType &z ); + + /// \brief Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector. + /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, + /// so only use if accuracy is not important. + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + /// \return true on success, false on failure. + template // templateType for this function must be a float or double + bool ReadVector( templateType &x, templateType &y, templateType &z ); + + /// \brief Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. + /// \param[in] w w + /// \param[in] x x + /// \param[in] y y + /// \param[in] z z + /// \return true on success, false on failure. + template // templateType for this function must be a float or double + bool ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z); + + /// \brief Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolatig the 4th. + /// \details Use 6 bytes instead of 36 + /// Lossy, although the result is renormalized + /// \return true on success, false on failure. + template // templateType for this function must be a float or double + bool ReadOrthMatrix( + templateType &m00, templateType &m01, templateType &m02, + templateType &m10, templateType &m11, templateType &m12, + templateType &m20, templateType &m21, templateType &m22 ); + + /// \brief Sets the read pointer back to the beginning of your data. + void ResetReadPointer( void ); + + /// \brief Sets the write pointer back to the beginning of your data. + void ResetWritePointer( void ); + + /// \brief This is good to call when you are done with the stream to make + /// sure you didn't leave any data left over void + void AssertStreamEmpty( void ); + + /// \brief RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging. + void PrintBits( char *out ) const; + void PrintBits( void ) const; + void PrintHex( char *out ) const; + void PrintHex( void ) const; + + /// \brief Ignore data we don't intend to read + /// \param[in] numberOfBits The number of bits to ignore + void IgnoreBits( const BitSize_t numberOfBits ); + + /// \brief Ignore data we don't intend to read + /// \param[in] numberOfBits The number of bytes to ignore + void IgnoreBytes( const unsigned int numberOfBytes ); + + /// \brief Move the write pointer to a position on the array. + /// \param[in] offset the offset from the start of the array. + /// \attention + /// \details Dangerous if you don't know what you are doing! + /// For efficiency reasons you can only write mid-stream if your data is byte aligned. + void SetWriteOffset( const BitSize_t offset ); + + /// \brief Returns the length in bits of the stream + inline BitSize_t GetNumberOfBitsUsed( void ) const {return GetWriteOffset();} + inline BitSize_t GetWriteOffset( void ) const {return numberOfBitsUsed;} + + /// \brief Returns the length in bytes of the stream + inline BitSize_t GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );} + + /// \brief Returns the number of bits into the stream that we have read + inline BitSize_t GetReadOffset( void ) const {return readOffset;} + + /// \brief Sets the read bit index + void SetReadOffset( const BitSize_t newReadOffset ) {readOffset=newReadOffset;} + + /// \brief Returns the number of bits left in the stream that haven't been read + inline BitSize_t GetNumberOfUnreadBits( void ) const {return numberOfBitsUsed - readOffset;} + + /// \brief Makes a copy of the internal data for you \a _data will point to + /// the stream. Partial bytes are left aligned. + /// \param[out] _data The allocated copy of GetData() + /// \return The length in bits of the stream. + BitSize_t CopyData( unsigned char** _data ) const; + + /// \internal + /// Set the stream to some initial data. + void SetData( unsigned char *inByteArray ); + + /// Gets the data that BitStream is writing to / reading from. + /// Partial bytes are left aligned. + /// \return A pointer to the internal state + inline unsigned char* GetData( void ) const {return data;} + + /// \brief Write numberToWrite bits from the input source. + /// \details Right aligned data means in the case of a partial byte, the bits are aligned + /// from the right (bit 0) rather than the left (as in the normal + /// internal representation) You would set this to true when + /// writing user data, and false when copying bitstream data, such + /// as writing one bitstream to another. + /// \param[in] inByteArray The data + /// \param[in] numberOfBitsToWrite The number of bits to write + /// \param[in] rightAlignedBits if true data will be right aligned + void WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits = true ); + + /// \brief Align the bitstream to the byte boundary and then write the + /// specified number of bits. + /// \details This is faster than WriteBits but + /// wastes the bits to do the alignment and requires you to call + /// ReadAlignedBits at the corresponding read position. + /// \param[in] inByteArray The data + /// \param[in] numberOfBytesToWrite The size of input. + void WriteAlignedBytes( const unsigned char *inByteArray, const unsigned int numberOfBytesToWrite ); + + // Endian swap bytes already in the bitstream + void EndianSwapBytes( int byteOffset, int length ); + + /// \brief Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite + /// \param[in] inByteArray The data + /// \param[in] inputLength The size of input. + /// \param[in] maxBytesToWrite Max bytes to write + void WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite ); + + /// \brief Read bits, starting at the next aligned bits. + /// \details Note that the modulus 8 starting offset of the sequence must be the same as + /// was used with WriteBits. This will be a problem with packet + /// coalescence unless you byte align the coalesced packets. + /// \param[in] inOutByteArray The byte array larger than @em numberOfBytesToRead + /// \param[in] numberOfBytesToRead The number of byte to read from the internal state + /// \return true if there is enough byte. + bool ReadAlignedBytes( unsigned char *inOutByteArray, const unsigned int numberOfBytesToRead ); + + /// \brief Reads what was written by WriteAlignedBytesSafe. + /// \param[in] inOutByteArray The data + /// \param[in] maxBytesToRead Maximum number of bytes to read + /// \return true on success, false on failure. + bool ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead ); + bool ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ); + + /// \brief Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to + /// \param[in] outByteArray outByteArray will be deleted if it is not a pointer to 0 + /// \return true on success, false on failure. + bool ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead ); + bool ReadAlignedBytesSafeAlloc( char **outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ); + + /// \brief Align the next write and/or read to a byte boundary. + /// \details This can be used to 'waste' bits to byte align for efficiency reasons It + /// can also be used to force coalesced bitstreams to start on byte + /// boundaries so so WriteAlignedBits and ReadAlignedBits both + /// calculate the same offset when aligning. + inline void AlignWriteToByteBoundary( void ) {numberOfBitsUsed += 8 - ( (( numberOfBitsUsed - 1 ) & 7) + 1 );} + + /// \brief Align the next write and/or read to a byte boundary. + /// \details This can be used to 'waste' bits to byte align for efficiency reasons It + /// can also be used to force coalesced bitstreams to start on byte + /// boundaries so so WriteAlignedBits and ReadAlignedBits both + /// calculate the same offset when aligning. + inline void AlignReadToByteBoundary( void ) {readOffset += 8 - ( (( readOffset - 1 ) & 7 ) + 1 );} + + /// \brief Read \a numberOfBitsToRead bits to the output source. + /// \details alignBitsToRight should be set to true to convert internal + /// bitstream data to userdata. It should be false if you used + /// WriteBits with rightAlignedBits false + /// \param[in] inOutByteArray The resulting bits array + /// \param[in] numberOfBitsToRead The number of bits to read + /// \param[in] alignBitsToRight if true bits will be right aligned. + /// \return true if there is enough bits to read + bool ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight = true ); + + /// \brief Write a 0 + void Write0( void ); + + /// \brief Write a 1 + void Write1( void ); + + /// \brief Reads 1 bit and returns true if that bit is 1 and false if it is 0. + bool ReadBit( void ); + + /// \brief If we used the constructor version with copy data off, this + /// *makes sure it is set to on and the data pointed to is copied. + void AssertCopyData( void ); + + /// \brief Use this if you pass a pointer copy to the constructor + /// *(_copyData==false) and want to overallocate to prevent + /// reallocation. + void SetNumberOfBitsAllocated( const BitSize_t lengthInBits ); + + /// \brief Reallocates (if necessary) in preparation of writing numberOfBitsToWrite + void AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite ); + + /// \internal + /// \return How many bits have been allocated internally + BitSize_t GetNumberOfBitsAllocated(void) const; + + /// \brief Read strings, non reference. + bool Read(char *varString); + bool Read(unsigned char *varString); + + /// Write zeros until the bitstream is filled up to \a bytes + void PadWithZeroToByteLength( unsigned int bytes ); + + /// Get the number of leading zeros for a number + /// \param[in] x Number to test + static int NumberOfLeadingZeroes( uint8_t x ); + static int NumberOfLeadingZeroes( uint16_t x ); + static int NumberOfLeadingZeroes( uint32_t x ); + static int NumberOfLeadingZeroes( uint64_t x ); + static int NumberOfLeadingZeroes( int8_t x ); + static int NumberOfLeadingZeroes( int16_t x ); + static int NumberOfLeadingZeroes( int32_t x ); + static int NumberOfLeadingZeroes( int64_t x ); + + /// \internal Unrolled inner loop, for when performance is critical + void WriteAlignedVar8(const char *inByteArray); + /// \internal Unrolled inner loop, for when performance is critical + bool ReadAlignedVar8(char *inOutByteArray); + /// \internal Unrolled inner loop, for when performance is critical + void WriteAlignedVar16(const char *inByteArray); + /// \internal Unrolled inner loop, for when performance is critical + bool ReadAlignedVar16(char *inOutByteArray); + /// \internal Unrolled inner loop, for when performance is critical + void WriteAlignedVar32(const char *inByteArray); + /// \internal Unrolled inner loop, for when performance is critical + bool ReadAlignedVar32(char *inOutByteArray); + + inline void Write(const char * const inStringVar) + { + RakString::Serialize(inStringVar, this); + } + inline void Write(const wchar_t * const inStringVar) + { + RakWString::Serialize(inStringVar, this); + } + inline void Write(const unsigned char * const inTemplateVar) + { + Write((const char*)inTemplateVar); + } + inline void Write(char * const inTemplateVar) + { + Write((const char*)inTemplateVar); + } + inline void Write(unsigned char * const inTemplateVar) + { + Write((const char*)inTemplateVar); + } + inline void WriteCompressed(const char * const inStringVar) + { + RakString::SerializeCompressed(inStringVar,this,0,false); + } + inline void WriteCompressed(const wchar_t * const inStringVar) + { + RakWString::Serialize(inStringVar,this); + } + inline void WriteCompressed(const unsigned char * const inTemplateVar) + { + WriteCompressed((const char*) inTemplateVar); + } + inline void WriteCompressed(char * const inTemplateVar) + { + WriteCompressed((const char*) inTemplateVar); + } + inline void WriteCompressed(unsigned char * const inTemplateVar) + { + WriteCompressed((const char*) inTemplateVar); + } + + /// ---- Member function template specialization declarations ---- + // Used for VC7 +#if defined(_MSC_VER) && _MSC_VER == 1300 + /// Write a bool to a bitstream. + /// \param[in] var The value to write + template <> + void Write(const bool &var); + + /// Write a systemAddress to a bitstream + /// \param[in] var The value to write + template <> + void Write(const SystemAddress &var); + + /// Write a uint24_t to a bitstream + /// \param[in] var The value to write + template <> + void Write(const uint24_t &var); + + /// Write a RakNetGUID to a bitsteam + /// \param[in] var The value to write + template <> + void Write(const RakNetGuid &var); + + /// Write a string to a bitstream + /// \param[in] var The value to write + template <> + void Write(const char* const &var); + template <> + void Write(const unsigned char* const &var); + template <> + void Write(char* const &var); + template <> + void Write(unsigned char* const &var); + template <> + void Write(const RakString &var); + template <> + void Write(const RakWString &var); + + /// \brief Write a systemAddress. + /// \details If the current value is different from the last value + /// the current value will be written. Otherwise, a single bit will be written + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template <> + void WriteDelta(const SystemAddress ¤tValue, const SystemAddress &lastValue); + + template <> + void WriteDelta(const uint24_t ¤tValue, const uint24_t &lastValue); + + template <> + void WriteDelta(const RakNetGUID ¤tValue, const RakNetGUID &lastValue); + + /// \brief Write a bool delta. + /// \details Same thing as just calling Write + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template <> + void WriteDelta(const bool ¤tValue, const bool &lastValue); + + template <> + void WriteCompressed(const SystemAddress &var); + + template <> + void WriteCompressed(const uint24_t &var); + + template <> + void WriteCompressed(const RakNetGUID &var); + + template <> + void WriteCompressed(const bool &var); + + /// For values between -1 and 1 + template <> + void WriteCompressed(const float &var); + + /// For values between -1 and 1 + template <> + void WriteCompressed(const double &var); + + /// Compressed string + template <> + void WriteCompressed(const char* var); + template <> + void WriteCompressed(const unsigned char* var); + template <> + void WriteCompressed(char* var); + template <> + void WriteCompressed(unsigned char* var); + template <> + void WriteCompressed(const RakString &var); + template <> + void WriteCompressed(const RakWString &var); + + /// \brief Write a bool delta. + /// \details Same thing as just calling Write + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template <> + void WriteCompressedDelta(const bool ¤tValue, const bool &lastValue); + + /// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) + /// when we have an unknown second bool + template <> + void WriteCompressedDelta(const bool ¤tValue); + + /// \brief Read a bool from a bitstream. + /// \param[in] var The value to read + /// \return true on success, false on failure. + template <> + bool Read(bool &var); + + /// \brief Read a systemAddress from a bitstream. + /// \param[in] var The value to read + /// \return true on success, false on failure. + template <> + bool Read(SystemAddress &var); + + template <> + bool Read(uint24_t &var); + + template <> + bool Read(RakNetGUID &var); + + /// \brief Read a String from a bitstream. + /// \param[in] var The value to read + /// \return true on success, false on failure. + template <> + bool Read(char *&var); + template <> + bool Read(wchar_t *&var); + template <> + bool Read(unsigned char *&var); + template <> + bool Read(RakString &var); + template <> + bool Read(RakWString &var); + + /// \brief Read a bool from a bitstream. + /// \param[in] var The value to read + /// \return true on success, false on failure. + template <> + bool ReadDelta(bool &var); + + template <> + bool ReadCompressed(SystemAddress &var); + + template <> + bool ReadCompressed(uint24_t &var); + + template <> + bool ReadCompressed(RakNetGUID &var); + + template <> + bool ReadCompressed(bool &var); + + template <> + bool ReadCompressed(float &var); + + /// For values between -1 and 1 + /// \return true on success, false on failure. + template <> + bool ReadCompressed(double &var); + + template <> + bool ReadCompressed(char* &var); + template <> + bool ReadCompressed(wchar_t* &var); + template <> + bool ReadCompressed(unsigned char *&var); + template <> + bool ReadCompressed(RakString &var); + template <> + bool ReadCompressed(RakWString &var); + + /// \brief Read a bool from a bitstream. + /// \param[in] var The value to read + /// \return true on success, false on failure. + template <> + bool ReadCompressedDelta(bool &var); +#endif + + inline static bool DoEndianSwap(void) { +#ifndef __BITSTREAM_NATIVE_END + return IsNetworkOrder()==false; +#else + return false; +#endif + } + inline static bool IsBigEndian(void) + { + return IsNetworkOrder(); + } + inline static bool IsNetworkOrder(void) {bool r = IsNetworkOrderInternal(); return r;} + // Not inline, won't compile on PC due to winsock include errors + static bool IsNetworkOrderInternal(void); + static void ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length); + static void ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length); + + private: + + BitStream( const BitStream &invalid) { + (void) invalid; + RakAssert(0); + } + + BitStream& operator = ( const BitStream& invalid ) { + (void) invalid; + RakAssert(0); + static BitStream i; + return i; + } + + /// \brief Assume the input source points to a native type, compress and write it. + void WriteCompressed( const unsigned char* inByteArray, const unsigned int size, const bool unsignedData ); + + /// \brief Assume the input source points to a compressed native type. Decompress and read it. + bool ReadCompressed( unsigned char* inOutByteArray, const unsigned int size, const bool unsignedData ); + + + BitSize_t numberOfBitsUsed; + + BitSize_t numberOfBitsAllocated; + + BitSize_t readOffset; + + unsigned char *data; + + /// true if the internal buffer is copy of the data passed to the constructor + bool copyData; + + /// BitStreams that use less than BITSTREAM_STACK_ALLOCATION_SIZE use the stack, rather than the heap to store data. It switches over if BITSTREAM_STACK_ALLOCATION_SIZE is exceeded + unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE]; + }; + + template + inline bool BitStream::Serialize(bool writeToBitstream, templateType &inOutTemplateVar) + { + if (writeToBitstream) + Write(inOutTemplateVar); + else + return Read(inOutTemplateVar); + return true; + } + + template + inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue) + { + if (writeToBitstream) + WriteDelta(inOutCurrentValue, lastValue); + else + return ReadDelta(inOutCurrentValue); + return true; + } + + template + inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue) + { + if (writeToBitstream) + WriteDelta(inOutCurrentValue); + else + return ReadDelta(inOutCurrentValue); + return true; + } + + template + inline bool BitStream::SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar) + { + if (writeToBitstream) + WriteCompressed(inOutTemplateVar); + else + return ReadCompressed(inOutTemplateVar); + return true; + } + + template + inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue) + { + if (writeToBitstream) + WriteCompressedDelta(inOutCurrentValue,lastValue); + else + return ReadCompressedDelta(inOutCurrentValue); + return true; + } +//Stoppedhere + template + inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue) + { + if (writeToBitstream) + WriteCompressedDelta(inOutCurrentValue); + else + return ReadCompressedDelta(inOutCurrentValue); + return true; + } + + inline bool BitStream::Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes ) + { + if (writeToBitstream) + Write(inOutByteArray, numberOfBytes); + else + return Read(inOutByteArray, numberOfBytes); + return true; + } + + template + bool BitStream::SerializeCasted( bool writeToBitstream, sourceType &value ) + { + if (writeToBitstream) WriteCasted(value); + else return ReadCasted(value); + return true; + } + + template + bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange ) + { + int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); + return SerializeBitsFromIntegerRange(writeToBitstream,value,minimum,maximum,requiredBits,allowOutsideRange); + } + template + bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange ) + { + if (writeToBitstream) WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); + else return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); + return true; + } + + template + inline bool BitStream::SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) + { + if (writeToBitstream) + WriteNormVector(x,y,z); + else + return ReadNormVector(x,y,z); + return true; + } + + template + inline bool BitStream::SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) + { + if (writeToBitstream) + WriteVector(x,y,z); + else + return ReadVector(x,y,z); + return true; + } + + template + inline bool BitStream::SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z) + { + if (writeToBitstream) + WriteNormQuat(w,x,y,z); + else + return ReadNormQuat(w,x,y,z); + return true; + } + + template + inline bool BitStream::SerializeOrthMatrix( + bool writeToBitstream, + templateType &m00, templateType &m01, templateType &m02, + templateType &m10, templateType &m11, templateType &m12, + templateType &m20, templateType &m21, templateType &m22 ) + { + if (writeToBitstream) + WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); + else + return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); + return true; + } + + inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits ) + { + if (writeToBitstream) + WriteBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits); + else + return ReadBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits); + return true; + } + + template + inline void BitStream::Write(const templateType &inTemplateVar) + { +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + if (sizeof(inTemplateVar)==1) + WriteBits( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true ); + else + { +#ifndef __BITSTREAM_NATIVE_END + if (DoEndianSwap()) + { + unsigned char output[sizeof(templateType)]; + ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType)); + WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); + } + else +#endif + WriteBits( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true ); + } + } + + template + inline void BitStream::WritePtr(templateType *inTemplateVar) + { +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + if (sizeof(templateType)==1) + WriteBits( ( unsigned char* ) inTemplateVar, sizeof( templateType ) * 8, true ); + else + { +#ifndef __BITSTREAM_NATIVE_END + if (DoEndianSwap()) + { + unsigned char output[sizeof(templateType)]; + ReverseBytes((unsigned char*) inTemplateVar, output, sizeof(templateType)); + WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); + } + else +#endif + WriteBits( ( unsigned char* ) inTemplateVar, sizeof(templateType) * 8, true ); + } + } + + /// \brief Write a bool to a bitstream. + /// \param[in] inTemplateVar The value to write + template <> + inline void BitStream::Write(const bool &inTemplateVar) + { + if ( inTemplateVar ) + Write1(); + else + Write0(); + } + + + /// \brief Write a systemAddress to a bitstream. + /// \param[in] inTemplateVar The value to write + template <> + inline void BitStream::Write(const SystemAddress &inTemplateVar) + { + Write(inTemplateVar.GetIPVersion()); + if (inTemplateVar.GetIPVersion()==4) + { + // Hide the address so routers don't modify it + SystemAddress var2=inTemplateVar; + uint32_t binaryAddress=~inTemplateVar.address.addr4.sin_addr.s_addr; + // Don't endian swap the address or port + WriteBits((unsigned char*)&binaryAddress, sizeof(binaryAddress)*8, true); + unsigned short p = var2.GetPortNetworkOrder(); + WriteBits((unsigned char*)&p, sizeof(unsigned short)*8, true); + } + else + { +#if RAKNET_SUPPORT_IPV6==1 + // Don't endian swap + WriteBits((const unsigned char*) &inTemplateVar.address.addr6, sizeof(inTemplateVar.address.addr6)*8, true); +#endif + } + } + + template <> + inline void BitStream::Write(const uint24_t &inTemplateVar) + { + AlignWriteToByteBoundary(); + AddBitsAndReallocate(3*8); + + if (IsBigEndian()==false) + { + data[( numberOfBitsUsed >> 3 ) + 0] = ((unsigned char *)&inTemplateVar.val)[0]; + data[( numberOfBitsUsed >> 3 ) + 1] = ((unsigned char *)&inTemplateVar.val)[1]; + data[( numberOfBitsUsed >> 3 ) + 2] = ((unsigned char *)&inTemplateVar.val)[2]; + } + else + { + data[( numberOfBitsUsed >> 3 ) + 0] = ((unsigned char *)&inTemplateVar.val)[3]; + data[( numberOfBitsUsed >> 3 ) + 1] = ((unsigned char *)&inTemplateVar.val)[2]; + data[( numberOfBitsUsed >> 3 ) + 2] = ((unsigned char *)&inTemplateVar.val)[1]; + } + + numberOfBitsUsed+=3*8; + } + + template <> + inline void BitStream::Write(const RakNetGUID &inTemplateVar) + { + Write(inTemplateVar.g); + } + + /// \brief Write a string to a bitstream. + /// \param[in] var The value to write + template <> + inline void BitStream::Write(const RakString &inTemplateVar) + { + inTemplateVar.Serialize(this); + } + template <> + inline void BitStream::Write(const RakWString &inTemplateVar) + { + inTemplateVar.Serialize(this); + } + template <> + inline void BitStream::Write(const char * const &inStringVar) + { + RakString::Serialize(inStringVar, this); + } + template <> + inline void BitStream::Write(const wchar_t * const &inStringVar) + { + RakWString::Serialize(inStringVar, this); + } + template <> + inline void BitStream::Write(const unsigned char * const &inTemplateVar) + { + Write((const char*)inTemplateVar); + } + template <> + inline void BitStream::Write(char * const &inTemplateVar) + { + Write((const char*)inTemplateVar); + } + template <> + inline void BitStream::Write(unsigned char * const &inTemplateVar) + { + Write((const char*)inTemplateVar); + } + + /// \brief Write any integral type to a bitstream. + /// \details If the current value is different from the last value + /// the current value will be written. Otherwise, a single bit will be written + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template + inline void BitStream::WriteDelta(const templateType ¤tValue, const templateType &lastValue) + { + if (currentValue==lastValue) + { + Write(false); + } + else + { + Write(true); + Write(currentValue); + } + } + + /// \brief Write a bool delta. Same thing as just calling Write + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template <> + inline void BitStream::WriteDelta(const bool ¤tValue, const bool &lastValue) + { + (void) lastValue; + + Write(currentValue); + } + + /// \brief WriteDelta when you don't know what the last value is, or there is no last value. + /// \param[in] currentValue The current value to write + template + inline void BitStream::WriteDelta(const templateType ¤tValue) + { + Write(true); + Write(currentValue); + } + + /// \brief Write any integral type to a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// \param[in] inTemplateVar The value to write + template + inline void BitStream::WriteCompressed(const templateType &inTemplateVar) + { +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + if (sizeof(inTemplateVar)==1) + WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true ); + else + { +#ifndef __BITSTREAM_NATIVE_END +#ifdef _MSC_VER +#pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'unsigned short', possible loss of data +#endif + + if (DoEndianSwap()) + { + unsigned char output[sizeof(templateType)]; + ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType)); + WriteCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true ); + } + else +#endif + WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true ); + } + } + + template <> + inline void BitStream::WriteCompressed(const SystemAddress &inTemplateVar) + { + Write(inTemplateVar); + } + + template <> + inline void BitStream::WriteCompressed(const RakNetGUID &inTemplateVar) + { + Write(inTemplateVar); + } + + template <> + inline void BitStream::WriteCompressed(const uint24_t &var) + { + Write(var); + } + + template <> + inline void BitStream::WriteCompressed(const bool &inTemplateVar) + { + Write(inTemplateVar); + } + + /// For values between -1 and 1 + template <> + inline void BitStream::WriteCompressed(const float &inTemplateVar) + { + RakAssert(inTemplateVar > -1.01f && inTemplateVar < 1.01f); + float varCopy=inTemplateVar; + if (varCopy < -1.0f) + varCopy=-1.0f; + if (varCopy > 1.0f) + varCopy=1.0f; + Write((unsigned short)((varCopy+1.0f)*32767.5f)); + } + + /// For values between -1 and 1 + template <> + inline void BitStream::WriteCompressed(const double &inTemplateVar) + { + RakAssert(inTemplateVar > -1.01 && inTemplateVar < 1.01); + double varCopy=inTemplateVar; + if (varCopy < -1.0f) + varCopy=-1.0f; + if (varCopy > 1.0f) + varCopy=1.0f; + Write((uint32_t)((varCopy+1.0)*2147483648.0)); + } + + /// Compress the string + template <> + inline void BitStream::WriteCompressed(const RakString &inTemplateVar) + { + inTemplateVar.SerializeCompressed(this,0,false); + } + template <> + inline void BitStream::WriteCompressed(const RakWString &inTemplateVar) + { + inTemplateVar.Serialize(this); + } + template <> + inline void BitStream::WriteCompressed(const char * const &inStringVar) + { + RakString::SerializeCompressed(inStringVar,this,0,false); + } + template <> + inline void BitStream::WriteCompressed(const wchar_t * const &inStringVar) + { + RakWString::Serialize(inStringVar,this); + } + template <> + inline void BitStream::WriteCompressed(const unsigned char * const &inTemplateVar) + { + WriteCompressed((const char*) inTemplateVar); + } + template <> + inline void BitStream::WriteCompressed(char * const &inTemplateVar) + { + WriteCompressed((const char*) inTemplateVar); + } + template <> + inline void BitStream::WriteCompressed(unsigned char * const &inTemplateVar) + { + WriteCompressed((const char*) inTemplateVar); + } + + + /// \brief Write any integral type to a bitstream. + /// \details If the current value is different from the last value + /// the current value will be written. Otherwise, a single bit will be written + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template + inline void BitStream::WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) + { + if (currentValue==lastValue) + { + Write(false); + } + else + { + Write(true); + WriteCompressed(currentValue); + } + } + + /// \brief Write a bool delta. Same thing as just calling Write + /// \param[in] currentValue The current value to write + /// \param[in] lastValue The last value to compare against + template <> + inline void BitStream::WriteCompressedDelta(const bool ¤tValue, const bool &lastValue) + { + (void) lastValue; + + Write(currentValue); + } + + /// \brief Save as WriteCompressedDelta(const templateType ¤tValue, const templateType &lastValue) + /// when we have an unknown second parameter + template + inline void BitStream::WriteCompressedDelta(const templateType ¤tValue) + { + Write(true); + WriteCompressed(currentValue); + } + + /// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) + /// when we have an unknown second bool + template <> + inline void BitStream::WriteCompressedDelta(const bool ¤tValue) + { + Write(currentValue); + } + + /// \brief Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping. + /// \param[in] outTemplateVar The value to read + template + inline bool BitStream::Read(templateType &outTemplateVar) + { +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + if (sizeof(outTemplateVar)==1) + return ReadBits( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true ); + else + { +#ifndef __BITSTREAM_NATIVE_END +#ifdef _MSC_VER +#pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'unsigned short', possible loss of data +#endif + if (DoEndianSwap()) + { + unsigned char output[sizeof(templateType)]; + if (ReadBits( ( unsigned char* ) output, sizeof(templateType) * 8, true )) + { + ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType)); + return true; + } + return false; + } + else +#endif + return ReadBits( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true ); + } + } + + /// \brief Read a bool from a bitstream. + /// \param[in] outTemplateVar The value to read + template <> + inline bool BitStream::Read(bool &outTemplateVar) + { + if ( readOffset + 1 > numberOfBitsUsed ) + return false; + + if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) // Is it faster to just write it out here? + outTemplateVar = true; + else + outTemplateVar = false; + + // Has to be on a different line for Mac + readOffset++; + + return true; + } + + /// \brief Read a systemAddress from a bitstream. + /// \param[in] outTemplateVar The value to read + template <> + inline bool BitStream::Read(SystemAddress &outTemplateVar) + { + unsigned char ipVersion; + Read(ipVersion); + if (ipVersion==4) + { + outTemplateVar.address.addr4.sin_family=AF_INET; + // Read(var.binaryAddress); + // Don't endian swap the address or port + uint32_t binaryAddress; + ReadBits( ( unsigned char* ) & binaryAddress, sizeof(binaryAddress) * 8, true ); + // Unhide the IP address, done to prevent routers from changing it + outTemplateVar.address.addr4.sin_addr.s_addr=~binaryAddress; + bool b = ReadBits(( unsigned char* ) & outTemplateVar.address.addr4.sin_port, sizeof(outTemplateVar.address.addr4.sin_port) * 8, true); + outTemplateVar.debugPort=ntohs(outTemplateVar.address.addr4.sin_port); + return b; + } + else + { +#if RAKNET_SUPPORT_IPV6==1 + bool b = ReadBits((unsigned char*) &outTemplateVar.address.addr6, sizeof(outTemplateVar.address.addr6)*8, true); + outTemplateVar.debugPort=ntohs(outTemplateVar.address.addr6.sin6_port); + return b; +#else + return false; +#endif + } + } + + template <> + inline bool BitStream::Read(uint24_t &outTemplateVar) + { + AlignReadToByteBoundary(); + if ( readOffset + 3*8 > numberOfBitsUsed ) + return false; + + if (IsBigEndian()==false) + { + ((unsigned char *)&outTemplateVar.val)[0]=data[ (readOffset >> 3) + 0]; + ((unsigned char *)&outTemplateVar.val)[1]=data[ (readOffset >> 3) + 1]; + ((unsigned char *)&outTemplateVar.val)[2]=data[ (readOffset >> 3) + 2]; + ((unsigned char *)&outTemplateVar.val)[3]=0; + } + else + { + + ((unsigned char *)&outTemplateVar.val)[3]=data[ (readOffset >> 3) + 0]; + ((unsigned char *)&outTemplateVar.val)[2]=data[ (readOffset >> 3) + 1]; + ((unsigned char *)&outTemplateVar.val)[1]=data[ (readOffset >> 3) + 2]; + ((unsigned char *)&outTemplateVar.val)[0]=0; + } + + readOffset+=3*8; + return true; + } + + template <> + inline bool BitStream::Read(RakNetGUID &outTemplateVar) + { + return Read(outTemplateVar.g); + } + + + template <> + inline bool BitStream::Read(RakString &outTemplateVar) + { + return outTemplateVar.Deserialize(this); + } + template <> + inline bool BitStream::Read(RakWString &outTemplateVar) + { + return outTemplateVar.Deserialize(this); + } + template <> + inline bool BitStream::Read(char *&varString) + { + return RakString::Deserialize(varString,this); + } + template <> + inline bool BitStream::Read(wchar_t *&varString) + { + return RakWString::Deserialize(varString,this); + } + template <> + inline bool BitStream::Read(unsigned char *&varString) + { + return RakString::Deserialize((char*) varString,this); + } + + /// \brief Read any integral type from a bitstream. + /// \details If the written value differed from the value compared against in the write function, + /// var will be updated. Otherwise it will retain the current value. + /// ReadDelta is only valid from a previous call to WriteDelta + /// \param[in] outTemplateVar The value to read + template + inline bool BitStream::ReadDelta(templateType &outTemplateVar) + { + bool dataWritten; + bool success; + success=Read(dataWritten); + if (dataWritten) + success=Read(outTemplateVar); + return success; + } + + /// \brief Read a bool from a bitstream. + /// \param[in] outTemplateVar The value to read + template <> + inline bool BitStream::ReadDelta(bool &outTemplateVar) + { + return Read(outTemplateVar); + } + + /// \brief Read any integral type from a bitstream. + /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// \param[in] outTemplateVar The value to read + template + inline bool BitStream::ReadCompressed(templateType &outTemplateVar) + { +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + if (sizeof(outTemplateVar)==1) + return ReadCompressed( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true ); + else + { +#ifndef __BITSTREAM_NATIVE_END + if (DoEndianSwap()) + { + unsigned char output[sizeof(templateType)]; + if (ReadCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true )) + { + ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType)); + return true; + } + return false; + } + else +#endif + return ReadCompressed( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true ); + } + } + + template <> + inline bool BitStream::ReadCompressed(SystemAddress &outTemplateVar) + { + return Read(outTemplateVar); + } + + template <> + inline bool BitStream::ReadCompressed(uint24_t &outTemplateVar) + { + return Read(outTemplateVar); + } + + template <> + inline bool BitStream::ReadCompressed(RakNetGUID &outTemplateVar) + { + return Read(outTemplateVar); + } + + template <> + inline bool BitStream::ReadCompressed(bool &outTemplateVar) + { + return Read(outTemplateVar); + } + + /// For values between -1 and 1 + template <> + inline bool BitStream::ReadCompressed(float &outTemplateVar) + { + unsigned short compressedFloat; + if (Read(compressedFloat)) + { + outTemplateVar = ((float)compressedFloat / 32767.5f - 1.0f); + return true; + } + return false; + } + + /// For values between -1 and 1 + template <> + inline bool BitStream::ReadCompressed(double &outTemplateVar) + { + uint32_t compressedFloat; + if (Read(compressedFloat)) + { + outTemplateVar = ((double)compressedFloat / 2147483648.0 - 1.0); + return true; + } + return false; + } + + /// For strings + template <> + inline bool BitStream::ReadCompressed(RakString &outTemplateVar) + { + return outTemplateVar.DeserializeCompressed(this,false); + } + template <> + inline bool BitStream::ReadCompressed(RakWString &outTemplateVar) + { + return outTemplateVar.Deserialize(this); + } + template <> + inline bool BitStream::ReadCompressed(char *&outTemplateVar) + { + return RakString::DeserializeCompressed(outTemplateVar,this,false); + } + template <> + inline bool BitStream::ReadCompressed(wchar_t *&outTemplateVar) + { + return RakWString::Deserialize(outTemplateVar,this); + } + template <> + inline bool BitStream::ReadCompressed(unsigned char *&outTemplateVar) + { + return RakString::DeserializeCompressed((char*) outTemplateVar,this,false); + } + + /// \brief Read any integral type from a bitstream. + /// \details If the written value differed from the value compared against in the write function, + /// var will be updated. Otherwise it will retain the current value. + /// the current value will be updated. + /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. + /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type + /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte + /// ReadCompressedDelta is only valid from a previous call to WriteDelta + /// \param[in] outTemplateVar The value to read + template + inline bool BitStream::ReadCompressedDelta(templateType &outTemplateVar) + { + bool dataWritten; + bool success; + success=Read(dataWritten); + if (dataWritten) + success=ReadCompressed(outTemplateVar); + return success; + } + + /// \brief Read a bool from a bitstream. + /// \param[in] outTemplateVar The value to read + template <> + inline bool BitStream::ReadCompressedDelta(bool &outTemplateVar) + { + return Read(outTemplateVar); + } + + template + void BitStream::WriteCasted( const sourceType &value ) + { + destinationType val = (destinationType) value; + Write(val); + } + + template + void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, bool allowOutsideRange ) + { + int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); + WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); + } + template + void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, const int requiredBits, bool allowOutsideRange ) + { + RakAssert(maximum>=minimum); + RakAssert(allowOutsideRange==true || (value>=minimum && value<=maximum)); + if (allowOutsideRange) + { + if (valuemaximum) + { + Write(true); + Write(value); + return; + } + Write(false); + } + templateType valueOffMin=value-minimum; + if (IsBigEndian()==true) + { + unsigned char output[sizeof(templateType)]; + ReverseBytes((unsigned char*)&valueOffMin, output, sizeof(templateType)); + WriteBits(output,requiredBits); + } + else + { + WriteBits((unsigned char*) &valueOffMin,requiredBits); + } + } + + template // templateType for this function must be a float or double + void BitStream::WriteNormVector( templateType x, templateType y, templateType z ) + { +#ifdef _DEBUG + RakAssert(x <= 1.01 && y <= 1.01 && z <= 1.01 && x >= -1.01 && y >= -1.01 && z >= -1.01); +#endif + + WriteFloat16((float)x,-1.0f,1.0f); + WriteFloat16((float)y,-1.0f,1.0f); + WriteFloat16((float)z,-1.0f,1.0f); + } + + template // templateType for this function must be a float or double + void BitStream::WriteVector( templateType x, templateType y, templateType z ) + { + templateType magnitude = sqrt(x * x + y * y + z * z); + Write((float)magnitude); + if (magnitude > 0.00001f) + { + WriteCompressed((float)(x/magnitude)); + WriteCompressed((float)(y/magnitude)); + WriteCompressed((float)(z/magnitude)); + // Write((unsigned short)((x/magnitude+1.0f)*32767.5f)); + // Write((unsigned short)((y/magnitude+1.0f)*32767.5f)); + // Write((unsigned short)((z/magnitude+1.0f)*32767.5f)); + } + } + + template // templateType for this function must be a float or double + void BitStream::WriteNormQuat( templateType w, templateType x, templateType y, templateType z) + { + Write((bool)(w<0.0)); + Write((bool)(x<0.0)); + Write((bool)(y<0.0)); + Write((bool)(z<0.0)); + Write((unsigned short)(fabs(x)*65535.0)); + Write((unsigned short)(fabs(y)*65535.0)); + Write((unsigned short)(fabs(z)*65535.0)); + // Leave out w and calculate it on the target + } + + template // templateType for this function must be a float or double + void BitStream::WriteOrthMatrix( + templateType m00, templateType m01, templateType m02, + templateType m10, templateType m11, templateType m12, + templateType m20, templateType m21, templateType m22 ) + { + + double qw; + double qx; + double qy; + double qz; + + // Convert matrix to quat + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ + float sum; + sum = 1 + m00 + m11 + m22; + if (sum < 0.0f) sum=0.0f; + qw = sqrt( sum ) / 2; + sum = 1 + m00 - m11 - m22; + if (sum < 0.0f) sum=0.0f; + qx = sqrt( sum ) / 2; + sum = 1 - m00 + m11 - m22; + if (sum < 0.0f) sum=0.0f; + qy = sqrt( sum ) / 2; + sum = 1 - m00 - m11 + m22; + if (sum < 0.0f) sum=0.0f; + qz = sqrt( sum ) / 2; + if (qw < 0.0) qw=0.0; + if (qx < 0.0) qx=0.0; + if (qy < 0.0) qy=0.0; + if (qz < 0.0) qz=0.0; + qx = _copysign( (double) qx, (double) (m21 - m12) ); + qy = _copysign( (double) qy, (double) (m02 - m20) ); + qz = _copysign( (double) qz, (double) (m10 - m01) ); + + WriteNormQuat(qw,qx,qy,qz); + } + + template + bool BitStream::ReadCasted( sourceType &value ) + { + serializationType val; + bool success = Read(val); + value=(sourceType) val; + return success; + } + + template + bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange ) + { + int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum)); + return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange); + } + template + bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange ) + { + RakAssert(maximum>=minimum); + if (allowOutsideRange) + { + bool isOutsideRange; + Read(isOutsideRange); + if (isOutsideRange) + return Read(value); + } + unsigned char output[sizeof(templateType)]; + memset(output,0,sizeof(output)); + bool success = ReadBits(output,requiredBits); + if (success) + { + if (IsBigEndian()==true) + ReverseBytesInPlace(output,sizeof(output)); + memcpy(&value,output,sizeof(output)); + + value+=minimum; + } + + return success; + } + + template // templateType for this function must be a float or double + bool BitStream::ReadNormVector( templateType &x, templateType &y, templateType &z ) + { + float xIn,yIn,zIn; + ReadFloat16(xIn,-1.0f,1.0f); + ReadFloat16(yIn,-1.0f,1.0f); + ReadFloat16(zIn,-1.0f,1.0f); + x=xIn; + y=yIn; + z=zIn; + return true; + } + + template // templateType for this function must be a float or double + bool BitStream::ReadVector( templateType &x, templateType &y, templateType &z ) + { + float magnitude; + //unsigned short sx,sy,sz; + if (!Read(magnitude)) + return false; + if (magnitude>0.00001f) + { + // Read(sx); + // Read(sy); + // if (!Read(sz)) + // return false; + // x=((float)sx / 32767.5f - 1.0f) * magnitude; + // y=((float)sy / 32767.5f - 1.0f) * magnitude; + // z=((float)sz / 32767.5f - 1.0f) * magnitude; + float cx=0.0f,cy=0.0f,cz=0.0f; + ReadCompressed(cx); + ReadCompressed(cy); + if (!ReadCompressed(cz)) + return false; + x=cx; + y=cy; + z=cz; + x*=magnitude; + y*=magnitude; + z*=magnitude; + } + else + { + x=0.0; + y=0.0; + z=0.0; + } + return true; + } + + template // templateType for this function must be a float or double + bool BitStream::ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z) + { + bool cwNeg=false, cxNeg=false, cyNeg=false, czNeg=false; + unsigned short cx,cy,cz; + Read(cwNeg); + Read(cxNeg); + Read(cyNeg); + Read(czNeg); + Read(cx); + Read(cy); + if (!Read(cz)) + return false; + + // Calculate w from x,y,z + x=(templateType)(cx/65535.0); + y=(templateType)(cy/65535.0); + z=(templateType)(cz/65535.0); + if (cxNeg) x=-x; + if (cyNeg) y=-y; + if (czNeg) z=-z; + float difference = 1.0f - x*x - y*y - z*z; + if (difference < 0.0f) + difference=0.0f; + w = (templateType)(sqrt(difference)); + if (cwNeg) + w=-w; + + return true; + } + + template // templateType for this function must be a float or double + bool BitStream::ReadOrthMatrix( + templateType &m00, templateType &m01, templateType &m02, + templateType &m10, templateType &m11, templateType &m12, + templateType &m20, templateType &m21, templateType &m22 ) + { + float qw,qx,qy,qz; + if (!ReadNormQuat(qw,qx,qy,qz)) + return false; + + // Quat to orthogonal rotation matrix + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm + double sqw = (double)qw*(double)qw; + double sqx = (double)qx*(double)qx; + double sqy = (double)qy*(double)qy; + double sqz = (double)qz*(double)qz; + m00 = (templateType)(sqx - sqy - sqz + sqw); // since sqw + sqx + sqy + sqz =1 + m11 = (templateType)(-sqx + sqy - sqz + sqw); + m22 = (templateType)(-sqx - sqy + sqz + sqw); + + double tmp1 = (double)qx*(double)qy; + double tmp2 = (double)qz*(double)qw; + m10 = (templateType)(2.0 * (tmp1 + tmp2)); + m01 = (templateType)(2.0 * (tmp1 - tmp2)); + + tmp1 = (double)qx*(double)qz; + tmp2 = (double)qy*(double)qw; + m20 =(templateType)(2.0 * (tmp1 - tmp2)); + m02 = (templateType)(2.0 * (tmp1 + tmp2)); + tmp1 = (double)qy*(double)qz; + tmp2 = (double)qx*(double)qw; + m21 = (templateType)(2.0 * (tmp1 + tmp2)); + m12 = (templateType)(2.0 * (tmp1 - tmp2)); + + return true; + } + + template + BitStream& operator<<(BitStream& out, templateType& c) + { + out.Write(c); + return out; + } + template + BitStream& operator>>(BitStream& in, templateType& c) + { + bool success = in.Read(c); + (void)success; + + RakAssert(success); + return in; + } + +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif + +#endif // VC6 diff --git a/include/raknet/CCRakNetSlidingWindow.hpp b/include/raknet/CCRakNetSlidingWindow.hpp new file mode 100644 index 0000000..36e5412 --- /dev/null +++ b/include/raknet/CCRakNetSlidingWindow.hpp @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/* +http://www.ssfnet.org/Exchange/tcp/tcpTutorialNotes.html + +cwnd=max bytes allowed on wire at once + +Start: +cwnd=mtu +ssthresh=unlimited + +Slow start: +On ack cwnd*=2 + +congestion avoidance: +On ack during new period +cwnd+=mtu*mtu/cwnd + +on loss or duplicate ack during period: +sshtresh=cwnd/2 +cwnd=MTU +This reenters slow start + +If cwnd < ssthresh, then use slow start +else use congestion avoidance + + +*/ + +#include "RakNetDefines.hpp" + +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1 + +#ifndef __CONGESTION_CONTROL_SLIDING_WINDOW_H +#define __CONGESTION_CONTROL_SLIDING_WINDOW_H + +#include "NativeTypes.hpp" +#include "RakNetTime.hpp" +#include "RakNetTypes.hpp" +#include "DS_Queue.hpp" + +/// Sizeof an UDP header in byte +#define UDP_HEADER_SIZE 28 + +#define CC_DEBUG_PRINTF_1(x) +#define CC_DEBUG_PRINTF_2(x,y) +#define CC_DEBUG_PRINTF_3(x,y,z) +#define CC_DEBUG_PRINTF_4(x,y,z,a) +#define CC_DEBUG_PRINTF_5(x,y,z,a,b) +//#define CC_DEBUG_PRINTF_1(x) printf(x) +//#define CC_DEBUG_PRINTF_2(x,y) printf(x,y) +//#define CC_DEBUG_PRINTF_3(x,y,z) printf(x,y,z) +//#define CC_DEBUG_PRINTF_4(x,y,z,a) printf(x,y,z,a) +//#define CC_DEBUG_PRINTF_5(x,y,z,a,b) printf(x,y,z,a,b) + +/// Set to 4 if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 +#define CC_TIME_TYPE_BYTES 8 + +#if CC_TIME_TYPE_BYTES==8 +typedef RakNet::TimeUS CCTimeType; +#else +typedef RakNet::TimeMS CCTimeType; +#endif + +typedef RakNet::uint24_t DatagramSequenceNumberType; +typedef double BytesPerMicrosecond; +typedef double BytesPerSecond; +typedef double MicrosecondsPerByte; + +namespace RakNet +{ + +class CCRakNetSlidingWindow +{ + public: + + CCRakNetSlidingWindow(); + ~CCRakNetSlidingWindow(); + + /// Reset all variables to their initial states, for a new connection + void Init(CCTimeType curTime, uint32_t maxDatagramPayload); + + /// Update over time + void Update(CCTimeType curTime, bool hasDataToSendOrResend); + + int GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); + int GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); + + /// Acks do not have to be sent immediately. Instead, they can be buffered up such that groups of acks are sent at a time + /// This reduces overall bandwidth usage + /// How long they can be buffered depends on the retransmit time of the sender + /// Should call once per update tick, and send if needed + bool ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick); + + /// Every data packet sent must contain a sequence number + /// Call this function to get it. The sequence number is passed into OnGotPacketPair() + DatagramSequenceNumberType GetAndIncrementNextDatagramSequenceNumber(void); + DatagramSequenceNumberType GetNextDatagramSequenceNumber(void); + + /// Call this when you send packets + /// Every 15th and 16th packets should be sent as a packet pair if possible + /// When packets marked as a packet pair arrive, pass to OnGotPacketPair() + /// When any packets arrive, (additionally) pass to OnGotPacket + /// Packets should contain our system time, so we can pass rtt to OnNonDuplicateAck() + void OnSendBytes(CCTimeType curTime, uint32_t numBytes); + + /// Call this when you get a packet pair + void OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime); + + /// Call this when you get a packet (including packet pairs) + /// If the DatagramSequenceNumberType is out of order, skippedMessageCount will be non-zero + /// In that case, send a NAK for every sequence number up to that count + bool OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount); + + /// Call when you get a NAK, with the sequence number of the lost message + /// Affects the congestion control + void OnResend(CCTimeType curTime, RakNet::TimeUS nextActionTime); + void OnNAK(CCTimeType curTime, DatagramSequenceNumberType nakSequenceNumber); + + /// Call this when an ACK arrives. + /// hasBAndAS are possibly written with the ack, see OnSendAck() + /// B and AS are used in the calculations in UpdateWindowSizeAndAckOnAckPerSyn + /// B and AS are updated at most once per SYN + void OnAck(CCTimeType curTime, CCTimeType rtt, bool hasBAndAS, BytesPerMicrosecond _B, BytesPerMicrosecond _AS, double totalUserDataBytesAcked, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber ); + void OnDuplicateAck( CCTimeType curTime, DatagramSequenceNumberType sequenceNumber ); + + /// Call when you send an ack, to see if the ack should have the B and AS parameters transmitted + /// Call before calling OnSendAck() + void OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS); + + /// Call when we send an ack, to write B and AS if needed + /// B and AS are only written once per SYN, to prevent slow calculations + /// Also updates SND, the period between sends, since data is written out + /// Be sure to call OnSendAckGetBAndAS() before calling OnSendAck(), since whether you write it or not affects \a numBytes + void OnSendAck(CCTimeType curTime, uint32_t numBytes); + + /// Call when we send a NACK + /// Also updates SND, the period between sends, since data is written out + void OnSendNACK(CCTimeType curTime, uint32_t numBytes); + + /// Retransmission time out for the sender + /// If the time difference between when a message was last transmitted, and the current time is greater than RTO then packet is eligible for retransmission, pending congestion control + /// RTO = (RTT + 4 * RTTVar) + SYN + /// If we have been continuously sending for the last RTO, and no ACK or NAK at all, SND*=2; + /// This is per message, which is different from UDT, but RakNet supports packetloss with continuing data where UDT is only RELIABLE_ORDERED + /// Minimum value is 100 milliseconds + CCTimeType GetRTOForRetransmission(unsigned char timesSent) const; + + /// Set the maximum amount of data that can be sent in one datagram + /// Default to MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE + void SetMTU(uint32_t bytes); + + /// Return what was set by SetMTU() + uint32_t GetMTU(void) const; + + /// Query for statistics + BytesPerMicrosecond GetLocalSendRate(void) const {return 0;} + BytesPerMicrosecond GetLocalReceiveRate(CCTimeType currentTime) const; + BytesPerMicrosecond GetRemoveReceiveRate(void) const {return 0;} + //BytesPerMicrosecond GetEstimatedBandwidth(void) const {return B;} + BytesPerMicrosecond GetEstimatedBandwidth(void) const {return GetLinkCapacityBytesPerSecond()*1000000.0;} + double GetLinkCapacityBytesPerSecond(void) const {return 0;} + + /// Query for statistics + double GetRTT(void) const; + + bool GetIsInSlowStart(void) const {return IsInSlowStart();} + uint32_t GetCWNDLimit(void) const {return (uint32_t) 0;} + + + /// Is a > b, accounting for variable overflow? + static bool GreaterThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); + /// Is a < b, accounting for variable overflow? + static bool LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); +// void SetTimeBetweenSendsLimit(unsigned int bitsPerSecond); + uint64_t GetBytesPerSecondLimitByCongestionControl(void) const; + + protected: + + // Maximum amount of bytes that the user can send, e.g. the size of one full datagram + uint32_t MAXIMUM_MTU_INCLUDING_UDP_HEADER; + + double cwnd; // max bytes on wire + double ssThresh; // Threshhold between slow start and congestion avoidance + + /// When we get an ack, if oldestUnsentAck==0, set it to the current time + /// When we send out acks, set oldestUnsentAck to 0 + CCTimeType oldestUnsentAck; + + CCTimeType GetSenderRTOForACK(void) const; + + /// Every outgoing datagram is assigned a sequence number, which increments by 1 every assignment + DatagramSequenceNumberType nextDatagramSequenceNumber; + DatagramSequenceNumberType nextCongestionControlBlock; + bool backoffThisBlock, speedUpThisBlock; + /// Track which datagram sequence numbers have arrived. + /// If a sequence number is skipped, send a NAK for all skipped messages + DatagramSequenceNumberType expectedNextSequenceNumber; + + bool _isContinuousSend; + + bool IsInSlowStart(void) const; + + double lastRtt, estimatedRTT, deviationRtt; + +}; + +} + +#endif + +#endif diff --git a/include/raknet/CCRakNetUDT.hpp b/include/raknet/CCRakNetUDT.hpp new file mode 100644 index 0000000..48035c7 --- /dev/null +++ b/include/raknet/CCRakNetUDT.hpp @@ -0,0 +1,404 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "RakNetDefines.hpp" + +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 + +#ifndef __CONGESTION_CONTROL_UDT_H +#define __CONGESTION_CONTROL_UDT_H + +#include "NativeTypes.hpp" +#include "RakNetTime.hpp" +#include "RakNetTypes.hpp" +#include "DS_Queue.hpp" + +/// Set to 4 if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 +#define CC_TIME_TYPE_BYTES 8 + +namespace RakNet +{ + +#if CC_TIME_TYPE_BYTES==8 +typedef uint64_t CCTimeType; +#else +typedef uint32_t CCTimeType; +#endif + +typedef uint24_t DatagramSequenceNumberType; +typedef double BytesPerMicrosecond; +typedef double BytesPerSecond; +typedef double MicrosecondsPerByte; + +/// CC_RAKNET_UDT_PACKET_HISTORY_LENGTH should be a power of 2 for the writeIndex variables to wrap properly +#define CC_RAKNET_UDT_PACKET_HISTORY_LENGTH 64 +#define RTT_HISTORY_LENGTH 64 + +/// Sizeof an UDP header in byte +#define UDP_HEADER_SIZE 28 + +#define CC_DEBUG_PRINTF_1(x) +#define CC_DEBUG_PRINTF_2(x,y) +#define CC_DEBUG_PRINTF_3(x,y,z) +#define CC_DEBUG_PRINTF_4(x,y,z,a) +#define CC_DEBUG_PRINTF_5(x,y,z,a,b) +//#define CC_DEBUG_PRINTF_1(x) printf(x) +//#define CC_DEBUG_PRINTF_2(x,y) printf(x,y) +//#define CC_DEBUG_PRINTF_3(x,y,z) printf(x,y,z) +//#define CC_DEBUG_PRINTF_4(x,y,z,a) printf(x,y,z,a) +//#define CC_DEBUG_PRINTF_5(x,y,z,a,b) printf(x,y,z,a,b) + +/// \brief Encapsulates UDT congestion control, as used by RakNet +/// Requirements: +///
    +///
  1. Each datagram is no more than MAXIMUM_MTU_SIZE, after accounting for the UDP header +///
  2. Each datagram containing a user message has a sequence number which is set after calling OnSendBytes(). Set it by calling GetAndIncrementNextDatagramSequenceNumber() +///
  3. System is designed to be used from a single thread. +///
  4. Each packet should have a timeout time based on GetSenderRTOForACK(). If this time elapses, add the packet to the head of the send list for retransmission. +///
+/// +/// Recommended: +///
    +///
  1. Call sendto in its own thread. This takes a significant amount of time in high speed networks. +///
+/// +/// Algorithm: +///
    +///
  1. On a new connection, call Init() +///
  2. On a periodic interval (SYN time is the best) call Update(). Also call ShouldSendACKs(), and send buffered ACKS if it returns true. +///
  3. Call OnSendAck() when sending acks. +///
  4. When you want to send or resend data, call GetNumberOfBytesToSend(). It will return you enough bytes to keep you busy for \a estimatedTimeToNextTick. You can send more than this to fill out a datagram, or to send packet pairs +///
  5. Call OnSendBytes() when sending datagrams. +///
  6. When data arrives, record the sequence number and buffer an ACK for it, to be sent from Update() if ShouldSendACKs() returns true +///
  7. Every 16 packets that you send, send two of them back to back (a packet pair) as long as both packets are the same size. If you don't have two packets the same size, it is fine to defer this until you do. +///
  8. When you get a packet, call OnGotPacket(). If the packet is also either of a packet pair, call OnGotPacketPair() +///
  9. If you get a packet, and the sequence number is not 1 + the last sequence number, send a NAK. On the remote system, call OnNAK() and resend that message. +///
  10. If you get an ACK, remove that message from retransmission. Call OnNonDuplicateAck(). +///
  11. If a message is not ACKed for GetRTOForRetransmission(), resend it. +///
+class CCRakNetUDT +{ + public: + + CCRakNetUDT(); + ~CCRakNetUDT(); + + /// Reset all variables to their initial states, for a new connection + void Init(CCTimeType curTime, uint32_t maxDatagramPayload); + + /// Update over time + void Update(CCTimeType curTime, bool hasDataToSendOrResend); + + int GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); + int GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend); + + /// Acks do not have to be sent immediately. Instead, they can be buffered up such that groups of acks are sent at a time + /// This reduces overall bandwidth usage + /// How long they can be buffered depends on the retransmit time of the sender + /// Should call once per update tick, and send if needed + bool ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick); + + /// Every data packet sent must contain a sequence number + /// Call this function to get it. The sequence number is passed into OnGotPacketPair() + DatagramSequenceNumberType GetAndIncrementNextDatagramSequenceNumber(void); + DatagramSequenceNumberType GetNextDatagramSequenceNumber(void); + + /// Call this when you send packets + /// Every 15th and 16th packets should be sent as a packet pair if possible + /// When packets marked as a packet pair arrive, pass to OnGotPacketPair() + /// When any packets arrive, (additionally) pass to OnGotPacket + /// Packets should contain our system time, so we can pass rtt to OnNonDuplicateAck() + void OnSendBytes(CCTimeType curTime, uint32_t numBytes); + + /// Call this when you get a packet pair + void OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime); + + /// Call this when you get a packet (including packet pairs) + /// If the DatagramSequenceNumberType is out of order, skippedMessageCount will be non-zero + /// In that case, send a NAK for every sequence number up to that count + bool OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount); + + /// Call when you get a NAK, with the sequence number of the lost message + /// Affects the congestion control + void OnResend(CCTimeType curTime, RakNet::TimeUS nextActionTime); + void OnNAK(CCTimeType curTime, DatagramSequenceNumberType nakSequenceNumber); + + /// Call this when an ACK arrives. + /// hasBAndAS are possibly written with the ack, see OnSendAck() + /// B and AS are used in the calculations in UpdateWindowSizeAndAckOnAckPerSyn + /// B and AS are updated at most once per SYN + void OnAck(CCTimeType curTime, CCTimeType rtt, bool hasBAndAS, BytesPerMicrosecond _B, BytesPerMicrosecond _AS, double totalUserDataBytesAcked, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber ); + void OnDuplicateAck( CCTimeType curTime, DatagramSequenceNumberType sequenceNumber ) {} + + /// Call when you send an ack, to see if the ack should have the B and AS parameters transmitted + /// Call before calling OnSendAck() + void OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS); + + /// Call when we send an ack, to write B and AS if needed + /// B and AS are only written once per SYN, to prevent slow calculations + /// Also updates SND, the period between sends, since data is written out + /// Be sure to call OnSendAckGetBAndAS() before calling OnSendAck(), since whether you write it or not affects \a numBytes + void OnSendAck(CCTimeType curTime, uint32_t numBytes); + + /// Call when we send a NACK + /// Also updates SND, the period between sends, since data is written out + void OnSendNACK(CCTimeType curTime, uint32_t numBytes); + + /// Retransmission time out for the sender + /// If the time difference between when a message was last transmitted, and the current time is greater than RTO then packet is eligible for retransmission, pending congestion control + /// RTO = (RTT + 4 * RTTVar) + SYN + /// If we have been continuously sending for the last RTO, and no ACK or NAK at all, SND*=2; + /// This is per message, which is different from UDT, but RakNet supports packetloss with continuing data where UDT is only RELIABLE_ORDERED + /// Minimum value is 100 milliseconds + CCTimeType GetRTOForRetransmission(unsigned char timesSent) const; + + /// Set the maximum amount of data that can be sent in one datagram + /// Default to MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE + void SetMTU(uint32_t bytes); + + /// Return what was set by SetMTU() + uint32_t GetMTU(void) const; + + /// Query for statistics + BytesPerMicrosecond GetLocalSendRate(void) const {return 1.0 / SND;} + BytesPerMicrosecond GetLocalReceiveRate(CCTimeType currentTime) const; + BytesPerMicrosecond GetRemoveReceiveRate(void) const {return AS;} + //BytesPerMicrosecond GetEstimatedBandwidth(void) const {return B;} + BytesPerMicrosecond GetEstimatedBandwidth(void) const {return GetLinkCapacityBytesPerSecond()*1000000.0;} + double GetLinkCapacityBytesPerSecond(void) const {return estimatedLinkCapacityBytesPerSecond;}; + + /// Query for statistics + double GetRTT(void) const; + + bool GetIsInSlowStart(void) const {return isInSlowStart;} + uint32_t GetCWNDLimit(void) const {return (uint32_t) (CWND*MAXIMUM_MTU_INCLUDING_UDP_HEADER);} + + + /// Is a > b, accounting for variable overflow? + static bool GreaterThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); + /// Is a < b, accounting for variable overflow? + static bool LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b); +// void SetTimeBetweenSendsLimit(unsigned int bitsPerSecond); + uint64_t GetBytesPerSecondLimitByCongestionControl(void) const; + + protected: + // --------------------------- PROTECTED VARIABLES --------------------------- + /// time interval between bytes, in microseconds. + /// Only used when slowStart==false + /// Increased over time as we continually get messages + /// Decreased on NAK and timeout + /// Starts at 0 (invalid) + MicrosecondsPerByte SND; + + /// Supportive window mechanism, controlling the maximum number of in-flight packets + /// Used both during and after slow-start, but primarily during slow-start + /// Starts at 2, which is also the low threshhold + /// Max is the socket receive buffer / MTU + /// CWND = AS * (RTT + SYN) + 16 + double CWND; + + /// When we do an update process on the SYN interval, nextSYNUpdate is set to the next time we should update + /// Normally this is nextSYNUpdate+=SYN, in order to update on a consistent schedule + /// However, if this would result in an immediate update yet again, it is set to SYN microseconds past the current time (in case the thread did not update for a long time) + CCTimeType nextSYNUpdate; + + + /// Index into packetPairRecieptHistory where we will next write + /// The history is always full (starting with default values) so no read index is needed + int packetPairRecieptHistoryWriteIndex; + + /// Sent to the sender by the receiver from packetPairRecieptHistory whenever a back to back packet arrives on the receiver + /// Updated by B = B * .875 + incomingB * .125 + //BytesPerMicrosecond B; + + /// Running round trip time (ping*2) + /// Only sender needs to know this + /// Initialized to UNSET + /// Set to rtt on first calculation + /// Updated gradually by RTT = RTT * 0.875 + rtt * 0.125 + double RTT; + + /// Round trip time variance + /// Only sender needs to know this + /// Initialized to UNSET + /// Set to rtt on first calculation + // double RTTVar; + /// Update: Use min/max, RTTVar follows current variance too closely resulting in packetloss + double minRTT, maxRTT; + + /// Used to calculate packet arrival rate (in UDT) but data arrival rate (in RakNet, where not all datagrams are the same size) + /// Filter is used to cull lowest half of values for bytesPerMicrosecond, to discount spikes and inactivity + /// Referred to in the documentation as AS, data arrival rate + /// AS is sent to the sender and calculated every 10th ack + /// Each node represents (curTime-lastPacketArrivalTime)/bytes + /// Used with ReceiverCalculateDataArrivalRate(); + BytesPerMicrosecond packetArrivalHistory[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH]; + BytesPerMicrosecond packetArrivalHistoryContinuousGaps[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH]; + unsigned char packetArrivalHistoryContinuousGapsIndex; + uint64_t continuousBytesReceived; + CCTimeType continuousBytesReceivedStartTime; + unsigned int packetArrivalHistoryWriteCount; + + /// Index into packetArrivalHistory where we will next write + /// The history is always full (starting with default values) so no read index is needed + int packetArrivalHistoryWriteIndex; + + /// Tracks the time the last packet that arrived, so BytesPerMicrosecond can be calculated for packetArrivalHistory when a new packet arrives + CCTimeType lastPacketArrivalTime; + + /// Data arrival rate from the sender to the receiver, as told to us by the receiver + /// Used to calculate initial sending rate when slow start stops + BytesPerMicrosecond AS; + + /// When the receiver last calculated and send B and AS, from packetArrivalHistory and packetPairRecieptHistory + /// Used to prevent it from being calculated and send too frequently, as they are slow operations + CCTimeType lastTransmitOfBAndAS; + + /// New connections start in slow start + /// During slow start, SND is not used, only CWND + /// Slow start ends when we get a NAK, or the maximum size of CWND is reached + /// SND is initialized to the inverse of the receiver's packet arrival rate when slow start ends + bool isInSlowStart; + + /// How many NAKs arrived this congestion period + /// Initialized to 1 when the congestion period starts + uint32_t NAKCount; + + /// How many NAKs do you get on average during a congestion period? + /// Starts at 1 + /// Used to generate a random number, DecRandom, between 1 and AvgNAKNum + uint32_t AvgNAKNum; + + /// How many times we have decremented SND this congestion period. Used to limit the number of decrements to 5 + uint32_t DecCount; + + /// Every DecInterval NAKs per congestion period, we decrease the send rate + uint32_t DecInterval; + + /// Every outgoing datagram is assigned a sequence number, which increments by 1 every assignment + DatagramSequenceNumberType nextDatagramSequenceNumber; + + /// If a packet is marked as a packet pair, lastPacketPairPacketArrivalTime is set to the time it arrives + /// This is used so when the 2nd packet of the pair arrives, we can calculate the time interval between the two + CCTimeType lastPacketPairPacketArrivalTime; + + /// If a packet is marked as a packet pair, lastPacketPairSequenceNumber is checked to see if the last packet we got + /// was the packet immediately before the one that arrived + /// If so, we can use lastPacketPairPacketArrivalTime to get the time between the two packets, and thus estimate the link capacity + /// Initialized to -1, so the first packet of a packet pair won't be treated as the second + DatagramSequenceNumberType lastPacketPairSequenceNumber; + + /// Used to cap UpdateWindowSizeAndAckOnAckPerSyn() to once speed increase per SYN + /// This is to prevent speeding up faster than congestion control can compensate for + CCTimeType lastUpdateWindowSizeAndAck; + + /// Every time SND is halved due to timeout, the RTO is increased + /// This is to prevent massive retransmissions to an unresponsive system + /// Reset on any data arriving + double ExpCount; + + /// Total number of user data bytes sent + /// Used to adjust the window size, on ACK, during slow start + uint64_t totalUserDataBytesSent; + + /// When we get an ack, if oldestUnsentAck==0, set it to the current time + /// When we send out acks, set oldestUnsentAck to 0 + CCTimeType oldestUnsentAck; + + // Maximum amount of bytes that the user can send, e.g. the size of one full datagram + uint32_t MAXIMUM_MTU_INCLUDING_UDP_HEADER; + + // Max window size + double CWND_MAX_THRESHOLD; + + /// Track which datagram sequence numbers have arrived. + /// If a sequence number is skipped, send a NAK for all skipped messages + DatagramSequenceNumberType expectedNextSequenceNumber; + + // How many times have we sent B and AS? Used to force it to send at least CC_RAKNET_UDT_PACKET_HISTORY_LENGTH times + // Otherwise, the default values in the array generate inaccuracy + uint32_t sendBAndASCount; + + /// Most recent values read into the corresponding lists + /// Used during the beginning of a connection, when the median filter is still inaccurate + BytesPerMicrosecond mostRecentPacketArrivalHistory; + + bool hasWrittenToPacketPairReceiptHistory; + +// uint32_t rttHistory[RTT_HISTORY_LENGTH]; +// uint32_t rttHistoryIndex; +// uint32_t rttHistoryWriteCount; +// uint32_t rttSum, rttLow; +// CCTimeType lastSndUpdateTime; + double estimatedLinkCapacityBytesPerSecond; + + // --------------------------- PROTECTED METHODS --------------------------- + /// Update nextSYNUpdate by SYN, or the same amount past the current time if no updates have occurred for a long time + void SetNextSYNUpdate(CCTimeType currentTime); + + /// Returns the rate of data arrival, based on packets arriving on the sender. + BytesPerMicrosecond ReceiverCalculateDataArrivalRate(CCTimeType curTime) const; + /// Returns the median of the data arrival rate + BytesPerMicrosecond ReceiverCalculateDataArrivalRateMedian(void) const; + + /// Calculates the median an array of BytesPerMicrosecond + static BytesPerMicrosecond CalculateListMedianRecursive(const BytesPerMicrosecond inputList[CC_RAKNET_UDT_PACKET_HISTORY_LENGTH], int inputListLength, int lessThanSum, int greaterThanSum); +// static uint32_t CalculateListMedianRecursive(const uint32_t inputList[RTT_HISTORY_LENGTH], int inputListLength, int lessThanSum, int greaterThanSum); + + /// Same as GetRTOForRetransmission, but does not factor in ExpCount + /// This is because the receiver does not know ExpCount for the sender, and even if it did, acks shouldn't be delayed for this reason + CCTimeType GetSenderRTOForACK(void) const; + + /// Stop slow start, and enter normal transfer rate + void EndSlowStart(void); + + /// Does the named conversion + inline double BytesPerMicrosecondToPacketsPerMillisecond(BytesPerMicrosecond in); + + /// Update the round trip time, from ACK or ACK2 + //void UpdateRTT(CCTimeType rtt); + + /// Update the corresponding variables pre-slow start + void UpdateWindowSizeAndAckOnAckPreSlowStart(double totalUserDataBytesAcked); + + /// Update the corresponding variables post-slow start + void UpdateWindowSizeAndAckOnAckPerSyn(CCTimeType curTime, CCTimeType rtt, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber); + + + /// Sets halveSNDOnNoDataTime to the future, and also resets ExpCount, which is used to multiple the RTO on no data arriving at all + void ResetOnDataArrivalHalveSNDOnNoDataTime(CCTimeType curTime); + + // Init array + void InitPacketArrivalHistory(void); + + // Printf + void PrintLowBandwidthWarning(void); + + // Bug: SND can sometimes get super high - have seen 11693 + void CapMinSnd(const char *file, int line); + + void DecreaseTimeBetweenSends(void); + void IncreaseTimeBetweenSends(void); + + int bytesCanSendThisTick; + + CCTimeType lastRttOnIncreaseSendRate; + CCTimeType lastRtt; + + DatagramSequenceNumberType nextCongestionControlBlock; + bool hadPacketlossThisBlock; + DataStructures::Queue pingsLastInterval; +}; + +} + +#endif + +#endif diff --git a/include/raknet/CheckSum.hpp b/include/raknet/CheckSum.hpp new file mode 100644 index 0000000..75f0393 --- /dev/null +++ b/include/raknet/CheckSum.hpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// +/// \file CheckSum.cpp +/// \brief [Internal] CheckSum implementation from http://www.flounder.com/checksum.htm +/// + +#ifndef __CHECKSUM_H +#define __CHECKSUM_H + +#include "RakMemoryOverride.hpp" + +/// Generates and validates checksums +class CheckSum +{ + +public: + + /// Default constructor + + CheckSum() + { + Clear(); + } + + void Clear() + { + sum = 0; + r = 55665; + c1 = 52845; + c2 = 22719; + } + + void Add ( unsigned int w ); + + + void Add ( unsigned short w ); + + void Add ( unsigned char* b, unsigned int length ); + + void Add ( unsigned char b ); + + unsigned int Get () + { + return sum; + } + +protected: + unsigned short r; + unsigned short c1; + unsigned short c2; + unsigned int sum; +}; + +#endif diff --git a/include/raknet/CloudClient.hpp b/include/raknet/CloudClient.hpp new file mode 100644 index 0000000..6f065b9 --- /dev/null +++ b/include/raknet/CloudClient.hpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file CloudClient.h +/// \brief Queries CloudMemoryServer to download data that other clients have uploaded +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_CloudClient==1 + +#ifndef __CLOUD_CLIENT_H +#define __CLOUD_CLIENT_H + +#include "PluginInterface2.hpp" +#include "CloudCommon.hpp" +#include "RakMemoryOverride.hpp" +#include "DS_Hash.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +class CloudClientCallback; + +/// \defgroup CLOUD_GROUP CloudComputing +/// \brief Contains the CloudClient and CloudServer plugins +/// \details The CloudServer plugins operates on requests from the CloudClient plugin. The servers are in a fully connected mesh topology, which the clients are connected to any server. Clients can interact with each other by posting and subscribing to memory updates, without being directly connected or even knowing about each other. +/// \ingroup PLUGINS_GROUP + +/// \brief Performs Post() and Get() operations on CloudMemoryServer +/// \details A CloudClient is a computer connected to one or more servers in a cloud configuration. Operations by one CloudClient can be received and subscribed to by other instances of CloudClient, without those clients being connected, even on different servers. +/// \ingroup CLOUD_GROUP +class RAK_DLL_EXPORT CloudClient : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(CloudClient) + + CloudClient(); + virtual ~CloudClient(); + + /// \brief Set the default callbacks for OnGetReponse(), OnSubscriptionNotification(), and OnSubscriptionDataDeleted() + /// \details Pointers to CloudAllocator and CloudClientCallback can be stored by the system if desired. If a callback is not provided to OnGetReponse(), OnSubscriptionNotification(), OnSubscriptionDataDeleted(), the callback passed here will be used instead. + /// \param[in] _allocator An instance of CloudAllocator + /// \param[in] _callback An instance of CloudClientCallback + virtual void SetDefaultCallbacks(CloudAllocator *_allocator, CloudClientCallback *_callback); + + /// \brief Uploads data to the cloud + /// \details Data uploaded to the cloud will be stored by the server sent to, identified by \a systemIdentifier. + /// As long as you are connected to this server, the data will persist. Queries for that data by the Get() operation will + /// return the RakNetGUID and SystemAddress of the uploader, as well as the data itself. + /// Furthermore, if any clients are subscribed to the particular CloudKey passed, those clients will get update notices that the data has changed + /// Passing data with the same \a cloudKey more than once will overwrite the prior value. + /// This call will silently fail if CloudServer::SetMaxUploadBytesPerClient() is exceeded + /// \param[in] cloudKey Identifies the data being uploaded + /// \param[in] data A pointer to data to upload. This pointer does not need to persist past the call + /// \param[in] dataLengthBytes The length in bytes of \a data + /// \param[in] systemIdentifier A remote system running CloudServer that we are already connected to. + virtual void Post(CloudKey *cloudKey, const unsigned char *data, uint32_t dataLengthBytes, RakNetGUID systemIdentifier); + + /// \brief Releases one or more data previously uploaded with Post() + /// \details If a remote system has subscribed to one or more of the \a keys uploaded, they will get ID_CLOUD_SUBSCRIPTION_NOTIFICATION notifications containing the last value uploaded before deletions + /// \param[in] cloudKey Identifies the data to release. It is possible to remove uploads from multiple Post() calls at once. + /// \param[in] systemIdentifier A remote system running CloudServer that we are already connected to. + virtual void Release(DataStructures::List &keys, RakNetGUID systemIdentifier); + + /// \brief Gets data from the cloud + /// \details For a given query containing one or more keys, return data that matches those keys. + /// The values will be returned in the ID_CLOUD_GET_RESPONSE packet, which should be passed to OnGetReponse() and will invoke CloudClientCallback::OnGet() + /// CloudQuery::startingRowIndex is used to skip the first n values that would normally be returned.. + /// CloudQuery::maxRowsToReturn is used to limit the number of rows returned. The number of rows returned may also be limited by CloudServer::SetMaxBytesPerDownload(); + /// CloudQuery::subscribeToResults if set to true, will cause ID_CLOUD_SUBSCRIPTION_NOTIFICATION to be returned to us when any of the keys in the query are updated or are deleted. + /// ID_CLOUD_GET_RESPONSE will be returned even if subscribing to the result list. Only later updates will return ID_CLOUD_SUBSCRIPTION_NOTIFICATION. + /// Calling Get() with CloudQuery::subscribeToResults false, when you are already subscribed, does not remove the subscription. Use Unsubscribe() for this. + /// Resubscribing using the same CloudKey but a different or no \a specificSystems overwrites the subscribed systems for those keys. + /// \param[in] cloudQuery One or more keys, and optional parameters to perform with the Get + /// \param[in] systemIdentifier A remote system running CloudServer that we are already connected to. + /// \param[in] specificSystems It is possible to get or subscribe to updates only for specific uploading CloudClient instances. Pass the desired instances here. The overload that does not have the specificSystems parameter is treated as subscribing to all updates from all clients. + virtual bool Get(CloudQuery *cloudQuery, RakNetGUID systemIdentifier); + virtual bool Get(CloudQuery *cloudQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); + virtual bool Get(CloudQuery *cloudQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); + + /// \brief Unsubscribe from updates previously subscribed to using Get() with the CloudQuery::subscribeToResults set to true + /// The \a keys and \a specificSystems parameters are logically treated as AND when checking subscriptions on the server + /// The overload that does not take specificSystems unsubscribes to all passed keys, regardless of system + /// You cannot unsubscribe specific systems when previously subscribed to updates from any system. To do this, first Unsubscribe() from all systems, and call Get() with the \a specificSystems parameter explicilty listing the systems you want to subscribe to. + virtual void Unsubscribe(DataStructures::List &keys, RakNetGUID systemIdentifier); + virtual void Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); + virtual void Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier); + + /// \brief Call this when you get ID_CLOUD_GET_RESPONSE + /// If \a callback or \a allocator are 0, the default callbacks passed to SetDefaultCallbacks() are used + /// \param[in] packet Packet structure returned from RakPeerInterface + /// \param[in] _callback Callback to be called from the function containing output parameters. If 0, default is used. + /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. + virtual void OnGetReponse(Packet *packet, CloudClientCallback *_callback=0, CloudAllocator *_allocator=0); + + /// \brief Call this when you get ID_CLOUD_GET_RESPONSE + /// Different form of OnGetReponse that returns to a structure that you pass, instead of using a callback + /// You are responsible for deallocation with this form + /// If \a allocator is 0, the default callback passed to SetDefaultCallbacks() are used + /// \param[out] cloudQueryResult A pointer to a structure that will be filled out with data + /// \param[in] packet Packet structure returned from RakPeerInterface + /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. + virtual void OnGetReponse(CloudQueryResult *cloudQueryResult, Packet *packet, CloudAllocator *_allocator=0); + + /// \brief Call this when you get ID_CLOUD_SUBSCRIPTION_NOTIFICATION + /// If \a callback or \a allocator are 0, the default callbacks passed to SetDefaultCallbacks() are used + /// \param[in] packet Packet structure returned from RakPeerInterface + /// \param[in] _callback Callback to be called from the function containing output parameters. If 0, default is used. + /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. + virtual void OnSubscriptionNotification(Packet *packet, CloudClientCallback *_callback=0, CloudAllocator *_allocator=0); + + /// \brief Call this when you get ID_CLOUD_SUBSCRIPTION_NOTIFICATION + /// Different form of OnSubscriptionNotification that returns to a structure that you pass, instead of using a callback + /// You are responsible for deallocation with this form + /// If \a allocator is 0, the default callback passed to SetDefaultCallbacks() are used + /// \param[out] wasUpdated If true, the row was updated. If false, it was deleted. \a result will contain the last value just before deletion + /// \param[out] row A pointer to a structure that will be filled out with data + /// \param[in] packet Packet structure returned from RakPeerInterface + /// \param[in] _allocator Allocator to be used to allocate data. If 0, default is used. + virtual void OnSubscriptionNotification(bool *wasUpdated, CloudQueryRow *row, Packet *packet, CloudAllocator *_allocator=0); + + /// If you never specified an allocator, and used the non-callback form of OnGetReponse(), deallocate cloudQueryResult with this function + virtual void DeallocateWithDefaultAllocator(CloudQueryResult *cloudQueryResult); + + /// If you never specified an allocator, and used the non-callback form of OnSubscriptionNotification(), deallocate row with this function + virtual void DeallocateWithDefaultAllocator(CloudQueryRow *row); + +protected: + PluginReceiveResult OnReceive(Packet *packet); + + CloudClientCallback *callback; + CloudAllocator *allocator; + + CloudAllocator unsetDefaultAllocator; +}; + +/// \ingroup CLOUD_GROUP +/// Parses ID_CLOUD_GET_RESPONSE and ID_CLOUD_SUBSCRIPTION_NOTIFICATION in a convenient callback form +class RAK_DLL_EXPORT CloudClientCallback +{ +public: + CloudClientCallback() {} + virtual ~CloudClientCallback() {} + + /// \brief Called in response to ID_CLOUD_GET_RESPONSE + /// \param[out] result Contains the original query passed to Get(), and a list of rows returned. + /// \param[out] deallocateRowsAfterReturn CloudQueryResult::rowsReturned will be deallocated after the function returns by default. Set to false to not deallocate these pointers. The pointers are allocated through CloudAllocator. + virtual void OnGet(RakNet::CloudQueryResult *result, bool *deallocateRowsAfterReturn) {(void) result; (void) deallocateRowsAfterReturn;} + + /// \brief Called in response to ID_CLOUD_SUBSCRIPTION_NOTIFICATION + /// \param[out] result Contains the row updated + /// \param[out] wasUpdated If true, the row was updated. If false, it was deleted. \a result will contain the last value just before deletion + /// \param[out] deallocateRowAfterReturn \a result will be deallocated after the function returns by default. Set to false to not deallocate these pointers. The pointers are allocated through CloudAllocator. + virtual void OnSubscriptionNotification(RakNet::CloudQueryRow *result, bool wasUpdated, bool *deallocateRowAfterReturn) {(void) result; (void) wasUpdated; (void) deallocateRowAfterReturn;} +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/CloudCommon.hpp b/include/raknet/CloudCommon.hpp new file mode 100644 index 0000000..0cf8ffc --- /dev/null +++ b/include/raknet/CloudCommon.hpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_CloudClient==1 || _RAKNET_SUPPORT_CloudServer==1 + +#ifndef __CLOUD_COMMON_H +#define __CLOUD_COMMON_H + +#include "RakNetTypes.hpp" +#include "RakString.hpp" + +namespace RakNet +{ + +class BitStream; +struct CloudQueryRow; + +/// Allocates CloudQueryRow and the row data. Override to use derived classes or different allocators +/// \ingroup CLOUD_GROUP +class RAK_DLL_EXPORT CloudAllocator +{ +public: + CloudAllocator() {} + virtual ~CloudAllocator() {} + + /// \brief Allocate a row + virtual CloudQueryRow* AllocateCloudQueryRow(void); + /// \brief Free a row + virtual void DeallocateCloudQueryRow(CloudQueryRow *row); + /// \brief Allocate CloudQueryRow::data + virtual unsigned char *AllocateRowData(uint32_t bytesNeededForData); + /// \brief Free CloudQueryRow::data + virtual void DeallocateRowData(void *data); +}; + +/// Serves as a key to identify data uploaded to or queried from the server. +/// \ingroup CLOUD_GROUP +struct RAK_DLL_EXPORT CloudKey +{ + CloudKey() {} + CloudKey(RakNet::RakString _primaryKey, uint32_t _secondaryKey) : primaryKey(_primaryKey), secondaryKey(_secondaryKey) {} + ~CloudKey() {} + + /// Identifies the primary key. This is intended to be a major category, such as the name of the application + /// Must be non-empty + RakNet::RakString primaryKey; + + /// Identifies the secondary key. This is intended to be a subcategory enumeration, such as PLAYER_LIST or RUNNING_SCORES + uint32_t secondaryKey; + + /// \internal + void Serialize(bool writeToBitstream, BitStream *bitStream); +}; + +/// \internal +int CloudKeyComp(const CloudKey &key, const CloudKey &data); + +/// Data members used to query the cloud +/// \ingroup CLOUD_GROUP +struct RAK_DLL_EXPORT CloudQuery +{ + CloudQuery() {startingRowIndex=0; maxRowsToReturn=0; subscribeToResults=false;} + + /// List of keys to query. Must be at least of length 1. + /// This query is run on uploads from all clients, and those that match the combination of primaryKey and secondaryKey are potentially returned + /// If you pass more than one key at a time, the results are concatenated so if you need to differentiate between queries then send two different queries + DataStructures::List keys; + + /// If limiting the number of rows to return, this is the starting offset into the list. Has no effect unless maxRowsToReturn is > 0 + uint32_t startingRowIndex; + + /// Maximum number of rows to return. Actual number may still be less than this. Pass 0 to mean no-limit. + uint32_t maxRowsToReturn; + + /// If true, automatically get updates as the results returned to you change. Unsubscribe with CloudMemoryClient::Unsubscribe() + bool subscribeToResults; + + /// \internal + void Serialize(bool writeToBitstream, BitStream *bitStream); +}; + +/// \ingroup CLOUD_GROUP +struct RAK_DLL_EXPORT CloudQueryRow +{ + /// Key used to identify this data + CloudKey key; + + /// Data uploaded + unsigned char *data; + + /// Length of data uploaded + uint32_t length; + + /// System address of server that is holding this data, and the client is connected to + SystemAddress serverSystemAddress; + + /// System address of client that uploaded this data + SystemAddress clientSystemAddress; + + /// RakNetGUID of server that is holding this data, and the client is connected to + RakNetGUID serverGUID; + + /// RakNetGUID of client that uploaded this data + RakNetGUID clientGUID; + + /// \internal + void Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator); +}; + +/// \ingroup CLOUD_GROUP +struct RAK_DLL_EXPORT CloudQueryResult +{ + /// Query originally passed to Download() + CloudQuery cloudQuery; + + /// Results returned from query. If there were multiple keys in CloudQuery::keys then see resultKeyIndices + DataStructures::List rowsReturned; + + /// If there were multiple keys in CloudQuery::keys, then each key is processed in order and the result concatenated to rowsReturned + /// The starting index of each query is written to resultKeyIndices + /// For example, if CloudQuery::keys had 4 keys, returning 3 rows, 0, rows, 5 rows, and 12 rows then + /// resultKeyIndices would be 0, 3, 3, 8 + DataStructures::List resultKeyIndices; + + /// Whatever was passed to CloudClient::Get() as CloudQuery::subscribeToResults + bool subscribeToResults; + + /// \internal + void Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator); + /// \internal + void SerializeHeader(bool writeToBitstream, BitStream *bitStream); + /// \internal + void SerializeNumRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream); + /// \internal + void SerializeCloudQueryRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream, CloudAllocator *allocator); +}; + +} // Namespace RakNet + +#endif // __CLOUD_COMMON_H + +#endif // #if _RAKNET_SUPPORT_CloudClient==1 || _RAKNET_SUPPORT_CloudServer==1 diff --git a/include/raknet/CloudServer.hpp b/include/raknet/CloudServer.hpp new file mode 100644 index 0000000..81f7743 --- /dev/null +++ b/include/raknet/CloudServer.hpp @@ -0,0 +1,383 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file CloudServer.h +/// \brief Stores client data, and allows cross-server communication to retrieve this data +/// \details TODO +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_CloudServer==1 + +#ifndef __CLOUD_SERVER_H +#define __CLOUD_SERVER_H + +#include "PluginInterface2.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" +#include "RakString.hpp" +#include "DS_Hash.hpp" +#include "CloudCommon.hpp" +#include "DS_OrderedList.hpp" + +/// If the data is smaller than this value, an allocation is avoid. However, this value exists for every row +#define CLOUD_SERVER_DATA_STACK_SIZE 32 + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \brief Zero or more instances of CloudServerQueryFilter can be attached to CloudServer to restrict client queries +/// All attached instances of CloudServerQueryFilter on each corresponding operation, from all directly connected clients +/// If any attached instance returns false for a given operation, that operation is silently rejected +/// \ingroup CLOUD_GROUP +class RAK_DLL_EXPORT CloudServerQueryFilter +{ +public: + CloudServerQueryFilter() {} + virtual ~CloudServerQueryFilter() {} + + /// Called when a local client wants to post data + /// \return true to allow, false to reject + virtual bool OnPostRequest(RakNetGUID clientGuid, SystemAddress clientAddress, CloudKey key, uint32_t dataLength, const char *data)=0; + + /// Called when a local client wants to release data that it has previously uploaded + /// \return true to allow, false to reject + virtual bool OnReleaseRequest(RakNetGUID clientGuid, SystemAddress clientAddress, DataStructures::List &cloudKeys)=0; + + /// Called when a local client wants to query data + /// If you return false, the client will get no response at all + /// \return true to allow, false to reject + virtual bool OnGetRequest(RakNetGUID clientGuid, SystemAddress clientAddress, CloudQuery &query, DataStructures::List &specificSystems)=0; + + /// Called when a local client wants to stop getting updates for data + /// If you return false, the client will keep getting updates for that data + /// \return true to allow, false to reject + virtual bool OnUnsubscribeRequest(RakNetGUID clientGuid, SystemAddress clientAddress, DataStructures::List &cloudKeys, DataStructures::List &specificSystems)=0; +}; + +/// \brief Stores client data, and allows cross-server communication to retrieve this data +/// \ingroup CLOUD_GROUP +class RAK_DLL_EXPORT CloudServer : public PluginInterface2, CloudAllocator +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(CloudServer) + + CloudServer(); + virtual ~CloudServer(); + + /// \brief Max bytes a client can upload + /// Data in excess of this value is silently ignored + /// defaults to 0 (unlimited) + /// \param[in] bytes Max bytes a client can upload. 0 means unlimited. + void SetMaxUploadBytesPerClient(uint64_t bytes); + + /// \brief Max bytes returned by a download. If the number of bytes would exceed this amount, the returned list is truncated + /// However, if this would result in no rows downloaded, then one row will be returned. + /// \param[in] bytes Max bytes a client can download from a single Get(). 0 means unlimited. + void SetMaxBytesPerDownload(uint64_t bytes); + + /// \brief Add a server, which is assumed to be connected in a fully connected mesh to all other servers and also running the CloudServer plugin + /// The other system must also call AddServer before getting the subscription data, or it will be rejected. + /// Sending a message telling the other system to call AddServer(), followed by calling AddServer() locally, would be sufficient for this to work. + /// \note This sends subscription data to the other system, using RELIABLE_ORDERED on channel 0 + /// \param[in] systemIdentifier Identifier of the remote system + void AddServer(RakNetGUID systemIdentifier); + + /// \brief Removes a server added through AddServer() + /// \param[in] systemIdentifier Identifier of the remote system + void RemoveServer(RakNetGUID systemIdentifier); + + /// Return list of servers added with AddServer() + /// \param[out] remoteServers List of servers added + void GetRemoteServers(DataStructures::List &remoteServersOut); + + /// \brief Frees all memory. Does not remove query filters + void Clear(void); + + /// \brief Report the specified SystemAddress to client queries, rather than what RakPeer reads. + /// This is useful if you already know your public IP + /// This only applies to future updates, so call it before updating to apply to all queries + /// \param[in] forcedAddress The systmeAddress to return in queries. Use UNASSIGNED_SYSTEM_ADDRESS (default) to use what RakPeer returns + void ForceExternalSystemAddress(SystemAddress forcedAddress); + + /// \brief Adds a callback called on each query. If all filters returns true for an operation, the operation is allowed. + /// If the filter was already added, the function silently fails + /// \param[in] filter An externally allocated instance of CloudServerQueryFilter. The instance must remain valid until it is removed with RemoveQueryFilter() or RemoveAllQueryFilters() + void AddQueryFilter(CloudServerQueryFilter* filter); + + /// \brief Removes a callback added with AddQueryFilter() + /// The instance is not deleted, only unreferenced. It is up to the user to delete the instance, if necessary + /// \param[in] filter An externally allocated instance of CloudServerQueryFilter. The instance must remain valid until it is removed with RemoveQueryFilter() or RemoveAllQueryFilters() + void RemoveQueryFilter(CloudServerQueryFilter* filter); + + /// \brief Removes all instances of CloudServerQueryFilter added with AddQueryFilter(). + /// The instances are not deleted, only unreferenced. It is up to the user to delete the instances, if necessary + void RemoveAllQueryFilters(void); + +protected: + virtual void Update(void); + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnRakPeerShutdown(void); + + + virtual void OnPostRequest(Packet *packet); + virtual void OnReleaseRequest(Packet *packet); + virtual void OnGetRequest(Packet *packet); + virtual void OnUnsubscribeRequest(Packet *packet); + virtual void OnServerToServerGetRequest(Packet *packet); + virtual void OnServerToServerGetResponse(Packet *packet); + + uint64_t maxUploadBytesPerClient, maxBytesPerDowload; + + // ---------------------------------------------------------------------------- + // For a given data key, quickly look up one or all systems that have uploaded + // ---------------------------------------------------------------------------- + struct CloudData + { + CloudData() {} + ~CloudData() {if (allocatedData) rakFree_Ex(allocatedData, _FILE_AND_LINE_);} + bool IsUnused(void) const {return isUploaded==false && specificSubscribers.Size()==0;} + void Clear(void) {if (dataPtr==allocatedData) rakFree_Ex(allocatedData, _FILE_AND_LINE_); allocatedData=0; dataPtr=0; dataLengthBytes=0; isUploaded=false;} + + unsigned char stackData[CLOUD_SERVER_DATA_STACK_SIZE]; + unsigned char *allocatedData; // Uses allocatedData instead of stackData if length of data exceeds CLOUD_SERVER_DATA_STACK_SIZE + unsigned char *dataPtr; // Points to either stackData or allocatedData + uint32_t dataLengthBytes; + bool isUploaded; + + /// System address of server that is holding this data, and the client is connected to + SystemAddress serverSystemAddress; + + /// System address of client that uploaded this data + SystemAddress clientSystemAddress; + + /// RakNetGUID of server that is holding this data, and the client is connected to + RakNetGUID serverGUID; + + /// RakNetGUID of client that uploaded this data + RakNetGUID clientGUID; + + /// When the key data changes from this particular system, notify these subscribers + /// This list mutually exclusive with CloudDataList::nonSpecificSubscribers + DataStructures::OrderedList specificSubscribers; + }; + void WriteCloudQueryRowFromResultList(unsigned int i, DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut); + void WriteCloudQueryRowFromResultList(DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut); + + static int KeyDataPtrComp( const RakNetGUID &key, CloudData* const &data ); + struct CloudDataList + { + bool IsUnused(void) const {return keyData.Size()==0 && nonSpecificSubscribers.Size()==0;} + bool IsNotUploaded(void) const {return uploaderCount==0;} + bool RemoveSubscriber(RakNetGUID g) { + bool objectExists; + unsigned int index; + index = nonSpecificSubscribers.GetIndexFromKey(g, &objectExists); + if (objectExists) + { + subscriberCount--; + nonSpecificSubscribers.RemoveAtIndex(index); + return true; + } + return false; + } + + unsigned int uploaderCount, subscriberCount; + CloudKey key; + + // Data uploaded from or subscribed to for various systems + DataStructures::OrderedList keyData; + + /// When the key data changes from any system, notify these subscribers + /// This list mutually exclusive with CloudData::specificSubscribers + DataStructures::OrderedList nonSpecificSubscribers; + }; + + static int KeyDataListComp( const CloudKey &key, CloudDataList * const &data ); + DataStructures::OrderedList dataRepository; + + struct KeySubscriberID + { + CloudKey key; + DataStructures::OrderedList specificSystemsSubscribedTo; + }; + static int KeySubscriberIDComp(const CloudKey &key, KeySubscriberID * const &data ); + + // Remote systems + struct RemoteCloudClient + { + bool IsUnused(void) const {return uploadedKeys.Size()==0 && subscribedKeys.Size()==0;} + + DataStructures::OrderedList uploadedKeys; + DataStructures::OrderedList subscribedKeys; + uint64_t uploadedBytes; + }; + DataStructures::Hash remoteSystems; + + // For a given user, release all subscribed and uploaded keys + void ReleaseSystem(RakNetGUID clientAddress ); + + // For a given user, release a set of keys + void ReleaseKeys(RakNetGUID clientAddress, DataStructures::List &keys ); + + void NotifyClientSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, DataStructures::OrderedList &subscribers, bool wasUpdated ); + void NotifyClientSubscribersOfDataChange( CloudQueryRow *row, DataStructures::OrderedList &subscribers, bool wasUpdated ); + void NotifyServerSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, bool wasUpdated ); + + struct RemoteServer + { + RakNetGUID serverAddress; + // This server needs to know about these keys when they are updated or deleted + DataStructures::OrderedList subscribedKeys; + // This server has uploaded these keys, and needs to know about Get() requests + DataStructures::OrderedList uploadedKeys; + + // Just for processing + bool workingFlag; + + // If false, we don't know what keys they have yet, so send everything + bool gotSubscribedAndUploadedKeys; + }; + + static int RemoteServerComp(const RakNetGUID &key, RemoteServer* const &data ); + DataStructures::OrderedList remoteServers; + + struct BufferedGetResponseFromServer + { + void Clear(CloudAllocator *allocator); + + RakNetGUID serverAddress; + CloudQueryResult queryResult; + bool gotResult; + }; + + struct CloudQueryWithAddresses + { + // Inputs + CloudQuery cloudQuery; + DataStructures::List specificSystems; + + void Serialize(bool writeToBitstream, BitStream *bitStream); + }; + + static int BufferedGetResponseFromServerComp(const RakNetGUID &key, BufferedGetResponseFromServer* const &data ); + struct GetRequest + { + void Clear(CloudAllocator *allocator); + bool AllRemoteServersHaveResponded(void) const; + CloudQueryWithAddresses cloudQueryWithAddresses; + + // When request started. If takes too long for a response from another system, can abort remaining systems + RakNet::Time requestStartTime; + + // Assigned by server that gets the request to identify response. See nextGetRequestId + uint32_t requestId; + + RakNetGUID requestingClient; + + DataStructures::OrderedList remoteServerResponses; + }; + static int GetRequestComp(const uint32_t &key, GetRequest* const &data ); + DataStructures::OrderedList getRequests; + RakNet::Time nextGetRequestsCheck; + + uint32_t nextGetRequestId; + + void ProcessAndTransmitGetRequest(GetRequest *getRequest); + + void ProcessCloudQueryWithAddresses( + CloudServer::CloudQueryWithAddresses &cloudQueryWithAddresses, + DataStructures::List &cloudDataResultList, + DataStructures::List &cloudKeyResultList + ); + + void SendUploadedAndSubscribedKeysToServer( RakNetGUID systemAddress ); + void SendUploadedKeyToServers( CloudKey &cloudKey ); + void SendSubscribedKeyToServers( CloudKey &cloudKey ); + void RemoveUploadedKeyFromServers( CloudKey &cloudKey ); + void RemoveSubscribedKeyFromServers( CloudKey &cloudKey ); + + void OnSendUploadedAndSubscribedKeysToServer( Packet *packet ); + void OnSendUploadedKeyToServers( Packet *packet ); + void OnSendSubscribedKeyToServers( Packet *packet ); + void OnRemoveUploadedKeyFromServers( Packet *packet ); + void OnRemoveSubscribedKeyFromServers( Packet *packet ); + void OnServerDataChanged( Packet *packet ); + + void GetServersWithUploadedKeys( + DataStructures::List &keys, + DataStructures::List &remoteServersWithData + ); + + CloudServer::CloudDataList *GetOrAllocateCloudDataList(CloudKey key, bool *dataRepositoryExists, unsigned int &dataRepositoryIndex); + + void UnsubscribeFromKey(RemoteCloudClient *remoteCloudClient, RakNetGUID remoteCloudClientGuid, unsigned int keySubscriberIndex, CloudKey &cloudKey, DataStructures::List &specificSystems); + void RemoveSpecificSubscriber(RakNetGUID specificSubscriber, CloudDataList *cloudDataList, RakNetGUID remoteCloudClientGuid); + + DataStructures::List queryFilters; + + SystemAddress forceAddress; +}; + + +} // namespace RakNet + +#endif + + +// Key subscription +// +// A given system can subscribe to one or more keys. +// The subscription can be further be defined as only subscribing to keys uploaded by or changed by a given system. +// It is possible to subscribe to keys not yet uploaded, or uploaded to another system +// +// Operations: +// +// 1. SubscribeToKey() - Get() operation with subscription +// A. Add to key subscription list for the client, which contains a keyId / specificUploaderList pair +// B. Send to remote servers that for this key, they should send us updates +// C. (Done, get operation returns current values) +// +// 2. UpdateData() - Post() operation +// A. Find all subscribers to this data, for the uploading system. +// B. Send them the uploaded data +// C. Find all servers that subscribe to this data +// D. Send them the uploaded data +// +// 3. DeleteData() - Release() operation +// A. Find all subscribers to this data, for the deleting system. +// B. Inform them of the deletion +// C. Find all servers that subscribe to this data +// D. Inform them of the deletion +// +// 4. Unsubscribe() +// A. Find this subscriber, and remove their subscription +// B. If no one else is subscribing to this key for any system, notify remote servers we no longer need subscription updates +// +// Internal operations: +// +// 1. Find if any connected client has subscribed to a given key +// A. This is used add and remove our subscription for this key to remote servers +// +// 2. For a given key and updating address, find all connected clients that care +// A. First find connected clients that have subscribed to this key, regardless of address +// B. Then find connected clients that have subscribed to this key for this particular address +// +// 3. Find all remote servers that have subscribed to a given key +// A. This is so when the key is updated or deleted, we know who to send it to +// +// 4. For a given client (such as on disconnect), remove all records of their subscriptions + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/CommandParserInterface.hpp b/include/raknet/CommandParserInterface.hpp new file mode 100644 index 0000000..c601e71 --- /dev/null +++ b/include/raknet/CommandParserInterface.hpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file CommandParserInterface.h +/// \brief Contains CommandParserInterface , from which you derive custom command parsers +/// + + +#ifndef __COMMAND_PARSER_INTERFACE +#define __COMMAND_PARSER_INTERFACE + +#include "RakMemoryOverride.hpp" +#include "RakNetTypes.hpp" +#include "DS_OrderedList.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class TransportInterface; + +/// \internal +/// Contains the information related to one command registered with RegisterCommand() +/// Implemented so I can have an automatic help system via SendCommandList() +struct RAK_DLL_EXPORT RegisteredCommand +{ + const char *command; + const char *commandHelp; + unsigned char parameterCount; +}; + +/// List of commands registered with RegisterCommand() +int RAK_DLL_EXPORT RegisteredCommandComp( const char* const & key, const RegisteredCommand &data ); + +/// \brief The interface used by command parsers. +/// \details CommandParserInterface provides a set of functions and interfaces that plug into the ConsoleServer class. +/// Each CommandParserInterface works at the same time as other interfaces in the system. +class RAK_DLL_EXPORT CommandParserInterface +{ +public: + CommandParserInterface(); + virtual ~CommandParserInterface(); + + /// You are responsible for overriding this function and returning a static string, which will identifier your parser. + /// This should return a static string + /// \return The name that you return. + virtual const char *GetName(void) const=0; + + /// \brief A callback for when \a systemAddress has connected to us. + /// \param[in] systemAddress The player that has connected. + /// \param[in] transport The transport interface that sent us this information. Can be used to send messages to this or other players. + virtual void OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport); + + /// \brief A callback for when \a systemAddress has disconnected, either gracefully or forcefully + /// \param[in] systemAddress The player that has disconnected. + /// \param[in] transport The transport interface that sent us this information. + virtual void OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport); + + /// \brief A callback for when you are expected to send a brief description of your parser to \a systemAddress + /// \param[in] transport The transport interface we can use to write to + /// \param[in] systemAddress The player that requested help. + virtual void SendHelp(TransportInterface *transport, const SystemAddress &systemAddress)=0; + + /// \brief Given \a command with parameters \a parameterList , do whatever processing you wish. + /// \param[in] command The command to process + /// \param[in] numParameters How many parameters were passed along with the command + /// \param[in] parameterList The list of parameters. parameterList[0] is the first parameter and so on. + /// \param[in] transport The transport interface we can use to write to + /// \param[in] systemAddress The player that sent this command. + /// \param[in] originalString The string that was actually sent over the network, in case you want to do your own parsing + virtual bool OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString)=0; + + /// \brief This is called every time transport interface is registered. + /// \details If you want to save a copy of the TransportInterface pointer + /// This is the place to do it + /// \param[in] transport The new TransportInterface + virtual void OnTransportChange(TransportInterface *transport); + + /// \internal + /// Scan commandList and return the associated array + /// \param[in] command The string to find + /// \param[out] rc Contains the result of this operation + /// \return True if we found the command, false otherwise + virtual bool GetRegisteredCommand(const char *command, RegisteredCommand *rc); + + /// \internal + /// Goes through str, replacing the delineating character with 0's. + /// \param[in] str The string sent by the transport interface + /// \param[in] delineator The character to scan for to use as a delineator + /// \param[in] delineatorToggle When encountered the delineator replacement is toggled on and off + /// \param[out] numParameters How many pointers were written to \a parameterList + /// \param[out] parameterList An array of pointers to characters. Will hold pointers to locations inside \a str + /// \param[in] parameterListLength How big the \a parameterList array is + static void ParseConsoleString(char *str, const char delineator, unsigned char delineatorToggle, unsigned *numParameters, char **parameterList, unsigned parameterListLength); + + /// \internal + /// Goes through the variable commandList and sends the command portion of each struct + /// \param[in] transport The transport interface we can use to write to + /// \param[in] systemAddress The player to write to + virtual void SendCommandList(TransportInterface *transport, const SystemAddress &systemAddress); + + static const unsigned char VARIABLE_NUMBER_OF_PARAMETERS; + + // Currently only takes static strings - doesn't make a copy of what you pass. + // parameterCount is the number of parameters that the sender has to include with the command. + // Pass 255 to parameterCount to indicate variable number of parameters + + /// Registers a command. + /// \param[in] parameterCount How many parameters your command requires. If you want to accept a variable number of commands, pass CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS + /// \param[in] command A pointer to a STATIC string that has your command. I keep a copy of the pointer here so don't deallocate the string. + /// \param[in] commandHelp A pointer to a STATIC string that has the help information for your command. I keep a copy of the pointer here so don't deallocate the string. + virtual void RegisterCommand(unsigned char parameterCount, const char *command, const char *commandHelp); + + /// \brief Just writes a string to the remote system based on the result ( \a res ) of your operation + /// \details This is not necessary to call, but makes it easier to return results of function calls. + /// \param[in] res The result to write + /// \param[in] command The command that this result came from + /// \param[in] transport The transport interface that will be written to + /// \param[in] systemAddress The player this result will be sent to + virtual void ReturnResult(bool res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress); + virtual void ReturnResult(char *res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress); + virtual void ReturnResult(SystemAddress res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress); + virtual void ReturnResult(int res, const char *command,TransportInterface *transport, const SystemAddress &systemAddress); + + /// \brief Just writes a string to the remote system when you are calling a function that has no return value. + /// \details This is not necessary to call, but makes it easier to return results of function calls. + /// \param[in] res The result to write + /// \param[in] command The command that this result came from + /// \param[in] transport The transport interface that will be written to + /// \param[in] systemAddress The player this result will be sent to + virtual void ReturnResult(const char *command,TransportInterface *transport, const SystemAddress &systemAddress); + +protected: + DataStructures::OrderedList commandList; +}; + +} // namespace RakNet + +#endif + diff --git a/include/raknet/ConnectionGraph2.hpp b/include/raknet/ConnectionGraph2.hpp new file mode 100644 index 0000000..f699c7c --- /dev/null +++ b/include/raknet/ConnectionGraph2.hpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file ConnectionGraph2.h +/// \brief Connection graph plugin, version 2. Tells new systems about existing and new connections +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_ConnectionGraph2==1 + +#ifndef __CONNECTION_GRAPH_2_H +#define __CONNECTION_GRAPH_2_H + +#include "RakMemoryOverride.hpp" +#include "RakNetTypes.hpp" +#include "PluginInterface2.hpp" +#include "DS_List.hpp" +#include "DS_WeightedGraph.hpp" +#include "GetTime.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \brief A one hop connection graph. +/// \details Sends ID_REMOTE_CONNECTION_LOST, ID_REMOTE_DISCONNECTION_NOTIFICATION, ID_REMOTE_NEW_INCOMING_CONNECTION
+/// All identifiers are followed by SystemAddress, then RakNetGUID +/// Also stores the list for you, which you can access with GetConnectionListForRemoteSystem +/// \ingroup CONNECTION_GRAPH_GROUP +class RAK_DLL_EXPORT ConnectionGraph2 : public PluginInterface2 +{ +public: + + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(ConnectionGraph2) + + ConnectionGraph2(); + ~ConnectionGraph2(); + + /// \brief Given a remote system identified by RakNetGUID, return the list of SystemAddresses and RakNetGUIDs they are connected to + /// \param[in] remoteSystemGuid Which system we are referring to. This only works for remote systems, not ourselves. + /// \param[out] saOut A preallocated array to hold the output list of SystemAddress. Can be 0 if you don't care. + /// \param[out] guidOut A preallocated array to hold the output list of RakNetGUID. Can be 0 if you don't care. + /// \param[in,out] outLength On input, the size of \a saOut and \a guidOut. On output, modified to reflect the number of elements actually written + /// \return True if \a remoteSystemGuid was found. Otherwise false, and \a saOut, \a guidOut remain unchanged. \a outLength will be set to 0. + bool GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid, SystemAddress *saOut, RakNetGUID *guidOut, unsigned int *outLength); + + /// Returns if g1 is connected to g2 + bool ConnectionExists(RakNetGUID g1, RakNetGUID g2); + + /// Returns the average ping between two systems in the connection graph. Returns -1 if no connection exists between those systems + uint16_t GetPingBetweenSystems(RakNetGUID g1, RakNetGUID g2) const; + + /// Returns the system with the lowest average ping among all its connections. + /// If you need one system in the peer to peer group to relay data, have the FullyConnectedMesh2 host call this function after host migration, and use that system + RakNetGUID GetLowestAveragePingSystem(void) const; + + /// \brief If called with false, then new connections are only added to the connection graph when you call ProcessNewConnection(); + /// \details This is useful if you want to perform validation before connecting a system to a mesh, or if you want a submesh (for example a server cloud) + /// \param[in] b True to automatically call ProcessNewConnection() on any new connection, false to not do so. Defaults to true. + void SetAutoProcessNewConnections(bool b); + + /// \brief Returns value passed to SetAutoProcessNewConnections() + /// \return Value passed to SetAutoProcessNewConnections(), or the default of true if it was never called + bool GetAutoProcessNewConnections(void) const; + + /// \brief If you call SetAutoProcessNewConnections(false);, then you will need to manually call ProcessNewConnection() on new connections + /// \details On ID_NEW_INCOMING_CONNECTION or ID_CONNECTION_REQUEST_ACCEPTED, adds that system to the graph + /// Do not call ProcessNewConnection() manually otherwise + /// \param[in] The packet->SystemAddress member + /// \param[in] The packet->guid member + void AddParticipant(const SystemAddress &systemAddress, RakNetGUID rakNetGUID); + + /// Get the participants added with AddParticipant() + /// \param[out] participantList Participants added with AddParticipant(); + void GetParticipantList(DataStructures::OrderedList &participantList); + + /// \internal + struct SystemAddressAndGuid + { + SystemAddress systemAddress; + RakNetGUID guid; + uint16_t sendersPingToThatSystem; + }; + /// \internal + static int SystemAddressAndGuidComp( const SystemAddressAndGuid &key, const SystemAddressAndGuid &data ); + + /// \internal + struct RemoteSystem + { + DataStructures::OrderedList remoteConnections; + RakNetGUID guid; + }; + /// \internal + static int RemoteSystemComp( const RakNetGUID &key, RemoteSystem * const &data ); + +protected: + /// \internal + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + /// \internal + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + /// \internal + virtual PluginReceiveResult OnReceive(Packet *packet); + + // List of systems I am connected to, which in turn stores which systems they are connected to + DataStructures::OrderedList remoteSystems; + + bool autoProcessNewConnections; + +}; + +} // namespace RakNet + +#endif // #ifndef __CONNECTION_GRAPH_2_H + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/ConsoleServer.hpp b/include/raknet/ConsoleServer.hpp new file mode 100644 index 0000000..f9d9b6b --- /dev/null +++ b/include/raknet/ConsoleServer.hpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file ConsoleServer.h +/// \brief Contains ConsoleServer , used to plugin to your game to accept remote console-based connections +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_ConsoleServer==1 + +#ifndef __CONSOLE_SERVER_H +#define __CONSOLE_SERVER_H + +#include "RakMemoryOverride.hpp" +#include "DS_List.hpp" +#include "RakNetTypes.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class TransportInterface; +class CommandParserInterface; + + +/// \brief The main entry point for the server portion of your remote console application support. +/// \details ConsoleServer takes one TransportInterface and one or more CommandParserInterface (s) +/// The TransportInterface will be used to send data between the server and the client. The connecting client must support the +/// protocol used by your derivation of TransportInterface . TelnetTransport and RakNetTransport are two such derivations . +/// When a command is sent by a remote console, it will be processed by your implementations of CommandParserInterface +class RAK_DLL_EXPORT ConsoleServer +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(ConsoleServer) + + ConsoleServer(); + ~ConsoleServer(); + + /// \brief Call this with a derivation of TransportInterface so that the console server can send and receive commands + /// \param[in] transportInterface Your interface to use. + /// \param[in] port The port to host on. Telnet uses port 23 by default. RakNet can use whatever you want. + void SetTransportProvider(TransportInterface *transportInterface, unsigned short port); + + /// \brief Add an implementation of CommandParserInterface to the list of command parsers. + /// \param[in] commandParserInterface The command parser referred to + void AddCommandParser(CommandParserInterface *commandParserInterface); + + /// \brief Remove an implementation of CommandParserInterface previously added with AddCommandParser(). + /// \param[in] commandParserInterface The command parser referred to + void RemoveCommandParser(CommandParserInterface *commandParserInterface); + + /// \brief Call update to read packet sent from your TransportInterface. + /// You should do this fairly frequently. + void Update(void); + + /// \brief Sets a prompt to show when waiting for user input. + /// \details Pass an empty string to clear the prompt + /// Defaults to no prompt + /// \param[in] _prompt Null-terminated string of the prompt to use. If you want a newline, be sure to use /r/n + void SetPrompt(const char *_prompt); + +protected: + void ListParsers(SystemAddress systemAddress); + void ShowPrompt(SystemAddress systemAddress); + TransportInterface *transport; + DataStructures::List commandParserList; + char* password[256]; + char *prompt; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/DR_SHA1.hpp b/include/raknet/DR_SHA1.hpp new file mode 100644 index 0000000..71c3615 --- /dev/null +++ b/include/raknet/DR_SHA1.hpp @@ -0,0 +1,308 @@ +/* + 100% free public domain implementation of the SHA-1 algorithm + by Dominik Reichl + Web: http://www.dominik-reichl.de/ + + Version 2.1 - 2012-06-19 + - Deconstructor (resetting internal variables) is now only + implemented if SHA1_WIPE_VARIABLES is defined (which is the + default). + - Renamed inclusion guard to contain a GUID. + - Demo application is now using C++/STL objects and functions. + - Unicode build of the demo application now outputs the hashes of both + the ANSI and Unicode representations of strings. + - Various other demo application improvements. + + Version 2.0 - 2012-06-14 + - Added 'limits.h' include. + - Renamed inclusion guard and macros for compliancy (names beginning + with an underscore are reserved). + + Version 1.9 - 2011-11-10 + - Added Unicode test vectors. + - Improved support for hashing files using the HashFile method that + are larger than 4 GB. + - Improved file hashing performance (by using a larger buffer). + - Disabled unnecessary compiler warnings. + - Internal variables are now private. + + Version 1.8 - 2009-03-16 + - Converted project files to Visual Studio 2008 format. + - Added Unicode support for HashFile utility method. + - Added support for hashing files using the HashFile method that are + larger than 2 GB. + - HashFile now returns an error code instead of copying an error + message into the output buffer. + - GetHash now returns an error code and validates the input parameter. + - Added ReportHashStl STL utility method. + - Added REPORT_HEX_SHORT reporting mode. + - Improved Linux compatibility of test program. + + Version 1.7 - 2006-12-21 + - Fixed buffer underrun warning that appeared when compiling with + Borland C Builder (thanks to Rex Bloom and Tim Gallagher for the + patch). + - Breaking change: ReportHash writes the final hash to the start + of the buffer, i.e. it's not appending it to the string anymore. + - Made some function parameters const. + - Added Visual Studio 2005 project files to demo project. + + Version 1.6 - 2005-02-07 (thanks to Howard Kapustein for patches) + - You can set the endianness in your files, no need to modify the + header file of the CSHA1 class anymore. + - Aligned data support. + - Made support/compilation of the utility functions (ReportHash and + HashFile) optional (useful when bytes count, for example in embedded + environments). + + Version 1.5 - 2005-01-01 + - 64-bit compiler compatibility added. + - Made variable wiping optional (define SHA1_WIPE_VARIABLES). + - Removed unnecessary variable initializations. + - ROL32 improvement for the Microsoft compiler (using _rotl). + + Version 1.4 - 2004-07-22 + - CSHA1 now compiles fine with GCC 3.3 under Mac OS X (thanks to Larry + Hastings). + + Version 1.3 - 2003-08-17 + - Fixed a small memory bug and made a buffer array a class member to + ensure correct working when using multiple CSHA1 class instances at + one time. + + Version 1.2 - 2002-11-16 + - Borlands C++ compiler seems to have problems with string addition + using sprintf. Fixed the bug which caused the digest report function + not to work properly. CSHA1 is now Borland compatible. + + Version 1.1 - 2002-10-11 + - Removed two unnecessary header file includes and changed BOOL to + bool. Fixed some minor bugs in the web page contents. + + Version 1.0 - 2002-06-20 + - First official release. + + ================ Test Vectors ================ + + SHA1("abc" in ANSI) = + A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D + SHA1("abc" in Unicode LE) = + 9F04F41A 84851416 2050E3D6 8C1A7ABB 441DC2B5 + + SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + in ANSI) = + 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 + SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + in Unicode LE) = + 51D7D876 9AC72C40 9C5B0E3F 69C60ADC 9A039014 + + SHA1(A million repetitions of "a" in ANSI) = + 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F + SHA1(A million repetitions of "a" in Unicode LE) = + C4609560 A108A0C6 26AA7F2B 38A65566 739353C5 +*/ + +#ifndef SHA1_H_A545E61D43E9404E8D736869AB3CBFE7 +#define SHA1_H_A545E61D43E9404E8D736869AB3CBFE7 + +// KevinJ: +#include "RakMemoryOverride.hpp" +#include // Needed for file access + +#include // Needed for memset and memcpy + +#include // Needed for strcat and strcpy +#include "Export.hpp" +//#define MAX_FILE_READ_BUFFER 8000 +#define SHA1_LENGTH 20 + + + +#if !defined(SHA1_UTILITY_FUNCTIONS) && !defined(SHA1_NO_UTILITY_FUNCTIONS) +#define SHA1_UTILITY_FUNCTIONS +#endif + +#if !defined(SHA1_STL_FUNCTIONS) && !defined(SHA1_NO_STL_FUNCTIONS) +#define SHA1_STL_FUNCTIONS +#if !defined(SHA1_UTILITY_FUNCTIONS) +#error STL functions require SHA1_UTILITY_FUNCTIONS. +#endif +#endif + + +#include + +#include + +#ifdef SHA1_UTILITY_FUNCTIONS +#include +#include +#endif + +#ifdef SHA1_STL_FUNCTIONS +#include +#endif + +#ifdef _MSC_VER +#include +#endif + +// You can define the endian mode in your files without modifying the SHA-1 +// source files. Just #define SHA1_LITTLE_ENDIAN or #define SHA1_BIG_ENDIAN +// in your files, before including the DR_SHA1.h header file. If you don't +// define anything, the class defaults to little endian. +#if !defined(SHA1_LITTLE_ENDIAN) && !defined(SHA1_BIG_ENDIAN) +#define SHA1_LITTLE_ENDIAN +#endif + +// If you want variable wiping, #define SHA1_WIPE_VARIABLES, if not, +// #define SHA1_NO_WIPE_VARIABLES. If you don't define anything, it +// defaults to wiping. +#if !defined(SHA1_WIPE_VARIABLES) && !defined(SHA1_NO_WIPE_VARIABLES) +#define SHA1_WIPE_VARIABLES +#endif + +#if defined(SHA1_HAS_TCHAR) +#include +#else +#ifdef _MSC_VER +#include +#else +#ifndef TCHAR + + #ifdef _WIN32 + #include + #else + #define TCHAR char + #endif + +#endif + +#ifndef _T +#define _T(__x) (__x) +#define _tmain main +#define _tprintf printf +#define _getts gets +#define _tcslen strlen +#define _tfopen fopen +#define _tcscpy strcpy +#define _tcscat strcat +#define _sntprintf snprintf +#endif +#endif +#endif + +/////////////////////////////////////////////////////////////////////////// +// Define variable types + +#ifndef UINT_8 +#ifdef _MSC_VER // Compiling with Microsoft compiler +#define UINT_8 unsigned __int8 +#else // !_MSC_VER +#define UINT_8 unsigned char +#endif // _MSC_VER +#endif + +#ifndef UINT_32 +#ifdef _MSC_VER // Compiling with Microsoft compiler +#define UINT_32 unsigned __int32 +#else // !_MSC_VER +#if (ULONG_MAX == 0xFFFFFFFFUL) +#define UINT_32 unsigned long +#else +#define UINT_32 unsigned int +#endif +#endif // _MSC_VER +#endif // UINT_32 + +#ifndef INT_64 +#ifdef _MSC_VER // Compiling with Microsoft compiler +#define INT_64 __int64 +#else // !_MSC_VER +#define INT_64 long long +#endif // _MSC_VER +#endif // INT_64 + +#ifndef UINT_64 +#ifdef _MSC_VER // Compiling with Microsoft compiler +#define UINT_64 unsigned __int64 +#else // !_MSC_VER +#define UINT_64 unsigned long long +#endif // _MSC_VER +#endif // UINT_64 + +/////////////////////////////////////////////////////////////////////////// +// Declare SHA-1 workspace + +typedef union +{ + UINT_8 c[64]; + UINT_32 l[16]; +} SHA1_WORKSPACE_BLOCK; + +class RAK_DLL_EXPORT CSHA1 +{ +public: +#ifdef SHA1_UTILITY_FUNCTIONS + // Different formats for ReportHash(Stl) + enum REPORT_TYPE + { + REPORT_HEX = 0, + REPORT_DIGIT = 1, + REPORT_HEX_SHORT = 2 + }; +#endif + + // Constructor and destructor + CSHA1(); + +#ifdef SHA1_WIPE_VARIABLES + ~CSHA1(); +#endif + + void Reset(); + + // Hash in binary data and strings + void Update(const UINT_8* pbData, UINT_32 uLen); + +#ifdef SHA1_UTILITY_FUNCTIONS + // Hash in file contents + bool HashFile(const TCHAR* tszFileName); +#endif + + // Finalize hash; call it before using ReportHash(Stl) + void Final(); + +#ifdef SHA1_UTILITY_FUNCTIONS + bool ReportHash(TCHAR* tszReport, REPORT_TYPE rtReportType = REPORT_HEX) const; +#endif + +#ifdef SHA1_STL_FUNCTIONS + bool ReportHashStl(std::basic_string& strOut, REPORT_TYPE rtReportType = + REPORT_HEX) const; +#endif + + // Get the raw message digest (20 bytes) + bool GetHash(UINT_8* pbDest20) const; + +unsigned char * GetHash( void ) const; +// KevinJ: http://cseweb.ucsd.edu/~mihir/papers/hmac-cb.pdf + static void HMAC(unsigned char *sharedKey, int sharedKeyLength, unsigned char *data, int dataLength, unsigned char output[SHA1_LENGTH]); + +private: + // Private SHA-1 transformation + void Transform(UINT_32* pState, const UINT_8* pBuffer); + + // Member variables + UINT_32 m_state[5]; + UINT_32 m_count[2]; + UINT_32 m_reserved0[1]; // Memory alignment padding + UINT_8 m_buffer[64]; + UINT_8 m_digest[20]; + UINT_32 m_reserved1[3]; // Memory alignment padding + + UINT_8 m_workspace[64]; + SHA1_WORKSPACE_BLOCK* m_block; // SHA1 pointer to the byte array above +}; + +#endif // SHA1_H_A545E61D43E9404E8D736869AB3CBFE7 diff --git a/include/raknet/DS_BPlusTree.hpp b/include/raknet/DS_BPlusTree.hpp new file mode 100644 index 0000000..47bcbac --- /dev/null +++ b/include/raknet/DS_BPlusTree.hpp @@ -0,0 +1,1154 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_BPlusTree.h +/// + + +#ifndef __B_PLUS_TREE_CPP +#define __B_PLUS_TREE_CPP + +#include "DS_MemoryPool.hpp" +#include "DS_Queue.hpp" +#include +#include "Export.hpp" + +// Java +// http://www.seanster.com/BplusTree/BplusTree.html + +// Overview +// http://babbage.clarku.edu/~achou/cs160/B+Trees/B+Trees.htm + +// Deletion +// http://dbpubs.stanford.edu:8090/pub/1995-19 + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +#include "RakMemoryOverride.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + /// Used in the BPlusTree. Used for both leaf and index nodes. + /// Don't use a constructor or destructor, due to the memory pool I am using + template + struct RAK_DLL_EXPORT Page + { + // We use the same data structure for both leaf and index nodes. + // It uses a little more memory for index nodes but reduces + // memory fragmentation, allocations, and deallocations. + bool isLeaf; + + // Used for both leaf and index nodes. + // For a leaf it means the number of elements in data + // For an index it means the number of keys and is one less than the number of children pointers. + int size; + + // Used for both leaf and index nodes. + KeyType keys[order]; + + // Used only for leaf nodes. Data is the actual data, while next is the pointer to the next leaf (for B+) + DataType data[order]; + Page *next; + Page *previous; + + // Used only for index nodes. Pointers to the children of this node. + Page *children[order+1]; + }; + + /// A BPlus tree + /// Written with efficiency and speed in mind. + template + class RAK_DLL_EXPORT BPlusTree + { + public: + struct ReturnAction + { + KeyType key1; + KeyType key2; + enum + { + NO_ACTION, + REPLACE_KEY1_WITH_KEY2, + PUSH_KEY_TO_PARENT, + SET_BRANCH_KEY, + } action; // 0=none, 1=replace key1 with key2 + }; + + BPlusTree(); + ~BPlusTree(); + void SetPoolPageSize(int size); // Set the page size for the memory pool. Optionsl + bool Get(const KeyType key, DataType &out) const; + bool Delete(const KeyType key); + bool Delete(const KeyType key, DataType &out); + bool Insert(const KeyType key, const DataType &data); + void Clear(void); + unsigned Size(void) const; + bool IsEmpty(void) const; + Page *GetListHead(void) const; + DataType GetDataHead(void) const; + void PrintLeaves(void); + void ForEachLeaf(void (*func)(Page * leaf, int index)); + void ForEachData(void (*func)(DataType input, int index)); + void PrintGraph(void); + protected: + void ValidateTreeRecursive(Page *cur); + void DeleteFromPageAtIndex(const int index, Page *cur); + static void PrintLeaf(Page * leaf, int index); + void FreePages(void); + bool GetIndexOf(const KeyType key, Page *page, int *out) const; + void ShiftKeysLeft(Page *cur); + bool CanRotateLeft(Page *cur, int childIndex); + bool CanRotateRight(Page *cur, int childIndex); + void RotateRight(Page *cur, int childIndex, ReturnAction *returnAction); + void RotateLeft(Page *cur, int childIndex, ReturnAction *returnAction); + Page* InsertIntoNode(const KeyType key, const DataType &childData, int insertionIndex, Page *nodeData, Page *cur, ReturnAction* returnAction); + Page* InsertBranchDown(const KeyType key, const DataType &data,Page *cur, ReturnAction* returnAction, bool *success); + Page* GetLeafFromKey(const KeyType key) const; + bool FindDeleteRebalance(const KeyType key, Page *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out); + bool FixUnderflow(int branchIndex, Page *cur, KeyType rightRootKey, ReturnAction *returnAction); + void ShiftNodeLeft(Page *cur); + void ShiftNodeRight(Page *cur); + + MemoryPool > pagePool; + Page *root, *leftmostLeaf; + }; + + template + BPlusTree::BPlusTree () + { + RakAssert(order>1); + root=0; + leftmostLeaf=0; + } + template + BPlusTree::~BPlusTree () + { + Clear(); + } + template + void BPlusTree::SetPoolPageSize(int size) + { + pagePool.SetPageSize(size); + } + template + bool BPlusTree::Get(const KeyType key, DataType &out) const + { + if (root==0) + return false; + + Page* leaf = GetLeafFromKey(key); + int childIndex; + + if (GetIndexOf(key, leaf, &childIndex)) + { + out=leaf->data[childIndex]; + return true; + } + return false; + } + template + void BPlusTree::DeleteFromPageAtIndex(const int index, Page *cur) + { + int i; + for (i=index; i < cur->size-1; i++) + cur->keys[i]=cur->keys[i+1]; + if (cur->isLeaf) + { + for (i=index; i < cur->size-1; i++) + cur->data[i]=cur->data[i+1]; + } + else + { + for (i=index; i < cur->size-1; i++) + cur->children[i+1]=cur->children[i+2]; + } + cur->size--; + } + template + bool BPlusTree::Delete(const KeyType key) + { + DataType temp; + return Delete(key, temp); + } + template + bool BPlusTree::Delete(const KeyType key, DataType &out) + { + if (root==0) + return false; + + ReturnAction returnAction; + returnAction.action=ReturnAction::NO_ACTION; + int childIndex; + bool underflow=false; + if (root==leftmostLeaf) + { + if (GetIndexOf(key, root, &childIndex)==false) + return false; + out=root->data[childIndex]; + DeleteFromPageAtIndex(childIndex,root); + if (root->size==0) + { + pagePool.Release(root, _FILE_AND_LINE_); + root=0; + leftmostLeaf=0; + } + return true; + } + else if (FindDeleteRebalance(key, root, &underflow,root->keys[0], &returnAction, out)==false) + return false; + +// RakAssert(returnAction.action==ReturnAction::NO_ACTION); + + if (underflow && root->size==0) + { + // Move the root down. + Page *oldRoot=root; + root=root->children[0]; + pagePool.Release(oldRoot, _FILE_AND_LINE_); + // memset(oldRoot,0,sizeof(root)); + } + + return true; + } + template + bool BPlusTree::FindDeleteRebalance(const KeyType key, Page *cur, bool *underflow, KeyType rightRootKey, ReturnAction *returnAction, DataType &out) + { + // Get index of child to follow. + int branchIndex, childIndex; + if (GetIndexOf(key, cur, &childIndex)) + branchIndex=childIndex+1; + else + branchIndex=childIndex; + + // If child is not a leaf, call recursively + if (cur->children[branchIndex]->isLeaf==false) + { + if (branchIndexsize) + rightRootKey=cur->keys[branchIndex]; // Shift right to left + else + rightRootKey=cur->keys[branchIndex-1]; // Shift center to left + + if (FindDeleteRebalance(key, cur->children[branchIndex], underflow, rightRootKey, returnAction, out)==false) + return false; + + // Call again in case the root key changed + if (branchIndexsize) + rightRootKey=cur->keys[branchIndex]; // Shift right to left + else + rightRootKey=cur->keys[branchIndex-1]; // Shift center to left + + if (returnAction->action==ReturnAction::SET_BRANCH_KEY && branchIndex!=childIndex) + { + returnAction->action=ReturnAction::NO_ACTION; + cur->keys[childIndex]=returnAction->key1; + + if (branchIndexsize) + rightRootKey=cur->keys[branchIndex]; // Shift right to left + else + rightRootKey=cur->keys[branchIndex-1]; // Shift center to left + } + } + else + { + // If child is a leaf, get the index of the key. If the item is not found, cancel delete. + if (GetIndexOf(key, cur->children[branchIndex], &childIndex)==false) + return false; + + // Delete: + // Remove childIndex from the child at branchIndex + out=cur->children[branchIndex]->data[childIndex]; + DeleteFromPageAtIndex(childIndex, cur->children[branchIndex]); + + if (childIndex==0) + { + if (branchIndex>0) + cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; + + if (branchIndex==0) + { + returnAction->action=ReturnAction::SET_BRANCH_KEY; + returnAction->key1=cur->children[0]->keys[0]; + } + } + + if (cur->children[branchIndex]->size < order/2) + *underflow=true; + else + *underflow=false; + } + + // Fix underflow: + if (*underflow) + { + *underflow=FixUnderflow(branchIndex, cur, rightRootKey, returnAction); + } + + return true; + } + template + bool BPlusTree::FixUnderflow(int branchIndex, Page *cur, KeyType rightRootKey, ReturnAction *returnAction) + { + // Borrow from a neighbor that has excess. + Page *source; + Page *dest; + + if (branchIndex>0 && cur->children[branchIndex-1]->size > order/2) + { + dest=cur->children[branchIndex]; + source=cur->children[branchIndex-1]; + + // Left has excess + ShiftNodeRight(dest); + if (dest->isLeaf) + { + dest->keys[0]=source->keys[source->size-1]; + dest->data[0]=source->data[source->size-1]; + } + else + { + dest->children[0]=source->children[source->size]; + dest->keys[0]=cur->keys[branchIndex-1]; + } + // Update the parent key for the child (middle) + cur->keys[branchIndex-1]=source->keys[source->size-1]; + source->size--; + + // if (branchIndex==0) + // { + // returnAction->action=ReturnAction::SET_BRANCH_KEY; + // returnAction->key1=dest->keys[0]; + // } + + // No underflow + return false; + } + else if (branchIndexsize && cur->children[branchIndex+1]->size > order/2) + { + dest=cur->children[branchIndex]; + source=cur->children[branchIndex+1]; + + // Right has excess + if (dest->isLeaf) + { + dest->keys[dest->size]=source->keys[0]; + dest->data[dest->size]=source->data[0]; + + // The first key in the leaf after shifting is the parent key for the right branch + cur->keys[branchIndex]=source->keys[1]; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + if (order<=3 && dest->size==0) + { + if (branchIndex==0) + { + returnAction->action=ReturnAction::SET_BRANCH_KEY; + returnAction->key1=dest->keys[0]; + } + else + cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; + } + } + else + { + if (returnAction->action==ReturnAction::NO_ACTION) + { + returnAction->action=ReturnAction::SET_BRANCH_KEY; + returnAction->key1=dest->keys[0]; + } + + dest->keys[dest->size]=rightRootKey; + dest->children[dest->size+1]=source->children[0]; + + // The shifted off key is the leftmost key for a node + cur->keys[branchIndex]=source->keys[0]; + } + + + dest->size++; + ShiftNodeLeft(source); + + //cur->keys[branchIndex]=source->keys[0]; + +// returnAction->action=ReturnAction::SET_BRANCH_KEY; +// returnAction->key1=dest->keys[dest->size-1]; + + // No underflow + return false; + } + else + { + int sourceIndex; + + // If no neighbors have excess, merge two branches. + // + // To merge two leaves, just copy the data and keys over. + // + // To merge two branches, copy the pointers and keys over, using rightRootKey as the key for the extra pointer + if (branchIndexsize) + { + // Merge right child to current child and delete right child. + dest=cur->children[branchIndex]; + source=cur->children[branchIndex+1]; + } + else + { + // Move current child to left and delete current child + dest=cur->children[branchIndex-1]; + source=cur->children[branchIndex]; + } + + // Merge + if (dest->isLeaf) + { + for (sourceIndex=0; sourceIndexsize; sourceIndex++) + { + dest->keys[dest->size]=source->keys[sourceIndex]; + dest->data[dest->size++]=source->data[sourceIndex]; + } + } + else + { + // We want the tree root key of the source, not the current. + dest->keys[dest->size]=rightRootKey; + dest->children[dest->size++ + 1]=source->children[0]; + for (sourceIndex=0; sourceIndexsize; sourceIndex++) + { + dest->keys[dest->size]=source->keys[sourceIndex]; + dest->children[dest->size++ + 1]=source->children[sourceIndex + 1]; + } + } + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + if (order<=3 && branchIndex>0 && cur->children[branchIndex]->isLeaf) // With order==2 it is possible to delete data[0], which is not possible with higher orders. + cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; + + if (branchIndexsize) + { + // Update the parent key, removing the source (right) + DeleteFromPageAtIndex(branchIndex, cur); + } + else + { + if (branchIndex>0) + { + // Update parent key, removing the source (current) + DeleteFromPageAtIndex(branchIndex-1, cur); + } + } + + if (branchIndex==0 && dest->isLeaf) + { + returnAction->action=ReturnAction::SET_BRANCH_KEY; + returnAction->key1=dest->keys[0]; + } + + if (source==leftmostLeaf) + leftmostLeaf=source->next; + + if (source->isLeaf) + { + if (source->previous) + source->previous->next=source->next; + if (source->next) + source->next->previous=source->previous; + } + + // Free the source node + pagePool.Release(source, _FILE_AND_LINE_); + // memset(source,0,sizeof(root)); + + // Return underflow or not of parent. + return cur->size < order/2; + } + } + template + void BPlusTree::ShiftNodeRight(Page *cur) + { + int i; + for (i=cur->size; i>0; i--) + cur->keys[i]=cur->keys[i-1]; + if (cur->isLeaf) + { + for (i=cur->size; i>0; i--) + cur->data[i]=cur->data[i-1]; + } + else + { + for (i=cur->size+1; i>0; i--) + cur->children[i]=cur->children[i-1]; + } + + cur->size++; + } + template + void BPlusTree::ShiftNodeLeft(Page *cur) + { + int i; + for (i=0; i < cur->size-1; i++) + cur->keys[i]=cur->keys[i+1]; + if (cur->isLeaf) + { + for (i=0; i < cur->size; i++) + cur->data[i]=cur->data[i+1]; + } + else + { + for (i=0; i < cur->size; i++) + cur->children[i]=cur->children[i+1]; + } + cur->size--; + } + template + Page* BPlusTree::InsertIntoNode(const KeyType key, const DataType &leafData, int insertionIndex, Page *nodeData, Page *cur, ReturnAction* returnAction) + { + int i; + if (cur->size < order) + { + for (i=cur->size; i > insertionIndex; i--) + cur->keys[i]=cur->keys[i-1]; + if (cur->isLeaf) + { + for (i=cur->size; i > insertionIndex; i--) + cur->data[i]=cur->data[i-1]; + } + else + { + for (i=cur->size+1; i > insertionIndex+1; i--) + cur->children[i]=cur->children[i-1]; + } + cur->keys[insertionIndex]=key; + if (cur->isLeaf) + cur->data[insertionIndex]=leafData; + else + cur->children[insertionIndex+1]=nodeData; + + cur->size++; + } + else + { + Page* newPage = pagePool.Allocate( _FILE_AND_LINE_ ); + newPage->isLeaf=cur->isLeaf; + if (cur->isLeaf) + { + newPage->next=cur->next; + if (cur->next) + cur->next->previous=newPage; + newPage->previous=cur; + cur->next=newPage; + } + + int destIndex, sourceIndex; + + if (insertionIndex>=(order+1)/2) + { + destIndex=0; + sourceIndex=order/2; + + for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) + { + newPage->keys[destIndex]=cur->keys[sourceIndex]; + } + newPage->keys[destIndex++]=key; + for (; sourceIndex < order; sourceIndex++, destIndex++) + { + newPage->keys[destIndex]=cur->keys[sourceIndex]; + } + + destIndex=0; + sourceIndex=order/2; + if (cur->isLeaf) + { + for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) + { + newPage->data[destIndex]=cur->data[sourceIndex]; + } + newPage->data[destIndex++]=leafData; + for (; sourceIndex < order; sourceIndex++, destIndex++) + { + newPage->data[destIndex]=cur->data[sourceIndex]; + } + } + else + { + + for (; sourceIndex < insertionIndex; sourceIndex++, destIndex++) + { + newPage->children[destIndex]=cur->children[sourceIndex+1]; + } + newPage->children[destIndex++]=nodeData; + + // sourceIndex+1 is sort of a hack but it works - because there is one extra child than keys + // skip past the last child for cur + for (; sourceIndex+1 < cur->size+1; sourceIndex++, destIndex++) + { + newPage->children[destIndex]=cur->children[sourceIndex+1]; + } + + // the first key is the middle key. Remove it from the page and push it to the parent + returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT; + returnAction->key1=newPage->keys[0]; + for (int j=0; j < destIndex-1; j++) + newPage->keys[j]=newPage->keys[j+1]; + + } + cur->size=order/2; + } + else + { + destIndex=0; + sourceIndex=(order+1)/2-1; + for (; sourceIndex < order; sourceIndex++, destIndex++) + newPage->keys[destIndex]=cur->keys[sourceIndex]; + destIndex=0; + if (cur->isLeaf) + { + sourceIndex=(order+1)/2-1; + for (; sourceIndex < order; sourceIndex++, destIndex++) + newPage->data[destIndex]=cur->data[sourceIndex]; + } + else + { + sourceIndex=(order+1)/2; + for (; sourceIndex < order+1; sourceIndex++, destIndex++) + newPage->children[destIndex]=cur->children[sourceIndex]; + + // the first key is the middle key. Remove it from the page and push it to the parent + returnAction->action=ReturnAction::PUSH_KEY_TO_PARENT; + returnAction->key1=newPage->keys[0]; + for (int j=0; j < destIndex-1; j++) + newPage->keys[j]=newPage->keys[j+1]; + } + cur->size=(order+1)/2-1; + if (cur->size) + { + bool b = GetIndexOf(key, cur, &insertionIndex); + (void) b; + RakAssert(b==false); + } + else + insertionIndex=0; + InsertIntoNode(key, leafData, insertionIndex, nodeData, cur, returnAction); + } + + newPage->size=destIndex; + + return newPage; + } + + return 0; + } + + template + bool BPlusTree::CanRotateLeft(Page *cur, int childIndex) + { + return childIndex>0 && cur->children[childIndex-1]->size + void BPlusTree::RotateLeft(Page *cur, int childIndex, ReturnAction *returnAction) + { + Page *dest = cur->children[childIndex-1]; + Page *source = cur->children[childIndex]; + returnAction->key1=source->keys[0]; + dest->keys[dest->size]=source->keys[0]; + dest->data[dest->size]=source->data[0]; + dest->size++; + for (int i=0; i < source->size-1; i++) + { + source->keys[i]=source->keys[i+1]; + source->data[i]=source->data[i+1]; + } + source->size--; + cur->keys[childIndex-1]=source->keys[0]; + returnAction->key2=source->keys[0]; + } + + template + bool BPlusTree::CanRotateRight(Page *cur, int childIndex) + { + return childIndex < cur->size && cur->children[childIndex+1]->size + void BPlusTree::RotateRight(Page *cur, int childIndex, ReturnAction *returnAction) + { + Page *dest = cur->children[childIndex+1]; + Page *source = cur->children[childIndex]; + returnAction->key1=dest->keys[0]; + for (int i= dest->size; i > 0; i--) + { + dest->keys[i]=dest->keys[i-1]; + dest->data[i]=dest->data[i-1]; + } + dest->keys[0]=source->keys[source->size-1]; + dest->data[0]=source->data[source->size-1]; + dest->size++; + source->size--; + + cur->keys[childIndex]=dest->keys[0]; + returnAction->key2=dest->keys[0]; + } + template + Page* BPlusTree::GetLeafFromKey(const KeyType key) const + { + Page* cur = root; + int childIndex; + while (cur->isLeaf==false) + { + // When searching, if we match the exact key we go down the pointer after that index + if (GetIndexOf(key, cur, &childIndex)) + childIndex++; + cur = cur->children[childIndex]; + } + return cur; + } + + template + Page* BPlusTree::InsertBranchDown(const KeyType key, const DataType &data,Page *cur, ReturnAction *returnAction, bool *success) + { + int childIndex; + int branchIndex; + if (GetIndexOf(key, cur, &childIndex)) + branchIndex=childIndex+1; + else + branchIndex=childIndex; + Page* newPage; + if (cur->isLeaf==false) + { + if (cur->children[branchIndex]->isLeaf==true && cur->children[branchIndex]->size==order) + { + if (branchIndex==childIndex+1) + { + *success=false; + return 0; // Already exists + } + + if (CanRotateLeft(cur, branchIndex)) + { + returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2; + if (key > cur->children[branchIndex]->keys[0]) + { + RotateLeft(cur, branchIndex, returnAction); + + int insertionIndex; + GetIndexOf(key, cur->children[branchIndex], &insertionIndex); + InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0); + } + else + { + // Move head element to left and replace it with key,data + Page* dest=cur->children[branchIndex-1]; + Page* source=cur->children[branchIndex]; + returnAction->key1=source->keys[0]; + returnAction->key2=key; + dest->keys[dest->size]=source->keys[0]; + dest->data[dest->size]=source->data[0]; + dest->size++; + source->keys[0]=key; + source->data[0]=data; + } + cur->keys[branchIndex-1]=cur->children[branchIndex]->keys[0]; + + return 0; + } + else if (CanRotateRight(cur, branchIndex)) + { + returnAction->action=ReturnAction::REPLACE_KEY1_WITH_KEY2; + + if (key < cur->children[branchIndex]->keys[cur->children[branchIndex]->size-1]) + { + RotateRight(cur, branchIndex, returnAction); + + int insertionIndex; + GetIndexOf(key, cur->children[branchIndex], &insertionIndex); + InsertIntoNode(key, data, insertionIndex, 0, cur->children[branchIndex], 0); + + } + else + { + // Insert to the head of the right leaf instead and change our key + returnAction->key1=cur->children[branchIndex+1]->keys[0]; + InsertIntoNode(key, data, 0, 0, cur->children[branchIndex+1], 0); + returnAction->key2=key; + } + cur->keys[branchIndex]=cur->children[branchIndex+1]->keys[0]; + return 0; + } + } + + newPage=InsertBranchDown(key,data,cur->children[branchIndex], returnAction, success); + if (returnAction->action==ReturnAction::REPLACE_KEY1_WITH_KEY2) + { + if (branchIndex>0 && cur->keys[branchIndex-1]==returnAction->key1) + cur->keys[branchIndex-1]=returnAction->key2; + } + if (newPage) + { + if (newPage->isLeaf==false) + { + RakAssert(returnAction->action==ReturnAction::PUSH_KEY_TO_PARENT); + newPage->size--; + return InsertIntoNode(returnAction->key1, data, branchIndex, newPage, cur, returnAction); + } + else + { + return InsertIntoNode(newPage->keys[0], data, branchIndex, newPage, cur, returnAction); + } + } + } + else + { + if (branchIndex==childIndex+1) + { + *success=false; + return 0; // Already exists + } + else + { + return InsertIntoNode(key, data, branchIndex, 0, cur, returnAction); + } + } + + return 0; + } + template + bool BPlusTree::Insert(const KeyType key, const DataType &data) + { + if (root==0) + { + // Allocate root and make root a leaf + root = pagePool.Allocate( _FILE_AND_LINE_ ); + root->isLeaf=true; + leftmostLeaf=root; + root->size=1; + root->keys[0]=key; + root->data[0]=data; + root->next=0; + root->previous=0; + } + else + { + bool success=true; + ReturnAction returnAction; + returnAction.action=ReturnAction::NO_ACTION; + Page* newPage = InsertBranchDown(key, data, root, &returnAction, &success); + if (success==false) + return false; + if (newPage) + { + KeyType newKey; + if (newPage->isLeaf==false) + { + // One key is pushed up through the stack. I store that at keys[0] but it has to be removed for the page to be correct + RakAssert(returnAction.action==ReturnAction::PUSH_KEY_TO_PARENT); + newKey=returnAction.key1; + newPage->size--; + } + else + newKey = newPage->keys[0]; + // propagate the root + Page* newRoot = pagePool.Allocate( _FILE_AND_LINE_ ); + newRoot->isLeaf=false; + newRoot->size=1; + newRoot->keys[0]=newKey; + newRoot->children[0]=root; + newRoot->children[1]=newPage; + root=newRoot; + } + } + + return true; + } + template + void BPlusTree::ShiftKeysLeft(Page *cur) + { + int i; + for (i=0; i < cur->size; i++) + cur->keys[i]=cur->keys[i+1]; + } + template + void BPlusTree::Clear(void) + { + if (root) + { + FreePages(); + leftmostLeaf=0; + root=0; + } + pagePool.Clear(_FILE_AND_LINE_); + } + template + unsigned BPlusTree::Size(void) const + { + unsigned int count=0; + DataStructures::Page *cur = GetListHead(); + while (cur) + { + count+=cur->size; + cur=cur->next; + } + return count; + } + template + bool BPlusTree::IsEmpty(void) const + { + return root==0; + } + template + bool BPlusTree::GetIndexOf(const KeyType key, Page *page, int *out) const + { + RakAssert(page->size>0); + int index, upperBound, lowerBound; + upperBound=page->size-1; + lowerBound=0; + index = page->size/2; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + if (key==page->keys[index]) + { + *out=index; + return true; + } + else if (keykeys[index]) + upperBound=index-1; + else + lowerBound=index+1; + + index=lowerBound+(upperBound-lowerBound)/2; + + if (lowerBound>upperBound) + { + *out=lowerBound; + return false; // No match + } + } + } + template + void BPlusTree::FreePages(void) + { + DataStructures::Queue *> queue; + DataStructures::Page *ptr; + int i; + queue.Push(root, _FILE_AND_LINE_ ); + while (queue.Size()) + { + ptr=queue.Pop(); + if (ptr->isLeaf==false) + { + for (i=0; i < ptr->size+1; i++) + queue.Push(ptr->children[i], _FILE_AND_LINE_ ); + } + pagePool.Release(ptr, _FILE_AND_LINE_); + // memset(ptr,0,sizeof(root)); + }; + } + template + Page *BPlusTree::GetListHead(void) const + { + return leftmostLeaf; + } + template + DataType BPlusTree::GetDataHead(void) const + { + return leftmostLeaf->data[0]; + } + template + void BPlusTree::ForEachLeaf(void (*func)(Page * leaf, int index)) + { + int count=0; + DataStructures::Page *cur = GetListHead(); + while (cur) + { + func(cur, count++); + cur=cur->next; + } + } + template + void BPlusTree::ForEachData(void (*func)(DataType input, int index)) + { + int count=0,i; + DataStructures::Page *cur = GetListHead(); + while (cur) + { + for (i=0; i < cur->size; i++) + func(cur->data[i], count++); + cur=cur->next; + } + } + template + void BPlusTree::PrintLeaf(Page * leaf, int index) + { + int i; + RAKNET_DEBUG_PRINTF("%i] SELF=%p\n", index+1, leaf); + for (i=0; i < leaf->size; i++) + RAKNET_DEBUG_PRINTF(" %i. %i\n", i+1, leaf->data[i]); + } + template + void BPlusTree::PrintLeaves(void) + { + ForEachLeaf(PrintLeaf); + } + + template + void BPlusTree::ValidateTreeRecursive(Page *cur) + { + RakAssert(cur==root || cur->size>=order/2); + + if (cur->children[0]->isLeaf) + { + RakAssert(cur->children[0]->keys[0] < cur->keys[0]); + for (int i=0; i < cur->size; i++) + { + RakAssert(cur->children[i+1]->keys[0]==cur->keys[i]); + } + } + else + { + for (int i=0; i < cur->size+1; i++) + ValidateTreeRecursive(cur->children[i]); + } + } + + template + void BPlusTree::PrintGraph(void) + { + DataStructures::Queue *> queue; + queue.Push(root,_FILE_AND_LINE_); + queue.Push(0,_FILE_AND_LINE_); + DataStructures::Page *ptr; + int i,j; + if (root) + { + RAKNET_DEBUG_PRINTF("%p(", root); + for (i=0; i < root->size; i++) + { + RAKNET_DEBUG_PRINTF("%i ", root->keys[i]); + } + RAKNET_DEBUG_PRINTF(") "); + RAKNET_DEBUG_PRINTF("\n"); + } + while (queue.Size()) + { + ptr=queue.Pop(); + if (ptr==0) + RAKNET_DEBUG_PRINTF("\n"); + else if (ptr->isLeaf==false) + { + for (i=0; i < ptr->size+1; i++) + { + RAKNET_DEBUG_PRINTF("%p(", ptr->children[i]); + //RAKNET_DEBUG_PRINTF("(", ptr->children[i]); + for (j=0; j < ptr->children[i]->size; j++) + RAKNET_DEBUG_PRINTF("%i ", ptr->children[i]->keys[j]); + RAKNET_DEBUG_PRINTF(") "); + queue.Push(ptr->children[i],_FILE_AND_LINE_); + } + queue.Push(0,_FILE_AND_LINE_); + RAKNET_DEBUG_PRINTF(" -- "); + } + } + RAKNET_DEBUG_PRINTF("\n"); + } +} +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif + +// Code to test this hellish data structure. +/* +#include "DS_BPlusTree.hpp" +#include + +// Handle underflow on root. If there is only one item left then I can go downwards. +// Make sure I keep the leftmost pointer valid by traversing it +// When I free a leaf, be sure to adjust the pointers around it. + +#include "Rand.hpp" + +void main(void) +{ + DataStructures::BPlusTree btree; + DataStructures::List haveList, removedList; + int temp; + int i, j, index; + int testSize; + bool b; + + for (testSize=0; testSize < 514; testSize++) + { + RAKNET_DEBUG_PRINTF("TestSize=%i\n", testSize); + + for (i=0; i < testSize; i++) + haveList.Insert(i); + + for (i=0; i < testSize; i++) + { + index=i+randomMT()%(testSize-i); + temp=haveList[index]; + haveList[index]=haveList[i]; + haveList[i]=temp; + } + + for (i=0; i + * + * OR + * + * AVLBalancedBinarySearchTree + * + * Use the AVL balanced tree if you want the tree to be balanced after every deletion and addition. This avoids the potential + * worst case scenario where ordered input to a binary search tree gives linear search time results. It's not needed + * if input will be evenly distributed, in which case the search time is O (log n). The search time for the AVL + * balanced binary tree is O (log n) irregardless of input. + * + * Has the following member functions + * unsigned int Height() - Returns the height of the tree at the optional specified starting index. Default is the root + * add(element) - adds an element to the BinarySearchTree + * bool del(element) - deletes the node containing element if the element is in the tree as defined by a comparison with the == operator. Returns true on success, false if the element is not found + * bool IsInelement) - returns true if element is in the tree as defined by a comparison with the == operator. Otherwise returns false + * DisplayInorder(array) - Fills an array with an inorder search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. + * DisplayPreorder(array) - Fills an array with an preorder search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. + * DisplayPostorder(array) - Fills an array with an postorder search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. + * DisplayBreadthFirstSearch(array) - Fills an array with a breadth first search of the elements in the tree. USER IS REPONSIBLE FOR ALLOCATING THE ARRAY!. + * clear - Destroys the tree. Same as calling the destructor + * unsigned int Height() - Returns the height of the tree + * unsigned int size() - returns the size of the BinarySearchTree + * GetPointerToNode(element) - returns a pointer to the comparision element in the tree, allowing for direct modification when necessary with complex data types. + * Be warned, it is possible to corrupt the tree if the element used for comparisons is modified. Returns NULL if the item is not found + * + * + * EXAMPLE + * @code + * BinarySearchTree A; + * A.Add(10); + * A.Add(15); + * A.Add(5); + * int* array = RakNet::OP_NEW(A.Size(), _FILE_AND_LINE_ ); + * A.DisplayInorder(array); + * array[0]; // returns 5 + * array[1]; // returns 10 + * array[2]; // returns 15 + * @endcode + * compress - reallocates memory to fit the number of elements. Best used when the number of elements decreases + * + * clear - empties the BinarySearchTree and returns storage + * The assignment and copy constructors are defined + * + * \note The template type must have the copy constructor and + * assignment operator defined and must work with >, <, and == All + * elements in the tree MUST be distinct The assignment operator is + * defined between BinarySearchTree and AVLBalancedBinarySearchTree + * as long as they are of the same template type. However, passing a + * BinarySearchTree to an AVLBalancedBinarySearchTree will lose its + * structure unless it happened to be AVL balanced to begin with + * Requires queue_linked_list.cpp for the breadth first search used + * in the copy constructor, overloaded assignment operator, and + * display_breadth_first_search. + * + * + */ + template + class RAK_DLL_EXPORT BinarySearchTree + { + + public: + + struct node + { + BinarySearchTreeType* item; + node* left; + node* right; + }; + + BinarySearchTree(); + virtual ~BinarySearchTree(); + BinarySearchTree( const BinarySearchTree& original_type ); + BinarySearchTree& operator= ( const BinarySearchTree& original_copy ); + unsigned int Size( void ); + void Clear( const char *file, unsigned int line ); + unsigned int Height( node* starting_node = 0 ); + node* Add ( const BinarySearchTreeType& input, const char *file, unsigned int line ); + node* Del( const BinarySearchTreeType& input, const char *file, unsigned int line ); + bool IsIn( const BinarySearchTreeType& input ); + void DisplayInorder( BinarySearchTreeType* return_array ); + void DisplayPreorder( BinarySearchTreeType* return_array ); + void DisplayPostorder( BinarySearchTreeType* return_array ); + void DisplayBreadthFirstSearch( BinarySearchTreeType* return_array ); + BinarySearchTreeType*& GetPointerToNode( const BinarySearchTreeType& element ); + + protected: + + node* root; + + enum Direction_Types + { + NOT_FOUND, LEFT, RIGHT, ROOT + } direction; + unsigned int HeightRecursive( node* current ); + unsigned int BinarySearchTree_size; + node*& Find( const BinarySearchTreeType& element, node** parent ); + node*& FindParent( const BinarySearchTreeType& element ); + void DisplayPostorderRecursive( node* current, BinarySearchTreeType* return_array, unsigned int& index ); + void FixTree( node* current ); + + }; + + /// An AVLBalancedBinarySearchTree is a binary tree that is always balanced + template + class RAK_DLL_EXPORT AVLBalancedBinarySearchTree : public BinarySearchTree + { + + public: + AVLBalancedBinarySearchTree() {} + virtual ~AVLBalancedBinarySearchTree(); + void Add ( const BinarySearchTreeType& input ); + void Del( const BinarySearchTreeType& input ); + BinarySearchTree& operator= ( BinarySearchTree& original_copy ) + { + return BinarySearchTree::operator= ( original_copy ); + } + + private: + void BalanceTree( typename BinarySearchTree::node* current, bool rotateOnce ); + void RotateRight( typename BinarySearchTree::node *C ); + void RotateLeft( typename BinarySearchTree::node* C ); + void DoubleRotateRight( typename BinarySearchTree::node *A ); + void DoubleRotateLeft( typename BinarySearchTree::node* A ); + bool RightHigher( typename BinarySearchTree::node* A ); + bool LeftHigher( typename BinarySearchTree::node* A ); + }; + + template + void AVLBalancedBinarySearchTree::BalanceTree( typename BinarySearchTree::node* current, bool rotateOnce ) + { + int left_height, right_height; + + while ( current ) + { + if ( current->left == 0 ) + left_height = 0; + else + left_height = Height( current->left ); + + if ( current->right == 0 ) + right_height = 0; + else + right_height = Height( current->right ); + + if ( right_height - left_height == 2 ) + { + if ( RightHigher( current->right ) ) + RotateLeft( current->right ); + else + DoubleRotateLeft( current ); + + if ( rotateOnce ) + break; + } + + else + if ( right_height - left_height == -2 ) + { + if ( LeftHigher( current->left ) ) + RotateRight( current->left ); + else + DoubleRotateRight( current ); + + if ( rotateOnce ) + break; + } + + if ( current == this->root ) + break; + + current = FindParent( *( current->item ) ); + + } + } + + template + void AVLBalancedBinarySearchTree::Add ( const BinarySearchTreeType& input ) + { + + typename BinarySearchTree::node * current = BinarySearchTree::Add ( input, _FILE_AND_LINE_ ); + BalanceTree( current, true ); + } + + template + void AVLBalancedBinarySearchTree::Del( const BinarySearchTreeType& input ) + { + typename BinarySearchTree::node * current = BinarySearchTree::Del( input, _FILE_AND_LINE_ ); + BalanceTree( current, false ); + + } + + template + bool AVLBalancedBinarySearchTree::RightHigher( typename BinarySearchTree::node *A ) + { + if ( A == 0 ) + return false; + + return Height( A->right ) > Height( A->left ); + } + + template + bool AVLBalancedBinarySearchTree::LeftHigher( typename BinarySearchTree::node *A ) + { + if ( A == 0 ) + return false; + + return Height( A->left ) > Height( A->right ); + } + + template + void AVLBalancedBinarySearchTree::RotateRight( typename BinarySearchTree::node *C ) + { + typename BinarySearchTree::node * A, *B, *D; + /* + RIGHT ROTATION + + A = parent(b) + b= parent(c) + c = node to rotate around + + A + | // Either direction + B + / \ + C + / \ + D + + TO + + A + | // Either Direction + C + / \ + B + / \ + D + + + + + */ + + B = FindParent( *( C->item ) ); + A = FindParent( *( B->item ) ); + D = C->right; + + if ( A ) + { + // Direction was set by the last find_parent call + + if ( this->direction == this->LEFT ) + A->left = C; + else + A->right = C; + } + + else + this->root = C; // If B has no parent parent then B must have been the root node + + B->left = D; + + C->right = B; + } + + template + void AVLBalancedBinarySearchTree::DoubleRotateRight( typename BinarySearchTree::node *A ) + { + // The left side of the left child must be higher for the tree to balance with a right rotation. If it isn't, rotate it left before the normal rotation so it is. + RotateLeft( A->left->right ); + RotateRight( A->left ); + } + + template + void AVLBalancedBinarySearchTree::RotateLeft( typename BinarySearchTree::node *C ) + { + typename BinarySearchTree::node * A, *B, *D; + /* + RIGHT ROTATION + + A = parent(b) + b= parent(c) + c = node to rotate around + + A + | // Either direction + B + / \ + C + / \ + D + + TO + + A + | // Either Direction + C + / \ + B + / \ + D + + + + + */ + + B = FindParent( *( C->item ) ); + A = FindParent( *( B->item ) ); + D = C->left; + + if ( A ) + { + // Direction was set by the last find_parent call + + if ( this->direction == this->LEFT ) + A->left = C; + else + A->right = C; + } + + else + this->root = C; // If B has no parent parent then B must have been the root node + + B->right = D; + + C->left = B; + } + + template + void AVLBalancedBinarySearchTree::DoubleRotateLeft( typename BinarySearchTree::node *A ) + { + // The left side of the right child must be higher for the tree to balance with a left rotation. If it isn't, rotate it right before the normal rotation so it is. + RotateRight( A->right->left ); + RotateLeft( A->right ); + } + + template + AVLBalancedBinarySearchTree::~AVLBalancedBinarySearchTree() + { + this->Clear(_FILE_AND_LINE_); + } + + template + unsigned int BinarySearchTree::Size( void ) + { + return BinarySearchTree_size; + } + + template + unsigned int BinarySearchTree::Height( typename BinarySearchTree::node* starting_node ) + { + if ( BinarySearchTree_size == 0 || starting_node == 0 ) + return 0; + else + return HeightRecursive( starting_node ); + } + + // Recursively return the height of a binary tree + template + unsigned int BinarySearchTree::HeightRecursive( typename BinarySearchTree::node* current ) + { + unsigned int left_height = 0, right_height = 0; + + if ( ( current->left == 0 ) && ( current->right == 0 ) ) + return 1; // Leaf + + if ( current->left != 0 ) + left_height = 1 + HeightRecursive( current->left ); + + if ( current->right != 0 ) + right_height = 1 + HeightRecursive( current->right ); + + if ( left_height > right_height ) + return left_height; + else + return right_height; + } + + template + BinarySearchTree::BinarySearchTree() + { + BinarySearchTree_size = 0; + root = 0; + } + + template + BinarySearchTree::~BinarySearchTree() + { + this->Clear(_FILE_AND_LINE_); + } + + template + BinarySearchTreeType*& BinarySearchTree::GetPointerToNode( const BinarySearchTreeType& element ) + { + static typename BinarySearchTree::node * tempnode; + static BinarySearchTreeType* dummyptr = 0; + tempnode = Find ( element, &tempnode ); + + if ( this->direction == this->NOT_FOUND ) + return dummyptr; + + return tempnode->item; + } + + template + typename BinarySearchTree::node*& BinarySearchTree::Find( const BinarySearchTreeType& element, typename BinarySearchTree::node** parent ) + { + static typename BinarySearchTree::node * current; + + current = this->root; + *parent = 0; + this->direction = this->ROOT; + + if ( BinarySearchTree_size == 0 ) + { + this->direction = this->NOT_FOUND; + return current = 0; + } + + // Check if the item is at the root + if ( element == *( current->item ) ) + { + this->direction = this->ROOT; + return current; + } + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while ( true ) + { + // Move pointer + + if ( element < *( current->item ) ) + { + *parent = current; + this->direction = this->LEFT; + current = current->left; + } + + else + if ( element > *( current->item ) ) + { + *parent = current; + this->direction = this->RIGHT; + current = current->right; + } + + if ( current == 0 ) + break; + + // Check if new position holds the item + if ( element == *( current->item ) ) + { + return current; + } + } + + + this->direction = this->NOT_FOUND; + return current = 0; + } + + template + typename BinarySearchTree::node*& BinarySearchTree::FindParent( const BinarySearchTreeType& element ) + { + static typename BinarySearchTree::node * parent; + Find ( element, &parent ); + return parent; + } + + // Performs a series of value swaps starting with current to fix the tree if needed + template + void BinarySearchTree::FixTree( typename BinarySearchTree::node* current ) + { + BinarySearchTreeType temp; + + while ( 1 ) + { + if ( ( ( current->left ) != 0 ) && ( *( current->item ) < *( current->left->item ) ) ) + { + // Swap the current value with the one to the left + temp = *( current->left->item ); + *( current->left->item ) = *( current->item ); + *( current->item ) = temp; + current = current->left; + } + + else + if ( ( ( current->right ) != 0 ) && ( *( current->item ) > *( current->right->item ) ) ) + { + // Swap the current value with the one to the right + temp = *( current->right->item ); + *( current->right->item ) = *( current->item ); + *( current->item ) = temp; + current = current->right; + } + + else + break; // current points to the right place so quit + } + } + + template + typename BinarySearchTree::node* BinarySearchTree::Del( const BinarySearchTreeType& input, const char *file, unsigned int line ) + { + typename BinarySearchTree::node * node_to_delete, *current, *parent; + + if ( BinarySearchTree_size == 0 ) + return 0; + + if ( BinarySearchTree_size == 1 ) + { + Clear(file, line); + return 0; + } + + node_to_delete = Find( input, &parent ); + + if ( direction == NOT_FOUND ) + return 0; // Couldn't find the element + + current = node_to_delete; + + // Replace the deleted node with the appropriate value + if ( ( current->right ) == 0 && ( current->left ) == 0 ) // Leaf node, just remove it + { + + if ( parent ) + { + if ( direction == LEFT ) + parent->left = 0; + else + parent->right = 0; + } + + RakNet::OP_DELETE(node_to_delete->item, file, line); + RakNet::OP_DELETE(node_to_delete, file, line); + BinarySearchTree_size--; + return parent; + } + else + if ( ( current->right ) != 0 && ( current->left ) == 0 ) // Node has only one child, delete it and cause the parent to point to that child + { + + if ( parent ) + { + if ( direction == RIGHT ) + parent->right = current->right; + else + parent->left = current->right; + } + + else + root = current->right; // Without a parent this must be the root node + + RakNet::OP_DELETE(node_to_delete->item, file, line); + + RakNet::OP_DELETE(node_to_delete, file, line); + + BinarySearchTree_size--; + + return parent; + } + else + if ( ( current->right ) == 0 && ( current->left ) != 0 ) // Node has only one child, delete it and cause the parent to point to that child + { + + if ( parent ) + { + if ( direction == RIGHT ) + parent->right = current->left; + else + parent->left = current->left; + } + + else + root = current->left; // Without a parent this must be the root node + + RakNet::OP_DELETE(node_to_delete->item, file, line); + + RakNet::OP_DELETE(node_to_delete, file, line); + + BinarySearchTree_size--; + + return parent; + } + else // Go right, then as left as far as you can + { + parent = current; + direction = RIGHT; + current = current->right; // Must have a right branch because the if statements above indicated that it has 2 branches + + while ( current->left ) + { + direction = LEFT; + parent = current; + current = current->left; + } + + // Replace the value held by the node to RakNet::OP_DELETE(with the value pointed to by current, _FILE_AND_LINE_); + *( node_to_delete->item ) = *( current->item ); + + // Delete current. + // If it is a leaf node just delete it + if ( current->right == 0 ) + { + if ( direction == RIGHT ) + parent->right = 0; + else + parent->left = 0; + + RakNet::OP_DELETE(current->item, file, line); + + RakNet::OP_DELETE(current, file, line); + + BinarySearchTree_size--; + + return parent; + } + + else + { + // Skip this node and make its parent point to its right branch + + if ( direction == RIGHT ) + parent->right = current->right; + else + parent->left = current->right; + + RakNet::OP_DELETE(current->item, file, line); + + RakNet::OP_DELETE(current, file, line); + + BinarySearchTree_size--; + + return parent; + } + } + } + + template + typename BinarySearchTree::node* BinarySearchTree::Add ( const BinarySearchTreeType& input, const char *file, unsigned int line ) + { + typename BinarySearchTree::node * current; + + // Add the new element to the tree according to the following alogrithm: + // 1. If the current node is empty add the new leaf + // 2. If the element is less than the current node then go down the left branch + // 3. If the element is greater than the current node then go down the right branch + + if ( BinarySearchTree_size == 0 ) + { + BinarySearchTree_size = 1; + root = RakNet::OP_NEW( file, line ); + root->item = RakNet::OP_NEW( file, line ); + *( root->item ) = input; + root->left = 0; + root->right = 0; + + return root; + } + + else + { + // start at the root + current = root; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while ( true ) // This loop traverses the tree to find a spot for insertion + { + + if ( input < *( current->item ) ) + { + if ( current->left == 0 ) + { + current->left = RakNet::OP_NEW( file, line ); + current->left->item = RakNet::OP_NEW( file, line ); + current = current->left; + current->left = 0; + current->right = 0; + *( current->item ) = input; + + BinarySearchTree_size++; + return current; + } + + else + { + current = current->left; + } + } + + else + if ( input > *( current->item ) ) + { + if ( current->right == 0 ) + { + current->right = RakNet::OP_NEW( file, line ); + current->right->item = RakNet::OP_NEW( file, line ); + current = current->right; + current->left = 0; + current->right = 0; + *( current->item ) = input; + + BinarySearchTree_size++; + return current; + } + + else + { + current = current->right; + } + } + + else + return 0; // ((input == current->item) == true) which is not allowed since the tree only takes discrete values. Do nothing + } + } + } + + template + bool BinarySearchTree::IsIn( const BinarySearchTreeType& input ) + { + typename BinarySearchTree::node * parent; + find( input, &parent ); + + if ( direction != NOT_FOUND ) + return true; + else + return false; + } + + + template + void BinarySearchTree::DisplayInorder( BinarySearchTreeType* return_array ) + { + typename BinarySearchTree::node * current, *parent; + bool just_printed = false; + + unsigned int index = 0; + + current = root; + + if ( BinarySearchTree_size == 0 ) + return ; // Do nothing for an empty tree + + else + if ( BinarySearchTree_size == 1 ) + { + return_array[ 0 ] = *( root->item ); + return ; + } + + + direction = ROOT; // Reset the direction + + while ( index != BinarySearchTree_size ) + { + // direction is set by the find function and holds the direction of the parent to the last node visited. It is used to prevent revisiting nodes + + if ( ( current->left != 0 ) && ( direction != LEFT ) && ( direction != RIGHT ) ) + { + // Go left if the following 2 conditions are true + // I can go left + // I did not just move up from a right child + // I did not just move up from a left child + + current = current->left; + direction = ROOT; // Reset the direction + } + + else + if ( ( direction != RIGHT ) && ( just_printed == false ) ) + { + // Otherwise, print the current node if the following 3 conditions are true: + // I did not just move up from a right child + // I did not print this ndoe last cycle + + return_array[ index++ ] = *( current->item ); + just_printed = true; + } + + else + if ( ( current->right != 0 ) && ( direction != RIGHT ) ) + { + // Otherwise, go right if the following 2 conditions are true + // I did not just move up from a right child + // I can go right + + current = current->right; + direction = ROOT; // Reset the direction + just_printed = false; + } + + else + { + // Otherwise I've done everything I can. Move up the tree one node + parent = FindParent( *( current->item ) ); + current = parent; + just_printed = false; + } + } + } + + template + void BinarySearchTree::DisplayPreorder( BinarySearchTreeType* return_array ) + { + typename BinarySearchTree::node * current, *parent; + + unsigned int index = 0; + + current = root; + + if ( BinarySearchTree_size == 0 ) + return ; // Do nothing for an empty tree + + else + if ( BinarySearchTree_size == 1 ) + { + return_array[ 0 ] = *( root->item ); + return ; + } + + + direction = ROOT; // Reset the direction + return_array[ index++ ] = *( current->item ); + + while ( index != BinarySearchTree_size ) + { + // direction is set by the find function and holds the direction of the parent to the last node visited. It is used to prevent revisiting nodes + + if ( ( current->left != 0 ) && ( direction != LEFT ) && ( direction != RIGHT ) ) + { + + current = current->left; + direction = ROOT; + + // Everytime you move a node print it + return_array[ index++ ] = *( current->item ); + } + + else + if ( ( current->right != 0 ) && ( direction != RIGHT ) ) + { + current = current->right; + direction = ROOT; + + // Everytime you move a node print it + return_array[ index++ ] = *( current->item ); + } + + else + { + // Otherwise I've done everything I can. Move up the tree one node + parent = FindParent( *( current->item ) ); + current = parent; + } + } + } + + template + inline void BinarySearchTree::DisplayPostorder( BinarySearchTreeType* return_array ) + { + unsigned int index = 0; + + if ( BinarySearchTree_size == 0 ) + return ; // Do nothing for an empty tree + + else + if ( BinarySearchTree_size == 1 ) + { + return_array[ 0 ] = *( root->item ); + return ; + } + + DisplayPostorderRecursive( root, return_array, index ); + } + + + // Recursively do a postorder traversal + template + void BinarySearchTree::DisplayPostorderRecursive( typename BinarySearchTree::node* current, BinarySearchTreeType* return_array, unsigned int& index ) + { + if ( current->left != 0 ) + DisplayPostorderRecursive( current->left, return_array, index ); + + if ( current->right != 0 ) + DisplayPostorderRecursive( current->right, return_array, index ); + + return_array[ index++ ] = *( current->item ); + + } + + + template + void BinarySearchTree::DisplayBreadthFirstSearch( BinarySearchTreeType* return_array ) + { + typename BinarySearchTree::node * current; + unsigned int index = 0; + + // Display the tree using a breadth first search + // Put the children of the current node into the queue + // Pop the queue, put its children into the queue, repeat until queue is empty + + if ( BinarySearchTree_size == 0 ) + return ; // Do nothing for an empty tree + + else + if ( BinarySearchTree_size == 1 ) + { + return_array[ 0 ] = *( root->item ); + return ; + } + + else + { + DataStructures::QueueLinkedList tree_queue; + + // Add the root of the tree I am copying from + tree_queue.Push( root ); + + do + { + current = tree_queue.Pop(); + return_array[ index++ ] = *( current->item ); + + // Add the child or children of the tree I am copying from to the queue + + if ( current->left != 0 ) + tree_queue.Push( current->left ); + + if ( current->right != 0 ) + tree_queue.Push( current->right ); + + } + + while ( tree_queue.Size() > 0 ); + } + } + + + template + BinarySearchTree::BinarySearchTree( const BinarySearchTree& original_copy ) + { + typename BinarySearchTree::node * current; + // Copy the tree using a breadth first search + // Put the children of the current node into the queue + // Pop the queue, put its children into the queue, repeat until queue is empty + + // This is a copy of the constructor. A bug in Visual C++ made it so if I just put the constructor call here the variable assignments were ignored. + BinarySearchTree_size = 0; + root = 0; + + if ( original_copy.BinarySearchTree_size == 0 ) + { + BinarySearchTree_size = 0; + } + + else + { + DataStructures::QueueLinkedList tree_queue; + + // Add the root of the tree I am copying from + tree_queue.Push( original_copy.root ); + + do + { + current = tree_queue.Pop(); + + Add ( *( current->item ), _FILE_AND_LINE_ ) + + ; + + // Add the child or children of the tree I am copying from to the queue + if ( current->left != 0 ) + tree_queue.Push( current->left ); + + if ( current->right != 0 ) + tree_queue.Push( current->right ); + + } + + while ( tree_queue.Size() > 0 ); + } + } + + template + BinarySearchTree& BinarySearchTree::operator= ( const BinarySearchTree& original_copy ) + { + typename BinarySearchTree::node * current; + + if ( ( &original_copy ) == this ) + return *this; + + Clear( _FILE_AND_LINE_ ); // Remove the current tree + + // This is a copy of the constructor. A bug in Visual C++ made it so if I just put the constructor call here the variable assignments were ignored. + BinarySearchTree_size = 0; + + root = 0; + + + // Copy the tree using a breadth first search + // Put the children of the current node into the queue + // Pop the queue, put its children into the queue, repeat until queue is empty + if ( original_copy.BinarySearchTree_size == 0 ) + { + BinarySearchTree_size = 0; + } + + else + { + DataStructures::QueueLinkedList tree_queue; + + // Add the root of the tree I am copying from + tree_queue.Push( original_copy.root ); + + do + { + current = tree_queue.Pop(); + + Add ( *( current->item ), _FILE_AND_LINE_ ) + + ; + + // Add the child or children of the tree I am copying from to the queue + if ( current->left != 0 ) + tree_queue.Push( current->left ); + + if ( current->right != 0 ) + tree_queue.Push( current->right ); + + } + + while ( tree_queue.Size() > 0 ); + } + + return *this; + } + + template + inline void BinarySearchTree::Clear ( const char *file, unsigned int line ) + { + typename BinarySearchTree::node * current, *parent; + + current = root; + + while ( BinarySearchTree_size > 0 ) + { + if ( BinarySearchTree_size == 1 ) + { + RakNet::OP_DELETE(root->item, file, line); + RakNet::OP_DELETE(root, file, line); + root = 0; + BinarySearchTree_size = 0; + } + + else + { + if ( current->left != 0 ) + { + current = current->left; + } + + else + if ( current->right != 0 ) + { + current = current->right; + } + + else // leaf + { + // Not root node so must have a parent + parent = FindParent( *( current->item ) ); + + if ( ( parent->left ) == current ) + parent->left = 0; + else + parent->right = 0; + + RakNet::OP_DELETE(current->item, file, line); + + RakNet::OP_DELETE(current, file, line); + + current = parent; + + BinarySearchTree_size--; + } + } + } + } + +} // End namespace + +#endif + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif diff --git a/include/raknet/DS_BytePool.hpp b/include/raknet/DS_BytePool.hpp new file mode 100644 index 0000000..499dd3e --- /dev/null +++ b/include/raknet/DS_BytePool.hpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_BytePool.h +/// + + +#ifndef __BYTE_POOL_H +#define __BYTE_POOL_H + +#include "RakMemoryOverride.hpp" +#include "DS_MemoryPool.hpp" +#include "Export.hpp" +#include "SimpleMutex.hpp" +#include "RakAssert.hpp" + +// #define _DISABLE_BYTE_POOL +// #define _THREADSAFE_BYTE_POOL + +namespace DataStructures +{ + // Allocate some number of bytes from pools. Uses the heap if necessary. + class RAK_DLL_EXPORT BytePool + { + public: + BytePool(); + ~BytePool(); + // Should be at least 8 times bigger than 8192 + void SetPageSize(int size); + unsigned char* Allocate(int bytesWanted, const char *file, unsigned int line); + void Release(unsigned char *data, const char *file, unsigned int line); + void Clear(const char *file, unsigned int line); + protected: + MemoryPool pool128; + MemoryPool pool512; + MemoryPool pool2048; + MemoryPool pool8192; +#ifdef _THREADSAFE_BYTE_POOL + SimpleMutex mutex128; + SimpleMutex mutex512; + SimpleMutex mutex2048; + SimpleMutex mutex8192; +#endif + }; +} + +#endif diff --git a/include/raknet/DS_ByteQueue.hpp b/include/raknet/DS_ByteQueue.hpp new file mode 100644 index 0000000..54488e6 --- /dev/null +++ b/include/raknet/DS_ByteQueue.hpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_ByteQueue.h +/// \internal +/// \brief Byte queue +/// + + +#ifndef __BYTE_QUEUE_H +#define __BYTE_QUEUE_H + +#include "RakMemoryOverride.hpp" +#include "Export.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + class ByteQueue + { + public: + ByteQueue(); + ~ByteQueue(); + void WriteBytes(const char *in, unsigned length, const char *file, unsigned int line); + bool ReadBytes(char *out, unsigned maxLengthToRead, bool peek); + unsigned GetBytesWritten(void) const; + char* PeekContiguousBytes(unsigned int *outLength) const; + void IncrementReadOffset(unsigned length); + void DecrementReadOffset(unsigned length); + void Clear(const char *file, unsigned int line); + void Print(void); + + protected: + char *data; + unsigned readOffset, writeOffset, lengthAllocated; + }; +} + +#endif diff --git a/include/raknet/DS_Hash.hpp b/include/raknet/DS_Hash.hpp new file mode 100644 index 0000000..06a5112 --- /dev/null +++ b/include/raknet/DS_Hash.hpp @@ -0,0 +1,357 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \internal +/// \brief Hashing container +/// + + +#ifndef __HASH_H +#define __HASH_H + +#include "RakAssert.hpp" +#include // memmove +#include "Export.hpp" +#include "RakMemoryOverride.hpp" +#include "RakString.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + struct HashIndex + { + unsigned int primaryIndex; + unsigned int secondaryIndex; + bool IsInvalid(void) const {return primaryIndex==(unsigned int) -1;} + void SetInvalid(void) {primaryIndex=(unsigned int) -1; secondaryIndex=(unsigned int) -1;} + }; + + /// \brief Using a string as a identifier for a node, store an allocated pointer to that node + template + class RAK_DLL_EXPORT Hash + { + public: + /// Default constructor + Hash(); + + // Destructor + ~Hash(); + + void Push(key_type key, const data_type &input, const char *file, unsigned int line ); + data_type* Peek(key_type key ); + bool Pop(data_type& out, key_type key, const char *file, unsigned int line ); + bool RemoveAtIndex(HashIndex index, const char *file, unsigned int line ); + bool Remove(key_type key, const char *file, unsigned int line ); + HashIndex GetIndexOf(key_type key); + bool HasData(key_type key); + data_type& ItemAtIndex(const HashIndex &index); + key_type KeyAtIndex(const HashIndex &index); + void GetAsList(DataStructures::List &itemList,DataStructures::List &keyList,const char *file, unsigned int line) const; + unsigned int Size(void) const; + + /// \brief Clear the list + void Clear( const char *file, unsigned int line ); + + struct Node + { + Node(key_type strIn, const data_type &_data) {string=strIn; data=_data;} + key_type string; + data_type data; + // Next in the list for this key + Node *next; + }; + + protected: + void ClearIndex(unsigned int index,const char *file, unsigned int line); + Node **nodeList; + unsigned int size; + }; + + template + Hash::Hash() + { + nodeList=0; + size=0; + } + + template + Hash::~Hash() + { + Clear(_FILE_AND_LINE_); + } + + template + void Hash::Push(key_type key, const data_type &input, const char *file, unsigned int line ) + { + unsigned long hashIndex = (*hashFunction)(key) % HASH_SIZE; + if (nodeList==0) + { + nodeList=RakNet::OP_NEW_ARRAY(HASH_SIZE,file,line); + memset(nodeList,0,sizeof(Node *)*HASH_SIZE); + } + + Node *newNode=RakNet::OP_NEW_2(file,line,key,input); + newNode->next=nodeList[hashIndex]; + nodeList[hashIndex]=newNode; + + size++; + } + + template + data_type* Hash::Peek(key_type key ) + { + if (nodeList==0) + return 0; + + unsigned long hashIndex = (*hashFunction)(key) % HASH_SIZE; + Node *node = nodeList[hashIndex]; + while (node!=0) + { + if (node->string==key) + return &node->data; + node=node->next; + } + return 0; + } + + template + bool Hash::Pop(data_type& out, key_type key, const char *file, unsigned int line ) + { + if (nodeList==0) + return false; + + unsigned long hashIndex = (*hashFunction)(key) % HASH_SIZE; + Node *node = nodeList[hashIndex]; + if (node==0) + return false; + if (node->next==0) + { + // Only one item. + if (node->string==key) + { + // Delete last item + out=node->data; + ClearIndex(hashIndex,_FILE_AND_LINE_); + return true; + } + else + { + // Single item doesn't match + return false; + } + } + else if (node->string==key) + { + // First item does match, but more than one item + out=node->data; + nodeList[hashIndex]=node->next; + RakNet::OP_DELETE(node,file,line); + size--; + return true; + } + + Node *last=node; + node=node->next; + + while (node!=0) + { + // First item does not match, but subsequent item might + if (node->string==key) + { + out=node->data; + // Skip over subsequent item + last->next=node->next; + // Delete existing item + RakNet::OP_DELETE(node,file,line); + size--; + return true; + } + last=node; + node=node->next; + } + return false; + } + + template + bool Hash::RemoveAtIndex(HashIndex index, const char *file, unsigned int line ) + { + if (index.IsInvalid()) + return false; + + Node *node = nodeList[index.primaryIndex]; + if (node==0) + return false; + if (node->next==0) + { + // Delete last item + ClearIndex(index.primaryIndex,file,line); + return true; + } + else if (index.secondaryIndex==0) + { + // First item does match, but more than one item + nodeList[index.primaryIndex]=node->next; + RakNet::OP_DELETE(node,file,line); + size--; + return true; + } + + Node *last=node; + node=node->next; + --index.secondaryIndex; + + while (index.secondaryIndex!=0) + { + last=node; + node=node->next; + --index.secondaryIndex; + } + + // Skip over subsequent item + last->next=node->next; + // Delete existing item + RakNet::OP_DELETE(node,file,line); + size--; + return true; + } + + template + bool Hash::Remove(key_type key, const char *file, unsigned int line ) + { + return RemoveAtIndex(GetIndexOf(key),file,line); + } + + template + HashIndex Hash::GetIndexOf(key_type key) + { + if (nodeList==0) + { + HashIndex temp; + temp.SetInvalid(); + return temp; + } + HashIndex idx; + idx.primaryIndex=(*hashFunction)(key) % HASH_SIZE; + Node *node = nodeList[idx.primaryIndex]; + if (node==0) + { + idx.SetInvalid(); + return idx; + } + idx.secondaryIndex=0; + while (node!=0) + { + if (node->string==key) + { + return idx; + } + node=node->next; + idx.secondaryIndex++; + } + + idx.SetInvalid(); + return idx; + } + + template + bool Hash::HasData(key_type key) + { + return GetIndexOf(key).IsInvalid()==false; + } + + template + data_type& Hash::ItemAtIndex(const HashIndex &index) + { + Node *node = nodeList[index.primaryIndex]; + RakAssert(node); + unsigned int i; + for (i=0; i < index.secondaryIndex; i++) + { + node=node->next; + RakAssert(node); + } + return node->data; + } + + template + key_type Hash::KeyAtIndex(const HashIndex &index) + { + Node *node = nodeList[index.primaryIndex]; + RakAssert(node); + unsigned int i; + for (i=0; i < index.secondaryIndex; i++) + { + node=node->next; + RakAssert(node); + } + return node->string; + } + + template + void Hash::Clear(const char *file, unsigned int line) + { + if (nodeList) + { + unsigned int i; + for (i=0; i < HASH_SIZE; i++) + ClearIndex(i,file,line); + RakNet::OP_DELETE_ARRAY(nodeList,file,line); + nodeList=0; + size=0; + } + } + + template + void Hash::ClearIndex(unsigned int index,const char *file, unsigned int line) + { + Node *node = nodeList[index]; + Node *next; + while (node) + { + next=node->next; + RakNet::OP_DELETE(node,file,line); + node=next; + size--; + } + nodeList[index]=0; + } + + template + void Hash::GetAsList(DataStructures::List &itemList,DataStructures::List &keyList,const char *file, unsigned int line) const + { + if (nodeList==0) + return; + itemList.Clear(false,_FILE_AND_LINE_); + keyList.Clear(false,_FILE_AND_LINE_); + + Node *node; + unsigned int i; + for (i=0; i < HASH_SIZE; i++) + { + if (nodeList[i]) + { + node=nodeList[i]; + while (node) + { + itemList.Push(node->data,file,line); + keyList.Push(node->string,file,line); + node=node->next; + } + } + } + } + template + unsigned int Hash::Size(void) const + { + return size; + } +} +#endif diff --git a/include/raknet/DS_Heap.hpp b/include/raknet/DS_Heap.hpp new file mode 100644 index 0000000..aaa04a0 --- /dev/null +++ b/include/raknet/DS_Heap.hpp @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_Heap.h +/// \internal +/// \brief Heap (Also serves as a priority queue) +/// + + + +#ifndef __RAKNET_HEAP_H +#define __RAKNET_HEAP_H + +#include "RakMemoryOverride.hpp" +#include "DS_List.hpp" +#include "Export.hpp" +#include "RakAssert.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + template + class RAK_DLL_EXPORT Heap + { + public: + struct HeapNode + { + HeapNode() {} + HeapNode(const weight_type &w, const data_type &d) : weight(w), data(d) {} + weight_type weight; // I'm assuming key is a native numerical type - float or int + data_type data; + }; + + Heap(); + ~Heap(); + void Push(const weight_type &weight, const data_type &data, const char *file, unsigned int line); + /// Call before calling PushSeries, for a new series of items + void StartSeries(void) {optimizeNextSeriesPush=false;} + /// If you are going to push a list of items, where the weights of the items on the list are in order and follow the heap order, PushSeries is faster than Push() + void PushSeries(const weight_type &weight, const data_type &data, const char *file, unsigned int line); + data_type Pop(const unsigned startingIndex); + data_type Peek(const unsigned startingIndex=0) const; + weight_type PeekWeight(const unsigned startingIndex=0) const; + void Clear(bool doNotDeallocateSmallBlocks, const char *file, unsigned int line); + data_type& operator[] ( const unsigned int position ) const; + unsigned Size(void) const; + + protected: + unsigned LeftChild(const unsigned i) const; + unsigned RightChild(const unsigned i) const; + unsigned Parent(const unsigned i) const; + void Swap(const unsigned i, const unsigned j); + DataStructures::List heap; + bool optimizeNextSeriesPush; + }; + + template + Heap::Heap() + { + optimizeNextSeriesPush=false; + } + + template + Heap::~Heap() + { + //Clear(true, _FILE_AND_LINE_); + } + + template + void Heap::PushSeries(const weight_type &weight, const data_type &data, const char *file, unsigned int line) + { + if (optimizeNextSeriesPush==false) + { + // If the weight of what we are inserting is greater than / less than in order of the heap of every sibling and sibling of parent, then can optimize next push + unsigned currentIndex = heap.Size(); + unsigned parentIndex; + if (currentIndex>0) + { + for (parentIndex = Parent(currentIndex); parentIndex < currentIndex; parentIndex++) + { +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + if (isMaxHeap) + { + // Every child is less than its parent + if (weight>heap[parentIndex].weight) + { + // Can't optimize + Push(weight,data,file,line); + return; + } + } + else + { + // Every child is greater than than its parent + if (weight + void Heap::Push(const weight_type &weight, const data_type &data, const char *file, unsigned int line) + { + unsigned currentIndex = heap.Size(); + unsigned parentIndex; + heap.Insert(HeapNode(weight, data), file, line); + while (currentIndex!=0) + { + parentIndex = Parent(currentIndex); +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + if (isMaxHeap) + { + if (heap[parentIndex].weight < weight) + { + Swap(currentIndex, parentIndex); + currentIndex=parentIndex; + } + else + break; + } + else + { + if (heap[parentIndex].weight > weight) + { + Swap(currentIndex, parentIndex); + currentIndex=parentIndex; + } + else + break; + } + } + } + + template + data_type Heap::Pop(const unsigned startingIndex) + { + // While we have children, swap out with the larger of the two children. + + // This line will assert on an empty heap + data_type returnValue=heap[startingIndex].data; + + // Move the last element to the head, and re-heapify + heap[startingIndex]=heap[heap.Size()-1]; + + unsigned currentIndex,leftChild,rightChild; + weight_type currentWeight; + currentIndex=startingIndex; + currentWeight=heap[startingIndex].weight; + heap.RemoveFromEnd(); + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + leftChild=LeftChild(currentIndex); + rightChild=RightChild(currentIndex); + if (leftChild >= heap.Size()) + { + // Done + return returnValue; + } + if (rightChild >= heap.Size()) + { + // Only left node. + if ((isMaxHeap==true && currentWeight < heap[leftChild].weight) || + (isMaxHeap==false && currentWeight > heap[leftChild].weight)) + Swap(leftChild, currentIndex); + + return returnValue; + } + else + { + // Swap with the bigger/smaller of the two children and continue + if (isMaxHeap) + { + if (heap[leftChild].weight <= currentWeight && heap[rightChild].weight <= currentWeight) + return returnValue; + + if (heap[leftChild].weight > heap[rightChild].weight) + { + Swap(leftChild, currentIndex); + currentIndex=leftChild; + } + else + { + Swap(rightChild, currentIndex); + currentIndex=rightChild; + } + } + else + { + if (heap[leftChild].weight >= currentWeight && heap[rightChild].weight >= currentWeight) + return returnValue; + + if (heap[leftChild].weight < heap[rightChild].weight) + { + Swap(leftChild, currentIndex); + currentIndex=leftChild; + } + else + { + Swap(rightChild, currentIndex); + currentIndex=rightChild; + } + } + } + } + } + + template + inline data_type Heap::Peek(const unsigned startingIndex) const + { + return heap[startingIndex].data; + } + + template + inline weight_type Heap::PeekWeight(const unsigned startingIndex) const + { + return heap[startingIndex].weight; + } + + template + void Heap::Clear(bool doNotDeallocateSmallBlocks, const char *file, unsigned int line) + { + heap.Clear(doNotDeallocateSmallBlocks, file, line); + } + + template + inline data_type& Heap::operator[] ( const unsigned int position ) const + { + return heap[position].data; + } + template + unsigned Heap::Size(void) const + { + return heap.Size(); + } + + template + inline unsigned Heap::LeftChild(const unsigned i) const + { + return i*2+1; + } + + template + inline unsigned Heap::RightChild(const unsigned i) const + { + return i*2+2; + } + + template + inline unsigned Heap::Parent(const unsigned i) const + { +#ifdef _DEBUG + RakAssert(i!=0); +#endif + return (i-1)/2; + } + + template + void Heap::Swap(const unsigned i, const unsigned j) + { + HeapNode temp; + temp=heap[i]; + heap[i]=heap[j]; + heap[j]=temp; + } +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif diff --git a/include/raknet/DS_HuffmanEncodingTree.hpp b/include/raknet/DS_HuffmanEncodingTree.hpp new file mode 100644 index 0000000..db78ad6 --- /dev/null +++ b/include/raknet/DS_HuffmanEncodingTree.hpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_HuffmanEncodingTree.h +/// \brief \b [Internal] Generates a huffman encoding tree, used for string and global compression. +/// + + +#ifndef __HUFFMAN_ENCODING_TREE +#define __HUFFMAN_ENCODING_TREE + +#include "RakMemoryOverride.hpp" +#include "DS_HuffmanEncodingTreeNode.hpp" +#include "BitStream.hpp" +#include "Export.hpp" +#include "DS_LinkedList.hpp" + +namespace RakNet +{ + +/// This generates special cases of the huffman encoding tree using 8 bit keys with the additional condition that unused combinations of 8 bits are treated as a frequency of 1 +class RAK_DLL_EXPORT HuffmanEncodingTree +{ + +public: + HuffmanEncodingTree(); + ~HuffmanEncodingTree(); + + /// \brief Pass an array of bytes to array and a preallocated BitStream to receive the output. + /// \param [in] input Array of bytes to encode + /// \param [in] sizeInBytes size of \a input + /// \param [out] output The bitstream to write to + void EncodeArray( unsigned char *input, size_t sizeInBytes, RakNet::BitStream * output ); + + // \brief Decodes an array encoded by EncodeArray(). + unsigned DecodeArray( RakNet::BitStream * input, BitSize_t sizeInBits, size_t maxCharsToWrite, unsigned char *output ); + void DecodeArray( unsigned char *input, BitSize_t sizeInBits, RakNet::BitStream * output ); + + /// \brief Given a frequency table of 256 elements, all with a frequency of 1 or more, generate the tree. + void GenerateFromFrequencyTable( unsigned int frequencyTable[ 256 ] ); + + /// \brief Free the memory used by the tree. + void FreeMemory( void ); + +private: + + /// The root node of the tree + + HuffmanEncodingTreeNode *root; + + /// Used to hold bit encoding for one character + + + struct CharacterEncoding + { + unsigned char* encoding; + unsigned short bitLength; + }; + + CharacterEncoding encodingTable[ 256 ]; + + void InsertNodeIntoSortedList( HuffmanEncodingTreeNode * node, DataStructures::LinkedList *huffmanEncodingTreeNodeList ) const; +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/DS_HuffmanEncodingTreeFactory.hpp b/include/raknet/DS_HuffmanEncodingTreeFactory.hpp new file mode 100644 index 0000000..f70826e --- /dev/null +++ b/include/raknet/DS_HuffmanEncodingTreeFactory.hpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_HuffmanEncodingTreeFactory.h +/// \internal +/// \brief Creates instances of the class HuffmanEncodingTree +/// + + +#ifndef __HUFFMAN_ENCODING_TREE_FACTORY +#define __HUFFMAN_ENCODING_TREE_FACTORY + +#include "RakMemoryOverride.hpp" + +namespace RakNet { +/// Forward declarations +class HuffmanEncodingTree; + +/// \brief Creates instances of the class HuffmanEncodingTree +/// \details This class takes a frequency table and given that frequence table, will generate an instance of HuffmanEncodingTree +class HuffmanEncodingTreeFactory +{ +public: + /// Default constructor + HuffmanEncodingTreeFactory(); + + /// \brief Reset the frequency table. + /// \details You don't need to call this unless you want to reuse the class for a new tree + void Reset( void ); + + /// \brief Pass an array of bytes to this to add those elements to the frequency table. + /// \param[in] array the data to insert into the frequency table + /// \param[in] size the size of the data to insert + void AddToFrequencyTable( unsigned char *array, int size ); + + /// \brief Copies the frequency table to the array passed. Retrieve the frequency table. + /// \param[in] _frequency The frequency table used currently + void GetFrequencyTable( unsigned int _frequency[ 256 ] ); + + /// \brief Returns the frequency table as a pointer. + /// \return the address of the frenquency table + unsigned int * GetFrequencyTable( void ); + + /// \brief Generate a HuffmanEncodingTree. + /// \details You can also use GetFrequencyTable and GenerateFromFrequencyTable in the tree itself + /// \return The generated instance of HuffmanEncodingTree + HuffmanEncodingTree * GenerateTree( void ); + +private: + + /// Frequency table + unsigned int frequency[ 256 ]; +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/DS_HuffmanEncodingTreeNode.hpp b/include/raknet/DS_HuffmanEncodingTreeNode.hpp new file mode 100644 index 0000000..71e5261 --- /dev/null +++ b/include/raknet/DS_HuffmanEncodingTreeNode.hpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] A single node in the Huffman Encoding Tree. +/// + +#ifndef __HUFFMAN_ENCODING_TREE_NODE +#define __HUFFMAN_ENCODING_TREE_NODE + +struct HuffmanEncodingTreeNode +{ + unsigned char value; + unsigned weight; + HuffmanEncodingTreeNode *left; + HuffmanEncodingTreeNode *right; + HuffmanEncodingTreeNode *parent; +}; + +#endif diff --git a/include/raknet/DS_LinkedList.hpp b/include/raknet/DS_LinkedList.hpp new file mode 100644 index 0000000..2daf0c8 --- /dev/null +++ b/include/raknet/DS_LinkedList.hpp @@ -0,0 +1,1257 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_LinkedList.h +/// \internal +/// \brief Straightforward linked list data structure. +/// + + +#ifndef __LINKED_LIST_H +#define __LINKED_LIST_H + +#include "Export.hpp" +#include "RakMemoryOverride.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + // Prototype to prevent error in CircularLinkedList class when a reference is made to a LinkedList class + template + class RAK_DLL_EXPORT LinkedList; + + /** + * \brief (Circular) Linked List ADT (Doubly Linked Pointer to Node Style) - + * + * \details + * Initilize with the following command + * LinkedList + * OR + * CircularLinkedList + * + * Has the following member functions + * - size: returns number of elements in the linked list + * - insert(item): inserts @em item at the current position in + * the LinkedList. + * - add(item): inserts @em item after the current position in + * the LinkedList. Does not increment the position + * - replace(item): replaces the element at the current position @em item. + * - peek: returns the element at the current position + * - pop: returns the element at the current position and deletes it + * - del: deletes the current element. Does nothing for an empty list. + * - clear: empties the LinkedList and returns storage + * - bool IsInitem): Does a linear search for @em item. Does not set + * the position to it, only returns true on item found, false otherwise + * - bool find(item): Does a linear search for @em item and sets the current + * position to point to it if and only if the item is found. Returns true + * on item found, false otherwise + * - sort: Sorts the elements of the list with a mergesort and sets the + * current pointer to the first element + * - concatenate(list L): This appends L to the current list + * - ++(prefix): moves the pointer one element up in the list and returns the + * appropriate copy of the element in the list + * - --(prefix): moves the pointer one element back in the list and returns + * the appropriate copy of the element in the list + * - beginning - moves the pointer to the start of the list. For circular + * linked lists this is first 'position' created. You should call this + * after the sort function to read the first value. + * - end - moves the pointer to the end of the list. For circular linked + * lists this is one less than the first 'position' created + * The assignment and copy constructor operators are defined + * + * \note + * 1. LinkedList and CircularLinkedList are exactly the same except LinkedList + * won't let you wrap around the root and lets you jump to two positions + * relative to the root/ + * 2. Postfix ++ and -- can be used but simply call the prefix versions. + * + * + * EXAMPLE: + * @code + * LinkedList A; // Creates a Linked List of integers called A + * CircularLinkedList B; // Creates a Circular Linked List of + * // integers called B + * + * A.Insert(20); // Adds 20 to A. A: 20 - current is 20 + * A.Insert(5); // Adds 5 to A. A: 5 20 - current is 5 + * A.Insert(1); // Adds 1 to A. A: 1 5 20 - current is 1 + * + * A.IsIn1); // returns true + * A.IsIn200); // returns false + * A.Find(5); // returns true and sets current to 5 + * A.Peek(); // returns 5 + * A.Find(1); // returns true and sets current to 1 + * + * (++A).Peek(); // Returns 5 + * A.Peek(); // Returns 5 + * + * A.Replace(10); // Replaces 5 with 10. + * A.Peek(); // Returns 10 + * + * A.Beginning(); // Current points to the beginning of the list at 1 + * + * (++A).Peek(); // Returns 5 + * A.Peek(); // Returns 10 + * + * A.Del(); // Deletes 10. Current points to the next element, which is 20 + * A.Peek(); // Returns 20 + * + * A.Beginning(); // Current points to the beginning of the list at 1 + * + * (++A).Peek(); // Returns 5 + * A.Peek(); // Returns 20 + * + * A.Clear(_FILE_AND_LINE_); // Deletes all nodes in A + * + * A.Insert(5); // A: 5 - current is 5 + * A.Insert(6); // A: 6 5 - current is 6 + * A.Insert(7); // A: 7 6 5 - current is 7 + * + * A.Clear(_FILE_AND_LINE_); + * B.Clear(_FILE_AND_LINE_); + * + * B.Add(10); + * B.Add(20); + * B.Add(30); + * B.Add(5); + * B.Add(2); + * B.Add(25); + * // Sorts the numbers in the list and sets the current pointer to the + * // first element + * B.sort(); + * + * // Postfix ++ just calls the prefix version and has no functional + * // difference. + * B.Peek(); // Returns 2 + * B++; + * B.Peek(); // Returns 5 + * B++; + * B.Peek(); // Returns 10 + * B++; + * B.Peek(); // Returns 20 + * B++; + * B.Peek(); // Returns 25 + * B++; + * B.Peek(); // Returns 30 + * @endcode + */ + template + + class CircularLinkedList + { + + public: + + struct node + { + CircularLinkedListType item; + + node* previous; + node* next; + }; + + CircularLinkedList(); + ~CircularLinkedList(); + CircularLinkedList( const CircularLinkedList& original_copy ); + // CircularLinkedList(LinkedList original_copy) {CircularLinkedList(original_copy);} // Converts linked list to circular type + bool operator= ( const CircularLinkedList& original_copy ); + CircularLinkedList& operator++(); // CircularLinkedList A; ++A; + CircularLinkedList& operator++( int ); // Circular_Linked List A; A++; + CircularLinkedList& operator--(); // CircularLinkedList A; --A; + CircularLinkedList& operator--( int ); // Circular_Linked List A; A--; + bool IsIn( const CircularLinkedListType& input ); + bool Find( const CircularLinkedListType& input ); + void Insert( const CircularLinkedListType& input ); + + CircularLinkedListType& Add ( const CircularLinkedListType& input ) + + ; // Adds after the current position + void Replace( const CircularLinkedListType& input ); + + void Del( void ); + + unsigned int Size( void ); + + CircularLinkedListType& Peek( void ); + + CircularLinkedListType Pop( void ); + + void Clear( void ); + + void Sort( void ); + + void Beginning( void ); + + void End( void ); + + void Concatenate( const CircularLinkedList& L ); + + protected: + unsigned int list_size; + + node *root; + + node *position; + + node* FindPointer( const CircularLinkedListType& input ); + + private: + CircularLinkedList Merge( CircularLinkedList L1, CircularLinkedList L2 ); + + CircularLinkedList Mergesort( const CircularLinkedList& L ); + }; + + template + + class LinkedList : public CircularLinkedList + { + + public: + LinkedList() + {} + + LinkedList( const LinkedList& original_copy ); + ~LinkedList(); + bool operator= ( const LinkedList& original_copy ); + LinkedList& operator++(); // LinkedList A; ++A; + LinkedList& operator++( int ); // Linked List A; A++; + LinkedList& operator--(); // LinkedList A; --A; + LinkedList& operator--( int ); // Linked List A; A--; + + private: + LinkedList Merge( LinkedList L1, LinkedList L2 ); + LinkedList Mergesort( const LinkedList& L ); + + }; + + + template + inline void CircularLinkedList::Beginning( void ) + { + if ( this->root ) + this->position = this->root; + } + + template + inline void CircularLinkedList::End( void ) + { + if ( this->root ) + this->position = this->root->previous; + } + + template + bool LinkedList::operator= ( const LinkedList& original_copy ) + { + typename LinkedList::node * original_copy_pointer, *last, *save_position; + + if ( ( &original_copy ) != this ) + { + + this->Clear(); + + + if ( original_copy.list_size == 0 ) + { + this->root = 0; + this->position = 0; + this->list_size = 0; + } + + else + if ( original_copy.list_size == 1 ) + { + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->root->next = this->root; + this->root->previous = this->root; + this->list_size = 1; + this->position = this->root; + // *(root->item)=*((original_copy.root)->item); + this->root->item = original_copy.root->item; + } + + else + { + // Setup the first part of the root node + original_copy_pointer = original_copy.root; + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->position = this->root; + // *(root->item)=*((original_copy.root)->item); + this->root->item = original_copy.root->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = this->position; + + do + { + + + // Save the current element + last = this->position; + + // Point to the next node in the source list + original_copy_pointer = original_copy_pointer->next; + + // Create a new node and point position to it + this->position = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // position->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + + // Copy the item to the new node + // *(position->item)=*(original_copy_pointer->item); + this->position->item = original_copy_pointer->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = this->position; + + + // Set the previous pointer for the new node + ( this->position->previous ) = last; + + // Set the next pointer for the old node to the new node + ( last->next ) = this->position; + + } + + while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); + + // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node + this->position->next = this->root; + + this->root->previous = this->position; + + this->list_size = original_copy.list_size; + + this->position = save_position; + } + } + + return true; + } + + + template + CircularLinkedList::CircularLinkedList() + { + this->root = 0; + this->position = 0; + this->list_size = 0; + } + + template + CircularLinkedList::~CircularLinkedList() + { + this->Clear(); + } + + template + LinkedList::~LinkedList() + { + this->Clear(); + } + + template + LinkedList::LinkedList( const LinkedList& original_copy ) + { + typename LinkedList::node * original_copy_pointer, *last, *save_position; + + if ( original_copy.list_size == 0 ) + { + this->root = 0; + this->position = 0; + this->list_size = 0; + return ; + } + + else + if ( original_copy.list_size == 1 ) + { + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->root->next = this->root; + this->root->previous = this->root; + this->list_size = 1; + this->position = this->root; + // *(root->item) = *((original_copy.root)->item); + this->root->item = original_copy.root->item; + } + + else + { + // Setup the first part of the root node + original_copy_pointer = original_copy.root; + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->position = this->root; + // *(root->item)=*((original_copy.root)->item); + this->root->item = original_copy.root->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = this->position; + + do + { + // Save the current element + last = this->position; + + // Point to the next node in the source list + original_copy_pointer = original_copy_pointer->next; + + // Create a new node and point position to it + this->position = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // position->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + + // Copy the item to the new node + // *(position->item)=*(original_copy_pointer->item); + this->position->item = original_copy_pointer->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = this->position; + + // Set the previous pointer for the new node + ( this->position->previous ) = last; + + // Set the next pointer for the old node to the new node + ( last->next ) = this->position; + + } + + while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); + + // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node + this->position->next = this->root; + + this->root->previous = this->position; + + this->list_size = original_copy.list_size; + + this->position = save_position; + } + } + +#ifdef _MSC_VER +#pragma warning( disable : 4701 ) // warning C4701: local variable may be used without having been initialized +#endif + template + CircularLinkedList::CircularLinkedList( const CircularLinkedList& original_copy ) + { + node * original_copy_pointer; + node *last; + node *save_position; + + if ( original_copy.list_size == 0 ) + { + this->root = 0; + this->position = 0; + this->list_size = 0; + return ; + } + + else + if ( original_copy.list_size == 1 ) + { + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->root->next = this->root; + this->root->previous = this->root; + this->list_size = 1; + this->position = this->root; + // *(root->item) = *((original_copy.root)->item); + this->root->item = original_copy.root->item; + } + + else + { + // Setup the first part of the root node + original_copy_pointer = original_copy.root; + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->position = this->root; + // *(root->item)=*((original_copy.root)->item); + this->root->item = original_copy.root->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = this->position; + + do + { + + + // Save the current element + last = this->position; + + // Point to the next node in the source list + original_copy_pointer = original_copy_pointer->next; + + // Create a new node and point position to it + this->position = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // position->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + + // Copy the item to the new node + // *(position->item)=*(original_copy_pointer->item); + this->position->item = original_copy_pointer->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = position; + + // Set the previous pointer for the new node + ( this->position->previous ) = last; + + // Set the next pointer for the old node to the new node + ( last->next ) = this->position; + + } + + while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); + + // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node + this->position->next = this->root; + + this->root->previous = position; + + this->list_size = original_copy.list_size; + + this->position = save_position; + } + } + +#ifdef _MSC_VER +#pragma warning( disable : 4701 ) // warning C4701: local variable may be used without having been initialized +#endif + template + bool CircularLinkedList::operator= ( const CircularLinkedList& original_copy ) + { + node * original_copy_pointer; + node *last; + node *save_position; + + if ( ( &original_copy ) != this ) + { + + this->Clear(); + + + if ( original_copy.list_size == 0 ) + { + this->root = 0; + this->position = 0; + this->list_size = 0; + } + + else + if ( original_copy.list_size == 1 ) + { + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->root->next = this->root; + this->root->previous = this->root; + this->list_size = 1; + this->position = this->root; + // *(root->item)=*((original_copy.root)->item); + this->root->item = original_copy.root->item; + } + + else + { + // Setup the first part of the root node + original_copy_pointer = original_copy.root; + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->position = this->root; + // *(root->item)=*((original_copy.root)->item); + this->root->item = original_copy.root->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = this->position; + + do + { + // Save the current element + last = this->position; + + // Point to the next node in the source list + original_copy_pointer = original_copy_pointer->next; + + // Create a new node and point position to it + this->position = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // position->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + + // Copy the item to the new node + // *(position->item)=*(original_copy_pointer->item); + this->position->item = original_copy_pointer->item; + + if ( original_copy_pointer == original_copy.position ) + save_position = this->position; + + // Set the previous pointer for the new node + ( this->position->previous ) = last; + + // Set the next pointer for the old node to the new node + ( last->next ) = this->position; + + } + + while ( ( original_copy_pointer->next ) != ( original_copy.root ) ); + + // Complete the circle. Set the next pointer of the newest node to the root and the previous pointer of the root to the newest node + this->position->next = this->root; + + this->root->previous = this->position; + + this->list_size = original_copy.list_size; + + this->position = save_position; + } + } + + return true; + } + + template + void CircularLinkedList::Insert( const CircularLinkedListType& input ) + { + node * new_node; + + if ( list_size == 0 ) + { + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + //*(root->item)=input; + this->root->item = input; + this->root->next = this->root; + this->root->previous = this->root; + this->list_size = 1; + this->position = this->root; + } + + else + if ( list_size == 1 ) + { + this->position = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // position->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->root->next = this->position; + this->root->previous = this->position; + this->position->previous = this->root; + this->position->next = this->root; + // *(position->item)=input; + this->position->item = input; + this->root = this->position; // Since we're inserting into a 1 element list the old root is now the second item + this->list_size = 2; + } + + else + { + /* + + B + | + A --- C + + position->previous=A + new_node=B + position=C + + Note that the order of the following statements is important */ + + new_node = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // new_node->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + + // *(new_node->item)=input; + new_node->item = input; + + // Point next of A to B + ( this->position->previous ) ->next = new_node; + + // Point last of B to A + new_node->previous = this->position->previous; + + // Point last of C to B + this->position->previous = new_node; + + // Point next of B to C + new_node->next = this->position; + + // Since the root pointer is bound to a node rather than an index this moves it back if you insert an element at the root + + if ( this->position == this->root ) + { + this->root = new_node; + this->position = this->root; + } + + // Increase the recorded size of the list by one + this->list_size++; + } + } + + template + CircularLinkedListType& CircularLinkedList::Add ( const CircularLinkedListType& input ) + { + node * new_node; + + if ( this->list_size == 0 ) + { + this->root = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // root->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // *(root->item)=input; + this->root->item = input; + this->root->next = this->root; + this->root->previous = this->root; + this->list_size = 1; + this->position = this->root; + // return *(position->item); + return this->position->item; + } + + else + if ( list_size == 1 ) + { + this->position = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // position->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + this->root->next = this->position; + this->root->previous = this->position; + this->position->previous = this->root; + this->position->next = this->root; + // *(position->item)=input; + this->position->item = input; + this->list_size = 2; + this->position = this->root; // Don't move the position from the root + // return *(position->item); + return this->position->item; + } + + else + { + /* + + B + | + A --- C + + new_node=B + position=A + position->next=C + + Note that the order of the following statements is important */ + + new_node = RakNet::OP_NEW( _FILE_AND_LINE_ ); + // new_node->item = RakNet::OP_NEW( _FILE_AND_LINE_ ); + + // *(new_node->item)=input; + new_node->item = input; + + // Point last of B to A + new_node->previous = this->position; + + // Point next of B to C + new_node->next = ( this->position->next ); + + // Point last of C to B + ( this->position->next ) ->previous = new_node; + + // Point next of A to B + ( this->position->next ) = new_node; + + // Increase the recorded size of the list by one + this->list_size++; + + // return *(new_node->item); + return new_node->item; + } + } + + template + inline void CircularLinkedList::Replace( const CircularLinkedListType& input ) + { + if ( this->list_size > 0 ) + // *(position->item)=input; + this->position->item = input; + } + + template + void CircularLinkedList::Del() + { + node * new_position; + + if ( this->list_size == 0 ) + return ; + + else + if ( this->list_size == 1 ) + { + // RakNet::OP_DELETE(root->item, _FILE_AND_LINE_); + RakNet::OP_DELETE(this->root, _FILE_AND_LINE_); + this->root = this->position = 0; + this->list_size = 0; + } + + else + { + ( this->position->previous ) ->next = this->position->next; + ( this->position->next ) ->previous = this->position->previous; + new_position = this->position->next; + + if ( this->position == this->root ) + this->root = new_position; + + // RakNet::OP_DELETE(position->item, _FILE_AND_LINE_); + RakNet::OP_DELETE(this->position, _FILE_AND_LINE_); + + this->position = new_position; + + this->list_size--; + } + } + + template + bool CircularLinkedList::IsIn(const CircularLinkedListType& input ) + { + node * return_value, *old_position; + + old_position = this->position; + + return_value = FindPointer( input ); + this->position = old_position; + + if ( return_value != 0 ) + return true; + else + return false; // Can't find the item don't do anything + } + + template + bool CircularLinkedList::Find( const CircularLinkedListType& input ) + { + node * return_value; + + return_value = FindPointer( input ); + + if ( return_value != 0 ) + { + this->position = return_value; + return true; + } + + else + return false; // Can't find the item don't do anything + } + + template + typename CircularLinkedList::node* CircularLinkedList::FindPointer( const CircularLinkedListType& input ) + { + node * current; + + if ( this->list_size == 0 ) + return 0; + + current = this->root; + + // Search for the item starting from the root node and incrementing the pointer after every check + // If you wind up pointing at the root again you looped around the list so didn't find the item, in which case return 0 + do + { + // if (*(current->item) == input) return current; + + if ( current->item == input ) + return current; + + current = current->next; + } + + while ( current != this->root ); + + return 0; + + } + + template + inline unsigned int CircularLinkedList::Size( void ) + { + return this->list_size; + } + + template + inline CircularLinkedListType& CircularLinkedList::Peek( void ) + { + // return *(position->item); + return this->position->item; + } + + template + CircularLinkedListType CircularLinkedList::Pop( void ) + { + CircularLinkedListType element; + element = Peek(); + Del(); + return CircularLinkedListType( element ); // return temporary + } + + // Prefix + template + CircularLinkedList& CircularLinkedList::operator++() + { + if ( this->list_size != 0 ) + position = position->next; + + return *this; + } + + /* + // Postfix + template + CircularLinkedList& CircularLinkedList::operator++(int) + { + CircularLinkedList before; + before=*this; + operator++(); + return before; + } + */ + + template + CircularLinkedList& CircularLinkedList::operator++( int ) + { + return this->operator++(); + } + + // Prefix + template + CircularLinkedList& CircularLinkedList::operator--() + { + if ( this->list_size != 0 ) + this->position = this->position->previous; + + return *this; + } + + /* + // Postfix + template + CircularLinkedList& CircularLinkedList::operator--(int) + { + CircularLinkedList before; + before=*this; + operator--(); + return before; + } + */ + + template + CircularLinkedList& CircularLinkedList::operator--( int ) + { + return this->operator--(); + } + + template + void CircularLinkedList::Clear( void ) + { + if ( this->list_size == 0 ){ + return ; + }else if ( this->list_size == 1 ) // {RakNet::OP_DELETE(root->item); RakNet::OP_DELETE(root, _FILE_AND_LINE_);} + { + RakNet::OP_DELETE(this->root, _FILE_AND_LINE_); + } + + else + { + node* current; + node* temp; + + current = this->root; + + do + { + temp = current; + current = current->next; + // RakNet::OP_DELETE(temp->item, _FILE_AND_LINE_); + RakNet::OP_DELETE(temp, _FILE_AND_LINE_); + } + + while ( current != this->root ); + } + + this->list_size = 0; + this->root = 0; + this->position = 0; + } + + template + inline void CircularLinkedList::Concatenate( const CircularLinkedList& L ) + { + unsigned int counter; + node* ptr; + + if ( L.list_size == 0 ) + return ; + + if ( this->list_size == 0 ) + * this = L; + + ptr = L.root; + + this->position = this->root->previous; + + // Cycle through each element in L and add it to the current list + for ( counter = 0; counter < L.list_size; counter++ ) + { + // Add item after the current item pointed to + // add(*(ptr->item)); + + Add ( ptr->item ); + + // Update pointers. Moving ptr keeps the current pointer at the end of the list since the add function does not move the pointer + ptr = ptr->next; + + this->position = this->position->next; + } + } + + template + inline void CircularLinkedList::Sort( void ) + { + if ( this->list_size <= 1 ) + return ; + + // Call equal operator to assign result of mergesort to current object + *this = Mergesort( *this ); + + this->position = this->root; + } + + template + CircularLinkedList CircularLinkedList::Mergesort( const CircularLinkedList& L ) + { + unsigned int counter; + node* location; + CircularLinkedList L1; + CircularLinkedList L2; + + location = L.root; + + // Split the list into two equal size sublists, L1 and L2 + + for ( counter = 0; counter < L.list_size / 2; counter++ ) + { + // L1.add (*(location->item)); + L1.Add ( location->item ); + location = location->next; + } + + for ( ;counter < L.list_size; counter++ ) + { + // L2.Add(*(location->item)); + L2.Add ( location->item ); + location = location->next; + } + + // Recursively sort the sublists + if ( L1.list_size > 1 ) + L1 = Mergesort( L1 ); + + if ( L2.list_size > 1 ) + L2 = Mergesort( L2 ); + + // Merge the two sublists + return Merge( L1, L2 ); + } + + template + CircularLinkedList CircularLinkedList::Merge( CircularLinkedList L1, CircularLinkedList L2 ) + { + CircularLinkedList X; + CircularLinkedListType element; + L1.position = L1.root; + L2.position = L2.root; + + // While neither list is empty + + while ( ( L1.list_size != 0 ) && ( L2.list_size != 0 ) ) + { + // Compare the first items of L1 and L2 + // Remove the smaller of the two items from the list + + if ( ( ( L1.root ) ->item ) < ( ( L2.root ) ->item ) ) + // if ((*((L1.root)->item)) < (*((L2.root)->item))) + { + // element = *((L1.root)->item); + element = ( L1.root ) ->item; + L1.Del(); + } + else + { + // element = *((L2.root)->item); + element = ( L2.root ) ->item; + L2.Del(); + } + + // Add this item to the end of X + X.Add( element ); + + X++; + } + + // Add the remaining list to X + if ( L1.list_size != 0 ) + X.Concatenate( L1 ); + else + X.Concatenate( L2 ); + + return X; + } + + template + LinkedList LinkedList::Mergesort( const LinkedList& L ) + { + unsigned int counter; + typename LinkedList::node* location; + LinkedList L1; + LinkedList L2; + + location = L.root; + + // Split the list into two equal size sublists, L1 and L2 + + for ( counter = 0; counter < L.LinkedList_size / 2; counter++ ) + { + // L1.add (*(location->item)); + L1.Add ( location->item ); + location = location->next; + } + + for ( ;counter < L.LinkedList_size; counter++ ) + { + // L2.Add(*(location->item)); + L2.Add ( location->item ); + location = location->next; + } + + // Recursively sort the sublists + if ( L1.list_size > 1 ) + L1 = Mergesort( L1 ); + + if ( L2.list_size > 1 ) + L2 = Mergesort( L2 ); + + // Merge the two sublists + return Merge( L1, L2 ); + } + + template + LinkedList LinkedList::Merge( LinkedList L1, LinkedList L2 ) + { + LinkedList X; + LinkedListType element; + L1.position = L1.root; + L2.position = L2.root; + + // While neither list is empty + + while ( ( L1.LinkedList_size != 0 ) && ( L2.LinkedList_size != 0 ) ) + { + // Compare the first items of L1 and L2 + // Remove the smaller of the two items from the list + + if ( ( ( L1.root ) ->item ) < ( ( L2.root ) ->item ) ) + // if ((*((L1.root)->item)) < (*((L2.root)->item))) + { + element = ( L1.root ) ->item; + // element = *((L1.root)->item); + L1.Del(); + } + else + { + element = ( L2.root ) ->item; + // element = *((L2.root)->item); + L2.Del(); + } + + // Add this item to the end of X + X.Add( element ); + } + + // Add the remaining list to X + if ( L1.LinkedList_size != 0 ) + X.concatenate( L1 ); + else + X.concatenate( L2 ); + + return X; + } + + + // Prefix + template + LinkedList& LinkedList::operator++() + { + if ( ( this->list_size != 0 ) && ( this->position->next != this->root ) ) + this->position = this->position->next; + + return *this; + } + + /* + // Postfix + template + LinkedList& LinkedList::operator++(int) + { + LinkedList before; + before=*this; + operator++(); + return before; + } + */ + // Postfix + template + LinkedList& LinkedList::operator++( int ) + { + return this->operator++(); + } + + // Prefix + template + LinkedList& LinkedList::operator--() + { + if ( ( this->list_size != 0 ) && ( this->position != this->root ) ) + this->position = this->position->previous; + + return *this; + } + + /* + // Postfix + template + LinkedList& LinkedList::operator--(int) + { + LinkedList before; + before=*this; + operator--(); + return before; + } + */ + + // Postfix + template + LinkedList& LinkedList::operator--( int ) + { + return this->operator--(); + } + +} // End namespace + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif diff --git a/include/raknet/DS_List.hpp b/include/raknet/DS_List.hpp new file mode 100644 index 0000000..1c53d5e --- /dev/null +++ b/include/raknet/DS_List.hpp @@ -0,0 +1,525 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_List.h +/// \internal +/// \brief Array based list. +/// \details Usually the Queue class is used instead, since it has all the same functionality and is only worse at random access. +/// + + +#ifndef __LIST_H +#define __LIST_H + +#include "RakAssert.hpp" +#include // memmove +#include "Export.hpp" +#include "RakMemoryOverride.hpp" + +/// Maximum unsigned long +static const unsigned int MAX_UNSIGNED_LONG = 4294967295U; + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + /// \brief Array based implementation of a list. + /// \note ONLY USE THIS FOR SHALLOW COPIES. I don't bother with operator= to improve performance. + template + class RAK_DLL_EXPORT List + { + public: + /// Default constructor + List(); + + // Destructor + ~List(); + + /// \brief Copy constructor. + /// \param[in] original_copy The list to duplicate + List( const List& original_copy ); + + /// \brief Assign one list to another. + List& operator= ( const List& original_copy ); + + /// \brief Access an element by its index in the array. + /// \param[in] position The index into the array. + /// \return The element at position \a position. + list_type& operator[] ( const unsigned int position ) const; + + /// \brief Access an element by its index in the array. + /// \param[in] position The index into the array. + /// \return The element at position \a position. + list_type& Get ( const unsigned int position ) const; + + /// \brief Push an element at the end of the stack. + /// \param[in] input The new element. + void Push(const list_type &input, const char *file, unsigned int line ); + + /// \brief Pop an element from the end of the stack. + /// \pre Size()>0 + /// \return The element at the end. + list_type& Pop(void); + + /// \brief Insert an element at position \a position in the list. + /// \param[in] input The new element. + /// \param[in] position The position of the new element. + void Insert( const list_type &input, const unsigned int position, const char *file, unsigned int line ); + + /// \brief Insert at the end of the list. + /// \param[in] input The new element. + void Insert( const list_type &input, const char *file, unsigned int line ); + + /// \brief Replace the value at \a position by \a input. + /// \details If the size of the list is less than @em position, it increase the capacity of + /// the list and fill slot with @em filler. + /// \param[in] input The element to replace at position @em position. + /// \param[in] filler The element use to fill new allocated capacity. + /// \param[in] position The position of input in the list. + void Replace( const list_type &input, const list_type filler, const unsigned int position, const char *file, unsigned int line ); + + /// \brief Replace the last element of the list by \a input. + /// \param[in] input The element used to replace the last element. + void Replace( const list_type &input ); + + /// \brief Delete the element at position \a position. + /// \param[in] position The index of the element to delete + void RemoveAtIndex( const unsigned int position ); + + /// \brief Delete the element at position \a position. + /// \note - swaps middle with end of list, only use if list order does not matter + /// \param[in] position The index of the element to delete + void RemoveAtIndexFast( const unsigned int position ); + + /// \brief Delete the element at the end of the list. + void RemoveFromEnd(const unsigned num=1); + + /// \brief Returns the index of the specified item or MAX_UNSIGNED_LONG if not found. + /// \param[in] input The element to check for + /// \return The index or position of @em input in the list. + /// \retval MAX_UNSIGNED_LONG The object is not in the list + /// \retval [Integer] The index of the element in the list + unsigned int GetIndexOf( const list_type &input ) const; + + /// \return The number of elements in the list + unsigned int Size( void ) const; + + /// \brief Clear the list + void Clear( bool doNotDeallocateSmallBlocks, const char *file, unsigned int line ); + + /// \brief Preallocate the list, so it needs fewer reallocations at runtime. + void Preallocate( unsigned countNeeded, const char *file, unsigned int line ); + + /// \brief Frees overallocated members, to use the minimum memory necessary. + /// \attention + /// This is a slow operation + void Compress( const char *file, unsigned int line ); + + private: + /// An array of user values + list_type* listArray; + + /// Number of elements in the list + unsigned int list_size; + + /// Size of \a array + unsigned int allocation_size; + }; + template + List::List() + { + allocation_size = 0; + listArray = 0; + list_size = 0; + } + + template + List::~List() + { + if (allocation_size>0) + RakNet::OP_DELETE_ARRAY(listArray, _FILE_AND_LINE_); + } + + + template + List::List( const List& original_copy ) + { + // Allocate memory for copy + + if ( original_copy.list_size == 0 ) + { + list_size = 0; + allocation_size = 0; + } + else + { + listArray = RakNet::OP_NEW_ARRAY( original_copy.list_size , _FILE_AND_LINE_ ); + + for ( unsigned int counter = 0; counter < original_copy.list_size; ++counter ) + listArray[ counter ] = original_copy.listArray[ counter ]; + + // Don't call constructors, assignment operators, etc. + //memcpy(listArray, original_copy.listArray, original_copy.list_size*sizeof(list_type)); + + list_size = allocation_size = original_copy.list_size; + } + } + + template + List& List::operator= ( const List& original_copy ) + { + if ( ( &original_copy ) != this ) + { + Clear( false, _FILE_AND_LINE_ ); + + // Allocate memory for copy + + if ( original_copy.list_size == 0 ) + { + list_size = 0; + allocation_size = 0; + } + + else + { + listArray = RakNet::OP_NEW_ARRAY( original_copy.list_size , _FILE_AND_LINE_ ); + + for ( unsigned int counter = 0; counter < original_copy.list_size; ++counter ) + listArray[ counter ] = original_copy.listArray[ counter ]; + // Don't call constructors, assignment operators, etc. + //memcpy(listArray, original_copy.listArray, original_copy.list_size*sizeof(list_type)); + + list_size = allocation_size = original_copy.list_size; + } + } + + return *this; + } + + + template + inline list_type& List::operator[] ( const unsigned int position ) const + { + #ifdef _DEBUG + if (position>=list_size) + { + RakAssert ( position < list_size ); + } + #endif + return listArray[ position ]; + } + + // Just here for debugging + template + inline list_type& List::Get ( const unsigned int position ) const + { + return listArray[ position ]; + } + + template + void List::Push(const list_type &input, const char *file, unsigned int line) + { + Insert(input, file, line); + } + + template + inline list_type& List::Pop(void) + { +#ifdef _DEBUG + RakAssert(list_size>0); +#endif + --list_size; + return listArray[list_size]; + } + + template + void List::Insert( const list_type &input, const unsigned int position, const char *file, unsigned int line ) + { +#ifdef _DEBUG + if (position>list_size) + { + RakAssert( position <= list_size ); + } +#endif + + // Reallocate list if necessary + if ( list_size == allocation_size ) + { + // allocate twice the currently allocated memory + list_type * new_array; + + if ( allocation_size == 0 ) + allocation_size = 16; + else + allocation_size *= 2; + + new_array = RakNet::OP_NEW_ARRAY( allocation_size , file, line ); + + // copy old array over + for ( unsigned int counter = 0; counter < list_size; ++counter ) + new_array[ counter ] = listArray[ counter ]; + + // Don't call constructors, assignment operators, etc. + //memcpy(new_array, listArray, list_size*sizeof(list_type)); + + // set old array to point to the newly allocated and twice as large array + RakNet::OP_DELETE_ARRAY(listArray, file, line); + + listArray = new_array; + } + + // Move the elements in the list to make room + for ( unsigned int counter = list_size; counter != position; counter-- ) + listArray[ counter ] = listArray[ counter - 1 ]; + + // Don't call constructors, assignment operators, etc. + //memmove(listArray+position+1, listArray+position, (list_size-position)*sizeof(list_type)); + + // Insert the new item at the correct spot + listArray[ position ] = input; + + ++list_size; + + } + + + template + void List::Insert( const list_type &input, const char *file, unsigned int line ) + { + // Reallocate list if necessary + + if ( list_size == allocation_size ) + { + // allocate twice the currently allocated memory + list_type * new_array; + + if ( allocation_size == 0 ) + allocation_size = 16; + else + allocation_size *= 2; + + new_array = RakNet::OP_NEW_ARRAY( allocation_size , file, line ); + + if (listArray) + { + // copy old array over + for ( unsigned int counter = 0; counter < list_size; ++counter ) + new_array[ counter ] = listArray[ counter ]; + + // Don't call constructors, assignment operators, etc. + //memcpy(new_array, listArray, list_size*sizeof(list_type)); + + // set old array to point to the newly allocated and twice as large array + RakNet::OP_DELETE_ARRAY(listArray, file, line); + } + + listArray = new_array; + } + + // Insert the new item at the correct spot + listArray[ list_size ] = input; + + ++list_size; + } + + template + inline void List::Replace( const list_type &input, const list_type filler, const unsigned int position, const char *file, unsigned int line ) + { + if ( ( list_size > 0 ) && ( position < list_size ) ) + { + // Direct replacement + listArray[ position ] = input; + } + else + { + if ( position >= allocation_size ) + { + // Reallocate the list to size position and fill in blanks with filler + list_type * new_array; + allocation_size = position + 1; + + new_array = RakNet::OP_NEW_ARRAY( allocation_size , file, line ); + + // copy old array over + + for ( unsigned int counter = 0; counter < list_size; ++counter ) + new_array[ counter ] = listArray[ counter ]; + + // Don't call constructors, assignment operators, etc. + //memcpy(new_array, listArray, list_size*sizeof(list_type)); + + // set old array to point to the newly allocated array + RakNet::OP_DELETE_ARRAY(listArray, file, line); + + listArray = new_array; + } + + // Fill in holes with filler + while ( list_size < position ) + listArray[ list_size++ ] = filler; + + // Fill in the last element with the new item + listArray[ list_size++ ] = input; + +#ifdef _DEBUG + + RakAssert( list_size == position + 1 ); + +#endif + + } + } + + template + inline void List::Replace( const list_type &input ) + { + if ( list_size > 0 ) + listArray[ list_size - 1 ] = input; + } + + template + void List::RemoveAtIndex( const unsigned int position ) + { +#ifdef _DEBUG + if (position >= list_size) + { + RakAssert( position < list_size ); + return; + } +#endif + + if ( position < list_size ) + { + // Compress the array + for ( unsigned int counter = position; counter < list_size - 1 ; ++counter ) + listArray[ counter ] = listArray[ counter + 1 ]; + // Don't call constructors, assignment operators, etc. + // memmove(listArray+position, listArray+position+1, (list_size-1-position) * sizeof(list_type)); + + RemoveFromEnd(); + } + } + + template + void List::RemoveAtIndexFast( const unsigned int position ) + { +#ifdef _DEBUG + if (position >= list_size) + { + RakAssert( position < list_size ); + return; + } +#endif + --list_size; + listArray[position]=listArray[list_size]; + } + + template + inline void List::RemoveFromEnd( const unsigned num ) + { + // Delete the last elements on the list. No compression needed +#ifdef _DEBUG + RakAssert(list_size>=num); +#endif + list_size-=num; + } + + template + unsigned int List::GetIndexOf( const list_type &input ) const + { + for ( unsigned int i = 0; i < list_size; ++i ) + if ( listArray[ i ] == input ) + return i; + + return MAX_UNSIGNED_LONG; + } + + template + inline unsigned int List::Size( void ) const + { + return list_size; + } + + template + void List::Clear( bool doNotDeallocateSmallBlocks, const char *file, unsigned int line ) + { + if ( allocation_size == 0 ) + return; + + if (allocation_size>512 || doNotDeallocateSmallBlocks==false) + { + RakNet::OP_DELETE_ARRAY(listArray, file, line); + allocation_size = 0; + listArray = 0; + } + list_size = 0; + } + + template + void List::Compress( const char *file, unsigned int line ) + { + list_type * new_array; + + if ( allocation_size == 0 ) + return ; + + new_array = RakNet::OP_NEW_ARRAY( allocation_size , file, line ); + + // copy old array over + for ( unsigned int counter = 0; counter < list_size; ++counter ) + new_array[ counter ] = listArray[ counter ]; + + // Don't call constructors, assignment operators, etc. + //memcpy(new_array, listArray, list_size*sizeof(list_type)); + + // set old array to point to the newly allocated array + RakNet::OP_DELETE_ARRAY(listArray, file, line); + + listArray = new_array; + } + + template + void List::Preallocate( unsigned countNeeded, const char *file, unsigned int line ) + { + unsigned amountToAllocate = allocation_size; + if (allocation_size==0) + amountToAllocate=16; + while (amountToAllocate < countNeeded) + amountToAllocate<<=1; + + if ( allocation_size < amountToAllocate) + { + // allocate twice the currently allocated memory + list_type * new_array; + + allocation_size=amountToAllocate; + + new_array = RakNet::OP_NEW_ARRAY< list_type >( allocation_size , file, line ); + + if (listArray) + { + // copy old array over + for ( unsigned int counter = 0; counter < list_size; ++counter ) + new_array[ counter ] = listArray[ counter ]; + + // Don't call constructors, assignment operators, etc. + //memcpy(new_array, listArray, list_size*sizeof(list_type)); + + // set old array to point to the newly allocated and twice as large array + RakNet::OP_DELETE_ARRAY(listArray, file, line); + } + + listArray = new_array; + } + } + +} // End namespace + +#endif diff --git a/include/raknet/DS_Map.hpp b/include/raknet/DS_Map.hpp new file mode 100644 index 0000000..755068b --- /dev/null +++ b/include/raknet/DS_Map.hpp @@ -0,0 +1,335 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_Map.h +/// \internal +/// \brief Map +/// + + +#ifndef __RAKNET_MAP_H +#define __RAKNET_MAP_H + +#include "DS_OrderedList.hpp" +#include "Export.hpp" +#include "RakMemoryOverride.hpp" +#include "RakAssert.hpp" + +// If I want to change this to a red-black tree, this is a good site: http://www.cs.auckland.ac.nz/software/AlgAnim/red_black.html +// This makes insertions and deletions faster. But then traversals are slow, while they are currently fast. + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + /// The default comparison has to be first so it can be called as a default parameter. + /// It then is followed by MapNode, followed by NodeComparisonFunc + template + int defaultMapKeyComparison(const key_type &a, const key_type &b) + { + if (a > + class RAK_DLL_EXPORT Map + { + public: + static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultMapKeyComparison(key_type(),key_type());} + + struct MapNode + { + MapNode() {} + MapNode(key_type _key, data_type _data) : mapNodeKey(_key), mapNodeData(_data) {} + MapNode& operator = ( const MapNode& input ) {mapNodeKey=input.mapNodeKey; mapNodeData=input.mapNodeData; return *this;} + MapNode( const MapNode & input) {mapNodeKey=input.mapNodeKey; mapNodeData=input.mapNodeData;} + key_type mapNodeKey; + data_type mapNodeData; + }; + + // Has to be a static because the comparison callback for DataStructures::OrderedList is a C function + static int NodeComparisonFunc(const key_type &a, const MapNode &b) + { +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + return key_comparison_func(a, b.mapNodeKey); + } + + Map(); + ~Map(); + Map( const Map& original_copy ); + Map& operator= ( const Map& original_copy ); + + data_type& Get(const key_type &key) const; + data_type Pop(const key_type &key); + // Add if needed + void Set(const key_type &key, const data_type &data); + // Must already exist + void SetExisting(const key_type &key, const data_type &data); + // Must add + void SetNew(const key_type &key, const data_type &data); + bool Has(const key_type &key) const; + bool Delete(const key_type &key); + data_type& operator[] ( const unsigned int position ) const; + key_type GetKeyAtIndex( const unsigned int position ) const; + unsigned GetIndexAtKey( const key_type &key ); + void RemoveAtIndex(const unsigned index); + void Clear(void); + unsigned Size(void) const; + + protected: + DataStructures::OrderedList< key_type,MapNode,&Map::NodeComparisonFunc > mapNodeList; + + void SaveLastSearch(const key_type &key, unsigned index) const; + bool HasSavedSearchResult(const key_type &key) const; + + unsigned lastSearchIndex; + key_type lastSearchKey; + bool lastSearchIndexValid; + }; + + template + Map::Map() + { + lastSearchIndexValid=false; + } + + template + Map::~Map() + { + Clear(); + } + + template + Map::Map( const Map& original_copy ) + { + mapNodeList=original_copy.mapNodeList; + lastSearchIndex=original_copy.lastSearchIndex; + lastSearchKey=original_copy.lastSearchKey; + lastSearchIndexValid=original_copy.lastSearchIndexValid; + } + + template + Map& Map::operator= ( const Map& original_copy ) + { + mapNodeList=original_copy.mapNodeList; + lastSearchIndex=original_copy.lastSearchIndex; + lastSearchKey=original_copy.lastSearchKey; + lastSearchIndexValid=original_copy.lastSearchIndexValid; + return *this; + } + + template + data_type& Map::Get(const key_type &key) const + { + if (HasSavedSearchResult(key)) + return mapNodeList[lastSearchIndex].mapNodeData; + + bool objectExists; + unsigned index; + index=mapNodeList.GetIndexFromKey(key, &objectExists); + RakAssert(objectExists); + SaveLastSearch(key,index); + return mapNodeList[index].mapNodeData; + } + + template + unsigned Map::GetIndexAtKey( const key_type &key ) + { + if (HasSavedSearchResult(key)) + return lastSearchIndex; + + bool objectExists; + unsigned index; + index=mapNodeList.GetIndexFromKey(key, &objectExists); + if (objectExists==false) + { + RakAssert(objectExists); + } + SaveLastSearch(key,index); + return index; + } + + template + void Map::RemoveAtIndex(const unsigned index) + { + mapNodeList.RemoveAtIndex(index); + lastSearchIndexValid=false; + } + + template + data_type Map::Pop(const key_type &key) + { + bool objectExists; + unsigned index; + if (HasSavedSearchResult(key)) + index=lastSearchIndex; + else + { + index=mapNodeList.GetIndexFromKey(key, &objectExists); + RakAssert(objectExists); + } + data_type tmp = mapNodeList[index].mapNodeData; + mapNodeList.RemoveAtIndex(index); + lastSearchIndexValid=false; + return tmp; + } + + template + void Map::Set(const key_type &key, const data_type &data) + { + bool objectExists; + unsigned index; + + if (HasSavedSearchResult(key)) + { + mapNodeList[lastSearchIndex].mapNodeData=data; + return; + } + + index=mapNodeList.GetIndexFromKey(key, &objectExists); + + if (objectExists) + { + SaveLastSearch(key,index); + mapNodeList[index].mapNodeData=data; + } + else + { + SaveLastSearch(key,mapNodeList.Insert(key,MapNode(key,data), true, _FILE_AND_LINE_)); + } + } + + template + void Map::SetExisting(const key_type &key, const data_type &data) + { + bool objectExists; + unsigned index; + + if (HasSavedSearchResult(key)) + { + index=lastSearchIndex; + } + else + { + index=mapNodeList.GetIndexFromKey(key, &objectExists); + RakAssert(objectExists); + SaveLastSearch(key,index); + } + + mapNodeList[index].mapNodeData=data; + } + + template + void Map::SetNew(const key_type &key, const data_type &data) + { +#ifdef _DEBUG + bool objectExists; + mapNodeList.GetIndexFromKey(key, &objectExists); + RakAssert(objectExists==false); +#endif + SaveLastSearch(key,mapNodeList.Insert(key,MapNode(key,data), true, _FILE_AND_LINE_)); + } + + template + bool Map::Has(const key_type &key) const + { + if (HasSavedSearchResult(key)) + return true; + + bool objectExists; + unsigned index; + index=mapNodeList.GetIndexFromKey(key, &objectExists); + if (objectExists) + SaveLastSearch(key,index); + return objectExists; + } + + template + bool Map::Delete(const key_type &key) + { + if (HasSavedSearchResult(key)) + { + lastSearchIndexValid=false; + mapNodeList.RemoveAtIndex(lastSearchIndex); + return true; + } + + bool objectExists; + unsigned index; + index=mapNodeList.GetIndexFromKey(key, &objectExists); + if (objectExists) + { + lastSearchIndexValid=false; + mapNodeList.RemoveAtIndex(index); + return true; + } + else + return false; + } + + template + void Map::Clear(void) + { + lastSearchIndexValid=false; + mapNodeList.Clear(false, _FILE_AND_LINE_); + } + + template + data_type& Map::operator[]( const unsigned int position ) const + { + return mapNodeList[position].mapNodeData; + } + + template + key_type Map::GetKeyAtIndex( const unsigned int position ) const + { + return mapNodeList[position].mapNodeKey; + } + + template + unsigned Map::Size(void) const + { + return mapNodeList.Size(); + } + + template + void Map::SaveLastSearch(const key_type &key, const unsigned index) const + { + (void) key; + (void) index; + + /* + lastSearchIndex=index; + lastSearchKey=key; + lastSearchIndexValid=true; + */ + } + + template + bool Map::HasSavedSearchResult(const key_type &key) const + { + (void) key; + + // Not threadsafe! + return false; + // return lastSearchIndexValid && key_comparison_func(key,lastSearchKey)==0; + } +} + +#endif diff --git a/include/raknet/DS_MemoryPool.hpp b/include/raknet/DS_MemoryPool.hpp new file mode 100644 index 0000000..9f5fe1e --- /dev/null +++ b/include/raknet/DS_MemoryPool.hpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_MemoryPool.h +/// + + +#ifndef __MEMORY_POOL_H +#define __MEMORY_POOL_H + +#ifndef __APPLE__ +// Use stdlib and not malloc for compatibility +#include +#endif +#include "RakAssert.hpp" +#include "Export.hpp" + +#include "RakMemoryOverride.hpp" + +// DS_MEMORY_POOL_MAX_FREE_PAGES must be > 1 +#define DS_MEMORY_POOL_MAX_FREE_PAGES 4 + +//#define _DISABLE_MEMORY_POOL + +namespace DataStructures +{ + /// Very fast memory pool for allocating and deallocating structures that don't have constructors or destructors. + /// Contains a list of pages, each of which has an array of the user structures + template + class RAK_DLL_EXPORT MemoryPool + { + public: + struct Page; + struct MemoryWithPage + { + MemoryBlockType userMemory; + Page *parentPage; + }; + struct Page + { + MemoryWithPage** availableStack; + int availableStackSize; + MemoryWithPage* block; + Page *next, *prev; + }; + + MemoryPool(); + ~MemoryPool(); + void SetPageSize(int size); // Defaults to 16384 bytes + MemoryBlockType *Allocate(const char *file, unsigned int line); + void Release(MemoryBlockType *m, const char *file, unsigned int line); + void Clear(const char *file, unsigned int line); + + int GetAvailablePagesSize(void) const {return availablePagesSize;} + int GetUnavailablePagesSize(void) const {return unavailablePagesSize;} + int GetMemoryPoolPageSize(void) const {return memoryPoolPageSize;} + protected: + int BlocksPerPage(void) const; + void AllocateFirst(void); + bool InitPage(Page *page, Page *prev, const char *file, unsigned int line); + + // availablePages contains pages which have room to give the user new blocks. We return these blocks from the head of the list + // unavailablePages are pages which are totally full, and from which we do not return new blocks. + // Pages move from the head of unavailablePages to the tail of availablePages, and from the head of availablePages to the tail of unavailablePages + Page *availablePages, *unavailablePages; + int availablePagesSize, unavailablePagesSize; + int memoryPoolPageSize; + }; + + template + MemoryPool::MemoryPool() + { +#ifndef _DISABLE_MEMORY_POOL + //AllocateFirst(); + availablePagesSize=0; + unavailablePagesSize=0; + memoryPoolPageSize=16384; +#endif + } + template + MemoryPool::~MemoryPool() + { +#ifndef _DISABLE_MEMORY_POOL + Clear(_FILE_AND_LINE_); +#endif + } + + template + void MemoryPool::SetPageSize(int size) + { + memoryPoolPageSize=size; + } + + template + MemoryBlockType* MemoryPool::Allocate(const char *file, unsigned int line) + { +#ifdef _DISABLE_MEMORY_POOL + return (MemoryBlockType*) rakMalloc_Ex(sizeof(MemoryBlockType), file, line); +#else + + if (availablePagesSize>0) + { + MemoryBlockType *retVal; + Page *curPage; + curPage=availablePages; + retVal = (MemoryBlockType*) curPage->availableStack[--(curPage->availableStackSize)]; + if (curPage->availableStackSize==0) + { + --availablePagesSize; + availablePages=curPage->next; + RakAssert(availablePagesSize==0 || availablePages->availableStackSize>0); + curPage->next->prev=curPage->prev; + curPage->prev->next=curPage->next; + + if (unavailablePagesSize++==0) + { + unavailablePages=curPage; + curPage->next=curPage; + curPage->prev=curPage; + } + else + { + curPage->next=unavailablePages; + curPage->prev=unavailablePages->prev; + unavailablePages->prev->next=curPage; + unavailablePages->prev=curPage; + } + } + + RakAssert(availablePagesSize==0 || availablePages->availableStackSize>0); + return retVal; + } + + availablePages = (Page *) rakMalloc_Ex(sizeof(Page), file, line); + if (availablePages==0) + return 0; + availablePagesSize=1; + if (InitPage(availablePages, availablePages, file, line)==false) + return 0; + // If this assert hits, we couldn't allocate even 1 block per page. Increase the page size + RakAssert(availablePages->availableStackSize>1); + + return (MemoryBlockType *) availablePages->availableStack[--availablePages->availableStackSize]; +#endif + } + template + void MemoryPool::Release(MemoryBlockType *m, const char *file, unsigned int line) + { +#ifdef _DISABLE_MEMORY_POOL + rakFree_Ex(m, file, line); + return; +#else + // Find the page this block is in and return it. + Page *curPage; + MemoryWithPage *memoryWithPage = (MemoryWithPage*)m; + curPage=memoryWithPage->parentPage; + + if (curPage->availableStackSize==0) + { + // The page is in the unavailable list so move it to the available list + curPage->availableStack[curPage->availableStackSize++]=memoryWithPage; + unavailablePagesSize--; + + // As this page is no longer totally empty, move it to the end of available pages + curPage->next->prev=curPage->prev; + curPage->prev->next=curPage->next; + + if (unavailablePagesSize>0 && curPage==unavailablePages) + unavailablePages=unavailablePages->next; + + if (availablePagesSize++==0) + { + availablePages=curPage; + curPage->next=curPage; + curPage->prev=curPage; + } + else + { + curPage->next=availablePages; + curPage->prev=availablePages->prev; + availablePages->prev->next=curPage; + availablePages->prev=curPage; + } + } + else + { + curPage->availableStack[curPage->availableStackSize++]=memoryWithPage; + + if (curPage->availableStackSize==BlocksPerPage() && + availablePagesSize>=DS_MEMORY_POOL_MAX_FREE_PAGES) + { + // After a certain point, just deallocate empty pages rather than keep them around + if (curPage==availablePages) + { + availablePages=curPage->next; + RakAssert(availablePages->availableStackSize>0); + } + curPage->prev->next=curPage->next; + curPage->next->prev=curPage->prev; + availablePagesSize--; + rakFree_Ex(curPage->availableStack, file, line ); + rakFree_Ex(curPage->block, file, line ); + rakFree_Ex(curPage, file, line ); + } + } +#endif + } + template + void MemoryPool::Clear(const char *file, unsigned int line) + { +#ifdef _DISABLE_MEMORY_POOL + return; +#else + Page *cur, *freed; + + if (availablePagesSize>0) + { + cur = availablePages; +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + while (true) + // do + { + rakFree_Ex(cur->availableStack, file, line ); + rakFree_Ex(cur->block, file, line ); + freed=cur; + cur=cur->next; + if (cur==availablePages) + { + rakFree_Ex(freed, file, line ); + break; + } + rakFree_Ex(freed, file, line ); + }// while(cur!=availablePages); + } + + if (unavailablePagesSize>0) + { + cur = unavailablePages; + while (1) + //do + { + rakFree_Ex(cur->availableStack, file, line ); + rakFree_Ex(cur->block, file, line ); + freed=cur; + cur=cur->next; + if (cur==unavailablePages) + { + rakFree_Ex(freed, file, line ); + break; + } + rakFree_Ex(freed, file, line ); + } // while(cur!=unavailablePages); + } + + availablePagesSize=0; + unavailablePagesSize=0; +#endif + } + template + int MemoryPool::BlocksPerPage(void) const + { + return memoryPoolPageSize / sizeof(MemoryWithPage); + } + template + bool MemoryPool::InitPage(Page *page, Page *prev, const char *file, unsigned int line) + { + int i=0; + const int bpp = BlocksPerPage(); + page->block=(MemoryWithPage*) rakMalloc_Ex(memoryPoolPageSize, file, line); + if (page->block==0) + return false; + page->availableStack=(MemoryWithPage**)rakMalloc_Ex(sizeof(MemoryWithPage*)*bpp, file, line); + if (page->availableStack==0) + { + rakFree_Ex(page->block, file, line ); + return false; + } + MemoryWithPage *curBlock = page->block; + MemoryWithPage **curStack = page->availableStack; + while (i < bpp) + { + curBlock->parentPage=page; + curStack[i]=curBlock++; + i++; + } + page->availableStackSize=bpp; + page->next=availablePages; + page->prev=prev; + return true; + } +} + +#endif + +/* +#include "DS_MemoryPool.hpp" +#include "DS_List.hpp" + +struct TestMemoryPool +{ + int allocationId; +}; + +int main(void) +{ + DataStructures::MemoryPool memoryPool; + DataStructures::List returnList; + + for (int i=0; i < 100000; i++) + returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); + for (int i=0; i < returnList.Size(); i+=2) + { + memoryPool.Release(returnList[i], _FILE_AND_LINE_); + returnList.RemoveAtIndexFast(i); + } + for (int i=0; i < 100000; i++) + returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); + while (returnList.Size()) + { + memoryPool.Release(returnList[returnList.Size()-1], _FILE_AND_LINE_); + returnList.RemoveAtIndex(returnList.Size()-1); + } + for (int i=0; i < 100000; i++) + returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); + while (returnList.Size()) + { + memoryPool.Release(returnList[returnList.Size()-1], _FILE_AND_LINE_); + returnList.RemoveAtIndex(returnList.Size()-1); + } + for (int i=0; i < 100000; i++) + returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); + for (int i=100000-1; i <= 0; i-=2) + { + memoryPool.Release(returnList[i], _FILE_AND_LINE_); + returnList.RemoveAtIndexFast(i); + } + for (int i=0; i < 100000; i++) + returnList.Push(memoryPool.Allocate(_FILE_AND_LINE_), _FILE_AND_LINE_); + while (returnList.Size()) + { + memoryPool.Release(returnList[returnList.Size()-1], _FILE_AND_LINE_); + returnList.RemoveAtIndex(returnList.Size()-1); + } + + return 0; +} +*/ diff --git a/include/raknet/DS_Multilist.hpp b/include/raknet/DS_Multilist.hpp new file mode 100644 index 0000000..f2c7be2 --- /dev/null +++ b/include/raknet/DS_Multilist.hpp @@ -0,0 +1,1650 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_Multilist.h +/// \internal +/// \brief ADT that can represent an unordered list, ordered list, stack, or queue with a common interface +/// + +#ifndef __MULTILIST_H +#define __MULTILIST_H + +#include "RakAssert.hpp" +#include // memmove +#include "Export.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" + + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#pragma warning( disable : 4512 ) // warning C4512: assignment operator could not be generated +#endif + +/// What algorithm to use to store the data for the Multilist +enum MultilistType +{ + /// Removing from the middle of the list will swap the end of the list rather than shift the elements. Push and Pop operate on the tail. + ML_UNORDERED_LIST, + /// A normal list, with the list order preserved. Push and Pop operate on the tail. + ML_STACK, + /// A queue. Push and Pop operate on the head + ML_QUEUE, + /// A list that is always kept in order. Elements must be unique, and compare against each other consistently using <, ==, and > + ML_ORDERED_LIST, + /// A list whose type can change at runtime + ML_VARIABLE_DURING_RUNTIME +}; + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + /// Can be used with Multilist::ForEach + /// Assuming the Multilist holds pointers, will delete those pointers + template + void DeletePtr_RakNet(templateType &ptr, const char *file, unsigned int line ) {RakNet::OP_DELETE(ptr, file, line);} + + /// Can be used with Multilist::ForEach + /// Assuming the Multilist holds pointers, will delete those pointers + template + void DeletePtr(templateType &ptr) {delete ptr;} + + /// The following is invalid. + /// bool operator<( const MyClass *myClass, const int &inputKey ) {return myClass->value < inputKey;} + /// At least one type has to be a reference to a class + /// MLKeyRef is a helper class to turn a native type into a class, so you can compare that native type against a pointer to a different class + /// Used for he Multilist, when _DataType != _KeyType + template < class templateType > + class MLKeyRef + { + public: + MLKeyRef(const templateType& input) : val(input) {} + const templateType &Get(void) const {return val;} + bool operator<( const templateType &right ) {return val < right;} + bool operator>( const templateType &right ) {return val > right;} + bool operator==( const templateType &right ) {return val == right;} + protected: + const templateType &val; + }; + + /// For the Multilist, when _DataType != _KeyType, you must define the comparison operators between the key and the data + /// This is non-trivial due to the need to use MLKeyRef in case the type held is a pointer to a structure or class and the key type is not a class + /// For convenience, this macro will implement the comparison operators under the following conditions + /// 1. _DataType is a pointer to a class or structure + /// 2. The key is a member variable of _DataType + #define DEFINE_MULTILIST_PTR_TO_MEMBER_COMPARISONS( _CLASS_NAME_, _KEY_TYPE_, _MEMBER_VARIABLE_NAME_ ) \ + bool operator<( const DataStructures::MLKeyRef<_KEY_TYPE_> &inputKey, const _CLASS_NAME_ *cls ) {return inputKey.Get() < cls->_MEMBER_VARIABLE_NAME_;} \ + bool operator>( const DataStructures::MLKeyRef<_KEY_TYPE_> &inputKey, const _CLASS_NAME_ *cls ) {return inputKey.Get() > cls->_MEMBER_VARIABLE_NAME_;} \ + bool operator==( const DataStructures::MLKeyRef<_KEY_TYPE_> &inputKey, const _CLASS_NAME_ *cls ) {return inputKey.Get() == cls->_MEMBER_VARIABLE_NAME_;} + + typedef uint32_t DefaultIndexType; + + /// \brief The multilist, representing an abstract data type that generally holds lists. + /// \param[in] _MultilistType What type of list this is, \sa MultilistType + /// \param[in] _DataType What type of data this list holds. + /// \param[in] _KeyType If a function takes a key to sort on, what type of key this is. The comparison operator between _DataType and _KeyType must be defined + /// \param[in] _IndexType What variable type to use for indices + template + class RAK_DLL_EXPORT Multilist + { + public: + Multilist(); + ~Multilist(); + Multilist( const Multilist& source ); + Multilist& operator= ( const Multilist& source ); + _DataType& operator[] ( const _IndexType position ) const; + /// Unordered list, stack is LIFO + /// QUEUE is FIFO + /// Ordered list is inserted in order + void Push(const _DataType &d, const char *file=__FILE__, unsigned int line=__LINE__ ); + void Push(const _DataType &d, const _KeyType &key, const char *file=__FILE__, unsigned int line=__LINE__ ); + + /// \brief Gets or removes and gets an element from the list, according to the same rules as Push(). + /// Ordered list is LIFO for the purposes of Pop and Peek. + _DataType &Pop(const char *file=__FILE__, unsigned int line=__LINE__); + _DataType &Peek(void) const; + + /// \brief Same as Push(), except FIFO and LIFO are reversed. + /// Ordered list still inserts in order. + void PushOpposite(const _DataType &d, const char *file=__FILE__, unsigned int line=__LINE__ ); + void PushOpposite(const _DataType &d, const _KeyType &key, const char *file=__FILE__, unsigned int line=__LINE__ ); + + /// \brief Same as Pop() and Peek(), except FIFO and LIFO are reversed. + _DataType &PopOpposite(const char *file=__FILE__, unsigned int line=__LINE__); + _DataType &PeekOpposite(void) const; + + /// \brief Stack,Queue: Inserts at index indicated, elements are shifted. + /// Ordered list: Inserts, position is ignored + void InsertAtIndex(const _DataType &d, _IndexType index, const char *file=__FILE__, unsigned int line=__LINE__); + + /// \brief Unordered list, removes at index indicated, swaps last element with that element. + /// Otherwise, array is shifted left to overwrite removed element + /// \details Index[0] returns the same as Pop() for a queue. + /// Same as PopOpposite() for the list and ordered list + void RemoveAtIndex(_IndexType position, const char *file=__FILE__, unsigned int line=__LINE__); + + /// \brief Find the index of \a key, and remove at that index. + bool RemoveAtKey(_KeyType key, bool assertIfDoesNotExist, const char *file=__FILE__, unsigned int line=__LINE__); + + /// \brief Finds the index of \a key. Return -1 if the key is not found. + _IndexType GetIndexOf(_KeyType key) const; + + /// \brief Returns where in the list we should insert the item, to preserve list order. + /// Returns -1 if the item is already in the list + _IndexType GetInsertionIndex(_KeyType key) const; + + /// \brief Finds the index of \a key. Return 0 if the key is not found. Useful if _DataType is always non-zero pointers. + _DataType GetPtr(_KeyType key) const; + + /// \brief Iterate over the list, calling the function pointer on each element. + void ForEach(void (*func)(_DataType &item, const char *file, unsigned int line), const char *file, unsigned int line); + void ForEach(void (*func)(_DataType &item)); + + /// \brief Returns if the list is empty. + bool IsEmpty(void) const; + + /// \brief Returns the number of elements used in the list. + _IndexType GetSize(void) const; + + /// \brief Empties the list. The list is not deallocated if it is small, + /// unless \a deallocateSmallBlocks is true + void Clear( bool deallocateSmallBlocks=true, const char *file=__FILE__, unsigned int line=__LINE__ ); + + /// \brief Empties the list, first calling RakNet::OP_Delete on all items. + /// \details The list is not deallocated if it is small, unless \a deallocateSmallBlocks is true + void ClearPointers( bool deallocateSmallBlocks=true, const char *file=__FILE__, unsigned int line=__LINE__ ); + + /// \brief Empty one item from the list, first calling RakNet::OP_Delete on that item. + void ClearPointer( _KeyType key, const char *file=__FILE__, unsigned int line=__LINE__ ); + + /// \brief Reverses the elements in the list, and flips the sort order + /// returned by GetSortOrder() if IsSorted() returns true at the time the function is called + void ReverseList(void); + + /// \brief Reallocates the list to a larger size. + /// If \a size is smaller than the value returned by GetSize(), the call does nothing. + void Reallocate(_IndexType size, const char *file=__FILE__, unsigned int line=__LINE__); + + /// \brief Sorts the list unless it is an ordered list, in which it does nothing as the list is assumed to already be sorted. + /// \details However, if \a force is true, it will also resort the ordered list, useful if the comparison operator between _KeyType and _DataType would now return different results + /// Once the list is sorted, further operations to lookup by key will be log2(n) until the list is modified + void Sort(bool force); + + /// \brief Sets the list to be remembered as sorted. + /// \details Optimization if the source is sorted already + void TagSorted(void); + + /// \brief Defaults to ascending. + /// \details Used by Sort(), and by ML_ORDERED_LIST + void SetSortOrder(bool ascending); + + /// \brief Returns true if ascending. + bool GetSortOrder(void) const; + + /// \brief Returns true if the list is currently believed to be in a sorted state. + /// \details Doesn't actually check for sortedness, just if Sort() + /// was recently called, or MultilistType is ML_ORDERED_LIST + bool IsSorted(void) const; + + /// Returns what type of list this is + MultilistType GetMultilistType(void) const; + + /// \brief Changes what type of list this is. + /// \pre Template must be defined with ML_VARIABLE_DURING_RUNTIME for this to do anything + /// \param[in] mlType Any value of the enum MultilistType, except ML_VARIABLE_DURING_RUNTIME + void SetMultilistType(MultilistType newType); + + /// \brief Returns the intersection of two lists. + /// Intersection is items common to both lists. + static void FindIntersection( + Multilist& source1, + Multilist& source2, + Multilist& intersection, + Multilist& uniqueToSource1, + Multilist& uniqueToSource2); + + protected: + void ReallocateIfNeeded(const char *file, unsigned int line); + void DeallocateIfNeeded(const char *file, unsigned int line); + void ReallocToSize(_IndexType newAllocationSize, const char *file, unsigned int line); + void ReverseListInternal(void); + void InsertInOrderedList(const _DataType &d, const _KeyType &key); + _IndexType GetIndexFromKeyInSortedList(const _KeyType &key, bool *objectExists) const; + void InsertShiftArrayRight(const _DataType &d, _IndexType index); + void DeleteShiftArrayLeft(_IndexType index); + void QSortAscending(_IndexType left, _IndexType right); + void QSortDescending(_IndexType left, _IndexType right); + void CopySource( const Multilist& source ); + + /// An array of user values + _DataType* data; + + /// Number of elements in the list + _IndexType dataSize; + + /// Size of \a array + _IndexType allocationSize; + + /// Array index for the head of the queue + _IndexType queueHead; + + /// Array index for the tail of the queue + _IndexType queueTail; + + /// How many bytes the user chose to preallocate + /// Won't automatically deallocate below this + _IndexType preallocationSize; + + enum + { + ML_UNSORTED, + ML_SORTED_ASCENDING, + ML_SORTED_DESCENDING + } sortState; + + bool ascendingSort; + + // In case we are using the variable type multilist + MultilistType variableMultilistType; + }; + + template + Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Multilist() + { + data=0; + dataSize=0; + allocationSize=0; + ascendingSort=true; + sortState=ML_UNSORTED; + queueHead=0; + queueTail=0; + preallocationSize=0; + + if (_MultilistType==ML_ORDERED_LIST) + sortState=ML_SORTED_ASCENDING; + else + sortState=ML_UNSORTED; + + if (_MultilistType==ML_VARIABLE_DURING_RUNTIME) + variableMultilistType=ML_UNORDERED_LIST; + } + + template + Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::~Multilist() + { + if (data!=0) + RakNet::OP_DELETE_ARRAY(data, _FILE_AND_LINE_); + } + + template + Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Multilist( const Multilist& source ) + { + CopySource(source); + } + + template + Multilist<_MultilistType, _DataType, _KeyType, _IndexType>& Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::operator= ( const Multilist& source ) + { + Clear(true); + CopySource(source); + return *this; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::CopySource( const Multilist& source ) + { + dataSize=source.GetSize(); + ascendingSort=source.ascendingSort; + sortState=source.sortState; + queueHead=0; + queueTail=dataSize; + preallocationSize=source.preallocationSize; + variableMultilistType=source.variableMultilistType; + if (source.data==0) + { + data=0; + allocationSize=0; + } + else + { + allocationSize=dataSize; + data = RakNet::OP_NEW_ARRAY<_DataType>(dataSize,_FILE_AND_LINE_); + _IndexType i; + for (i=0; i < dataSize; i++) + data[i]=source[i]; + } + } + + template + _DataType& Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::operator[] ( const _IndexType position ) const + { + RakAssert(position= allocationSize ) + return data[ queueHead + position - allocationSize ]; + else + return data[ queueHead + position ]; + } + + return data[position]; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Push(const _DataType &d, const char *file, unsigned int line ) + { + Push(d,d,file,line); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Push(const _DataType &d, const _KeyType &key, const char *file, unsigned int line ) + { + ReallocateIfNeeded(file,line); + + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK) + { + data[dataSize]=d; + dataSize++; + } + else if (GetMultilistType()==ML_QUEUE) + { + data[queueTail++] = d; + + if ( queueTail == allocationSize ) + queueTail = 0; + dataSize++; + } + else + { + RakAssert(GetMultilistType()==ML_ORDERED_LIST); + InsertInOrderedList(d,key); + } + + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_QUEUE) + { + // Break sort if no longer sorted + if (sortState!=ML_UNSORTED && dataSize>1) + { + if (ascendingSort) + { + if ( MLKeyRef<_KeyType>(key) < operator[](dataSize-2) ) + sortState=ML_UNSORTED; + } + else + { + if ( MLKeyRef<_KeyType>(key) > operator[](dataSize-2) ) + sortState=ML_UNSORTED; + } + + sortState=ML_UNSORTED; + } + } + } + + template + _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Pop(const char *file, unsigned int line) + { + RakAssert(IsEmpty()==false); + DeallocateIfNeeded(file,line); + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) + { + dataSize--; + return data[dataSize]; + } + else + { + RakAssert(GetMultilistType()==ML_QUEUE); + + if ( ++queueHead == allocationSize ) + queueHead = 0; + + if ( queueHead == 0 ) + return data[ allocationSize -1 ]; + + dataSize--; + return data[ queueHead -1 ]; + } + } + + template + _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Peek(void) const + { + RakAssert(IsEmpty()==false); + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) + { + return data[dataSize-1]; + } + else + { + RakAssert(GetMultilistType()==ML_QUEUE); + return data[ queueHead ]; + } + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PushOpposite(const _DataType &d, const char *file, unsigned int line ) + { + PushOpposite(d,d,file,line); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PushOpposite(const _DataType &d, const _KeyType &key, const char *file, unsigned int line ) + { + ReallocateIfNeeded(file,line); + + // Unordered list Push at back + if (GetMultilistType()==ML_UNORDERED_LIST) + { + data[dataSize]=d; + dataSize++; + } + else if (GetMultilistType()==ML_STACK) + { + // Stack push at front of the list, instead of back as normal + InsertAtIndex(d,0,file,line); + } + else if (GetMultilistType()==ML_QUEUE) + { + // Queue push at front of the list, instead of back as normal + InsertAtIndex(d,0,file,line); + } + else + { + RakAssert(GetMultilistType()==ML_ORDERED_LIST); + InsertInOrderedList(d,key); + } + + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_QUEUE) + { + // Break sort if no longer sorted + if (sortState!=ML_UNSORTED && dataSize>1) + { + if (ascendingSort) + { + if ( MLKeyRef<_KeyType>(key) > operator[](1) ) + sortState=ML_UNSORTED; + } + else + { + if ( MLKeyRef<_KeyType>(key) < operator[](1) ) + sortState=ML_UNSORTED; + } + } + } + } + + template + _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PopOpposite(const char *file, unsigned int line) + { + RakAssert(IsEmpty()==false); + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) + { + // Copy leftmost to end + ReallocateIfNeeded(file,line); + data[dataSize]=data[0]; + DeleteShiftArrayLeft(0); + --dataSize; + // Assuming still leaves at least one element past the end of the list allocated + DeallocateIfNeeded(file,line); + // Return end + return data[dataSize+1]; + } + else + { + RakAssert(GetMultilistType()==ML_QUEUE); + // Deallocate first, since we are returning off the existing list + DeallocateIfNeeded(file,line); + dataSize--; + + if (queueTail==0) + queueTail=allocationSize-1; + else + --queueTail; + + return data[queueTail]; + } + } + + template + _DataType &Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::PeekOpposite(void) const + { + RakAssert(IsEmpty()==false); + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) + { + return data[0]; + } + else + { + RakAssert(GetMultilistType()==ML_QUEUE); + _IndexType priorIndex; + if (queueTail==0) + priorIndex=allocationSize-1; + else + priorIndex=queueTail-1; + + return data[priorIndex]; + } + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::InsertAtIndex(const _DataType &d, _IndexType index, const char *file, unsigned int line) + { + ReallocateIfNeeded(file,line); + + if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) + { + if (index>=dataSize) + { + // insert at end + data[dataSize]=d; + + dataSize++; + } + else + { + // insert at index + InsertShiftArrayRight(d,index); + } + } + else + { + data[queueTail++] = d; + + if ( queueTail == allocationSize ) + queueTail = 0; + + ++dataSize; + + if (dataSize==1) + return; + + _IndexType writeIndex, readIndex, trueWriteIndex, trueReadIndex; + writeIndex=dataSize-1; + readIndex=writeIndex-1; + while (readIndex >= index) + { + if ( queueHead + writeIndex >= allocationSize ) + trueWriteIndex = queueHead + writeIndex - allocationSize; + else + trueWriteIndex = queueHead + writeIndex; + + if ( queueHead + readIndex >= allocationSize ) + trueReadIndex = queueHead + readIndex - allocationSize; + else + trueReadIndex = queueHead + readIndex; + + data[trueWriteIndex]=data[trueReadIndex]; + + if (readIndex==0) + break; + writeIndex--; + readIndex--; + } + + if ( queueHead + index >= allocationSize ) + trueWriteIndex = queueHead + index - allocationSize; + else + trueWriteIndex = queueHead + index; + + data[trueWriteIndex]=d; + } + + if (_MultilistType!=ML_ORDERED_LIST) + sortState=ML_UNSORTED; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::RemoveAtIndex(_IndexType position, const char *file, unsigned int line) + { + RakAssert(position < dataSize); + RakAssert(IsEmpty()==false); + + if (GetMultilistType()==ML_UNORDERED_LIST) + { + // Copy tail to current + data[position]=data[dataSize-1]; + } + else if (GetMultilistType()==ML_STACK || GetMultilistType()==ML_ORDERED_LIST) + { + DeleteShiftArrayLeft(position); + } + else + { + RakAssert(GetMultilistType()==ML_QUEUE); + + _IndexType index, next; + + if ( queueHead + position >= allocationSize ) + index = queueHead + position - allocationSize; + else + index = queueHead + position; + + next = index + 1; + + if ( next == allocationSize ) + next = 0; + + while ( next != queueTail ) + { + // Overwrite the previous element + data[ index ] = data[ next ]; + index = next; + //next = (next + 1) % allocationSize; + + if ( ++next == allocationSize ) + next = 0; + } + + // Move the queueTail back + if ( queueTail == 0 ) + queueTail = allocationSize - 1; + else + --queueTail; + } + + + dataSize--; + DeallocateIfNeeded(file,line); + } + + template + bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::RemoveAtKey(_KeyType key, bool assertIfDoesNotExist, const char *file, unsigned int line) + { + _IndexType index = GetIndexOf(key); + if (index==(_IndexType)-1) + { + RakAssert(assertIfDoesNotExist==false && "RemoveAtKey element not found"); + return false; + } + RemoveAtIndex(index,file,line); + return true; + } + + template + _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetIndexOf(_KeyType key) const + { + _IndexType i; + if (IsSorted()) + { + bool objectExists; + i=GetIndexFromKeyInSortedList(key, &objectExists); + if (objectExists) + return i; + return (_IndexType)-1; + } + else if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK) + { + for (i=0; i < dataSize; i++) + { + if (MLKeyRef<_KeyType>(key)==data[i]) + return i; + } + return (_IndexType)-1; + } + else + { + RakAssert( GetMultilistType()==ML_QUEUE ); + + for (i=0; i < dataSize; i++) + { + if (MLKeyRef<_KeyType>(key)==operator[](i)) + return i; + } + return (_IndexType)-1; + } + } + + template + _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetInsertionIndex(_KeyType key) const + { + _IndexType i; + if (IsSorted()) + { + bool objectExists; + i=GetIndexFromKeyInSortedList(key, &objectExists); + if (objectExists) + return (_IndexType)-1; + return i; + } + else if (GetMultilistType()==ML_UNORDERED_LIST || GetMultilistType()==ML_STACK) + { + for (i=0; i < dataSize; i++) + { + if (MLKeyRef<_KeyType>(key)==data[i]) + return (_IndexType)-1; + } + return dataSize; + } + else + { + RakAssert( GetMultilistType()==ML_QUEUE ); + + for (i=0; i < dataSize; i++) + { + if (MLKeyRef<_KeyType>(key)==operator[](i)) + return (_IndexType)-1; + } + return dataSize; + } + } + + template + _DataType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetPtr(_KeyType key) const + { + _IndexType i = GetIndexOf(key); + if (i==(_IndexType)-1) + return 0; + return data[i]; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ForEach(void (*func)(_DataType &item, const char *file, unsigned int line), const char *file, unsigned int line) + { + _IndexType i; + for (i=0; i < dataSize; i++) + func(operator[](i), file, line); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ForEach(void (*func)(_DataType &item)) + { + _IndexType i; + for (i=0; i < dataSize; i++) + func(operator[](i)); + } + + template + bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::IsEmpty(void) const + { + return dataSize==0; + } + + template + _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetSize(void) const + { + return dataSize; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Clear( bool deallocateSmallBlocks, const char *file, unsigned int line ) + { + dataSize=0; + if (GetMultilistType()==ML_ORDERED_LIST) + if (ascendingSort) + sortState=ML_SORTED_ASCENDING; + else + sortState=ML_SORTED_DESCENDING; + else + sortState=ML_UNSORTED; + queueHead=0; + queueTail=0; + + if (deallocateSmallBlocks && allocationSize < 128 && data) + { + RakNet::OP_DELETE_ARRAY(data,file,line); + data=0; + allocationSize=0; + } + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ClearPointers( bool deallocateSmallBlocks, const char *file, unsigned int line ) + { + _IndexType i; + for (i=0; i < dataSize; i++) + RakNet::OP_DELETE(operator[](i), file, line); + Clear(deallocateSmallBlocks, file, line); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ClearPointer( _KeyType key, const char *file, unsigned int line ) + { + _IndexType i; + i = GetIndexOf(key); + if (i!=-1) + { + RakNet::OP_DELETE(operator[](i), file, line); + RemoveAtIndex(i); + } + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReverseList(void) + { + if (IsSorted()) + ascendingSort=!ascendingSort; + + ReverseListInternal(); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Reallocate(_IndexType size, const char *file, unsigned int line) + { + _IndexType newAllocationSize; + if (size < dataSize) + newAllocationSize=dataSize; + else + newAllocationSize=size; + preallocationSize=size; + ReallocToSize(newAllocationSize,file,line); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::Sort(bool force) + { + if (IsSorted() && force==false) + return; + + if (dataSize>1) + { + if (ascendingSort) + QSortAscending(0,dataSize-1); + else + QSortDescending(0,dataSize-1); + } + + TagSorted(); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::TagSorted(void) + { + if (ascendingSort) + sortState=ML_SORTED_ASCENDING; + else + sortState=ML_SORTED_DESCENDING; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::QSortAscending(_IndexType leftEdge, _IndexType rightEdge) + { + _DataType temp; + _IndexType left=leftEdge; + _IndexType right=rightEdge; + _IndexType pivotIndex=left++; + + while (left data[pivotIndex]) + { + --left; + + data[pivotIndex]=data[left]; + data[left]=temp; + } + else + { + data[pivotIndex]=data[left]; + data[left]=temp; + + --left; + } + + if (left!=leftEdge) + QSortAscending(leftEdge, left); + + if (right!=rightEdge) + QSortAscending(right, rightEdge); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::QSortDescending(_IndexType leftEdge, _IndexType rightEdge) + { + _DataType temp; + _IndexType left=leftEdge; + _IndexType right=rightEdge; + _IndexType pivotIndex=left++; + + while (left= data[pivotIndex]) + { + ++left; + } + else + { + temp=data[left]; + data[left]=data[right]; + data[right]=temp; + --right; + } + } + + temp=data[pivotIndex]; + + // Move pivot to center + if (data[left] < data[pivotIndex]) + { + --left; + + data[pivotIndex]=data[left]; + data[left]=temp; + } + else + { + data[pivotIndex]=data[left]; + data[left]=temp; + + --left; + } + + if (left!=leftEdge) + QSortDescending(leftEdge, left); + + if (right!=rightEdge) + QSortDescending(right, rightEdge); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::SetSortOrder(bool ascending) + { + if (ascendingSort!=ascending && IsSorted()) + { + ascendingSort=ascending; + // List is sorted, and the sort order has changed. So reverse the list + ReverseListInternal(); + } + else + ascendingSort=ascending; + } + + template + bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetSortOrder(void) const + { + return ascendingSort; + } + + template + bool Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::IsSorted(void) const + { + return GetMultilistType()==ML_ORDERED_LIST || sortState!=ML_UNSORTED; + } + + template + MultilistType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetMultilistType(void) const + { + if (_MultilistType==ML_VARIABLE_DURING_RUNTIME) + return variableMultilistType; + return _MultilistType; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::SetMultilistType(MultilistType newType) + { + RakAssert(_MultilistType==ML_VARIABLE_DURING_RUNTIME); + switch (variableMultilistType) + { + case ML_UNORDERED_LIST: + switch (newType) + { + case ML_UNORDERED_LIST: + // No change + break; + case ML_STACK: + // Same data format + break; + case ML_QUEUE: + queueHead=0; + queueTail=dataSize; + break; + case ML_ORDERED_LIST: + Sort(false); + break; + } + break; + case ML_STACK: + switch (newType) + { + case ML_UNORDERED_LIST: + // Same data format + break; + case ML_STACK: + // No change + break; + case ML_QUEUE: + queueHead=0; + queueTail=dataSize; + break; + case ML_ORDERED_LIST: + Sort(false); + break; + } + break; + case ML_QUEUE: + switch (newType) + { + case ML_UNORDERED_LIST: + case ML_STACK: + case ML_ORDERED_LIST: + if (queueTail < queueHead) + { + // Realign data if wrapped + ReallocToSize(dataSize, _FILE_AND_LINE_); + } + else + { + // Else can just copy starting at head + _IndexType i; + for (i=0; i < dataSize; i++) + data[i]=operator[](i); + } + if (newType==ML_ORDERED_LIST) + Sort(false); + break; + case ML_QUEUE: + // No change + break; + } + break; + case ML_ORDERED_LIST: + switch (newType) + { + case ML_UNORDERED_LIST: + case ML_STACK: + case ML_QUEUE: + // Same data format + // Tag as sorted + if (ascendingSort) + sortState=ML_SORTED_ASCENDING; + else + sortState=ML_SORTED_DESCENDING; + if (newType==ML_QUEUE) + { + queueHead=0; + queueTail=dataSize; + } + break; + case ML_ORDERED_LIST: + // No change + break; + } + break; + } + + variableMultilistType=newType; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::FindIntersection( + Multilist& source1, + Multilist& source2, + Multilist& intersection, + Multilist& uniqueToSource1, + Multilist& uniqueToSource2) + { + _IndexType index1=0, index2=0; + source1.SetSortOrder(true); + source2.SetSortOrder(true); + source1.Sort(false); + source2.Sort(false); + intersection.Clear(true,_FILE_AND_LINE_); + uniqueToSource1.Clear(true,_FILE_AND_LINE_); + uniqueToSource2.Clear(true,_FILE_AND_LINE_); + + while (index1 < source1.GetSize() && index2 < source2.GetSize()) + { + if (source1[index1] + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReallocateIfNeeded(const char *file, unsigned int line) + { + if (dataSize65536) + newAllocationSize=allocationSize+65536; + else + { + newAllocationSize=allocationSize<<1; // * 2 + // Protect against underflow + if (newAllocationSize < allocationSize) + newAllocationSize=allocationSize+65536; + } + + ReallocToSize(newAllocationSize,file,line); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::DeallocateIfNeeded(const char *file, unsigned int line) + { + if (allocationSize<512) + return; + if (dataSize >= allocationSize/3 ) + return; + if (dataSize <= preallocationSize ) + return; + + _IndexType newAllocationSize = dataSize<<1; // * 2 + + ReallocToSize(newAllocationSize,file,line); + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReallocToSize(_IndexType newAllocationSize, const char *file, unsigned int line) + { + _DataType* newData = RakNet::OP_NEW_ARRAY<_DataType>(newAllocationSize,file,line); + _IndexType i; + for (i=0; i < dataSize; i++) + newData[i]=operator[](i); + if (dataSize>0) + { + RakNet::OP_DELETE_ARRAY(data,file,line); + if (GetMultilistType()==ML_QUEUE) + { + queueHead=0; + queueTail=dataSize; + } + } + data=newData; + allocationSize=newAllocationSize; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::ReverseListInternal(void) + { + _DataType temp; + _IndexType i; + for (i=0; i < dataSize/2; i++) + { + temp=operator[](i); + operator[](i)=operator[](dataSize-1-i); + operator[](dataSize-1-i)=temp; + } + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::InsertInOrderedList(const _DataType &d, const _KeyType &key) + { + RakAssert(GetMultilistType()==ML_ORDERED_LIST); + + bool objectExists; + _IndexType index; + index = GetIndexFromKeyInSortedList(key, &objectExists); + + // if (objectExists) + // { + // Ordered list only allows unique insertions + // RakAssert("Duplicate insertion into ordered list" && false); + // return; + // } + + if (index>=dataSize) + { + // insert at end + data[dataSize]=d; + dataSize++; + } + else + { + // insert at index + InsertShiftArrayRight(d,index); + } + } + + template + _IndexType Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::GetIndexFromKeyInSortedList(const _KeyType &key, bool *objectExists) const + { + RakAssert(IsSorted()); + _IndexType index, upperBound, lowerBound; + + if (dataSize==0) + { + *objectExists=false; + return 0; + } + + upperBound=dataSize-1; + lowerBound=0; + index = dataSize/2; + +#ifdef _MSC_VER + #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + if (MLKeyRef<_KeyType>(key) > operator[](index) ) + { + if (ascendingSort) + lowerBound=index+1; + else + upperBound=index-1; + } + else if (MLKeyRef<_KeyType>(key) < operator[](index) ) + { + if (ascendingSort) + upperBound=index-1; + else + lowerBound=index+1; + } + else + { + // == + *objectExists=true; + return index; + } + + index=lowerBound+(upperBound-lowerBound)/2; + + if (lowerBound>upperBound || upperBound==(_IndexType)-1) + { + *objectExists=false; + return lowerBound; // No match + } + } + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::InsertShiftArrayRight(const _DataType &d, _IndexType index) + { + RakAssert(_MultilistType!=ML_QUEUE); + + // Move the elements in the list to make room + _IndexType i; + for ( i = dataSize; i != index; i-- ) + data[ i ] = data[ i - 1 ]; + + // Insert the new item at the correct spot + data[ index ] = d; + + ++dataSize; + } + + template + void Multilist<_MultilistType, _DataType, _KeyType, _IndexType>::DeleteShiftArrayLeft( _IndexType index ) + { + RakAssert(index < dataSize); + RakAssert(_MultilistType!=ML_QUEUE); + + _IndexType i; + for ( i = index; i < dataSize-1; i++ ) + data[i]=data[i+1]; + } +}; + +/* +struct KeyAndValue +{ + int key; + short value; +}; + +DEFINE_MULTILIST_PTR_TO_MEMBER_COMPARISONS(KeyAndValue,int,key) + +void MultilistUnitTest(void) +{ + DataStructures::DefaultIndexType oldSize; + DataStructures::Multilist ml1; + ml1.Reallocate(64); + RakAssert(ml1.IsEmpty()); + ml1.Push(53); + RakAssert(ml1.Peek()==53); + RakAssert(ml1.IsEmpty()==false); + RakAssert(ml1.Pop()==53); + RakAssert(ml1.IsEmpty()==true); + for (int i=0; i < 512; i++) + ml1.Push(i); + RakAssert(ml1.GetIndexOf(200)==200); + RakAssert(ml1.PeekOpposite()==0); + RakAssert(ml1.PopOpposite()==0); + RakAssert(ml1.PeekOpposite()==1); + RakAssert(ml1.Peek()==511); + ml1.ReverseList(); + for (int i=0; i < 511; i++) + RakAssert(ml1[i]==511-i); + RakAssert(ml1.PeekOpposite()==511); + RakAssert(ml1.Peek()==1); + oldSize = ml1.GetSize(); + ml1.RemoveAtIndex(0); + RakAssert(ml1.GetSize()==oldSize-1); + RakAssert(ml1.PeekOpposite()==1); + ml1.Clear(_FILE_AND_LINE_); + RakAssert(ml1.IsEmpty()==true); + + ml1.Sort(true); + ml1.Clear(_FILE_AND_LINE_); + + ml1.Push(100); + ml1.Sort(true); + ml1.Clear(_FILE_AND_LINE_); + + ml1.Push(50); + ml1.Push(100); + ml1.Sort(true); + ml1.Clear(_FILE_AND_LINE_); + + ml1.Push(100); + ml1.Push(50); + ml1.Sort(true); + ml1.Clear(_FILE_AND_LINE_); + + ml1.Push(100); + ml1.Push(50); + ml1.Push(150); + ml1.Push(25); + ml1.Push(175); + ml1.Sort(true); + RakAssert(ml1[0]==25); + RakAssert(ml1[1]==50); + RakAssert(ml1[2]==100); + RakAssert(ml1[3]==150); + RakAssert(ml1[4]==175); + RakAssert(ml1.GetIndexOf(25)==0); + RakAssert(ml1.GetIndexOf(50)==1); + RakAssert(ml1.GetIndexOf(100)==2); + RakAssert(ml1.GetIndexOf(150)==3); + RakAssert(ml1.GetIndexOf(175)==4); + ml1.Clear(_FILE_AND_LINE_); + + ml1.Push(1); + ml1.Push(2); + ml1.Push(3); + ml1.Push(4); + ml1.Push(5); + ml1.Sort(true); + RakAssert(ml1[0]==1); + RakAssert(ml1[1]==2); + RakAssert(ml1[2]==3); + RakAssert(ml1[3]==4); + RakAssert(ml1[4]==5); + RakAssert(ml1.GetIndexOf(1)==0); + RakAssert(ml1.GetIndexOf(2)==1); + RakAssert(ml1.GetIndexOf(3)==2); + RakAssert(ml1.GetIndexOf(4)==3); + RakAssert(ml1.GetIndexOf(5)==4); + ml1.Clear(_FILE_AND_LINE_); + + ml1.Push(5); + ml1.Push(4); + ml1.Push(3); + ml1.Push(2); + ml1.Push(1); + ml1.Sort(true); + RakAssert(ml1[0]==1); + RakAssert(ml1[1]==2); + RakAssert(ml1[2]==3); + RakAssert(ml1[3]==4); + RakAssert(ml1[4]==5); + RakAssert(ml1.GetIndexOf(1)==0); + RakAssert(ml1.GetIndexOf(2)==1); + RakAssert(ml1.GetIndexOf(3)==2); + RakAssert(ml1.GetIndexOf(4)==3); + RakAssert(ml1.GetIndexOf(5)==4); + ml1.Sort(true); + RakAssert(ml1[0]==1); + RakAssert(ml1[1]==2); + RakAssert(ml1[2]==3); + RakAssert(ml1[3]==4); + RakAssert(ml1[4]==5); + RakAssert(ml1.GetIndexOf(1)==0); + RakAssert(ml1.GetIndexOf(2)==1); + RakAssert(ml1.GetIndexOf(3)==2); + RakAssert(ml1.GetIndexOf(4)==3); + RakAssert(ml1.GetIndexOf(5)==4); + ml1.Clear(_FILE_AND_LINE_); + + DataStructures::Multilist ml2; + ml2.Reallocate(64); + RakAssert(ml2.IsEmpty()); + ml2.Push(53); + RakAssert(ml2.Peek()==53); + RakAssert(ml2.IsEmpty()==false); + RakAssert(ml2.Pop()==53); + RakAssert(ml2.IsEmpty()==true); + for (int i=0; i < 512; i++) + ml2.Push(i); + RakAssert(ml2.GetIndexOf(200)==200); + RakAssert(ml2.PeekOpposite()==0); + RakAssert(ml2.PopOpposite()==0); + RakAssert(ml2.PeekOpposite()==1); + RakAssert(ml2.Peek()==511); + ml2.ReverseList(); + for (int i=0; i < 511; i++) + RakAssert(ml2[i]==511-i); + RakAssert(ml2.PeekOpposite()==511); + RakAssert(ml2.Peek()==1); + oldSize = ml2.GetSize(); + ml2.RemoveAtIndex(0); + RakAssert(ml2.GetSize()==oldSize-1); + RakAssert(ml2.Peek()==1); + RakAssert(ml2.PeekOpposite()==510); + ml2.Clear(_FILE_AND_LINE_); + RakAssert(ml2.IsEmpty()==true); + + DataStructures::Multilist ml3; + RakAssert(ml3.IsEmpty()); + ml3.Push(53); + RakAssert(ml3.Peek()==53); + RakAssert(ml3.IsEmpty()==false); + RakAssert(ml3.Pop()==53); + RakAssert(ml3.IsEmpty()==true); + for (int i=0; i < 512; i++) + ml3.Push(i); + RakAssert(ml3.GetIndexOf(200)==200); + RakAssert(ml3.PeekOpposite()==511); + RakAssert(ml3.PopOpposite()==511); + RakAssert(ml3.PeekOpposite()==510); + RakAssert(ml3.Peek()==0); + ml3.ReverseList(); + for (int i=0; i < 511; i++) + RakAssert(ml3[i]==511-1-i); + RakAssert(ml3.PeekOpposite()==0); + RakAssert(ml3.Peek()==510); + oldSize = ml3.GetSize(); + ml3.RemoveAtIndex(0); + RakAssert(ml3.GetSize()==oldSize-1); + RakAssert(ml3.Peek()==509); + RakAssert(ml3.PeekOpposite()==0); + ml3.Clear(_FILE_AND_LINE_); + RakAssert(ml3.IsEmpty()==true); + + ml3.PushOpposite(100); + ml3.PushOpposite(50); + ml3.PushOpposite(150); + ml3.PushOpposite(25); + ml3.PushOpposite(175); + ml3.Sort(true); + RakAssert(ml3[0]==25); + RakAssert(ml3[1]==50); + RakAssert(ml3[2]==100); + RakAssert(ml3[3]==150); + RakAssert(ml3[4]==175); + RakAssert(ml3.GetIndexOf(25)==0); + RakAssert(ml3.GetIndexOf(50)==1); + RakAssert(ml3.GetIndexOf(100)==2); + RakAssert(ml3.GetIndexOf(150)==3); + RakAssert(ml3.GetIndexOf(175)==4); + ml3.Clear(_FILE_AND_LINE_); + + ml3.PushOpposite(1); + ml3.PushOpposite(2); + ml3.PushOpposite(3); + ml3.PushOpposite(4); + ml3.PushOpposite(5); + ml3.Sort(true); + RakAssert(ml3[0]==1); + RakAssert(ml3[1]==2); + RakAssert(ml3[2]==3); + RakAssert(ml3[3]==4); + RakAssert(ml3[4]==5); + RakAssert(ml3.GetIndexOf(1)==0); + RakAssert(ml3.GetIndexOf(2)==1); + RakAssert(ml3.GetIndexOf(3)==2); + RakAssert(ml3.GetIndexOf(4)==3); + RakAssert(ml3.GetIndexOf(5)==4); + ml3.Clear(_FILE_AND_LINE_); + + ml3.PushOpposite(5); + ml3.PushOpposite(4); + ml3.PushOpposite(3); + ml3.PushOpposite(2); + ml3.PushOpposite(1); + ml3.Sort(true); + RakAssert(ml3[0]==1); + RakAssert(ml3[1]==2); + RakAssert(ml3[2]==3); + RakAssert(ml3[3]==4); + RakAssert(ml3[4]==5); + RakAssert(ml3.GetIndexOf(1)==0); + RakAssert(ml3.GetIndexOf(2)==1); + RakAssert(ml3.GetIndexOf(3)==2); + RakAssert(ml3.GetIndexOf(4)==3); + RakAssert(ml3.GetIndexOf(5)==4); + ml3.Sort(true); + RakAssert(ml3[0]==1); + RakAssert(ml3[1]==2); + RakAssert(ml3[2]==3); + RakAssert(ml3[3]==4); + RakAssert(ml3[4]==5); + RakAssert(ml3.GetIndexOf(1)==0); + RakAssert(ml3.GetIndexOf(2)==1); + RakAssert(ml3.GetIndexOf(3)==2); + RakAssert(ml3.GetIndexOf(4)==3); + RakAssert(ml3.GetIndexOf(5)==4); + + ml3.SetSortOrder(false); + ml3.Sort(false); + RakAssert(ml3[0]==5); + RakAssert(ml3[1]==4); + RakAssert(ml3[2]==3); + RakAssert(ml3[3]==2); + RakAssert(ml3[4]==1); + RakAssert(ml3.GetIndexOf(1)==4); + RakAssert(ml3.GetIndexOf(2)==3); + RakAssert(ml3.GetIndexOf(3)==2); + RakAssert(ml3.GetIndexOf(4)==1); + RakAssert(ml3.GetIndexOf(5)==0); + + ml3.Clear(_FILE_AND_LINE_); + + DataStructures::Multilist ml4; + ml4.Reallocate(64); + RakAssert(ml4.IsEmpty()); + ml4.Push(53); + RakAssert(ml4.Peek()==53); + RakAssert(ml4.IsEmpty()==false); + RakAssert(ml4.Pop()==53); + RakAssert(ml4.IsEmpty()==true); + for (int i=0; i < 512; i++) + ml4.Push(i); + RakAssert(ml4.GetIndexOf(200)==200); + RakAssert(ml4.PeekOpposite()==0); + RakAssert(ml4.PopOpposite()==0); + RakAssert(ml4.PeekOpposite()==1); + RakAssert(ml4.Peek()==511); + ml4.ReverseList(); + for (int i=0; i < 511; i++) + RakAssert(ml4[i]==511-i); + RakAssert(ml4.PeekOpposite()==511); + RakAssert(ml4.Peek()==1); + oldSize = ml4.GetSize(); + ml4.RemoveAtIndex(0); + RakAssert(ml4.GetSize()==oldSize-1); + RakAssert(ml4.Peek()==1); + RakAssert(ml4.PeekOpposite()==510); + ml4.Clear(_FILE_AND_LINE_); + RakAssert(ml4.IsEmpty()==true); + + DataStructures::Multilist ml5; + + for (int i=0; i < 16; i++) + { + KeyAndValue *kav = new KeyAndValue; + kav->key=i; + kav->value=i+100; + ml5.Push(kav,kav->key); + } + + RakAssert(ml5.GetIndexOf(0)==0); + RakAssert(ml5.GetIndexOf(5)==5); + RakAssert(ml5.GetIndexOf(15)==15); + RakAssert(ml5.GetIndexOf(16)==-1); + ml5.RemoveAtKey(0,true); + RakAssert(ml5.GetIndexOf(1)==0); + KeyAndValue *iPtr = ml5.GetPtr(5); + RakAssert(iPtr); + RakAssert(iPtr->value=105); + iPtr = ml5.GetPtr(1234); + RakAssert(iPtr==0); + ml5.ForEach(DataStructures::DeletePtr); + + + DataStructures::Multilist ml6; + ml6.Push(2); + ml6.Push(1); + ml6.Push(6); + ml6.Push(3); + RakAssert(ml6.Peek()==3); + ml6.SetMultilistType(ML_STACK); + RakAssert(ml6.Peek()==3); + ml6.SetMultilistType(ML_QUEUE); + RakAssert(ml6.Peek()==2); + ml6.SetMultilistType(ML_ORDERED_LIST); + RakAssert(ml6.Peek()=6); + ml6.SetMultilistType(ML_STACK); + RakAssert(ml6.Peek()==6); + ml6.SetMultilistType(ML_QUEUE); + RakAssert(ml6.Peek()==1); +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif +*/ + +#endif diff --git a/include/raknet/DS_OrderedChannelHeap.hpp b/include/raknet/DS_OrderedChannelHeap.hpp new file mode 100644 index 0000000..ba82d24 --- /dev/null +++ b/include/raknet/DS_OrderedChannelHeap.hpp @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_OrderedChannelHeap.h +/// \internal +/// \brief Ordered Channel Heap . This is a heap where you add to it on multiple ordered channels, with each channel having a different weight. +/// + + +#ifndef __RAKNET_ORDERED_CHANNEL_HEAP_H +#define __RAKNET_ORDERED_CHANNEL_HEAP_H + +#include "DS_Heap.hpp" +#include "DS_Map.hpp" +#include "DS_Queue.hpp" +#include "Export.hpp" +#include "RakAssert.hpp" +#include "Rand.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + template > + class RAK_DLL_EXPORT OrderedChannelHeap + { + public: + static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultMapKeyComparison(channel_key_type(),channel_key_type());} + + OrderedChannelHeap(); + ~OrderedChannelHeap(); + void Push(const channel_key_type &channelID, const heap_data_type &data); + void PushAtHead(const unsigned index, const channel_key_type &channelID, const heap_data_type &data); + heap_data_type Pop(const unsigned startingIndex=0); + heap_data_type Peek(const unsigned startingIndex) const; + void AddChannel(const channel_key_type &channelID, const double weight); + void RemoveChannel(channel_key_type channelID); + void Clear(void); + heap_data_type& operator[] ( const unsigned int position ) const; + unsigned ChannelSize(const channel_key_type &channelID); + unsigned Size(void) const; + + struct QueueAndWeight + { + DataStructures::Queue randResultQueue; + double weight; + bool signalDeletion; + }; + + struct HeapChannelAndData + { + HeapChannelAndData() {} + HeapChannelAndData(const channel_key_type &_channel, const heap_data_type &_data) : data(_data), channel(_channel) {} + heap_data_type data; + channel_key_type channel; + }; + + protected: + DataStructures::Map map; + DataStructures::Heap heap; + void GreatestRandResult(void); + }; + + template + OrderedChannelHeap::OrderedChannelHeap() + { + } + + template + OrderedChannelHeap::~OrderedChannelHeap() + { + Clear(); + } + + template + void OrderedChannelHeap::Push(const channel_key_type &channelID, const heap_data_type &data) + { + PushAtHead(MAX_UNSIGNED_LONG, channelID, data); + } + + template + void OrderedChannelHeap::GreatestRandResult(void) + { + double greatest; + unsigned i; + greatest=0.0; + for (i=0; i < map.Size(); i++) + { + if (map[i]->randResultQueue.Size() && map[i]->randResultQueue[0]>greatest) + greatest=map[i]->randResultQueue[0]; + } + return greatest; + } + + template + void OrderedChannelHeap::PushAtHead(const unsigned index, const channel_key_type &channelID, const heap_data_type &data) + { + // If an assert hits here then this is an unknown channel. Call AddChannel first. + QueueAndWeight *queueAndWeight=map.Get(channelID); + double maxRange, minRange, rnd; + if (queueAndWeight->randResultQueue.Size()==0) + { + // Set maxRange to the greatest random number waiting to be returned, rather than 1.0 necessarily + // This is so weights are scaled similarly among channels. For example, if the head weight for a used channel was .25 + // and then we added another channel, the new channel would need to choose between .25 and 0 + // If we chose between 1.0 and 0, it would be 1/.25 (4x) more likely to be at the head of the heap than it should be + maxRange=GreatestRandResult(); + if (maxRange==0.0) + maxRange=1.0; + minRange=0.0; + } + else if (index >= queueAndWeight->randResultQueue.Size()) + { + maxRange=queueAndWeight->randResultQueue[queueAndWeight->randResultQueue.Size()-1]*.99999999; + minRange=0.0; + } + else + { + if (index==0) + { + maxRange=GreatestRandResult(); + if (maxRange==queueAndWeight->randResultQueue[0]) + maxRange=1.0; + } + else if (index >= queueAndWeight->randResultQueue.Size()) + maxRange=queueAndWeight->randResultQueue[queueAndWeight->randResultQueue.Size()-1]*.99999999; + else + maxRange=queueAndWeight->randResultQueue[index-1]*.99999999; + + minRange=maxRange=queueAndWeight->randResultQueue[index]*1.00000001; + } + +#ifdef _DEBUG + RakAssert(maxRange!=0.0); +#endif + rnd=frandomMT() * (maxRange - minRange); + if (rnd==0.0) + rnd=maxRange/2.0; + + if (index >= queueAndWeight->randResultQueue.Size()) + queueAndWeight->randResultQueue.Push(rnd); + else + queueAndWeight->randResultQueue.PushAtHead(rnd, index); + + heap.Push(rnd*queueAndWeight->weight, HeapChannelAndData(channelID, data)); + } + + template + heap_data_type OrderedChannelHeap::Pop(const unsigned startingIndex) + { + RakAssert(startingIndex < heap.Size()); + + QueueAndWeight *queueAndWeight=map.Get(heap[startingIndex].channel); + if (startingIndex!=0) + { + // Ugly - have to count in the heap how many nodes have the same channel, so we know where to delete from in the queue + unsigned indiceCount=0; + unsigned i; + for (i=0; i < startingIndex; i++) + if (channel_key_comparison_func(heap[i].channel,heap[startingIndex].channel)==0) + indiceCount++; + queueAndWeight->randResultQueue.RemoveAtIndex(indiceCount); + } + else + { + // TODO - ordered channel heap uses progressively lower values as items are inserted. But this won't give relative ordering among channels. I have to renormalize after every pop. + queueAndWeight->randResultQueue.Pop(); + } + + // Try to remove the channel after every pop, because doing so is not valid while there are elements in the list. + if (queueAndWeight->signalDeletion) + RemoveChannel(heap[startingIndex].channel); + + return heap.Pop(startingIndex).data; + } + + template + heap_data_type OrderedChannelHeap::Peek(const unsigned startingIndex) const + { + HeapChannelAndData heapChannelAndData = heap.Peek(startingIndex); + return heapChannelAndData.data; + } + + template + void OrderedChannelHeap::AddChannel(const channel_key_type &channelID, const double weight) + { + QueueAndWeight *qaw = RakNet::OP_NEW( _FILE_AND_LINE_ ); + qaw->weight=weight; + qaw->signalDeletion=false; + map.SetNew(channelID, qaw); + } + + template + void OrderedChannelHeap::RemoveChannel(channel_key_type channelID) + { + if (map.Has(channelID)) + { + unsigned i; + i=map.GetIndexAtKey(channelID); + if (map[i]->randResultQueue.Size()==0) + { + RakNet::OP_DELETE(map[i], _FILE_AND_LINE_); + map.RemoveAtIndex(i); + } + else + { + // Signal this channel for deletion later, because the heap has nodes with this channel right now + map[i]->signalDeletion=true; + } + } + } + + template + unsigned OrderedChannelHeap::Size(void) const + { + return heap.Size(); + } + + template + heap_data_type& OrderedChannelHeap::operator[]( const unsigned int position ) const + { + return heap[position].data; + } + + + template + unsigned OrderedChannelHeap::ChannelSize(const channel_key_type &channelID) + { + QueueAndWeight *queueAndWeight=map.Get(channelID); + return queueAndWeight->randResultQueue.Size(); + } + + template + void OrderedChannelHeap::Clear(void) + { + unsigned i; + for (i=0; i < map.Size(); i++) + RakNet::OP_DELETE(map[i], _FILE_AND_LINE_); + map.Clear(_FILE_AND_LINE_); + heap.Clear(_FILE_AND_LINE_); + } +} + +#endif diff --git a/include/raknet/DS_OrderedList.hpp b/include/raknet/DS_OrderedList.hpp new file mode 100644 index 0000000..0aa1fa7 --- /dev/null +++ b/include/raknet/DS_OrderedList.hpp @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_OrderedList.h +/// \internal +/// \brief Quicksort ordered list. +/// + +#include "DS_List.hpp" +#include "RakMemoryOverride.hpp" +#include "Export.hpp" + +#ifndef __ORDERED_LIST_H +#define __ORDERED_LIST_H + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + template + int defaultOrderedListComparison(const key_type &a, const data_type &b) + { + if (a > + class RAK_DLL_EXPORT OrderedList + { + public: + static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultOrderedListComparison(key_type(),data_type());} + + OrderedList(); + ~OrderedList(); + OrderedList( const OrderedList& original_copy ); + OrderedList& operator= ( const OrderedList& original_copy ); + + /// comparisonFunction must take a key_type and a data_type and return <0, ==0, or >0 + /// If the data type has comparison operators already defined then you can just use defaultComparison + bool HasData(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; + // GetIndexFromKey returns where the insert should go at the same time checks if it is there + unsigned GetIndexFromKey(const key_type &key, bool *objectExists, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; + data_type GetElementFromKey(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; + bool GetElementFromKey(const key_type &key, data_type &element, int (*cf)(const key_type&, const data_type&)=default_comparison_function) const; + unsigned Insert(const key_type &key, const data_type &data, bool assertOnDuplicate, const char *file, unsigned int line, int (*cf)(const key_type&, const data_type&)=default_comparison_function); + unsigned Remove(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function); + unsigned RemoveIfExists(const key_type &key, int (*cf)(const key_type&, const data_type&)=default_comparison_function); + data_type& operator[] ( const unsigned int position ) const; + void RemoveAtIndex(const unsigned index); + void InsertAtIndex(const data_type &data, const unsigned index, const char *file, unsigned int line); + void InsertAtEnd(const data_type &data, const char *file, unsigned int line); + void RemoveFromEnd(const unsigned num=1); + void Clear(bool doNotDeallocate, const char *file, unsigned int line); + unsigned Size(void) const; + + protected: + DataStructures::List orderedList; + }; + + template + OrderedList::OrderedList() + { + } + + template + OrderedList::~OrderedList() + { + Clear(false, _FILE_AND_LINE_); + } + + template + OrderedList::OrderedList( const OrderedList& original_copy ) + { + orderedList=original_copy.orderedList; + } + + template + OrderedList& OrderedList::operator= ( const OrderedList& original_copy ) + { + orderedList=original_copy.orderedList; + return *this; + } + + template + bool OrderedList::HasData(const key_type &key, int (*cf)(const key_type&, const data_type&)) const + { + bool objectExists; + GetIndexFromKey(key, &objectExists, cf); + return objectExists; + } + + template + data_type OrderedList::GetElementFromKey(const key_type &key, int (*cf)(const key_type&, const data_type&)) const + { + bool objectExists; + unsigned index; + index = GetIndexFromKey(key, &objectExists, cf); + RakAssert(objectExists); + return orderedList[index]; + } + template + bool OrderedList::GetElementFromKey(const key_type &key, data_type &element, int (*cf)(const key_type&, const data_type&)) const + { + bool objectExists; + unsigned index; + index = GetIndexFromKey(key, &objectExists, cf); + if (objectExists) + element = orderedList[index]; + return objectExists; + } + template + unsigned OrderedList::GetIndexFromKey(const key_type &key, bool *objectExists, int (*cf)(const key_type&, const data_type&)) const + { + int index, upperBound, lowerBound; + int res; + + if (orderedList.Size()==0) + { + *objectExists=false; + return 0; + } + + upperBound=(int)orderedList.Size()-1; + lowerBound=0; + index = (int)orderedList.Size()/2; + +#ifdef _MSC_VER + #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + res = cf(key,orderedList[index]); + if (res==0) + { + *objectExists=true; + return (unsigned)index; + } + else if (res<0) + { + upperBound=index-1; + } + else// if (res>0) + { + + lowerBound=index+1; + } + + index=lowerBound+(upperBound-lowerBound)/2; + + if (lowerBound>upperBound) + { + *objectExists=false; + return (unsigned)lowerBound; // No match + } + + if (index < 0 || index >= (int) orderedList.Size()) + { + // This should never hit unless the comparison function was inconsistent + RakAssert(index && 0); + *objectExists=false; + return 0; + } + } + } + + template + unsigned OrderedList::Insert(const key_type &key, const data_type &data, bool assertOnDuplicate, const char *file, unsigned int line, int (*cf)(const key_type&, const data_type&)) + { + (void) assertOnDuplicate; + bool objectExists; + unsigned index; + index = GetIndexFromKey(key, &objectExists, cf); + + // Don't allow duplicate insertion. + if (objectExists) + { + // This is usually a bug! + RakAssert(assertOnDuplicate==false); + return (unsigned)-1; + } + + if (index>=orderedList.Size()) + { + orderedList.Insert(data, file, line); + return orderedList.Size()-1; + } + else + { + orderedList.Insert(data,index, file, line); + return index; + } + } + + template + unsigned OrderedList::Remove(const key_type &key, int (*cf)(const key_type&, const data_type&)) + { + bool objectExists; + unsigned index; + index = GetIndexFromKey(key, &objectExists, cf); + + // Can't find the element to remove if this assert hits + // RakAssert(objectExists==true); + if (objectExists==false) + { + RakAssert(objectExists==true); + return 0; + } + + orderedList.RemoveAtIndex(index); + return index; + } + + template + unsigned OrderedList::RemoveIfExists(const key_type &key, int (*cf)(const key_type&, const data_type&)) + { + bool objectExists; + unsigned index; + index = GetIndexFromKey(key, &objectExists, cf); + + // Can't find the element to remove if this assert hits + if (objectExists==false) + return 0; + + orderedList.RemoveAtIndex(index); + return index; + } + + template + void OrderedList::RemoveAtIndex(const unsigned index) + { + orderedList.RemoveAtIndex(index); + } + + template + void OrderedList::InsertAtIndex(const data_type &data, const unsigned index, const char *file, unsigned int line) + { + orderedList.Insert(data, index, file, line); + } + + template + void OrderedList::InsertAtEnd(const data_type &data, const char *file, unsigned int line) + { + orderedList.Insert(data, file, line); + } + + template + void OrderedList::RemoveFromEnd(const unsigned num) + { + orderedList.RemoveFromEnd(num); + } + + template + void OrderedList::Clear(bool doNotDeallocate, const char *file, unsigned int line) + { + orderedList.Clear(doNotDeallocate, file, line); + } + + template + data_type& OrderedList::operator[]( const unsigned int position ) const + { + return orderedList[position]; + } + + template + unsigned OrderedList::Size(void) const + { + return orderedList.Size(); + } +} + +#endif diff --git a/include/raknet/DS_Queue.hpp b/include/raknet/DS_Queue.hpp new file mode 100644 index 0000000..f623df7 --- /dev/null +++ b/include/raknet/DS_Queue.hpp @@ -0,0 +1,461 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_Queue.h +/// \internal +/// \brief A queue used by RakNet. +/// + + +#ifndef __QUEUE_H +#define __QUEUE_H + +// Template classes have to have all the code in the header file +#include "RakAssert.hpp" +#include "Export.hpp" +#include "RakMemoryOverride.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + /// \brief A queue implemented as an array with a read and write index. + template + class RAK_DLL_EXPORT Queue + { + public: + Queue(); + ~Queue(); + Queue( Queue& original_copy ); + bool operator= ( const Queue& original_copy ); + void Push( const queue_type& input, const char *file, unsigned int line ); + void PushAtHead( const queue_type& input, unsigned index, const char *file, unsigned int line ); + queue_type& operator[] ( unsigned int position ) const; // Not a normal thing you do with a queue but can be used for efficiency + void RemoveAtIndex( unsigned int position ); // Not a normal thing you do with a queue but can be used for efficiency + inline queue_type Peek( void ) const; + inline queue_type PeekTail( void ) const; + inline queue_type Pop( void ); + inline queue_type PopTail( void ); + // Debug: Set pointer to 0, for memory leak detection + inline queue_type PopDeref( void ); + inline unsigned int Size( void ) const; + inline bool IsEmpty(void) const; + inline unsigned int AllocationSize( void ) const; + inline void Clear( const char *file, unsigned int line ); + void Compress( const char *file, unsigned int line ); + bool Find ( const queue_type& q ); + void ClearAndForceAllocation( int size, const char *file, unsigned int line ); // Force a memory allocation to a certain larger size + + private: + queue_type* array; + unsigned int head; // Array index for the head of the queue + unsigned int tail; // Array index for the tail of the queue + unsigned int allocation_size; + }; + + + template + inline unsigned int Queue::Size( void ) const + { + if ( head <= tail ) + return tail -head; + else + return allocation_size -head + tail; + } + + template + inline bool Queue::IsEmpty(void) const + { + return head==tail; + } + + template + inline unsigned int Queue::AllocationSize( void ) const + { + return allocation_size; + } + + template + Queue::Queue() + { + //allocation_size = 16; + //array = RakNet::OP_NEW_ARRAY(allocation_size, _FILE_AND_LINE_ ); + allocation_size = 0; + array=0; + head = 0; + tail = 0; + } + + template + Queue::~Queue() + { + if (allocation_size>0) + RakNet::OP_DELETE_ARRAY(array, _FILE_AND_LINE_); + } + + template + inline queue_type Queue::Pop( void ) + { +#ifdef _DEBUG + RakAssert( head != tail); +#endif + //head=(head+1) % allocation_size; + + if ( ++head == allocation_size ) + head = 0; + + if ( head == 0 ) + return ( queue_type ) array[ allocation_size -1 ]; + + return ( queue_type ) array[ head -1 ]; + } + + template + inline queue_type Queue::PopTail( void ) + { +#ifdef _DEBUG + RakAssert( head != tail ); +#endif + if (tail!=0) + { + --tail; + return ( queue_type ) array[ tail ]; + } + else + { + tail=allocation_size-1; + return ( queue_type ) array[ tail ]; + } + } + + template + inline queue_type Queue::PopDeref( void ) + { + if ( ++head == allocation_size ) + head = 0; + + queue_type q; + if ( head == 0 ) + { + q=array[ allocation_size -1 ]; + array[ allocation_size -1 ]=0; + return q; + } + + q=array[ head -1 ]; + array[ head -1 ]=0; + return q; + } + + template + void Queue::PushAtHead( const queue_type& input, unsigned index, const char *file, unsigned int line ) + { + RakAssert(index <= Size()); + + // Just force a reallocation, will be overwritten + Push(input, file, line ); + + if (Size()==1) + return; + + unsigned writeIndex, readIndex, trueWriteIndex, trueReadIndex; + writeIndex=Size()-1; + readIndex=writeIndex-1; + while (readIndex >= index) + { + if ( head + writeIndex >= allocation_size ) + trueWriteIndex = head + writeIndex - allocation_size; + else + trueWriteIndex = head + writeIndex; + + if ( head + readIndex >= allocation_size ) + trueReadIndex = head + readIndex - allocation_size; + else + trueReadIndex = head + readIndex; + + array[trueWriteIndex]=array[trueReadIndex]; + + if (readIndex==0) + break; + writeIndex--; + readIndex--; + } + + if ( head + index >= allocation_size ) + trueWriteIndex = head + index - allocation_size; + else + trueWriteIndex = head + index; + + array[trueWriteIndex]=input; + } + + + template + inline queue_type Queue::Peek( void ) const + { +#ifdef _DEBUG + RakAssert( head != tail ); +#endif + + return ( queue_type ) array[ head ]; + } + + template + inline queue_type Queue::PeekTail( void ) const + { +#ifdef _DEBUG + RakAssert( head != tail ); +#endif + if (tail!=0) + return ( queue_type ) array[ tail-1 ]; + else + return ( queue_type ) array[ allocation_size-1 ]; + } + + template + void Queue::Push( const queue_type& input, const char *file, unsigned int line ) + { + if ( allocation_size == 0 ) + { + array = RakNet::OP_NEW_ARRAY(16, file, line ); + head = 0; + tail = 1; + array[ 0 ] = input; + allocation_size = 16; + return ; + } + + array[ tail++ ] = input; + + if ( tail == allocation_size ) + tail = 0; + + if ( tail == head ) + { + // unsigned int index=tail; + + // Need to allocate more memory. + queue_type * new_array; + new_array = RakNet::OP_NEW_ARRAY((int)allocation_size * 2, file, line ); +#ifdef _DEBUG + RakAssert( new_array ); +#endif + if (new_array==0) + return; + + for ( unsigned int counter = 0; counter < allocation_size; ++counter ) + new_array[ counter ] = array[ ( head + counter ) % ( allocation_size ) ]; + + head = 0; + + tail = allocation_size; + + allocation_size *= 2; + + // Delete the old array and move the pointer to the new array + RakNet::OP_DELETE_ARRAY(array, file, line); + + array = new_array; + } + + } + + template + Queue::Queue( Queue& original_copy ) + { + // Allocate memory for copy + + if ( original_copy.Size() == 0 ) + { + allocation_size = 0; + } + + else + { + array = RakNet::OP_NEW_ARRAY( original_copy.Size() + 1 , _FILE_AND_LINE_ ); + + for ( unsigned int counter = 0; counter < original_copy.Size(); ++counter ) + array[ counter ] = original_copy.array[ ( original_copy.head + counter ) % ( original_copy.allocation_size ) ]; + + head = 0; + + tail = original_copy.Size(); + + allocation_size = original_copy.Size() + 1; + } + } + + template + bool Queue::operator= ( const Queue& original_copy ) + { + if ( ( &original_copy ) == this ) + return false; + + Clear(_FILE_AND_LINE_); + + // Allocate memory for copy + if ( original_copy.Size() == 0 ) + { + allocation_size = 0; + } + + else + { + array = RakNet::OP_NEW_ARRAY( original_copy.Size() + 1 , _FILE_AND_LINE_ ); + + for ( unsigned int counter = 0; counter < original_copy.Size(); ++counter ) + array[ counter ] = original_copy.array[ ( original_copy.head + counter ) % ( original_copy.allocation_size ) ]; + + head = 0; + + tail = original_copy.Size(); + + allocation_size = original_copy.Size() + 1; + } + + return true; + } + + template + inline void Queue::Clear ( const char *file, unsigned int line ) + { + if ( allocation_size == 0 ) + return ; + + if (allocation_size > 32) + { + RakNet::OP_DELETE_ARRAY(array, file, line); + allocation_size = 0; + } + + head = 0; + tail = 0; + } + + template + void Queue::Compress ( const char *file, unsigned int line ) + { + queue_type* new_array; + unsigned int newAllocationSize; + if (allocation_size==0) + return; + + newAllocationSize=1; + while (newAllocationSize <= Size()) + newAllocationSize<<=1; // Must be a better way to do this but I'm too dumb to figure it out quickly :) + + new_array = RakNet::OP_NEW_ARRAY(newAllocationSize, file, line ); + + for (unsigned int counter=0; counter < Size(); ++counter) + new_array[counter] = array[(head + counter)%(allocation_size)]; + + tail=Size(); + allocation_size=newAllocationSize; + head=0; + + // Delete the old array and move the pointer to the new array + RakNet::OP_DELETE_ARRAY(array, file, line); + array=new_array; + } + + template + bool Queue::Find ( const queue_type &q ) + { + if ( allocation_size == 0 ) + return false; + + unsigned int counter = head; + + while ( counter != tail ) + { + if ( array[ counter ] == q ) + return true; + + counter = ( counter + 1 ) % allocation_size; + } + + return false; + } + + template + void Queue::ClearAndForceAllocation( int size, const char *file, unsigned int line ) + { + RakNet::OP_DELETE_ARRAY(array, file, line); + if (size>0) + array = RakNet::OP_NEW_ARRAY(size, file, line ); + else + array=0; + allocation_size = size; + head = 0; + tail = 0; + } + + template + inline queue_type& Queue::operator[] ( unsigned int position ) const + { +#ifdef _DEBUG + RakAssert( position < Size() ); +#endif + //return array[(head + position) % allocation_size]; + + if ( head + position >= allocation_size ) + return array[ head + position - allocation_size ]; + else + return array[ head + position ]; + } + + template + void Queue::RemoveAtIndex( unsigned int position ) + { +#ifdef _DEBUG + RakAssert( position < Size() ); + RakAssert( head != tail ); +#endif + + if ( head == tail || position >= Size() ) + return ; + + unsigned int index; + + unsigned int next; + + //index = (head + position) % allocation_size; + if ( head + position >= allocation_size ) + index = head + position - allocation_size; + else + index = head + position; + + //next = (index + 1) % allocation_size; + next = index + 1; + + if ( next == allocation_size ) + next = 0; + + while ( next != tail ) + { + // Overwrite the previous element + array[ index ] = array[ next ]; + index = next; + //next = (next + 1) % allocation_size; + + if ( ++next == allocation_size ) + next = 0; + } + + // Move the tail back + if ( tail == 0 ) + tail = allocation_size - 1; + else + --tail; + } +} // End namespace + +#endif + diff --git a/include/raknet/DS_QueueLinkedList.hpp b/include/raknet/DS_QueueLinkedList.hpp new file mode 100644 index 0000000..eea8f0c --- /dev/null +++ b/include/raknet/DS_QueueLinkedList.hpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_QueueLinkedList.h +/// \internal +/// \brief A queue implemented as a linked list. +/// + + +#ifndef __QUEUE_LINKED_LIST_H +#define __QUEUE_LINKED_LIST_H + +#include "DS_LinkedList.hpp" +#include "Export.hpp" +#include "RakMemoryOverride.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + /// \brief A queue implemented using a linked list. Rarely used. + template + class RAK_DLL_EXPORT QueueLinkedList + { + + public: + QueueLinkedList(); + QueueLinkedList( const QueueLinkedList& original_copy ); + bool operator= ( const QueueLinkedList& original_copy ); + QueueType Pop( void ); + QueueType& Peek( void ); + QueueType& EndPeek( void ); + void Push( const QueueType& input ); + unsigned int Size( void ); + void Clear( void ); + void Compress( void ); + + private: + LinkedList data; + }; + + template + QueueLinkedList::QueueLinkedList() + { + } + + template + inline unsigned int QueueLinkedList::Size() + { + return data.Size(); + } + + template + inline QueueType QueueLinkedList::Pop( void ) + { + data.Beginning(); + return ( QueueType ) data.Pop(); + } + + template + inline QueueType& QueueLinkedList::Peek( void ) + { + data.Beginning(); + return ( QueueType ) data.Peek(); + } + + template + inline QueueType& QueueLinkedList::EndPeek( void ) + { + data.End(); + return ( QueueType ) data.Peek(); + } + + template + void QueueLinkedList::Push( const QueueType& input ) + { + data.End(); + data.Add( input ); + } + + template + QueueLinkedList::QueueLinkedList( const QueueLinkedList& original_copy ) + { + data = original_copy.data; + } + + template + bool QueueLinkedList::operator= ( const QueueLinkedList& original_copy ) + { + if ( ( &original_copy ) == this ) + return false; + + data = original_copy.data; + } + + template + void QueueLinkedList::Clear ( void ) + { + data.Clear(); + } +} // End namespace + +#endif diff --git a/include/raknet/DS_RangeList.hpp b/include/raknet/DS_RangeList.hpp new file mode 100644 index 0000000..68143be --- /dev/null +++ b/include/raknet/DS_RangeList.hpp @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_RangeList.h +/// \internal +/// \brief A queue implemented as a linked list. +/// + + +#ifndef __RANGE_LIST_H +#define __RANGE_LIST_H + +#include "DS_OrderedList.hpp" +#include "BitStream.hpp" +#include "RakMemoryOverride.hpp" +#include "RakAssert.hpp" + +namespace DataStructures +{ + template + struct RangeNode + { + RangeNode() {} + ~RangeNode() {} + RangeNode(range_type min, range_type max) {minIndex=min; maxIndex=max;} + range_type minIndex; + range_type maxIndex; + }; + + + template + int RangeNodeComp(const range_type &a, const RangeNode &b) + { + if (a + class RAK_DLL_EXPORT RangeList + { + public: + RangeList(); + ~RangeList(); + void Insert(range_type index); + void Clear(void); + unsigned Size(void) const; + unsigned RangeSum(void) const; + RakNet::BitSize_t Serialize(RakNet::BitStream *in, RakNet::BitSize_t maxBits, bool clearSerialized); + bool Deserialize(RakNet::BitStream *out); + + DataStructures::OrderedList , RangeNodeComp > ranges; + }; + + template + RakNet::BitSize_t RangeList::Serialize(RakNet::BitStream *in, RakNet::BitSize_t maxBits, bool clearSerialized) + { + RakAssert(ranges.Size() < (unsigned short)-1); + RakNet::BitStream tempBS; + RakNet::BitSize_t bitsWritten; + unsigned short countWritten; + unsigned i; + countWritten=0; + bitsWritten=0; + for (i=0; i < ranges.Size(); i++) + { + if ((int)sizeof(unsigned short)*8+bitsWritten+(int)sizeof(range_type)*8*2+1>maxBits) + break; + unsigned char minEqualsMax; + if (ranges[i].minIndex==ranges[i].maxIndex) + minEqualsMax=1; + else + minEqualsMax=0; + tempBS.Write(minEqualsMax); // Use one byte, intead of one bit, for speed, as this is done a lot + tempBS.Write(ranges[i].minIndex); + bitsWritten+=sizeof(range_type)*8+8; + if (ranges[i].minIndex!=ranges[i].maxIndex) + { + tempBS.Write(ranges[i].maxIndex); + bitsWritten+=sizeof(range_type)*8; + } + countWritten++; + } + + in->AlignWriteToByteBoundary(); + RakNet::BitSize_t before=in->GetWriteOffset(); + in->Write(countWritten); + bitsWritten+=in->GetWriteOffset()-before; + // RAKNET_DEBUG_PRINTF("%i ", in->GetNumberOfBitsUsed()); + in->Write(&tempBS, tempBS.GetNumberOfBitsUsed()); + // RAKNET_DEBUG_PRINTF("%i %i \n", tempBS.GetNumberOfBitsUsed(),in->GetNumberOfBitsUsed()); + + if (clearSerialized && countWritten) + { + unsigned rangeSize=ranges.Size(); + for (i=0; i < rangeSize-countWritten; i++) + { + ranges[i]=ranges[i+countWritten]; + } + ranges.RemoveFromEnd(countWritten); + } + + return bitsWritten; + } + template + bool RangeList::Deserialize(RakNet::BitStream *out) + { + ranges.Clear(true, _FILE_AND_LINE_); + unsigned short count; + out->AlignReadToByteBoundary(); + out->Read(count); + unsigned short i; + range_type min,max; + unsigned char maxEqualToMin=0; + + for (i=0; i < count; i++) + { + out->Read(maxEqualToMin); + if (out->Read(min)==false) + return false; + if (maxEqualToMin==false) + { + if (out->Read(max)==false) + return false; + if (max(min,max), _FILE_AND_LINE_); + } + return true; + } + + template + RangeList::RangeList() + { + RangeNodeComp(0, RangeNode()); + } + + template + RangeList::~RangeList() + { + Clear(); + } + + template + void RangeList::Insert(range_type index) + { + if (ranges.Size()==0) + { + ranges.Insert(index, RangeNode(index, index), true, _FILE_AND_LINE_); + return; + } + + bool objectExists; + unsigned insertionIndex=ranges.GetIndexFromKey(index, &objectExists); + if (insertionIndex==ranges.Size()) + { + if (index == ranges[insertionIndex-1].maxIndex+(range_type)1) + ranges[insertionIndex-1].maxIndex++; + else if (index > ranges[insertionIndex-1].maxIndex+(range_type)1) + { + // Insert at end + ranges.Insert(index, RangeNode(index, index), true, _FILE_AND_LINE_); + } + + return; + } + + if (index < ranges[insertionIndex].minIndex-(range_type)1) + { + // Insert here + ranges.InsertAtIndex(RangeNode(index, index), insertionIndex, _FILE_AND_LINE_); + + return; + } + else if (index == ranges[insertionIndex].minIndex-(range_type)1) + { + // Decrease minIndex and join left + ranges[insertionIndex].minIndex--; + if (insertionIndex>0 && ranges[insertionIndex-1].maxIndex+(range_type)1==ranges[insertionIndex].minIndex) + { + ranges[insertionIndex-1].maxIndex=ranges[insertionIndex].maxIndex; + ranges.RemoveAtIndex(insertionIndex); + } + + return; + } + else if (index >= ranges[insertionIndex].minIndex && index <= ranges[insertionIndex].maxIndex) + { + // Already exists + return; + } + else if (index == ranges[insertionIndex].maxIndex+(range_type)1) + { + // Increase maxIndex and join right + ranges[insertionIndex].maxIndex++; + if (insertionIndex + void RangeList::Clear(void) + { + ranges.Clear(true, _FILE_AND_LINE_); + } + + template + unsigned RangeList::Size(void) const + { + return ranges.Size(); + } + + template + unsigned RangeList::RangeSum(void) const + { + unsigned sum=0,i; + for (i=0; i < ranges.Size(); i++) + sum+=ranges[i].maxIndex-ranges[i].minIndex+1; + return sum; + } + +} + +#endif diff --git a/include/raknet/DS_Table.hpp b/include/raknet/DS_Table.hpp new file mode 100644 index 0000000..72a64ef --- /dev/null +++ b/include/raknet/DS_Table.hpp @@ -0,0 +1,351 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_Table.h +/// + + +#ifndef __TABLE_H +#define __TABLE_H + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +#include "DS_List.hpp" +#include "DS_BPlusTree.hpp" +#include "RakMemoryOverride.hpp" +#include "Export.hpp" +#include "RakString.hpp" + +#define _TABLE_BPLUS_TREE_ORDER 16 +#define _TABLE_MAX_COLUMN_NAME_LENGTH 64 + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + + /// \brief Holds a set of columns, a set of rows, and rows times columns cells. + /// \details The table data structure is useful if you want to store a set of structures and perform queries on those structures.
+ /// This is a relatively simple and fast implementation of the types of tables commonly used in databases.
+ /// See TableSerializer to serialize data members of the table.
+ /// See LightweightDatabaseClient and LightweightDatabaseServer to transmit the table over the network. + class RAK_DLL_EXPORT Table + { + public: + + enum ColumnType + { + // Cell::i used + NUMERIC, + + // Cell::c used to hold a null terminated string. + STRING, + + // Cell::c holds data. Cell::i holds data length of c in bytes. + BINARY, + + // Cell::c holds data. Not deallocated. Set manually by assigning ptr. + POINTER, + }; + + + /// Holds the actual data in the table + // Note: If this structure is changed the struct in the swig files need to be changed as well + struct RAK_DLL_EXPORT Cell + { + Cell(); + ~Cell(); + Cell(double numericValue, char *charValue, void *ptr, ColumnType type); + void SetByType(double numericValue, char *charValue, void *ptr, ColumnType type); + void Clear(void); + + /// Numeric + void Set(int input); + void Set(unsigned int input); + void Set(double input); + + /// String + void Set(const char *input); + + /// Binary + void Set(const char *input, int inputLength); + + /// Pointer + void SetPtr(void* p); + + /// Numeric + void Get(int *output); + void Get(double *output); + + /// String + void Get(char *output); + + /// Binary + void Get(char *output, int *outputLength); + + RakNet::RakString ToString(ColumnType columnType); + + // assignment operator and copy constructor + Cell& operator = ( const Cell& input ); + Cell( const Cell & input); + + ColumnType EstimateColumnType(void) const; + + bool isEmpty; + double i; + char *c; + void *ptr; + }; + + /// Stores the name and type of the column + /// \internal + // Note: If this structure is changed the struct in the swig files need to be changed as well + struct RAK_DLL_EXPORT ColumnDescriptor + { + ColumnDescriptor(); + ~ColumnDescriptor(); + ColumnDescriptor(const char cn[_TABLE_MAX_COLUMN_NAME_LENGTH],ColumnType ct); + + char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]; + ColumnType columnType; + }; + + /// Stores the list of cells for this row, and a special flag used for internal sorting + // Note: If this structure is changed the struct in the swig files need to be changed as well + struct RAK_DLL_EXPORT Row + { + // list of cells + DataStructures::List cells; + + /// Numeric + void UpdateCell(unsigned columnIndex, double value); + + /// String + void UpdateCell(unsigned columnIndex, const char *str); + + /// Binary + void UpdateCell(unsigned columnIndex, int byteLength, const char *data); + }; + + // Operations to perform for cell comparison + enum FilterQueryType + { + QF_EQUAL, + QF_NOT_EQUAL, + QF_GREATER_THAN, + QF_GREATER_THAN_EQ, + QF_LESS_THAN, + QF_LESS_THAN_EQ, + QF_IS_EMPTY, + QF_NOT_EMPTY, + }; + + // Compare the cell value for a row at columnName to the cellValue using operation. + // Note: If this structure is changed the struct in the swig files need to be changed as well + struct RAK_DLL_EXPORT FilterQuery + { + FilterQuery(); + ~FilterQuery(); + FilterQuery(unsigned column, Cell *cell, FilterQueryType op); + + // If columnName is specified, columnIndex will be looked up using it. + char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]; + unsigned columnIndex; + Cell *cellValue; + FilterQueryType operation; + }; + + /// Increasing or decreasing sort order + enum SortQueryType + { + QS_INCREASING_ORDER, + QS_DECREASING_ORDER, + }; + + // Sort on increasing or decreasing order for a particular column + // Note: If this structure is changed the struct in the swig files need to be changed as well + struct RAK_DLL_EXPORT SortQuery + { + /// The index of the table column we are sorting on + unsigned columnIndex; + + /// See SortQueryType + SortQueryType operation; + }; + + // Constructor + Table(); + + // Destructor + ~Table(); + + /// \brief Adds a column to the table + /// \param[in] columnName The name of the column + /// \param[in] columnType What type of data this column will hold + /// \return The index of the new column + unsigned AddColumn(const char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType columnType); + + /// \brief Removes a column by index + /// \param[in] columnIndex The index of the column to remove + void RemoveColumn(unsigned columnIndex); + + /// \brief Gets the index of a column by name + /// \details Column indices are stored in the order they are added. + /// \param[in] columnName The name of the column + /// \return The index of the column, or (unsigned)-1 if no such column + unsigned ColumnIndex(char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]) const; + unsigned ColumnIndex(const char *columnName) const; + + /// \brief Gives the string name of the column at a certain index + /// \param[in] index The index of the column + /// \return The name of the column, or 0 if an invalid index + char* ColumnName(unsigned index) const; + + /// \brief Returns the type of a column, referenced by index + /// \param[in] index The index of the column + /// \return The type of the column + ColumnType GetColumnType(unsigned index) const; + + /// Returns the number of columns + /// \return The number of columns in the table + unsigned GetColumnCount(void) const; + + /// Returns the number of rows + /// \return The number of rows in the table + unsigned GetRowCount(void) const; + + /// \brief Adds a row to the table + /// \details New rows are added with empty values for all cells. However, if you specify initialCelLValues you can specify initial values + /// It's up to you to ensure that the values in the specific cells match the type of data used by that row + /// rowId can be considered the primary key for the row. It is much faster to lookup a row by its rowId than by searching keys. + /// rowId must be unique + /// Rows are stored in sorted order in the table, using rowId as the sort key + /// \param[in] rowId The UNIQUE primary key for the row. This can never be changed. + /// \param[in] initialCellValues Initial values to give the row (optional) + /// \return The newly added row + Table::Row* AddRow(unsigned rowId); + Table::Row* AddRow(unsigned rowId, DataStructures::List &initialCellValues); + Table::Row* AddRow(unsigned rowId, DataStructures::List &initialCellValues, bool copyCells=false); + + /// \brief Removes a row specified by rowId. + /// \param[in] rowId The ID of the row + /// \return true if the row was deleted. False if not. + bool RemoveRow(unsigned rowId); + + /// \brief Removes all the rows with IDs that the specified table also has. + /// \param[in] tableContainingRowIDs The IDs of the rows + void RemoveRows(Table *tableContainingRowIDs); + + /// \brief Updates a particular cell in the table. + /// \note If you are going to update many cells of a particular row, it is more efficient to call GetRow and perform the operations on the row directly. + /// \note Row pointers do not change, so you can also write directly to the rows for more efficiency. + /// \param[in] rowId The ID of the row + /// \param[in] columnIndex The column of the cell + /// \param[in] value The data to set + bool UpdateCell(unsigned rowId, unsigned columnIndex, int value); + bool UpdateCell(unsigned rowId, unsigned columnIndex, char *str); + bool UpdateCell(unsigned rowId, unsigned columnIndex, int byteLength, char *data); + bool UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int value); + bool UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, char *str); + bool UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int byteLength, char *data); + + /// \brief Note this is much less efficient to call than GetRow, then working with the cells directly. + /// Numeric, string, binary + void GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, int *output); + void GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output); + void GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output, int *outputLength); + + /// \brief Gets a row. More efficient to do this and access Row::cells than to repeatedly call GetCell. + /// You can also update cells in rows from this function. + /// \param[in] rowId The ID of the row + /// \return The desired row, or 0 if no such row. + Row* GetRowByID(unsigned rowId) const; + + /// \brief Gets a row at a specific index. + /// rowIndex should be less than GetRowCount() + /// \param[in] rowIndex The index of the row + /// \param[out] key The ID of the row returned + /// \return The desired row, or 0 if no such row. + Row* GetRowByIndex(unsigned rowIndex, unsigned *key) const; + + /// \brief Queries the table, optionally returning only a subset of columns and rows. + /// \param[in] columnSubset An array of column indices. Only columns in this array are returned. Pass 0 for all columns + /// \param[in] numColumnSubset The number of elements in \a columnSubset + /// \param[in] inclusionFilters An array of FilterQuery. All filters must pass for the row to be returned. + /// \param[in] numInclusionFilters The number of elements in \a inclusionFilters + /// \param[in] rowIds An arrow of row IDs. Only these rows with these IDs are returned. Pass 0 for all rows. + /// \param[in] numRowIDs The number of elements in \a rowIds + /// \param[out] result The result of the query. If no rows are returned, the table will only have columns. + void QueryTable(unsigned *columnIndicesSubset, unsigned numColumnSubset, FilterQuery *inclusionFilters, unsigned numInclusionFilters, unsigned *rowIds, unsigned numRowIDs, Table *result); + + /// \brief Sorts the table by rows + /// \details You can sort the table in ascending or descending order on one or more columns + /// Columns have precedence in the order they appear in the \a sortQueries array + /// If a row cell on column n has the same value as a a different row on column n, then the row will be compared on column n+1 + /// \param[in] sortQueries A list of SortQuery structures, defining the sorts to perform on the table + /// \param[in] numColumnSubset The number of elements in \a numSortQueries + /// \param[out] out The address of an array of Rows, which will receive the sorted output. The array must be long enough to contain all returned rows, up to GetRowCount() + void SortTable(Table::SortQuery *sortQueries, unsigned numSortQueries, Table::Row** out); + + /// \brief Frees all memory in the table. + void Clear(void); + + /// \brief Prints out the names of all the columns. + /// \param[out] out A pointer to an array of bytes which will hold the output. + /// \param[in] outLength The size of the \a out array + /// \param[in] columnDelineator What character to print to delineate columns + void PrintColumnHeaders(char *out, int outLength, char columnDelineator) const; + + /// \brief Writes a text representation of the row to \a out. + /// \param[out] out A pointer to an array of bytes which will hold the output. + /// \param[in] outLength The size of the \a out array + /// \param[in] columnDelineator What character to print to delineate columns + /// \param[in] printDelineatorForBinary Binary output is not printed. True to still print the delineator. + /// \param[in] inputRow The row to print + void PrintRow(char *out, int outLength, char columnDelineator, bool printDelineatorForBinary, Table::Row* inputRow) const; + + /// \brief Direct access to make things easier. + const DataStructures::List& GetColumns(void) const; + + /// \brief Direct access to make things easier. + const DataStructures::BPlusTree& GetRows(void) const; + + /// \brief Get the head of a linked list containing all the row data. + DataStructures::Page * GetListHead(void); + + /// \brief Get the first free row id. + /// This could be made more efficient. + unsigned GetAvailableRowId(void) const; + + Table& operator = ( const Table& input ); + + protected: + Table::Row* AddRowColumns(unsigned rowId, Row *row, DataStructures::List columnIndices); + + void DeleteRow(Row *row); + + void QueryRow(DataStructures::List &inclusionFilterColumnIndices, DataStructures::List &columnIndicesToReturn, unsigned key, Table::Row* row, FilterQuery *inclusionFilters, Table *result); + + // 16 is arbitrary and is the order of the BPlus tree. Higher orders are better for searching while lower orders are better for + // Insertions and deletions. + DataStructures::BPlusTree rows; + + // Columns in the table. + DataStructures::List columns; + }; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif diff --git a/include/raknet/DS_ThreadsafeAllocatingQueue.hpp b/include/raknet/DS_ThreadsafeAllocatingQueue.hpp new file mode 100644 index 0000000..e32f88c --- /dev/null +++ b/include/raknet/DS_ThreadsafeAllocatingQueue.hpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_ThreadsafeAllocatingQueue.h +/// \internal +/// A threadsafe queue, that also uses a memory pool for allocation + +#ifndef __THREADSAFE_ALLOCATING_QUEUE +#define __THREADSAFE_ALLOCATING_QUEUE + +#include "DS_Queue.hpp" +#include "SimpleMutex.hpp" +#include "DS_MemoryPool.hpp" + +// #if defined(new) +// #pragma push_macro("new") +// #undef new +// #define RMO_NEW_UNDEF_ALLOCATING_QUEUE +// #endif + +namespace DataStructures +{ + +template +class RAK_DLL_EXPORT ThreadsafeAllocatingQueue +{ +public: + // Queue operations + void Push(structureType *s); + structureType *PopInaccurate(void); + structureType *Pop(void); + void SetPageSize(int size); + bool IsEmpty(void); + structureType * operator[] ( unsigned int position ); + void RemoveAtIndex( unsigned int position ); + unsigned int Size( void ); + + // Memory pool operations + structureType *Allocate(const char *file, unsigned int line); + void Deallocate(structureType *s, const char *file, unsigned int line); + void Clear(const char *file, unsigned int line); +protected: + + mutable MemoryPool memoryPool; + RakNet::SimpleMutex memoryPoolMutex; + Queue queue; + RakNet::SimpleMutex queueMutex; +}; + +template +void ThreadsafeAllocatingQueue::Push(structureType *s) +{ + queueMutex.Lock(); + queue.Push(s, _FILE_AND_LINE_ ); + queueMutex.Unlock(); +} + +template +structureType *ThreadsafeAllocatingQueue::PopInaccurate(void) +{ + structureType *s; + if (queue.IsEmpty()) + return 0; + queueMutex.Lock(); + if (queue.IsEmpty()==false) + s=queue.Pop(); + else + s=0; + queueMutex.Unlock(); + return s; +} + +template +structureType *ThreadsafeAllocatingQueue::Pop(void) +{ + structureType *s; + queueMutex.Lock(); + if (queue.IsEmpty()) + { + queueMutex.Unlock(); + return 0; + } + s=queue.Pop(); + queueMutex.Unlock(); + return s; +} + +template +structureType *ThreadsafeAllocatingQueue::Allocate(const char *file, unsigned int line) +{ + structureType *s; + memoryPoolMutex.Lock(); + s=memoryPool.Allocate(file, line); + memoryPoolMutex.Unlock(); + // Call new operator, memoryPool doesn't do this + s = new ((void*)s) structureType; + return s; +} +template +void ThreadsafeAllocatingQueue::Deallocate(structureType *s, const char *file, unsigned int line) +{ + // Call delete operator, memory pool doesn't do this + s->~structureType(); + memoryPoolMutex.Lock(); + memoryPool.Release(s, file, line); + memoryPoolMutex.Unlock(); +} + +template +void ThreadsafeAllocatingQueue::Clear(const char *file, unsigned int line) +{ + memoryPoolMutex.Lock(); + for (unsigned int i=0; i < queue.Size(); i++) + { + queue[i]->~structureType(); + memoryPool.Release(queue[i], file, line); + } + queue.Clear(file, line); + memoryPoolMutex.Unlock(); + memoryPoolMutex.Lock(); + memoryPool.Clear(file, line); + memoryPoolMutex.Unlock(); +} + +template +void ThreadsafeAllocatingQueue::SetPageSize(int size) +{ + memoryPool.SetPageSize(size); +} + +template +bool ThreadsafeAllocatingQueue::IsEmpty(void) +{ + bool isEmpty; + queueMutex.Lock(); + isEmpty=queue.IsEmpty(); + queueMutex.Unlock(); + return isEmpty; +} + +template +structureType * ThreadsafeAllocatingQueue::operator[] ( unsigned int position ) +{ + structureType *s; + queueMutex.Lock(); + s=queue[position]; + queueMutex.Unlock(); + return s; +} + +template +void ThreadsafeAllocatingQueue::RemoveAtIndex( unsigned int position ) +{ + queueMutex.Lock(); + queue.RemoveAtIndex(position); + queueMutex.Unlock(); +} + +template +unsigned int ThreadsafeAllocatingQueue::Size( void ) +{ + unsigned int s; + queueMutex.Lock(); + s=queue.Size(); + queueMutex.Unlock(); + return s; +} + +} + + +// #if defined(RMO_NEW_UNDEF_ALLOCATING_QUEUE) +// #pragma pop_macro("new") +// #undef RMO_NEW_UNDEF_ALLOCATING_QUEUE +// #endif + +#endif diff --git a/include/raknet/DS_Tree.hpp b/include/raknet/DS_Tree.hpp new file mode 100644 index 0000000..bf950ce --- /dev/null +++ b/include/raknet/DS_Tree.hpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_Tree.h +/// \internal +/// \brief Just a regular tree +/// + + + +#ifndef __DS_TREE_H +#define __DS_TREE_H + +#include "Export.hpp" +#include "DS_List.hpp" +#include "DS_Queue.hpp" +#include "RakMemoryOverride.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + template + class RAK_DLL_EXPORT Tree + { + public: + Tree(); + Tree(TreeType &inputData); + ~Tree(); + void LevelOrderTraversal(DataStructures::List &output); + void AddChild(TreeType &newData); + void DeleteDecendants(void); + + TreeType data; + DataStructures::List children; + }; + + template + Tree::Tree() + { + + } + + template + Tree::Tree(TreeType &inputData) + { + data=inputData; + } + + template + Tree::~Tree() + { + DeleteDecendants(); + } + + template + void Tree::LevelOrderTraversal(DataStructures::List &output) + { + unsigned i; + Tree *node; + DataStructures::Queue*> queue; + + for (i=0; i < children.Size(); i++) + queue.Push(children[i]); + + while (queue.Size()) + { + node=queue.Pop(); + output.Insert(node, _FILE_AND_LINE_); + for (i=0; i < node->children.Size(); i++) + queue.Push(node->children[i]); + } + } + + template + void Tree::AddChild(TreeType &newData) + { + children.Insert(RakNet::OP_NEW(newData, _FILE_AND_LINE_)); + } + + template + void Tree::DeleteDecendants(void) + { + /* + DataStructures::List output; + LevelOrderTraversal(output); + unsigned i; + for (i=0; i < output.Size(); i++) + RakNet::OP_DELETE(output[i], _FILE_AND_LINE_); +*/ + + // Already recursive to do this + unsigned int i; + for (i=0; i < children.Size(); i++) + RakNet::OP_DELETE(children[i], _FILE_AND_LINE_); + } +} + +#endif diff --git a/include/raknet/DS_WeightedGraph.hpp b/include/raknet/DS_WeightedGraph.hpp new file mode 100644 index 0000000..73b6428 --- /dev/null +++ b/include/raknet/DS_WeightedGraph.hpp @@ -0,0 +1,544 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DS_WeightedGraph.h +/// \internal +/// \brief Weighted graph. +/// \details I'm assuming the indices are complex map types, rather than sequential numbers (which could be implemented much more efficiently). +/// + + +#ifndef __WEIGHTED_GRAPH_H +#define __WEIGHTED_GRAPH_H + +#include "DS_OrderedList.hpp" +#include "DS_Map.hpp" +#include "DS_Heap.hpp" +#include "DS_Queue.hpp" +#include "DS_Tree.hpp" +#include "RakAssert.hpp" +#include "RakMemoryOverride.hpp" +#ifdef _DEBUG +#include +#endif + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + template + class RAK_DLL_EXPORT WeightedGraph + { + public: + static void IMPLEMENT_DEFAULT_COMPARISON(void) {DataStructures::defaultMapKeyComparison(node_type(),node_type());} + + WeightedGraph(); + ~WeightedGraph(); + WeightedGraph( const WeightedGraph& original_copy ); + WeightedGraph& operator= ( const WeightedGraph& original_copy ); + void AddNode(const node_type &node); + void RemoveNode(const node_type &node); + void AddConnection(const node_type &node1, const node_type &node2, weight_type weight); + void RemoveConnection(const node_type &node1, const node_type &node2); + bool HasConnection(const node_type &node1, const node_type &node2); + void Print(void); + void Clear(void); + bool GetShortestPath(DataStructures::List &path, node_type startNode, node_type endNode, weight_type INFINITE_WEIGHT); + bool GetSpanningTree(DataStructures::Tree &outTree, DataStructures::List *inputNodes, node_type startNode, weight_type INFINITE_WEIGHT ); + unsigned GetNodeCount(void) const; + unsigned GetConnectionCount(unsigned nodeIndex) const; + void GetConnectionAtIndex(unsigned nodeIndex, unsigned connectionIndex, node_type &outNode, weight_type &outWeight) const; + node_type GetNodeAtIndex(unsigned nodeIndex) const; + + protected: + void ClearDijkstra(void); + void GenerateDisjktraMatrix(node_type startNode, weight_type INFINITE_WEIGHT); + + DataStructures::Map *> adjacencyLists; + + // All these variables are for path finding with Dijkstra + // 08/23/06 Won't compile as a DLL inside this struct + // struct + // { + bool isValidPath; + node_type rootNode; + DataStructures::OrderedList costMatrixIndices; + weight_type *costMatrix; + node_type *leastNodeArray; + // } dijkstra; + + struct NodeAndParent + { + DataStructures::Tree*node; + DataStructures::Tree*parent; + }; + }; + + template + WeightedGraph::WeightedGraph() + { + isValidPath=false; + costMatrix=0; + } + + template + WeightedGraph::~WeightedGraph() + { + Clear(); + } + + template + WeightedGraph::WeightedGraph( const WeightedGraph& original_copy ) + { + adjacencyLists=original_copy.adjacencyLists; + + isValidPath=original_copy.isValidPath; + if (isValidPath) + { + rootNode=original_copy.rootNode; + costMatrixIndices=original_copy.costMatrixIndices; + costMatrix = RakNet::OP_NEW_ARRAY(costMatrixIndices.Size() * costMatrixIndices.Size(), _FILE_AND_LINE_ ); + leastNodeArray = RakNet::OP_NEW_ARRAY(costMatrixIndices.Size(), _FILE_AND_LINE_ ); + memcpy(costMatrix, original_copy.costMatrix, costMatrixIndices.Size() * costMatrixIndices.Size() * sizeof(weight_type)); + memcpy(leastNodeArray, original_copy.leastNodeArray, costMatrixIndices.Size() * sizeof(weight_type)); + } + } + + template + WeightedGraph& WeightedGraph::operator=( const WeightedGraph& original_copy ) + { + adjacencyLists=original_copy.adjacencyLists; + + isValidPath=original_copy.isValidPath; + if (isValidPath) + { + rootNode=original_copy.rootNode; + costMatrixIndices=original_copy.costMatrixIndices; + costMatrix = RakNet::OP_NEW_ARRAY(costMatrixIndices.Size() * costMatrixIndices.Size(), _FILE_AND_LINE_ ); + leastNodeArray = RakNet::OP_NEW_ARRAY(costMatrixIndices.Size(), _FILE_AND_LINE_ ); + memcpy(costMatrix, original_copy.costMatrix, costMatrixIndices.Size() * costMatrixIndices.Size() * sizeof(weight_type)); + memcpy(leastNodeArray, original_copy.leastNodeArray, costMatrixIndices.Size() * sizeof(weight_type)); + } + + return *this; + } + + template + void WeightedGraph::AddNode(const node_type &node) + { + adjacencyLists.SetNew(node, RakNet::OP_NEW >( _FILE_AND_LINE_) ); + } + + template + void WeightedGraph::RemoveNode(const node_type &node) + { + unsigned i; + DataStructures::Queue removeNodeQueue; + + removeNodeQueue.Push(node, _FILE_AND_LINE_ ); + while (removeNodeQueue.Size()) + { + RakNet::OP_DELETE(adjacencyLists.Pop(removeNodeQueue.Pop()), _FILE_AND_LINE_); + + // Remove this node from all of the other lists as well + for (i=0; i < adjacencyLists.Size(); i++) + { + adjacencyLists[i]->Delete(node); + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + if (allow_unlinkedNodes==false && adjacencyLists[i]->Size()==0) + removeNodeQueue.Push(adjacencyLists.GetKeyAtIndex(i), _FILE_AND_LINE_ ); + } + } + + ClearDijkstra(); + } + + template + bool WeightedGraph::HasConnection(const node_type &node1, const node_type &node2) + { + if (node1==node2) + return false; + if (adjacencyLists.Has(node1)==false) + return false; + return adjacencyLists.Get(node1)->Has(node2); + } + + template + void WeightedGraph::AddConnection(const node_type &node1, const node_type &node2, weight_type weight) + { + if (node1==node2) + return; + + if (adjacencyLists.Has(node1)==false) + AddNode(node1); + adjacencyLists.Get(node1)->Set(node2, weight); + if (adjacencyLists.Has(node2)==false) + AddNode(node2); + adjacencyLists.Get(node2)->Set(node1, weight); + } + + template + void WeightedGraph::RemoveConnection(const node_type &node1, const node_type &node2) + { + adjacencyLists.Get(node2)->Delete(node1); + adjacencyLists.Get(node1)->Delete(node2); + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + if (allow_unlinkedNodes==false) // If we do not allow _unlinked nodes, then if there are no connections, remove the node + { + if (adjacencyLists.Get(node1)->Size()==0) + RemoveNode(node1); // Will also remove node1 from the adjacency list of node2 + if (adjacencyLists.Has(node2) && adjacencyLists.Get(node2)->Size()==0) + RemoveNode(node2); + } + + ClearDijkstra(); + } + + template + void WeightedGraph::Clear(void) + { + unsigned i; + for (i=0; i < adjacencyLists.Size(); i++) + RakNet::OP_DELETE(adjacencyLists[i], _FILE_AND_LINE_); + adjacencyLists.Clear(); + + ClearDijkstra(); + } + + template + bool WeightedGraph::GetShortestPath(DataStructures::List &path, node_type startNode, node_type endNode, weight_type INFINITE_WEIGHT) + { + path.Clear(false, _FILE_AND_LINE_); + if (startNode==endNode) + { + path.Insert(startNode, _FILE_AND_LINE_); + path.Insert(endNode, _FILE_AND_LINE_); + return true; + } + + if (isValidPath==false || rootNode!=startNode) + { + ClearDijkstra(); + GenerateDisjktraMatrix(startNode, INFINITE_WEIGHT); + } + + // return the results + bool objectExists; + unsigned col,row; + weight_type currentWeight; + DataStructures::Queue outputQueue; + col=costMatrixIndices.GetIndexFromKey(endNode, &objectExists); + if (costMatrixIndices.Size()<2) + { + return false; + } + if (objectExists==false) + { + return false; + } + node_type vertex; + row=costMatrixIndices.Size()-2; + if (row==0) + { + path.Insert(startNode, _FILE_AND_LINE_); + path.Insert(endNode, _FILE_AND_LINE_); + return true; + } + currentWeight=costMatrix[row*adjacencyLists.Size() + col]; + if (currentWeight==INFINITE_WEIGHT) + { + // No path + return true; + } + vertex=endNode; + outputQueue.PushAtHead(vertex, 0, _FILE_AND_LINE_); + row--; +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + while (costMatrix[row*adjacencyLists.Size() + col] == currentWeight) + { + if (row==0) + { + path.Insert(startNode, _FILE_AND_LINE_); + for (col=0; outputQueue.Size(); col++) + path.Insert(outputQueue.Pop(), _FILE_AND_LINE_); + return true; + } + --row; + } + + vertex=leastNodeArray[row]; + outputQueue.PushAtHead(vertex, 0, _FILE_AND_LINE_); + if (row==0) + break; + col=costMatrixIndices.GetIndexFromKey(vertex, &objectExists); + currentWeight=costMatrix[row*adjacencyLists.Size() + col]; + } + + path.Insert(startNode, _FILE_AND_LINE_); + for (col=0; outputQueue.Size(); col++) + path.Insert(outputQueue.Pop(), _FILE_AND_LINE_); + return true; + } + + template + node_type WeightedGraph::GetNodeAtIndex(unsigned nodeIndex) const + { + return adjacencyLists.GetKeyAtIndex(nodeIndex); + } + + template + unsigned WeightedGraph::GetNodeCount(void) const + { + return adjacencyLists.Size(); + } + + template + unsigned WeightedGraph::GetConnectionCount(unsigned nodeIndex) const + { + return adjacencyLists[nodeIndex]->Size(); + } + + template + void WeightedGraph::GetConnectionAtIndex(unsigned nodeIndex, unsigned connectionIndex, node_type &outNode, weight_type &outWeight) const + { + outWeight=adjacencyLists[nodeIndex]->operator[](connectionIndex); + outNode=adjacencyLists[nodeIndex]->GetKeyAtIndex(connectionIndex); + } + + template + bool WeightedGraph::GetSpanningTree(DataStructures::Tree &outTree, DataStructures::List *inputNodes, node_type startNode, weight_type INFINITE_WEIGHT ) + { + // Find the shortest path from the start node to each of the input nodes. Add this path to a new WeightedGraph if the result is reachable + DataStructures::List path; + DataStructures::WeightedGraph outGraph; + bool res; + unsigned i,j; + for (i=0; i < inputNodes->Size(); i++) + { + res=GetShortestPath(path, startNode, (*inputNodes)[i], INFINITE_WEIGHT); + if (res && path.Size()>0) + { + for (j=0; j < path.Size()-1; j++) + { + // Don't bother looking up the weight + outGraph.AddConnection(path[j], path[j+1], INFINITE_WEIGHT); + } + } + } + + // Copy the graph to a tree. + DataStructures::Queue nodesToProcess; + DataStructures::Tree *current; + DataStructures::Map *adjacencyList; + node_type key; + NodeAndParent nap, nap2; + outTree.DeleteDecendants(); + outTree.data=startNode; + current=&outTree; + if (outGraph.adjacencyLists.Has(startNode)==false) + return false; + adjacencyList = outGraph.adjacencyLists.Get(startNode); + + for (i=0; i < adjacencyList->Size(); i++) + { + nap2.node=RakNet::OP_NEW >( _FILE_AND_LINE_ ); + nap2.node->data=adjacencyList->GetKeyAtIndex(i); + nap2.parent=current; + nodesToProcess.Push(nap2, _FILE_AND_LINE_ ); + current->children.Insert(nap2.node, _FILE_AND_LINE_); + } + + while (nodesToProcess.Size()) + { + nap=nodesToProcess.Pop(); + current=nap.node; + adjacencyList = outGraph.adjacencyLists.Get(nap.node->data); + + for (i=0; i < adjacencyList->Size(); i++) + { + key=adjacencyList->GetKeyAtIndex(i); + if (key!=nap.parent->data) + { + nap2.node=RakNet::OP_NEW >( _FILE_AND_LINE_ ); + nap2.node->data=key; + nap2.parent=current; + nodesToProcess.Push(nap2, _FILE_AND_LINE_ ); + current->children.Insert(nap2.node, _FILE_AND_LINE_); + } + } + } + + return true; + } + + template + void WeightedGraph::GenerateDisjktraMatrix(node_type startNode, weight_type INFINITE_WEIGHT) + { + if (adjacencyLists.Size()==0) + return; + + costMatrix = RakNet::OP_NEW_ARRAY(adjacencyLists.Size() * adjacencyLists.Size(), _FILE_AND_LINE_ ); + leastNodeArray = RakNet::OP_NEW_ARRAY(adjacencyLists.Size(), _FILE_AND_LINE_ ); + + node_type currentNode; + unsigned col, row, row2, openSetIndex; + node_type adjacentKey; + unsigned adjacentIndex; + weight_type edgeWeight, currentNodeWeight, adjacentNodeWeight; + DataStructures::Map *adjacencyList; + DataStructures::Heap minHeap; + DataStructures::Map openSet; + + for (col=0; col < adjacencyLists.Size(); col++) + { + // This should be already sorted, so it's a bit inefficient to do an insertion sort, but what the heck + costMatrixIndices.Insert(adjacencyLists.GetKeyAtIndex(col),adjacencyLists.GetKeyAtIndex(col), true, _FILE_AND_LINE_); + } + for (col=0; col < adjacencyLists.Size() * adjacencyLists.Size(); col++) + costMatrix[col]=INFINITE_WEIGHT; + currentNode=startNode; + row=0; + currentNodeWeight=0; + rootNode=startNode; + + // Clear the starting node column + if (adjacencyLists.Size()) + { + adjacentIndex=adjacencyLists.GetIndexAtKey(startNode); + for (row2=0; row2 < adjacencyLists.Size(); row2++) + costMatrix[row2*adjacencyLists.Size() + adjacentIndex]=0; + } + + while (row < adjacencyLists.Size()-1) + { + adjacencyList = adjacencyLists.Get(currentNode); + // Go through all connections from the current node. If the new weight is less than the current weight, then update that weight. + for (col=0; col < adjacencyList->Size(); col++) + { + edgeWeight=(*adjacencyList)[col]; + adjacentKey=adjacencyList->GetKeyAtIndex(col); + adjacentIndex=adjacencyLists.GetIndexAtKey(adjacentKey); + adjacentNodeWeight=costMatrix[row*adjacencyLists.Size() + adjacentIndex]; + + if (currentNodeWeight + edgeWeight < adjacentNodeWeight) + { + // Update the weight for the adjacent node + for (row2=row; row2 < adjacencyLists.Size(); row2++) + costMatrix[row2*adjacencyLists.Size() + adjacentIndex]=currentNodeWeight + edgeWeight; + openSet.Set(adjacentKey, currentNodeWeight + edgeWeight); + } + } + + // Find the lowest in the open set + minHeap.Clear(true,_FILE_AND_LINE_); + for (openSetIndex=0; openSetIndex < openSet.Size(); openSetIndex++) + minHeap.Push(openSet[openSetIndex], openSet.GetKeyAtIndex(openSetIndex),_FILE_AND_LINE_); + + /* + unsigned i,j; + for (i=0; i < adjacencyLists.Size()-1; i++) + { + for (j=0; j < adjacencyLists.Size(); j++) + { + RAKNET_DEBUG_PRINTF("%2i ", costMatrix[i*adjacencyLists.Size() + j]); + } + RAKNET_DEBUG_PRINTF("Node=%i", leastNodeArray[i]); + RAKNET_DEBUG_PRINTF("\n"); + } + */ + + if (minHeap.Size()==0) + { + // Unreachable nodes + isValidPath=true; + return; + } + + currentNodeWeight=minHeap.PeekWeight(0); + leastNodeArray[row]=minHeap.Pop(0); + currentNode=leastNodeArray[row]; + openSet.Delete(currentNode); + row++; + } + + /* +#ifdef _DEBUG + unsigned i,j; + for (i=0; i < adjacencyLists.Size()-1; i++) + { + for (j=0; j < adjacencyLists.Size(); j++) + { + RAKNET_DEBUG_PRINTF("%2i ", costMatrix[i*adjacencyLists.Size() + j]); + } + RAKNET_DEBUG_PRINTF("Node=%i", leastNodeArray[i]); + RAKNET_DEBUG_PRINTF("\n"); + } +#endif + */ + + isValidPath=true; + } + + template + void WeightedGraph::ClearDijkstra(void) + { + if (isValidPath) + { + isValidPath=false; + RakNet::OP_DELETE_ARRAY(costMatrix, _FILE_AND_LINE_); + RakNet::OP_DELETE_ARRAY(leastNodeArray, _FILE_AND_LINE_); + costMatrixIndices.Clear(false, _FILE_AND_LINE_); + } + } + + template + void WeightedGraph::Print(void) + { +#ifdef _DEBUG + unsigned i,j; + for (i=0; i < adjacencyLists.Size(); i++) + { + //RAKNET_DEBUG_PRINTF("%i connected to ", i); + RAKNET_DEBUG_PRINTF("%s connected to ", adjacencyLists.GetKeyAtIndex(i).systemAddress.ToString()); + + if (adjacencyLists[i]->Size()==0) + RAKNET_DEBUG_PRINTF(""); + else + { + for (j=0; j < adjacencyLists[i]->Size(); j++) + // RAKNET_DEBUG_PRINTF("%i (%.2f) ", adjacencyLists.GetIndexAtKey(adjacencyLists[i]->GetKeyAtIndex(j)), (float) adjacencyLists[i]->operator[](j) ); + RAKNET_DEBUG_PRINTF("%s (%.2f) ", adjacencyLists[i]->GetKeyAtIndex(j).systemAddress.ToString(), (float) adjacencyLists[i]->operator[](j) ); + } + + RAKNET_DEBUG_PRINTF("\n"); + } +#endif + } +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif diff --git a/include/raknet/DataCompressor.hpp b/include/raknet/DataCompressor.hpp new file mode 100644 index 0000000..d718330 --- /dev/null +++ b/include/raknet/DataCompressor.hpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DataCompressor.h +/// \brief DataCompressor does compression on a block of data. +/// \details Not very good compression, but it's small and fast so is something you can use per-message at runtime. +/// + + +#ifndef __DATA_COMPRESSOR_H +#define __DATA_COMPRESSOR_H + +#include "RakMemoryOverride.hpp" +#include "DS_HuffmanEncodingTree.hpp" +#include "Export.hpp" + +namespace RakNet +{ + +/// \brief Does compression on a block of data. Not very good compression, but it's small and fast so is something you can compute at runtime. +class RAK_DLL_EXPORT DataCompressor +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(DataCompressor) + + static void Compress( unsigned char *userData, unsigned sizeInBytes, RakNet::BitStream * output ); + static unsigned DecompressAndAllocate( RakNet::BitStream * input, unsigned char **output ); +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/DirectoryDeltaTransfer.hpp b/include/raknet/DirectoryDeltaTransfer.hpp new file mode 100644 index 0000000..06f2fc0 --- /dev/null +++ b/include/raknet/DirectoryDeltaTransfer.hpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DirectoryDeltaTransfer.h +/// \brief Simple class to send changes between directories. +/// \details In essence, a simple autopatcher that can be used for transmitting levels, skins, etc. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_DirectoryDeltaTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 + +#ifndef __DIRECTORY_DELTA_TRANSFER_H +#define __DIRECTORY_DELTA_TRANSFER_H + +#include "RakMemoryOverride.hpp" +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "PluginInterface2.hpp" +#include "DS_Map.hpp" +#include "PacketPriority.hpp" + +/// \defgroup DIRECTORY_DELTA_TRANSFER_GROUP DirectoryDeltaTransfer +/// \brief Simple class to send changes between directories +/// \details +/// \ingroup PLUGINS_GROUP + +/// \brief Simple class to send changes between directories. In essence, a simple autopatcher that can be used for transmitting levels, skins, etc. +/// \details +/// \sa AutopatcherClient class for database driven patching, including binary deltas and search by date. +/// +/// To use, first set the path to your application. For example "C:/Games/MyRPG/"
+/// To allow other systems to download files, call AddUploadsFromSubdirectory, where the parameter is a path relative
+/// to the path to your application. This includes subdirectories.
+/// For example:
+/// SetApplicationDirectory("C:/Games/MyRPG/");
+/// AddUploadsFromSubdirectory("Mods/Skins/");
+/// would allow downloads from
+/// "C:/Games/MyRPG/Mods/Skins/*.*" as well as "C:/Games/MyRPG/Mods/Skins/Level1/*.*"
+/// It would NOT allow downloads from C:/Games/MyRPG/Levels, nor would it allow downloads from C:/Windows
+/// While pathToApplication can be anything you want, applicationSubdirectory must match either partially or fully between systems. +/// \ingroup DIRECTORY_DELTA_TRANSFER_GROUP + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +class FileList; +struct Packet; +struct InternalPacket; +struct DownloadRequest; +class FileListTransfer; +class FileListTransferCBInterface; +class FileListProgress; +class IncrementalReadInterface; + +class RAK_DLL_EXPORT DirectoryDeltaTransfer : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(DirectoryDeltaTransfer) + + // Constructor + DirectoryDeltaTransfer(); + + // Destructor + virtual ~DirectoryDeltaTransfer(); + + /// \brief This plugin has a dependency on the FileListTransfer plugin, which it uses to actually send the files. + /// \details So you need an instance of that plugin registered with RakPeerInterface, and a pointer to that interface should be passed here. + /// \param[in] flt A pointer to a registered instance of FileListTransfer + void SetFileListTransferPlugin(FileListTransfer *flt); + + /// \brief Set the local root directory to base all file uploads and downloads off of. + /// \param[in] pathToApplication This path will be prepended to \a applicationSubdirectory in AddUploadsFromSubdirectory to find the actual path on disk. + void SetApplicationDirectory(const char *pathToApplication); + + /// \brief What parameters to use for the RakPeerInterface::Send() call when uploading files. + /// \param[in] _priority See RakPeerInterface::Send() + /// \param[in] _orderingChannel See RakPeerInterface::Send() + void SetUploadSendParameters(PacketPriority _priority, char _orderingChannel); + + /// \brief Add all files in the specified subdirectory recursively. + /// \details \a subdir is appended to \a pathToApplication in SetApplicationDirectory(). + /// All files in the resultant directory and subdirectories are then hashed so that users can download them. + /// \pre You must call SetFileListTransferPlugin with a valid FileListTransfer plugin + /// \param[in] subdir Concatenated with pathToApplication to form the final path from which to allow uploads. + void AddUploadsFromSubdirectory(const char *subdir); + + /// \brief Downloads files from the matching parameter \a subdir in AddUploadsFromSubdirectory. + /// \details \a subdir must contain all starting characters in \a subdir in AddUploadsFromSubdirectory + /// Therefore, + /// AddUploadsFromSubdirectory("Levels/Level1/"); would allow you to download using DownloadFromSubdirectory("Levels/Level1/Textures/"... + /// but it would NOT allow you to download from DownloadFromSubdirectory("Levels/"... or DownloadFromSubdirectory("Levels/Level2/"... + /// \pre You must call SetFileListTransferPlugin with a valid FileListTransfer plugin + /// \note Blocking. Will block while hashes of the local files are generated + /// \param[in] subdir A directory passed to AddUploadsFromSubdirectory on the remote system. The passed dir can be more specific than the remote dir. + /// \param[in] outputSubdir The directory to write the output to. Usually this will match \a subdir but it can be different if you want. + /// \param[in] prependAppDirToOutputSubdir True to prepend outputSubdir with pathToApplication when determining the final output path. Usually you want this to be true. + /// \param[in] host The address of the remote system to send the message to. + /// \param[in] onFileCallback Callback to call per-file (optional). When fileIndex+1==setCount in the callback then the download is done + /// \param[in] _priority See RakPeerInterface::Send() + /// \param[in] _orderingChannel See RakPeerInterface::Send() + /// \param[in] cb Callback to get progress updates. Pass 0 to not use. + /// \return A set ID, identifying this download set. Returns 65535 on host unreachable. + unsigned short DownloadFromSubdirectory(const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, PacketPriority _priority, char _orderingChannel, FileListProgress *cb); + + /// \brief Downloads files from the matching parameter \a subdir in AddUploadsFromSubdirectory. + /// \details \a subdir must contain all starting characters in \a subdir in AddUploadsFromSubdirectory + /// Therefore, + /// AddUploadsFromSubdirectory("Levels/Level1/"); would allow you to download using DownloadFromSubdirectory("Levels/Level1/Textures/"... + /// but it would NOT allow you to download from DownloadFromSubdirectory("Levels/"... or DownloadFromSubdirectory("Levels/Level2/"... + /// \pre You must call SetFileListTransferPlugin with a valid FileListTransfer plugin + /// \note Nonblocking, but requires call to GenerateHashes() + /// \param[in] localFiles Hashes of local files already on the harddrive. Populate with GenerateHashes(), which you may wish to call from a thread + /// \param[in] subdir A directory passed to AddUploadsFromSubdirectory on the remote system. The passed dir can be more specific than the remote dir. + /// \param[in] outputSubdir The directory to write the output to. Usually this will match \a subdir but it can be different if you want. + /// \param[in] prependAppDirToOutputSubdir True to prepend outputSubdir with pathToApplication when determining the final output path. Usually you want this to be true. + /// \param[in] host The address of the remote system to send the message to. + /// \param[in] onFileCallback Callback to call per-file (optional). When fileIndex+1==setCount in the callback then the download is done + /// \param[in] _priority See RakPeerInterface::Send() + /// \param[in] _orderingChannel See RakPeerInterface::Send() + /// \param[in] cb Callback to get progress updates. Pass 0 to not use. + /// \return A set ID, identifying this download set. Returns 65535 on host unreachable. + unsigned short DownloadFromSubdirectory(FileList &localFiles, const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, PacketPriority _priority, char _orderingChannel, FileListProgress *cb); + + /// Hash files already on the harddrive, in preparation for a call to DownloadFromSubdirectory(). Passed to second version of DownloadFromSubdirectory() + /// This is slow, and it is exposed so you can call it from a thread before calling DownloadFromSubdirectory() + /// \param[out] localFiles List of hashed files populated from \a outputSubdir and \a prependAppDirToOutputSubdir + /// \param[in] outputSubdir The directory to write the output to. Usually this will match \a subdir but it can be different if you want. + /// \param[in] prependAppDirToOutputSubdir True to prepend outputSubdir with pathToApplication when determining the final output path. Usually you want this to be true. + void GenerateHashes(FileList &localFiles, const char *outputSubdir, bool prependAppDirToOutputSubdir); + + /// \brief Clear all allowed uploads previously set with AddUploadsFromSubdirectory + void ClearUploads(void); + + /// \brief Returns how many files are available for upload + /// \return How many files are available for upload + unsigned GetNumberOfFilesForUpload(void) const; + + /// \brief Normally, if a remote system requests files, those files are all loaded into memory and sent immediately. + /// \details This function allows the files to be read in incremental chunks, saving memory + /// \param[in] _incrementalReadInterface If a file in \a fileList has no data, filePullInterface will be used to read the file in chunks of size \a chunkSize + /// \param[in] _chunkSize How large of a block of a file to send at once + void SetDownloadRequestIncrementalReadInterface(IncrementalReadInterface *_incrementalReadInterface, unsigned int _chunkSize); + + /// \internal For plugin handling + virtual PluginReceiveResult OnReceive(Packet *packet); +protected: + void OnDownloadRequest(Packet *packet); + + char applicationDirectory[512]; + FileListTransfer *fileListTransfer; + FileList *availableUploads; + PacketPriority priority; + char orderingChannel; + IncrementalReadInterface *incrementalReadInterface; + unsigned int chunkSize; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/DynDNS.hpp b/include/raknet/DynDNS.hpp new file mode 100644 index 0000000..1cedc59 --- /dev/null +++ b/include/raknet/DynDNS.hpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file DynDNS.h +/// \brief Helper to class to update DynDNS +/// This can be used to determine what permissions are should be allowed to the other system +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_DynDNS==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#ifndef __DYN_DNS_H +#define __DYN_DNS_H + +#include "RakString.hpp" + +namespace RakNet +{ + +class TCPInterface; + +enum DynDnsResultCode +{ + // ----- Success ----- + RC_SUCCESS, + RC_DNS_ALREADY_SET, // RakNet detects no action is needed + + // ----- Ignorable failure (treat same as success) ----- + RC_NO_CHANGE, // DynDNS detects no action is needed (treated as abuse though) + + // ----- User error ----- + RC_NOT_DONATOR, // You have to pay to do this + RC_NO_HOST, // This host does not exist at all + RC_BAD_AUTH, // You set the wrong password + RC_NOT_YOURS, // This is not your host + + // ----- Permanent failure ----- + RC_ABUSE, // Your host has been blocked, too many failures disable your account + RC_TCP_FAILED_TO_START, // TCP port already in use + RC_TCP_DID_NOT_CONNECT, // DynDNS down? + RC_UNKNOWN_RESULT, // DynDNS returned a result code that was not documented as of 12/4/2010 on http://www.dyndns.com/developers/specs/flow.pdf + RC_PARSING_FAILURE, // Can't read the result returned, format change? + RC_CONNECTION_LOST_WITHOUT_RESPONSE, // Lost the connection to DynDNS while communicating + RC_BAD_AGENT, // ??? + RC_BAD_SYS, // ??? + RC_DNS_ERROR, // ??? + RC_NOT_FQDN, // ??? + RC_NUM_HOST, // ??? + RC_911, // ??? + RC_DYNDNS_TIMEOUT // DynDNS did not respond +}; + +// Can only process one at a time with the current implementation +class RAK_DLL_EXPORT DynDNS +{ +public: + DynDNS(); + ~DynDNS(); + + // Pass 0 for newIPAddress to autodetect whatever you are uploading from + // usernameAndPassword should be in the format username:password + void UpdateHostIPAsynch(const char *dnsHost, const char *newIPAddress, const char *usernameAndPassword ); + void Update(void); + + // Output + bool IsRunning(void) const {return connectPhase!=CP_IDLE;} + bool IsCompleted(void) const {return connectPhase==CP_IDLE;} + RakNet::DynDnsResultCode GetCompletedResultCode(void) {return result;} + const char *GetCompletedDescription(void) const {return resultDescription;} + bool WasResultSuccessful(void) const {return result==RC_SUCCESS || result==RC_DNS_ALREADY_SET || result==RC_NO_CHANGE;} + char *GetMyPublicIP(void) const {return (char*) myIPStr;} // We get our public IP as part of the process. This is valid once completed + +protected: + void Stop(void); + void SetCompleted(RakNet::DynDnsResultCode _result, const char *_resultDescription) {Stop(); result=_result; resultDescription=_resultDescription;} + + enum ConnectPhase + { + CP_CONNECTING_TO_CHECKIP, + CP_WAITING_FOR_CHECKIP_RESPONSE, + CP_CONNECTING_TO_DYNDNS, + CP_WAITING_FOR_DYNDNS_RESPONSE, + CP_IDLE + }; + + TCPInterface *tcp; + RakNet::RakString getString; + SystemAddress serverAddress; + ConnectPhase connectPhase; + RakNet::RakString host; + RakNet::Time phaseTimeout; + SystemAddress checkIpAddress; + const char *resultDescription; + RakNet::DynDnsResultCode result; + char myIPStr[32]; +}; + +} // namespace RakNet + +#endif // __DYN_DNS_H + +#endif // _RAKNET_SUPPORT_DynDNS diff --git a/include/raknet/EmailSender.hpp b/include/raknet/EmailSender.hpp new file mode 100644 index 0000000..1a7b6f1 --- /dev/null +++ b/include/raknet/EmailSender.hpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file EmailSender.h +/// \brief Rudimentary class to send email from code. Don't expect anything fancy. +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_EmailSender==1 && _RAKNET_SUPPORT_TCPInterface==1 && _RAKNET_SUPPORT_FileOperations==1 + +#ifndef __EMAIL_SENDER_H +#define __EMAIL_SENDER_H + +#include "RakNetTypes.hpp" +#include "RakMemoryOverride.hpp" +#include "Export.hpp" +#include "Rand.hpp" +#include "TCPInterface.hpp" + +namespace RakNet +{ +/// Forward declarations +class FileList; +class TCPInterface; + +/// \brief Rudimentary class to send email from code. +class RAK_DLL_EXPORT EmailSender +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(EmailSender) + + /// \brief Sends an email. + /// \param[in] hostAddress The address of the email server. + /// \param[in] hostPort The port of the email server (usually 25) + /// \param[in] sender The email address you are sending from. + /// \param[in] recipient The email address you are sending to. + /// \param[in] senderName The email address you claim to be sending from + /// \param[in] recipientName The email address you claim to be sending to + /// \param[in] subject Email subject + /// \param[in] body Email body + /// \param[in] attachedFiles List of files to attach to the email. (Can be 0 to send none). + /// \param[in] doPrintf true to output SMTP info to console(for debugging?) + /// \param[in] password Used if the server uses AUTHENTICATE PLAIN over TLS (such as gmail) + /// \return 0 on success, otherwise a string indicating the error message + const char *Send(const char *hostAddress, unsigned short hostPort, const char *sender, const char *recipient, const char *senderName, const char *recipientName, const char *subject, const char *body, FileList *attachedFiles, bool doPrintf, const char *password); + +protected: + const char *GetResponse(TCPInterface *tcpInterface, const SystemAddress &emailServer, bool doPrintf); + RakNetRandom rakNetRandom; +}; + +} // namespace RakNet + +#endif + + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/EmptyHeader.hpp b/include/raknet/EmptyHeader.hpp new file mode 100644 index 0000000..293abfa --- /dev/null +++ b/include/raknet/EmptyHeader.hpp @@ -0,0 +1 @@ +// This is here to remove Missing #include header? in the Unreal Engine diff --git a/include/raknet/EpochTimeToString.hpp b/include/raknet/EpochTimeToString.hpp new file mode 100644 index 0000000..610204f --- /dev/null +++ b/include/raknet/EpochTimeToString.hpp @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + + +/// \file EpochTimeToString.h +/// + + +#ifndef __EPOCH_TIME_TO_STRING_H +#define __EPOCH_TIME_TO_STRING_H + +#include "Export.hpp" + +RAK_DLL_EXPORT char * EpochTimeToString(long long time); + +#endif + diff --git a/include/raknet/Export.hpp b/include/raknet/Export.hpp new file mode 100644 index 0000000..f883c95 --- /dev/null +++ b/include/raknet/Export.hpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "RakNetDefines.hpp" + +#if defined(_WIN32) && !(defined(__GNUC__) || defined(__GCCXML__)) && !defined(_RAKNET_LIB) && defined(_RAKNET_DLL) +#define RAK_DLL_EXPORT __declspec(dllexport) +#else +#define RAK_DLL_EXPORT +#endif + +#define STATIC_FACTORY_DECLARATIONS(x) static x* GetInstance(void); \ +static void DestroyInstance( x *i); + +#define STATIC_FACTORY_DEFINITIONS(x,y) x* x::GetInstance(void) {return RakNet::OP_NEW( _FILE_AND_LINE_ );} \ +void x::DestroyInstance( x *i) {RakNet::OP_DELETE(( y* ) i, _FILE_AND_LINE_);} diff --git a/include/raknet/FileList.hpp b/include/raknet/FileList.hpp new file mode 100644 index 0000000..c64a326 --- /dev/null +++ b/include/raknet/FileList.hpp @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file FileList.h +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_FileOperations==1 + +#ifndef __FILE_LIST +#define __FILE_LIST + +#include "Export.hpp" +#include "DS_List.hpp" +#include "RakMemoryOverride.hpp" +#include "RakNetTypes.hpp" +#include "FileListNodeContext.hpp" +#include "RakString.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +namespace RakNet +{ + class BitStream; +} + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +class FileList; + + +/// Represents once instance of a file +struct FileListNode +{ + /// Name of the file + RakNet::RakString filename; + + /// Full path to the file, which may be different than filename + RakNet::RakString fullPathToFile; + + /// File data (may be null if not ready) + char *data; + + /// Length of \a data. May be greater than fileLength if prepended with a file hash + BitSize_t dataLengthBytes; + + /// Length of the file + unsigned fileLengthBytes; + + /// User specific data for whatever, describing this file. + FileListNodeContext context; + + /// If true, data and dataLengthBytes should be empty. This is just storing the filename + bool isAReference; +}; + +/// Callback interface set with FileList::SetCallback() in case you want progress notifications when FileList::AddFilesFromDirectory() is called +class RAK_DLL_EXPORT FileListProgress +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(FileListProgress) + + FileListProgress() {} + virtual ~FileListProgress() {} + + /// First callback called when FileList::AddFilesFromDirectory() starts + virtual void OnAddFilesFromDirectoryStarted(FileList *fileList, char *dir) { + (void) fileList; + (void) dir; + } + + /// Called for each directory, when that directory begins processing + virtual void OnDirectory(FileList *fileList, char *dir, unsigned int directoriesRemaining) { + (void) fileList; + (void) dir; + (void) directoriesRemaining; + } + + /// Called for each file, when that file begins processing + virtual void OnFile(FileList *fileList, char *dir, char *fileName, unsigned int fileSize) { + (void) fileList; + (void) dir; + (void) fileName; + (void) fileSize; + } + + /// \brief This function is called when we are sending a file to a remote system. + /// \param[in] fileName The name of the file being sent + /// \param[in] fileLengthBytes How long the file is + /// \param[in] offset The offset in bytes into the file that we are sending + /// \param[in] bytesBeingSent How many bytes we are sending this push + /// \param[in] done If this file is now done with this push + /// \param[in] targetSystem Who we are sending to + virtual void OnFilePush(const char *fileName, unsigned int fileLengthBytes, unsigned int offset, unsigned int bytesBeingSent, bool done, SystemAddress targetSystem, unsigned short setId) + { + (void) fileName; + (void) fileLengthBytes; + (void) offset; + (void) bytesBeingSent; + (void) done; + (void) targetSystem; + (void) setId; + } + + /// \brief This function is called when all files have been read and are being transferred to a remote system + virtual void OnFilePushesComplete( SystemAddress systemAddress, unsigned short setId ) + { + (void) systemAddress; + (void) setId; + } + + /// \brief This function is called when a send to a system was aborted (probably due to disconnection) + virtual void OnSendAborted( SystemAddress systemAddress ) + { + (void) systemAddress; + } +}; + +/// Implementation of FileListProgress to use RAKNET_DEBUG_PRINTF +class RAK_DLL_EXPORT FLP_Printf : public FileListProgress +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(FLP_Printf) + + FLP_Printf() {} + virtual ~FLP_Printf() {} + + /// First callback called when FileList::AddFilesFromDirectory() starts + virtual void OnAddFilesFromDirectoryStarted(FileList *fileList, char *dir); + + /// Called for each directory, when that directory begins processing + virtual void OnDirectory(FileList *fileList, char *dir, unsigned int directoriesRemaining); + + /// \brief This function is called when all files have been transferred to a particular remote system + virtual void OnFilePushesComplete( SystemAddress systemAddress, unsigned short setID ); + + /// \brief This function is called when a send to a system was aborted (probably due to disconnection) + virtual void OnSendAborted( SystemAddress systemAddress ); +}; + +class RAK_DLL_EXPORT FileList +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(FileList) + + FileList(); + ~FileList(); + /// \brief Add all the files at a given directory. + /// \param[in] applicationDirectory The first part of the path. This is not stored as part of the filename. Use \ as the path delineator. + /// \param[in] subDirectory The rest of the path to the file. This is stored as a prefix to the filename + /// \param[in] writeHash The first 4 bytes is a hash of the file, with the remainder the actual file data (should \a writeData be true) + /// \param[in] writeData Write the contents of each file + /// \param[in] recursive Whether or not to visit subdirectories + /// \param[in] context User defined byte to store with each file. Use for whatever you want. + void AddFilesFromDirectory(const char *applicationDirectory, const char *subDirectory, bool writeHash, bool writeData, bool recursive, FileListNodeContext context); + + /// Deallocate all memory + void Clear(void); + + /// Write all encoded data into a bitstream + void Serialize(RakNet::BitStream *outBitStream); + + /// Read all encoded data from a bitstream. Clear() is called before deserializing. + bool Deserialize(RakNet::BitStream *inBitStream); + + /// \brief Given the existing set of files, search applicationDirectory for the same files. + /// \details For each file that is missing or different, add that file to \a missingOrChangedFiles. Note: the file contents are not written, and only the hash if written if \a alwaysWriteHash is true + /// alwaysWriteHash and neverWriteHash are optimizations to avoid reading the file contents to generate the hash if not necessary because the file is missing or has different lengths anyway. + /// \param[in] applicationDirectory The first part of the path. This is not stored as part of the filename. Use \ as the path delineator. + /// \param[out] missingOrChangedFiles Output list written to + /// \param[in] alwaysWriteHash If true, and neverWriteHash is false, will hash the file content of the file on disk, and write that as the file data with a length of SHA1_LENGTH bytes. If false, if the file length is different, will only write the filename. + /// \param[in] neverWriteHash If true, will never write the hash, even if available. If false, will write the hash if the file lengths are the same and it was forced to do a comparison. + void ListMissingOrChangedFiles(const char *applicationDirectory, FileList *missingOrChangedFiles, bool alwaysWriteHash, bool neverWriteHash); + + /// \brief Return the files that need to be written to make \a input match this current FileList. + /// \details Specify dirSubset to only consider files that start with this path + /// specify remoteSubdir to assume that all filenames in input start with this path, so strip it off when comparing filenames. + /// \param[in] input Full list of files + /// \param[out] output Files that we need to match input + /// \param[in] dirSubset If the filename does not start with this path, just skip this file. + /// \param[in] remoteSubdir Remove this from the filenames of \a input when comparing to existing filenames. + void GetDeltaToCurrent(FileList *input, FileList *output, const char *dirSubset, const char *remoteSubdir); + + /// \brief Assuming FileList contains a list of filenames presumably without data, read the data for these filenames + /// \param[in] applicationDirectory Prepend this path to each filename. Trailing slash will be added if necessary. Use \ as the path delineator. + /// \param[in] writeFileData True to read and store the file data. The first SHA1_LENGTH bytes will contain the hash if \a writeFileHash is true + /// \param[in] writeFileHash True to read and store the hash of the file data. The first SHA1_LENGTH bytes will contain the hash if \a writeFileHash is true + /// \param[in] removeUnknownFiles If a file does not exist on disk but is in the file list, remove it from the file list? + void PopulateDataFromDisk(const char *applicationDirectory, bool writeFileData, bool writeFileHash, bool removeUnknownFiles); + + /// By default, GetDeltaToCurrent tags files as non-references, meaning they are assumed to be populated later + /// This tags all files as references, required for IncrementalReadInterface to process them incrementally + void FlagFilesAsReferences(void); + + /// \brief Write all files to disk, prefixing the paths with applicationDirectory + /// \param[in] applicationDirectory path prefix + void WriteDataToDisk(const char *applicationDirectory); + + /// \brief Add a file, given data already in memory. + /// \param[in] filename Name of a file, optionally prefixed with a partial or complete path. Use \ as the path delineator. + /// \param[in] fullPathToFile Full path to the file on disk + /// \param[in] data Contents to write + /// \param[in] dataLength length of the data, which may be greater than fileLength should you prefix extra data, such as the hash + /// \param[in] fileLength Length of the file + /// \param[in] context User defined byte to store with each file. Use for whatever you want. + /// \param[in] isAReference Means that this is just a reference to a file elsewhere - does not actually have any data + /// \param[in] takeDataPointer If true, do not allocate dataLength. Just take the pointer passed to the \a data parameter + void AddFile(const char *filename, const char *fullPathToFile, const char *data, const unsigned dataLength, const unsigned fileLength, FileListNodeContext context, bool isAReference=false, bool takeDataPointer=false); + + /// \brief Add a file, reading it from disk. + /// \param[in] filepath Complete path to the file, including the filename itself + /// \param[in] filename filename to store internally, anything you want, but usually either the complete path or a subset of the complete path. + /// \param[in] context User defined byte to store with each file. Use for whatever you want. + void AddFile(const char *filepath, const char *filename, FileListNodeContext context); + + /// \brief Delete all files stored in the file list. + /// \param[in] applicationDirectory Prefixed to the path to each filename. Use \ as the path delineator. + void DeleteFiles(const char *applicationDirectory); + + /// \brief Adds a callback to get progress reports about what the file list instances do. + /// \param[in] cb A pointer to an externally defined instance of FileListProgress. This pointer is held internally, so should remain valid as long as this class is valid. + void AddCallback(FileListProgress *cb); + + /// \brief Removes a callback + /// \param[in] cb A pointer to an externally defined instance of FileListProgress that was previously added with AddCallback() + void RemoveCallback(FileListProgress *cb); + + /// \brief Removes all callbacks + void ClearCallbacks(void); + + /// Returns all callbacks added with AddCallback() + /// \param[out] callbacks The list is set to the list of callbacks + void GetCallbacks(DataStructures::List &callbacks); + + // Here so you can read it, but don't modify it + DataStructures::List fileList; + + static bool FixEndingSlash(char *str); +protected: + DataStructures::List fileListProgressCallbacks; +}; + +} // namespace RakNet + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif + +#endif // _RAKNET_SUPPORT_FileOperations diff --git a/include/raknet/FileListNodeContext.hpp b/include/raknet/FileListNodeContext.hpp new file mode 100644 index 0000000..e68e7db --- /dev/null +++ b/include/raknet/FileListNodeContext.hpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file FileListNodeContext.h +/// + + +#ifndef __FILE_LIST_NODE_CONTEXT_H +#define __FILE_LIST_NODE_CONTEXT_H + +#include "BitStream.hpp" + +struct FileListNodeContext +{ + FileListNodeContext() {dataPtr=0; dataLength=0;} + FileListNodeContext(unsigned char o, uint32_t f1, uint32_t f2, uint32_t f3) : op(o), flnc_extraData1(f1), flnc_extraData2(f2), flnc_extraData3(f3) {dataPtr=0; dataLength=0;} + ~FileListNodeContext() {} + + unsigned char op; + uint32_t flnc_extraData1; + uint32_t flnc_extraData2; + uint32_t flnc_extraData3; + void *dataPtr; + unsigned int dataLength; +}; + +inline RakNet::BitStream& operator<<(RakNet::BitStream& out, FileListNodeContext& in) +{ + out.Write(in.op); + out.Write(in.flnc_extraData1); + out.Write(in.flnc_extraData2); + out.Write(in.flnc_extraData3); + return out; +} +inline RakNet::BitStream& operator>>(RakNet::BitStream& in, FileListNodeContext& out) +{ + in.Read(out.op); + bool success = in.Read(out.flnc_extraData1); + (void) success; + assert(success); + success = in.Read(out.flnc_extraData2); + (void) success; + assert(success); + success = in.Read(out.flnc_extraData3); + (void) success; + assert(success); + return in; +} + +#endif diff --git a/include/raknet/FileListTransfer.hpp b/include/raknet/FileListTransfer.hpp new file mode 100644 index 0000000..361f3ff --- /dev/null +++ b/include/raknet/FileListTransfer.hpp @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file FileListTransfer.h +/// \brief A plugin to provide a simple way to compress and incrementally send the files in the FileList structure. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_FileListTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 + +#ifndef __FILE_LIST_TRANFER_H +#define __FILE_LIST_TRANFER_H + +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "PluginInterface2.hpp" +#include "DS_Map.hpp" +#include "RakNetTypes.hpp" +#include "PacketPriority.hpp" +#include "RakMemoryOverride.hpp" +#include "FileList.hpp" +#include "DS_Queue.hpp" +#include "SimpleMutex.hpp" +#include "ThreadPool.hpp" + +namespace RakNet +{ +/// Forward declarations +class IncrementalReadInterface; +class FileListTransferCBInterface; +class FileListProgress; +struct FileListReceiver; + +/// \defgroup FILE_LIST_TRANSFER_GROUP FileListTransfer +/// \brief A plugin to provide a simple way to compress and incrementally send the files in the FileList structure. +/// \details +/// \ingroup PLUGINS_GROUP + +/// \brief A plugin to provide a simple way to compress and incrementally send the files in the FileList structure. +/// \details Similar to the DirectoryDeltaTransfer plugin, except that it doesn't send deltas based on pre-existing files or actually write the files to disk. +/// +/// Usage: +/// Call SetupReceive to allow one file set to arrive. The value returned by FileListTransfer::SetupReceive()
+/// is the setID that is allowed.
+/// It's up to you to transmit this value to the other system, along with information indicating what kind of files you want to get.
+/// The other system should then prepare a FileList and call FileListTransfer::Send(), passing the return value of FileListTransfer::SetupReceive()
+/// as the \a setID parameter to FileListTransfer::Send() +/// \ingroup FILE_LIST_TRANSFER_GROUP +class RAK_DLL_EXPORT FileListTransfer : public PluginInterface2 +{ +public: + + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(FileListTransfer) + + FileListTransfer(); + virtual ~FileListTransfer(); + + /// \brief Optionally start worker threads when using _incrementalReadInterface for the Send() operation + /// \param[in] numThreads how many worker threads to start + /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. + void StartIncrementalReadThreads(int numThreads, int threadPriority=-99999); + + /// \brief Allows one corresponding Send() call from another system to arrive. + /// \param[in] handler The class to call on each file + /// \param[in] deleteHandler True to delete the handler when it is no longer needed. False to not do so. + /// \param[in] allowedSender Which system to allow files from. + /// \return A set ID value, which should be passed as the \a setID value to the Send() call on the other system. This value will be returned in the callback and is unique per file set. Returns 65535 on failure (not connected to sender) + unsigned short SetupReceive(FileListTransferCBInterface *handler, bool deleteHandler, SystemAddress allowedSender); + + /// \brief Send the FileList structure to another system, which must have previously called SetupReceive(). + /// \param[in] fileList A list of files. The data contained in FileList::data will be sent incrementally and compressed among all files in the set + /// \param[in] rakPeer The instance of RakNet to use to send the message. Pass 0 to use the instance the plugin is attached to + /// \param[in] recipient The address of the system to send to + /// \param[in] setID The return value of SetupReceive() which was previously called on \a recipient + /// \param[in] priority Passed to RakPeerInterface::Send() + /// \param[in] orderingChannel Passed to RakPeerInterface::Send() + /// \param[in] _incrementalReadInterface If a file in \a fileList has no data, _incrementalReadInterface will be used to read the file in chunks of size \a chunkSize + /// \param[in] _chunkSize How large of a block of a file to read/send at once. Large values use more memory but transfer slightly faster. + void Send(FileList *fileList, RakNet::RakPeerInterface *rakPeer, SystemAddress recipient, unsigned short setID, PacketPriority priority, char orderingChannel, IncrementalReadInterface *_incrementalReadInterface=0, unsigned int _chunkSize=262144*4*16); + + /// Return number of files waiting to go out to a particular address + unsigned int GetPendingFilesToAddress(SystemAddress recipient); + + /// \brief Stop a download. + void CancelReceive(unsigned short setId); + + /// \brief Remove all handlers associated with a particular system address. + void RemoveReceiver(SystemAddress systemAddress); + + /// \brief Is a handler passed to SetupReceive still running? + bool IsHandlerActive(unsigned short setId); + + /// \brief Adds a callback to get progress reports about what the file list instances do. + /// \param[in] cb A pointer to an externally defined instance of FileListProgress. This pointer is held internally, so should remain valid as long as this class is valid. + void AddCallback(FileListProgress *cb); + + /// \brief Removes a callback + /// \param[in] cb A pointer to an externally defined instance of FileListProgress that was previously added with AddCallback() + void RemoveCallback(FileListProgress *cb); + + /// \brief Removes all callbacks + void ClearCallbacks(void); + + /// Returns all callbacks added with AddCallback() + /// \param[out] callbacks The list is set to the list of callbacks + void GetCallbacks(DataStructures::List &callbacks); + + /// \internal For plugin handling + virtual PluginReceiveResult OnReceive(Packet *packet); + /// \internal For plugin handling + virtual void OnRakPeerShutdown(void); + /// \internal For plugin handling + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + /// \internal For plugin handling + virtual void Update(void); + +protected: + bool DecodeSetHeader(Packet *packet); + bool DecodeFile(Packet *packet, bool fullFile); + + void Clear(void); + + void OnReferencePush(Packet *packet, bool fullFile); + void OnReferencePushAck(Packet *packet); + void SendIRIToAddress(SystemAddress systemAddress, unsigned short setId); + + DataStructures::Map fileListReceivers; + unsigned short setId; + DataStructures::List fileListProgressCallbacks; + + struct FileToPush + { + FileListNode fileListNode; + PacketPriority packetPriority; + char orderingChannel; + unsigned int currentOffset; + ////unsigned short setID; + unsigned int setIndex; + IncrementalReadInterface *incrementalReadInterface; + unsigned int chunkSize; + }; + struct FileToPushRecipient + { + unsigned int refCount; + SimpleMutex refCountMutex; + void DeleteThis(void); + void AddRef(void); + void Deref(void); + + SystemAddress systemAddress; + unsigned short setId; + + //// SimpleMutex filesToPushMutex; + DataStructures::Queue filesToPush; + }; + DataStructures::List< FileToPushRecipient* > fileToPushRecipientList; + SimpleMutex fileToPushRecipientListMutex; + void RemoveFromList(FileToPushRecipient *ftpr); + + struct ThreadData + { + FileListTransfer *fileListTransfer; + SystemAddress systemAddress; + unsigned short setId; + }; + + ThreadPool threadPool; + + friend int SendIRIToAddressCB(FileListTransfer::ThreadData threadData, bool *returnOutput, void* perThreadData); +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/FileListTransferCBInterface.hpp b/include/raknet/FileListTransferCBInterface.hpp new file mode 100644 index 0000000..1de388e --- /dev/null +++ b/include/raknet/FileListTransferCBInterface.hpp @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file FileListTransferCBInterface.h +/// + + +#ifndef __FILE_LIST_TRANSFER_CALLBACK_INTERFACE_H +#define __FILE_LIST_TRANSFER_CALLBACK_INTERFACE_H + +#include "RakMemoryOverride.hpp" +#include "FileListNodeContext.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +namespace RakNet +{ + +/// \brief Used by FileListTransfer plugin as a callback for when we get a file. +/// \details You get the last file when fileIndex==numberOfFilesInThisSet +/// \sa FileListTransfer +class FileListTransferCBInterface +{ +public: + // Note: If this structure is changed the struct in the swig files need to be changed as well + struct OnFileStruct + { + /// \brief The index into the set of files, from 0 to numberOfFilesInThisSet + unsigned fileIndex; + + /// \brief The name of the file + char fileName[512]; + + /// \brief The data pointed to by the file + char *fileData; + + /// \brief The amount of data to be downloaded for this file + BitSize_t byteLengthOfThisFile; + + /// \brief How many bytes of this file has been downloaded + BitSize_t bytesDownloadedForThisFile; + + /// \brief Files are transmitted in sets, where more than one set of files can be transmitted at the same time. + /// \details This is the identifier for the set, which is returned by FileListTransfer::SetupReceive + unsigned short setID; + + /// \brief The number of files that are in this set. + unsigned numberOfFilesInThisSet; + + /// \brief The total length of the transmitted files for this set, after being uncompressed + unsigned byteLengthOfThisSet; + + /// \brief The total length, in bytes, downloaded for this set. + unsigned bytesDownloadedForThisSet; + + /// \brief User data passed to one of the functions in the FileList class. + /// \details However, on error, this is instead changed to one of the enumerations in the PatchContext structure. + FileListNodeContext context; + + /// \brief Who sent this file + SystemAddress senderSystemAddress; + + /// \brief Who sent this file. Not valid when using TCP, only RakPeer (UDP) + RakNetGUID senderGuid; + }; + + // Note: If this structure is changed the struct in the swig files need to be changed as well + struct FileProgressStruct + { + /// \param[out] onFileStruct General information about this file, such as the filename and the first \a partLength bytes. You do NOT need to save this data yourself. The complete file will arrive normally. + OnFileStruct *onFileStruct; + /// \param[out] partCount The zero based index into partTotal. The percentage complete done of this file is 100 * (partCount+1)/partTotal + unsigned int partCount; + /// \param[out] partTotal The total number of parts this file was split into. Each part will be roughly the MTU size, minus the UDP header and RakNet headers + unsigned int partTotal; + /// \param[out] dataChunkLength How many bytes long firstDataChunk and iriDataChunk are + unsigned int dataChunkLength; + /// \param[out] firstDataChunk The first \a partLength of the final file. If you store identifying information about the file in the first \a partLength bytes, you can read them while the download is taking place. If this hasn't arrived yet, firstDataChunk will be 0 + char *firstDataChunk; + /// \param[out] iriDataChunk If the remote system is sending this file using IncrementalReadInterface, then this is the chunk we just downloaded. It will not exist in memory after this callback. You should either store this to disk, or in memory. If it is 0, then the file is smaller than one chunk, and will be held in memory automatically + char *iriDataChunk; + /// \param[out] iriWriteOffset Offset in bytes from the start of the file for the data pointed to by iriDataChunk + unsigned int iriWriteOffset; + /// \param[out] Who sent this file + SystemAddress senderSystemAddress; + /// \param[out] Who sent this file. Not valid when using TCP, only RakPeer (UDP) + RakNetGUID senderGuid; + /// \param[in] allocateIrIDataChunkAutomatically If true, then RakNet will hold iriDataChunk for you and return it in OnFile. Defaults to true + bool allocateIrIDataChunkAutomatically; + }; + + struct DownloadCompleteStruct + { + /// \brief Files are transmitted in sets, where more than one set of files can be transmitted at the same time. + /// \details This is the identifier for the set, which is returned by FileListTransfer::SetupReceive + unsigned short setID; + + /// \brief The number of files that are in this set. + unsigned numberOfFilesInThisSet; + + /// \brief The total length of the transmitted files for this set, after being uncompressed + unsigned byteLengthOfThisSet; + + /// \brief Who sent this file + SystemAddress senderSystemAddress; + + /// \brief Who sent this file. Not valid when using TCP, only RakPeer (UDP) + RakNetGUID senderGuid; + }; + + FileListTransferCBInterface() {} + virtual ~FileListTransferCBInterface() {} + + /// \brief Got a file. + /// \details This structure is only valid for the duration of this function call. + /// \return Return true to have RakNet delete the memory allocated to hold this file for this function call. + virtual bool OnFile(OnFileStruct *onFileStruct)=0; + + /// \brief Got part of a big file internally in RakNet + /// \details This is called in one of two circumstances: Either the transport layer is returning ID_PROGRESS_NOTIFICATION, or you got a block via IncrementalReadInterface + /// If the transport layer is returning ID_PROGRESS_NOTIFICATION (see RakPeer::SetSplitMessageProgressInterval()) then FileProgressStruct::iriDataChunk will be 0. + /// If this is a block via IncrementalReadInterface, then iriDataChunk will point to the block just downloaded. + /// If not using IncrementalReadInterface, then you only care about partCount and partTotal to tell how far the download has progressed. YOu can use firstDataChunk to read the first part of the file if desired. The file is usable when you get the OnFile callback. + /// If using IncrementalReadInterface and you let RakNet buffer the files in memory (default), then it is the same as above. The file is usable when you get the OnFile callback. + /// If using IncrementalReadInterface and you do not let RakNet buffer the files in memory, then set allocateIrIDataChunkAutomatically to false. Write the file to disk whenever you get OnFileProgress and iriDataChunk is not 0, and ignore OnFile. + virtual void OnFileProgress(FileProgressStruct *fps)=0; + + /// \brief Called while the handler is active by FileListTransfer + /// \details Return false when you are done with the class. + /// At that point OnDereference will be called and the class will no longer be maintained by the FileListTransfer plugin. + virtual bool Update(void) {return true;} + + /// \brief Called when the download is completed. + /// \details If you are finished with this class, return false. + /// At that point OnDereference will be called and the class will no longer be maintained by the FileListTransfer plugin. + /// Otherwise return true, and Update will continue to be called. + virtual bool OnDownloadComplete(DownloadCompleteStruct *dcs) {(void) dcs; return false;} + + /// \brief This function is called when this instance is about to be dereferenced by the FileListTransfer plugin. + /// \details Update will no longer be called. + /// It will will be deleted automatically if true was passed to FileListTransfer::SetupReceive::deleteHandler + /// Otherwise it is up to you to delete it yourself. + virtual void OnDereference(void) {} +}; + +} // namespace RakNet + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif + diff --git a/include/raknet/FileOperations.hpp b/include/raknet/FileOperations.hpp new file mode 100644 index 0000000..a677df1 --- /dev/null +++ b/include/raknet/FileOperations.hpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file FileOperations.h +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_FileOperations==1 + +#ifndef __FILE_OPERATIONS_H +#define __FILE_OPERATIONS_H + +#include "Export.hpp" + +bool RAK_DLL_EXPORT WriteFileWithDirectories( const char *path, char *data, unsigned dataLength ); +bool RAK_DLL_EXPORT IsSlash(unsigned char c); +void RAK_DLL_EXPORT AddSlash( char *input ); +void RAK_DLL_EXPORT QuoteIfSpaces(char *str); +bool RAK_DLL_EXPORT DirectoryExists(const char *directory); +unsigned int RAK_DLL_EXPORT GetFileLength(const char *path); + +#endif + +#endif // _RAKNET_SUPPORT_FileOperations diff --git a/include/raknet/FormatString.hpp b/include/raknet/FormatString.hpp new file mode 100644 index 0000000..8a2555f --- /dev/null +++ b/include/raknet/FormatString.hpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file FormatString.h +/// + + +#ifndef __FORMAT_STRING_H +#define __FORMAT_STRING_H + +#include "Export.hpp" + +extern "C" { +char * FormatString(const char *format, ...); +} +// Threadsafe +extern "C" { +char * FormatStringTS(char *output, const char *format, ...); +} + + +#endif + diff --git a/include/raknet/FullyConnectedMesh2.hpp b/include/raknet/FullyConnectedMesh2.hpp new file mode 100644 index 0000000..420e7dc --- /dev/null +++ b/include/raknet/FullyConnectedMesh2.hpp @@ -0,0 +1,424 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file FullyConnectedMesh2.h +/// \brief Fully connected mesh plugin, revision 2. +/// \details This will connect RakPeer to all connecting peers, and all peers the connecting peer knows about. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_FullyConnectedMesh2==1 + +#ifndef __FULLY_CONNECTED_MESH_2_H +#define __FULLY_CONNECTED_MESH_2_H + +#include "PluginInterface2.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" +#include "DS_List.hpp" +#include "RakString.hpp" +#include "BitStream.hpp" + +typedef int64_t FCM2Guid; + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \brief Fully connected mesh plugin, revision 2 +/// \details This will connect RakPeer to all connecting peers, and all peers the connecting peer knows about.
+/// It will also calculate which system has been running longest, to find out who should be host, if you need one system to act as a host +/// \pre You must also install the ConnectionGraph2 plugin in order to use SetConnectOnNewRemoteConnection() +/// \ingroup FULLY_CONNECTED_MESH_GROUP +class RAK_DLL_EXPORT FullyConnectedMesh2 : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(FullyConnectedMesh2) + + FullyConnectedMesh2(); + virtual ~FullyConnectedMesh2(); + + /// When the message ID_REMOTE_NEW_INCOMING_CONNECTION arrives, we try to connect to that system + /// If \a attemptConnection is false, you can manually connect to all systems listed in ID_REMOTE_NEW_INCOMING_CONNECTION with ConnectToRemoteNewIncomingConnections() + /// \note This will not work on any console. It will also not work if NAT punchthrough is needed. Generally, this should be false and you should connect manually. It is here for legacy reasons. + /// \param[in] attemptConnection If true, we try to connect to any systems we are notified about with ID_REMOTE_NEW_INCOMING_CONNECTION, which comes from the ConnectionGraph2 plugin. Defaults to true. + /// \param[in] pw The password to use to connect with. Only used if \a attemptConnection is true + void SetConnectOnNewRemoteConnection(bool attemptConnection, RakNet::RakString pw); + + /// \brief The connected host is whichever system we are connected to that has been running the longest. + /// \details Will return UNASSIGNED_RAKNET_GUID if we are not connected to anyone, or if we are connected and are calculating the host + /// If includeCalculating is true, will return the estimated calculated host as long as the calculation is nearly complete + /// includeCalculating should be true if you are taking action based on another system becoming host, because not all host calculations may complete at the exact same time + /// \sa ConnectionGraph2::GetLowestAveragePingSystem() . If you need one system in the peer to peer group to relay data, have the host call this function after host migration, and use that system + /// \return System address of whichever system is host. + RakNetGUID GetConnectedHost(void) const; + SystemAddress GetConnectedHostAddr(void) const; + + /// \return System address of whichever system is host. Always returns something, even though it may be our own system. + RakNetGUID GetHostSystem(void) const; + + /// \return If our system is host + bool IsHostSystem(void) const; + + /// Get the list of connected systems, from oldest connected to newest + /// This is also the order that the hosts will be chosen in + void GetHostOrder(DataStructures::List &hostList); + + /// \param[in] includeCalculating If true, and we are currently calculating a new host, return the new host if the calculation is nearly complete + /// \return If our system is host + bool IsConnectedHost(void) const; + + /// \brief Automatically add new connections to the fully connected mesh. + /// Each remote system that you want to check should be added as a participant, either through SetAutoparticipateConnections() or by calling this function + /// \details Defaults to true. + /// \param[in] b As stated + void SetAutoparticipateConnections(bool b); + + /// Clear our own host order, and recalculate as if we had just reconnected + /// Call this to reset the running time of the host just before joining/creating a game room for networking + void ResetHostCalculation(void); + + /// \brief if SetAutoparticipateConnections() is called with false, then you need to use AddParticipant before these systems will be added to the mesh + /// FullyConnectedMesh2 will track who is the who host among a fully connected mesh of participants + /// Each remote system that you want to check should be added as a participant, either through SetAutoparticipateConnections() or by calling this function + /// \param[in] participant The new participant + /// \param[in] userContext Static data to be passed around with each participant, which can be queried with GetParticipantData(). + /// \sa StartVerifiedJoin() + void AddParticipant(RakNetGUID rakNetGuid); + + /// Get the participants added with AddParticipant() + /// \param[out] participantList Participants added with AddParticipant(); + void GetParticipantList(DataStructures::List &participantList); + + /// \brief Returns if a participant is in the participant list + /// \param[in] RakNetGUID of the participant to query + /// \return True if in the list + bool HasParticipant(RakNetGUID participantGuid); + + /// \brief Reads userData written with SetMyContext() + /// \param[in] RakNetGUID of the participant to query + /// \param[out] userContext Pointer to BitStream to be written to + /// \return True if data was written + // bool GetParticipantContext(RakNetGUID participantGuid, BitStream *userContext); + + /// Set data for other systems to read with GetParticipantContext + /// \param[in] userContext Pointer to BitStream to be read from + // void SetMyContext(BitStream *userContext); + + /// Connect to all systems from ID_REMOTE_NEW_INCOMING_CONNECTION + /// You can call this if SetConnectOnNewRemoteConnection is false + /// \param[in] packet The packet containing ID_REMOTE_NEW_INCOMING_CONNECTION + /// \param[in] connectionPassword Password passed to RakPeerInterface::Connect() + /// \param[in] connectionPasswordLength Password length passed to RakPeerInterface::Connect() + void ConnectToRemoteNewIncomingConnections(Packet *packet); + + /// \brief Clear all memory and reset everything + void Clear(void); + + unsigned int GetParticipantCount(void) const; + void GetParticipantCount(unsigned int *participantListSize) const; + + /// In the simple case of forming a peer to peer mesh: + /// + /// 1. AddParticipant() is called on the host whenever you get a new connection + /// 2. The host sends all participants to the new client + /// 3. The client connects to the participant list + /// + /// However, the above steps assumes connections to all systems in the mesh always complete. + /// When there is a risk of failure, such as if relying on NATPunchthroughClient, you may not want to call AddParticipant() until are connections have completed to all other particpants + /// StartVerifiedJoin() can manage the overhead of the negotiation involved so the programmer only has to deal with overall success or failure + /// + /// Processing: + /// 1. Send the RakNetGUID and SystemAddress values of GetParticipantList() to the client with ID_FCM2_VERIFIED_JOIN_START + /// 2. The client, on ID_FCM2_VERIFIED_JOIN_START, can execute NatPunchthroughClient::OpenNAT() (optional), followed by RakPeerInterface::Connect() if punchthrough success, for each system returned from GetVerifiedJoinRequiredProcessingList() + /// 3. After all participants in step 2 have connected, failed to connect, or failed NatPunchthrough, the client automatically sends the results to the server. + /// 4. The server compares the results of the operations in step 2 with the values from GetParticpantList(). + /// 4A. If the client failed to connect to a current participant, return ID_FCM2_VERIFIED_JOIN_FAILED to the client. CloseConnection() is automatically called on the client for the failed participants. + /// 4B. If AddParticipant() was called between steps 1 and 4, go back to step 1, transmitting new participants. + /// 4C. If the client successfully connected to all participants, the server gets ID_FCM2_VERIFIED_JOIN_CAPABLE. The server programmer, on the same frame, should execute RespondOnVerifiedJoinCapable() to either accept or reject the client. + /// 5. If the client got ID_FCM2_VERIFIED_JOIN_ACCEPTED, AddParticipant() is automatically called for each system in the mesh. + /// 6. If the client got ID_FCM2_VERIFIED_JOIN_REJECTED, CloseConnection() is automatically called for each system in the mesh. The connection is NOT automatically closed to the original host that sent StartVerifiedJoin(). + /// 7. If the client's connection to the server was lost before getting ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED, return to the programmer ID_FCM2_VERIFIED_JOIN_FAILED and call RakPeerInterface::CloseConnection() + /// + /// \brief Notify the client of GetParticipantList() in order to connect to each of those systems until the mesh has been completed + /// \param[in] client The system to send ID_FCM2_VERIFIED_JOIN_START to + virtual void StartVerifiedJoin(RakNetGUID client); + + /// \brief On ID_FCM2_VERIFIED_JOIN_CAPABLE , accept or reject the new connection + /// \code + /// fullyConnectedMesh->RespondOnVerifiedJoinCapable(packet, true, 0); + /// \endcode + /// \param[in] packet The system that sent ID_FCM2_VERIFIED_JOIN_CAPABLE. Based on \accept, ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED will be sent in reply + /// \param[in] accept True to accept, and thereby automatically call AddParticipant() on all systems on the mesh. False to reject, and call CloseConnection() to all mesh systems on the target + /// \param[in] additionalData Any additional data you want to add to the ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED messages + /// \sa WriteVJCUserData() + virtual void RespondOnVerifiedJoinCapable(Packet *packet, bool accept, BitStream *additionalData); + + /// \brief On ID_FCM2_VERIFIED_JOIN_START, read the SystemAddress and RakNetGUID values of each system to connect to + /// \code + /// DataStructures::List addresses; + /// DataStructures::List guids; + /// fullyConnectedMesh->GetVerifiedJoinRequiredProcessingList(packet->guid, addresses, guids); + /// for (unsigned int i=0; i < addresses.Size(); i++) + /// rakPeer[i]->Connect(addresses[i].ToString(false), addresses[i].GetPort(), 0, 0); + /// \endcode + /// \param[in] host Which system sent ID_FCM2_VERIFIED_JOIN_START + /// \param[out] addresses SystemAddress values of systems to connect to. List has the same number and order as \a guids + /// \param[out] guids RakNetGUID values of systems to connect to. List has the same number and order as \a guids + /// \param[out] userData What was written with WriteVJSUserData + virtual void GetVerifiedJoinRequiredProcessingList(RakNetGUID host, + DataStructures::List &addresses, + DataStructures::List &guids, + DataStructures::List &userData); + + /// \brief On ID_FCM2_VERIFIED_JOIN_ACCEPTED, read additional data passed to RespondOnVerifiedJoinCapable() + /// \code + /// bool thisSystemAccepted; + /// DataStructures::List systemsAccepted; + /// RakNet::BitStream additionalData; + /// fullyConnectedMesh->GetVerifiedJoinAcceptedAdditionalData(packet, &thisSystemAccepted, systemsAccepted, &additionalData); + /// \endcode + /// \param[in] packet Packet containing the ID_FCM2_VERIFIED_JOIN_ACCEPTED message + /// \param[out] thisSystemAccepted If true, it was this instance of RakPeerInterface that was accepted. If false, this is notification for another system + /// \param[out] systemsAccepted Which system(s) were added with AddParticipant(). If \a thisSystemAccepted is false, this list will only have length 1 + /// \param[out] additionalData \a additionalData parameter passed to RespondOnVerifiedJoinCapable() + virtual void GetVerifiedJoinAcceptedAdditionalData(Packet *packet, bool *thisSystemAccepted, DataStructures::List &systemsAccepted, BitStream *additionalData); + + /// \brief On ID_FCM2_VERIFIED_JOIN_REJECTED, read additional data passed to RespondOnVerifiedJoinCapable() + /// \details This does not automatically close the connection. The following code will do so: + /// \code + /// rakPeer[i]->CloseConnection(packet->guid, true); + /// \endcode + /// \param[in] packet Packet containing the ID_FCM2_VERIFIED_JOIN_REJECTED message + /// \param[out] additionalData \a additionalData parameter passed to RespondOnVerifiedJoinCapable(). + virtual void GetVerifiedJoinRejectedAdditionalData(Packet *packet, BitStream *additionalData); + + /// Override to write data when ID_FCM2_VERIFIED_JOIN_CAPABLE is sent + virtual void WriteVJCUserData(RakNet::BitStream *bsOut) {(void) bsOut;} + + /// Use to read data written from WriteVJCUserData() + /// \code + /// RakNet::BitStream bsIn(packet->data,packet->length,false); + /// FullyConnectedMesh2::SkipToVJCUserData(&bsIn); + /// // Your code here + static void SkipToVJCUserData(RakNet::BitStream *bsIn); + + /// Write custom user data to be sent with ID_FCM2_VERIFIED_JOIN_START, per user + /// \param[out] bsOut Write your data here, if any. Has to match what is read by ReadVJSUserData + /// \param[in] userGuid The RakNetGuid of the user you are writing for + /// \param[in] userContext The data set with SetMyContext() for that system. May be empty. To properly write userContext, you will need to first write userContext->GetNumberOfBitsUsed(), followed by bsOut->Write(userContext); + //virtual void WriteVJSUserData(RakNet::BitStream *bsOut, RakNetGUID userGuid, BitStream *userContext) {(void) bsOut; (void) userGuid; (void) userContext;} + virtual void WriteVJSUserData(RakNet::BitStream *bsOut, RakNetGUID userGuid) {(void) bsOut; (void) userGuid;} + + /// \internal + RakNet::TimeUS GetElapsedRuntime(void); + + /// \internal + virtual PluginReceiveResult OnReceive(Packet *packet); + /// \internal + virtual void OnRakPeerStartup(void); + /// \internal + virtual void OnAttach(void); + /// \internal + virtual void OnRakPeerShutdown(void); + /// \internal + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + /// \internal + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + /// \internal + virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason); + + /// \internal + struct FCM2Participant + { + FCM2Participant() {} + FCM2Participant(const FCM2Guid &_fcm2Guid, const RakNetGUID &_rakNetGuid) : fcm2Guid(_fcm2Guid), rakNetGuid(_rakNetGuid) {} + + // Low half is a random number. + // High half is the order we connected in (totalConnectionCount) + FCM2Guid fcm2Guid; + RakNetGUID rakNetGuid; + // BitStream userContext; + }; + + enum JoinInProgressState + { + JIPS_PROCESSING, + JIPS_FAILED, + JIPS_CONNECTED, + JIPS_UNNECESSARY, + }; + + struct VerifiedJoinInProgressMember + { + SystemAddress systemAddress; + RakNetGUID guid; + JoinInProgressState joinInProgressState; + BitStream *userData; + + bool workingFlag; + }; + + /// \internal + struct VerifiedJoinInProgress + { + RakNetGUID requester; + DataStructures::List vjipMembers; + //bool sentResults; + }; + + /// \internal for debugging + unsigned int GetTotalConnectionCount(void) const; + +protected: + void PushNewHost(const RakNetGUID &guid, RakNetGUID oldHost); + void SendOurFCMGuid(SystemAddress addr); + void SendFCMGuidRequest(RakNetGUID rakNetGuid); + void SendConnectionCountResponse(SystemAddress addr, unsigned int responseTotalConnectionCount); + void OnRequestFCMGuid(Packet *packet); + //void OnUpdateUserContext(Packet *packet); + void OnRespondConnectionCount(Packet *packet); + void OnInformFCMGuid(Packet *packet); + void OnUpdateMinTotalConnectionCount(Packet *packet); + void AssignOurFCMGuid(void); + void CalculateHost(RakNetGUID *rakNetGuid, FCM2Guid *fcm2Guid); + // bool AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid, BitStream *userContext ); + bool AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid ); + void CalculateAndPushHost(void); + bool ParticipantListComplete(void); + void IncrementTotalConnectionCount(unsigned int i); + PluginReceiveResult OnVerifiedJoinStart(Packet *packet); + PluginReceiveResult OnVerifiedJoinCapable(Packet *packet); + virtual void OnVerifiedJoinFailed(RakNetGUID hostGuid, bool callCloseConnection); + virtual void OnVerifiedJoinAccepted(Packet *packet); + virtual void OnVerifiedJoinRejected(Packet *packet); + unsigned int GetJoinsInProgressIndex(RakNetGUID requester) const; + void UpdateVerifiedJoinInProgressMember(const AddressOrGUID systemIdentifier, RakNetGUID guidToAssign, JoinInProgressState newState); + bool ProcessVerifiedJoinInProgressIfCompleted(VerifiedJoinInProgress *vjip); + void ReadVerifiedJoinInProgressMember(RakNet::BitStream *bsIn, VerifiedJoinInProgressMember *vjipm); + unsigned int GetVerifiedJoinInProgressMemberIndex(const AddressOrGUID systemIdentifier, VerifiedJoinInProgress *vjip); + void DecomposeJoinCapable(Packet *packet, VerifiedJoinInProgress *vjip); + void WriteVerifiedJoinCapable(RakNet::BitStream *bsOut, VerifiedJoinInProgress *vjip); + void CategorizeVJIP(VerifiedJoinInProgress *vjip, + DataStructures::List &participatingMembersOnClientSucceeded, + DataStructures::List &participatingMembersOnClientFailed, + DataStructures::List &participatingMembersNotOnClient, + DataStructures::List &clientMembersNotParticipatingSucceeded, + DataStructures::List &clientMembersNotParticipatingFailed); + + // Used to track how long RakNet has been running. This is so we know who has been running longest + RakNet::TimeUS startupTime; + + // Option for SetAutoparticipateConnections + bool autoParticipateConnections; + + // totalConnectionCount is roughly maintained across all systems, and increments by 1 each time a new system connects to the mesh + // It is always kept at the highest known value + // It is used as the high 4 bytes for new FCMGuids. This causes newer values of FCM2Guid to be higher than lower values. The lowest value is the host. + unsigned int totalConnectionCount; + + // Our own ourFCMGuid. Starts at unassigned (0). Assigned once we send ID_FCM2_REQUEST_FCMGUID and get back ID_FCM2_RESPOND_CONNECTION_COUNT + FCM2Guid ourFCMGuid; + + /// List of systems we know the FCM2Guid for + DataStructures::List fcm2ParticipantList; + + RakNetGUID lastPushedHost; + + // Optimization: Store last calculated host in these variables. + RakNetGUID hostRakNetGuid; + FCM2Guid hostFCM2Guid; + + RakNet::RakString connectionPassword; + bool connectOnNewRemoteConnections; + + DataStructures::List joinsInProgress; + BitStream myContext; +}; + +} // namespace RakNet + +/* +Startup() +ourFCMGuid=unknown +totalConnectionCount=0 +Set startupTime + +AddParticipant() +if (sender by guid is a participant) +return; +AddParticipantInternal(guid); +if (ourFCMGuid==unknown) +Send to that system a request for their fcmGuid, totalConnectionCount. Inform startupTime. +else +Send to that system a request for their fcmGuid. Inform total connection count, our fcmGuid + +OnRequestGuid() +if (sender by guid is not a participant) +{ + // They added us as a participant, but we didn't add them. This can be caused by lag where both participants are not added at the same time. + // It doesn't affect the outcome as long as we still process the data + AddParticipantInternal(guid); +} +if (ourFCMGuid==unknown) +{ + if (includedStartupTime) + { + // Nobody has a fcmGuid + + if (their startup time is greater than our startup time) + ReplyConnectionCount(1); + else + ReplyConnectionCount(2); + } + else + { + // They have a fcmGuid, we do not + + SetMaxTotalConnectionCount(remoteCount); + AssignTheirGuid() + GenerateOurGuid(); + SendOurGuid(all); + } +} +else +{ + if (includedStartupTime) + { + // We have a fcmGuid they do not + + ReplyConnectionCount(totalConnectionCount+1); + SendOurGuid(sender); + } + else + { + // We both have fcmGuids + + SetMaxTotalConnectionCount(remoteCount); + AssignTheirGuid(); + SendOurGuid(sender); + } +} + +OnReplyConnectionCount() +SetMaxTotalConnectionCount(remoteCount); +GenerateOurGuid(); +SendOurGuid(allParticipants); + +OnReceiveTheirGuid() +AssignTheirGuid() +*/ + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/GetTime.hpp b/include/raknet/GetTime.hpp new file mode 100644 index 0000000..98abf0b --- /dev/null +++ b/include/raknet/GetTime.hpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file GetTime.h +/// \brief Returns the value from QueryPerformanceCounter. This is the function RakNet uses to represent time. This time won't match the time returned by GetTimeCount(). See http://www.jenkinssoftware.com/forum/index.php?topic=2798.0 +/// + + +#ifndef __GET_TIME_H +#define __GET_TIME_H + +#include "Export.hpp" +#include "RakNetTime.hpp" // For RakNet::TimeMS + +namespace RakNet +{ + /// Same as GetTimeMS + /// Holds the time in either a 32 or 64 bit variable, depending on __GET_TIME_64BIT + RakNet::Time RAK_DLL_EXPORT GetTime( void ); + + /// Return the time as 32 bit + /// \note The maximum delta between returned calls is 1 second - however, RakNet calls this constantly anyway. See NormalizeTime() in the cpp. + RakNet::TimeMS RAK_DLL_EXPORT GetTimeMS( void ); + + /// Return the time as 64 bit + /// \note The maximum delta between returned calls is 1 second - however, RakNet calls this constantly anyway. See NormalizeTime() in the cpp. + RakNet::TimeUS RAK_DLL_EXPORT GetTimeUS( void ); + + /// a > b? + extern RAK_DLL_EXPORT bool GreaterThan(RakNet::Time a, RakNet::Time b); + /// a < b? + extern RAK_DLL_EXPORT bool LessThan(RakNet::Time a, RakNet::Time b); +} + +#endif diff --git a/include/raknet/Getche.hpp b/include/raknet/Getche.hpp new file mode 100644 index 0000000..af6c1c9 --- /dev/null +++ b/include/raknet/Getche.hpp @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#if defined(_WIN32) +#include /* getche() */ + +#else +#include +#include +#include +char getche(); +#endif diff --git a/include/raknet/Gets.hpp b/include/raknet/Gets.hpp new file mode 100644 index 0000000..bfe4d3d --- /dev/null +++ b/include/raknet/Gets.hpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __GETS__H_ +#define __GETS__H_ + +#ifdef __cplusplus +extern "C" { + +char * Gets ( char * str, int num ); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/include/raknet/GridSectorizer.hpp b/include/raknet/GridSectorizer.hpp new file mode 100644 index 0000000..f20f5ae --- /dev/null +++ b/include/raknet/GridSectorizer.hpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef _GRID_SECTORIZER_H +#define _GRID_SECTORIZER_H + +//#define _USE_ORDERED_LIST + +#include "RakMemoryOverride.hpp" + +#ifdef _USE_ORDERED_LIST +#include "DS_OrderedList.hpp" +#else +#include "DS_List.hpp" +#endif + +class GridSectorizer +{ +public: + GridSectorizer(); + ~GridSectorizer(); + + // _cellWidth, _cellHeight is the width and height of each cell in world units + // minX, minY, maxX, maxY are the world dimensions (can be changed to dynamically allocate later if needed) + void Init(const float _maxCellWidth, const float _maxCellHeight, const float minX, const float minY, const float maxX, const float maxY); + + // Adds a pointer to the grid with bounding rectangle dimensions + void AddEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); + +#ifdef _USE_ORDERED_LIST + + // Removes a pointer, as above + void RemoveEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); + + // Adds and removes in one pass, more efficient than calling both functions consecutively + void MoveEntry(void *entry, const float sourceMinX, const float sourceMinY, const float sourceMaxX, const float sourceMaxY, + const float destMinX, const float destMinY, const float destMaxX, const float destMaxY); + +#endif + + // Adds to intersectionList all entries in a certain radius + void GetEntries(DataStructures::List& intersectionList, const float minX, const float minY, const float maxX, const float maxY); + + void Clear(void); + +protected: + int WorldToCellX(const float input) const; + int WorldToCellY(const float input) const; + int WorldToCellXOffsetAndClamped(const float input) const; + int WorldToCellYOffsetAndClamped(const float input) const; + + // Returns true or false if a position crosses cells in the grid. If false, you don't need to move entries + bool PositionCrossesCells(const float originX, const float originY, const float destinationX, const float destinationY) const; + + float cellOriginX, cellOriginY; + float cellWidth, cellHeight; + float invCellWidth, invCellHeight; + float gridWidth, gridHeight; + int gridCellWidthCount, gridCellHeightCount; + + + // int gridWidth, gridHeight; + +#ifdef _USE_ORDERED_LIST + DataStructures::OrderedList* grid; +#else + DataStructures::List* grid; +#endif +}; + +#endif diff --git a/include/raknet/HTTPConnection.hpp b/include/raknet/HTTPConnection.hpp new file mode 100644 index 0000000..7dae877 --- /dev/null +++ b/include/raknet/HTTPConnection.hpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file HTTPConnection.h +/// \brief Contains HTTPConnection, used to communicate with web servers +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_HTTPConnection==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#ifndef __HTTP_CONNECTION +#define __HTTP_CONNECTION + +#include "Export.hpp" +#include "RakString.hpp" +#include "RakMemoryOverride.hpp" +#include "RakNetTypes.hpp" +#include "DS_Queue.hpp" + +namespace RakNet +{ +/// Forward declarations +class TCPInterface; +struct SystemAddress; + +/// \brief Use HTTPConnection to communicate with a web server. +/// \details Start an instance of TCPInterface via the Start() command. +/// Instantiate a new instance of HTTPConnection, and associate TCPInterface with the class in the constructor. +/// Use Post() to send commands to the web server, and ProcessDataPacket() to update the connection with packets returned from TCPInterface that have the system address of the web server +/// This class will handle connecting and reconnecting as necessary. +/// +/// Note that only one Post() can be handled at a time. +/// \deprecated, use HTTPConnection2 +class RAK_DLL_EXPORT HTTPConnection +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(HTTPConnection) + + /// Returns a HTTP object associated with this tcp connection + HTTPConnection(); + virtual ~HTTPConnection(); + + /// \pre tcp should already be started + void Init(TCPInterface *_tcp, const char *host, unsigned short port=80); + + /// Submit data to the HTTP server + /// HTTP only allows one request at a time per connection + /// + /// \pre IsBusy()==false + /// \param path the path on the remote server you want to POST to. For example "index.html" + /// \param data A NULL terminated string to submit to the server + /// \param contentType "Content-Type:" passed to post. + void Post(const char *path, const char *data, const char *_contentType="application/x-www-form-urlencoded"); + + /// Get a file from a webserver + /// \param path the path on the remote server you want to GET from. For example "index.html" + void Get(const char *path); + + /// Is there a Read result ready? + bool HasRead(void) const; + + /// Get one result from the server + /// \pre HasResult must return true + RakNet::RakString Read(void); + + /// Call periodically to do time-based updates + void Update(void); + + /// Returns the address of the server we are connected to + SystemAddress GetServerAddress(void) const; + + /// Process an HTTP data packet returned from TCPInterface + /// Returns true when we have gotten all the data from the HTTP server. + /// If this returns true then it's safe to Post() another request + /// Deallocate the packet as usual via TCPInterface + /// \param packet NULL or a packet associated with our host and port + void ProcessTCPPacket(Packet *packet); + + /// Results of HTTP requests. Standard response codes are < 999 + /// ( define HTTP codes and our internal codes as needed ) + enum ResponseCodes { NoBody=1001, OK=200, Deleted=1002 }; + + HTTPConnection& operator=(const HTTPConnection& rhs){(void) rhs; return *this;} + + /// Encapsulates a raw HTTP response and response code + struct BadResponse + { + public: + BadResponse() {code=0;} + + BadResponse(const unsigned char *_data, int _code) + : data((const char *)_data), code(_code) {} + + BadResponse(const char *_data, int _code) + : data(_data), code(_code) {} + + operator int () const { return code; } + + RakNet::RakString data; + int code; // ResponseCodes + }; + + /// Queued events of failed exchanges with the HTTP server + bool HasBadResponse(int *code, RakNet::RakString *data); + + /// Returns false if the connection is not doing anything else + bool IsBusy(void) const; + + /// \internal + int GetState(void) const; + + struct OutgoingCommand + { + RakNet::RakString remotePath; + RakNet::RakString data; + RakNet::RakString contentType; + bool isPost; + }; + + DataStructures::Queue outgoingCommand; + OutgoingCommand currentProcessingCommand; + +private: + SystemAddress server; + TCPInterface *tcp; + RakNet::RakString host; + unsigned short port; + DataStructures::Queue badResponses; + + enum ConnectionState + { + CS_NONE, + CS_DISCONNECTING, + CS_CONNECTING, + CS_CONNECTED, + CS_PROCESSING, + } connectionState; + + RakNet::RakString incomingData; + DataStructures::Queue results; + + void CloseConnection(); + + /* + enum { RAK_HTTP_INITIAL, + RAK_HTTP_STARTING, + RAK_HTTP_CONNECTING, + RAK_HTTP_ESTABLISHED, + RAK_HTTP_REQUEST_SENT, + RAK_HTTP_IDLE } state; + + RakNet::RakString outgoing, incoming, path, contentType; + void Process(Packet *packet); // the workhorse + + // this helps check the various status lists in TCPInterface + typedef SystemAddress (TCPInterface::*StatusCheckFunction)(void); + bool InList(StatusCheckFunction func); + */ + +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/HTTPConnection2.hpp b/include/raknet/HTTPConnection2.hpp new file mode 100644 index 0000000..f03178e --- /dev/null +++ b/include/raknet/HTTPConnection2.hpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file HTTPConnection2.h +/// \brief Contains HTTPConnection2, used to communicate with web servers +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#ifndef __HTTP_CONNECTION_2 +#define __HTTP_CONNECTION_2 + +#include "Export.hpp" +#include "RakString.hpp" +#include "RakMemoryOverride.hpp" +#include "RakNetTypes.hpp" +#include "DS_List.hpp" +#include "DS_Queue.hpp" +#include "PluginInterface2.hpp" +#include "SimpleMutex.hpp" + +namespace RakNet +{ +/// Forward declarations +class TCPInterface; +struct SystemAddress; + +/// \brief Use HTTPConnection2 to communicate with a web server. +/// \details Start an instance of TCPInterface via the Start() command. +/// This class will handle connecting to transmit a request +class RAK_DLL_EXPORT HTTPConnection2 : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(HTTPConnection2) + + HTTPConnection2(); + virtual ~HTTPConnection2(); + + /// \brief Connect to, then transmit a request to a TCP based server + /// \param[in] tcp An instance of TCPInterface that previously had TCPInterface::Start() called + /// \param[in] stringToTransmit What string to transmit. See RakString::FormatForPOST(), RakString::FormatForGET(), RakString::FormatForDELETE() + /// \param[in] host The IP address to connect to + /// \param[in] port The port to connect to + /// \param[in] useSSL If to use SSL to connect. OPEN_SSL_CLIENT_SUPPORT must be defined to 1 in RakNetDefines.h or RakNetDefinesOverrides.h + /// \param[in] ipVersion 4 for IPV4, 6 for IPV6 + /// \param[in] useAddress Assume we are connected to this address and send to it, rather than do a lookup + /// \param[in] userData + /// \return false if host is not a valid IP address or domain name + bool TransmitRequest(const char* stringToTransmit, const char* host, unsigned short port=80, bool useSSL=false, int ipVersion=4, SystemAddress useAddress=UNASSIGNED_SYSTEM_ADDRESS, void *userData=0); + + /// \brief Check for and return a response from a prior call to TransmitRequest() + /// As TCP is stream based, you may get a webserver reply over several calls to TCPInterface::Receive() + /// HTTPConnection2 will store Packet::data and return the response to you either when the connection to the webserver is lost, or enough data has been received() + /// This will only potentially return true after a call to ProcessTCPPacket() or OnLostConnection() + /// \param[out] stringTransmitted The original string transmitted + /// \param[out] hostTransmitted The parameter of the same name passed to TransmitRequest() + /// \param[out] responseReceived The response, if any + /// \param[out] hostReceived The SystemAddress from ProcessTCPPacket() or OnLostConnection() + /// \param[out] contentOffset The offset from the start of responseReceived to the data body. Equivalent to searching for \r\n\r\n in responseReceived. + /// \param[out] userData Whatever you passed to TransmitRequest + /// \return true if there was a response. false if not. + bool GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, int &contentOffset, void **userData ); + bool GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, int &contentOffset ); + + /// \brief Return if any requests are pending + bool IsBusy(void) const; + + /// \brief Return if any requests are waiting to be read by the user + bool HasResponse(void) const; + + struct Request + { + RakString stringToTransmit; + RakString stringReceived; + RakString host; + SystemAddress hostEstimatedAddress; + SystemAddress hostCompletedAddress; + unsigned short port; + bool useSSL; + int contentOffset; + int contentLength; + int ipVersion; + void *userData; + bool chunked; + size_t thisChunkSize; + size_t bytesReadForThisChunk; + }; + + /// \internal + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason); + +protected: + + bool IsConnected(SystemAddress sa); + void SendRequest(Request *request); + void RemovePendingRequest(SystemAddress sa); + void SendNextPendingRequest(void); + void SendPendingRequestToConnectedSystem(SystemAddress sa); + + DataStructures::Queue pendingRequests; + DataStructures::List sentRequests; + DataStructures::List completedRequests; + + SimpleMutex pendingRequestsMutex, sentRequestsMutex, completedRequestsMutex; + +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/IncrementalReadInterface.hpp b/include/raknet/IncrementalReadInterface.hpp new file mode 100644 index 0000000..ba9a9e4 --- /dev/null +++ b/include/raknet/IncrementalReadInterface.hpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __INCREMENTAL_READ_INTERFACE_H +#define __INCREMENTAL_READ_INTERFACE_H + +#include "FileListNodeContext.hpp" +#include "Export.hpp" + +namespace RakNet +{ + +class RAK_DLL_EXPORT IncrementalReadInterface +{ +public: + IncrementalReadInterface() {} + virtual ~IncrementalReadInterface() {} + + /// Read part of a file into \a destination + /// Return the number of bytes written. Return 0 when file is done. + /// \param[in] filename Filename to read + /// \param[in] startReadBytes What offset from the start of the file to read from + /// \param[in] numBytesToRead How many bytes to read. This is also how many bytes have been allocated to preallocatedDestination + /// \param[out] preallocatedDestination Write your data here + /// \return The number of bytes read, or 0 if none + virtual unsigned int GetFilePart( const char *filename, unsigned int startReadBytes, unsigned int numBytesToRead, void *preallocatedDestination, FileListNodeContext context); +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/InternalPacket.hpp b/include/raknet/InternalPacket.hpp new file mode 100644 index 0000000..e6ae67a --- /dev/null +++ b/include/raknet/InternalPacket.hpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] A class which stores a user message, and all information associated with sending and receiving that message. +/// + +#ifndef __INTERNAL_PACKET_H +#define __INTERNAL_PACKET_H + +#include "PacketPriority.hpp" +#include "RakNetTypes.hpp" +#include "RakMemoryOverride.hpp" +#include "RakNetDefines.hpp" +#include "NativeTypes.hpp" +#include "RakNetDefines.hpp" +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 +#include "CCRakNetUDT.hpp" +#else +#include "CCRakNetSlidingWindow.hpp" +#endif + +namespace RakNet { + +typedef uint16_t SplitPacketIdType; +typedef uint32_t SplitPacketIndexType; + +/// This is the counter used for holding packet numbers, so we can detect duplicate packets. It should be large enough that if the variables +/// Internally assumed to be 4 bytes, but written as 3 bytes in ReliabilityLayer::WriteToBitStreamFromInternalPacket +typedef uint24_t MessageNumberType; + +/// This is the counter used for holding ordered packet numbers, so we can detect out-of-order packets. It should be large enough that if the variables +/// were to wrap, the newly wrapped values would no longer be in use. Warning: Too large of a value wastes bandwidth! +typedef MessageNumberType OrderingIndexType; + +typedef RakNet::TimeUS RemoteSystemTimeType; + +struct InternalPacketFixedSizeTransmissionHeader +{ + /// A unique numerical identifier given to this user message. Used to identify reliable messages on the network + MessageNumberType reliableMessageNumber; + ///The ID used as identification for ordering messages. Also included in sequenced messages + OrderingIndexType orderingIndex; + // Used only with sequenced messages + OrderingIndexType sequencingIndex; + ///What ordering channel this packet is on, if the reliability type uses ordering channels + unsigned char orderingChannel; + ///The ID of the split packet, if we have split packets. This is the maximum number of split messages we can send simultaneously per connection. + SplitPacketIdType splitPacketId; + ///If this is a split packet, the index into the array of subsplit packets + SplitPacketIndexType splitPacketIndex; + ///The size of the array of subsplit packets + SplitPacketIndexType splitPacketCount;; + ///How many bits long the data is + BitSize_t dataBitLength; + ///What type of reliability algorithm to use with this packet + PacketReliability reliability; + // Not endian safe + // unsigned char priority : 3; + // unsigned char reliability : 5; +}; + +/// Used in InternalPacket when pointing to sharedDataBlock, rather than allocating itself +struct InternalPacketRefCountedData +{ + unsigned char *sharedDataBlock; + unsigned int refCount; +}; + +/// Holds a user message, and related information +/// Don't use a constructor or destructor, due to the memory pool I am using +struct InternalPacket : public InternalPacketFixedSizeTransmissionHeader +{ + /// Identifies the order in which this number was sent. Used locally + MessageNumberType messageInternalOrder; + /// Has this message number been assigned yet? We don't assign until the message is actually sent. + /// This fixes a bug where pre-determining message numbers and then sending a message on a different channel creates a huge gap. + /// This causes performance problems and causes those messages to timeout. + bool messageNumberAssigned; + /// Was this packet number used this update to track windowing drops or increases? Each packet number is only used once per update. +// bool allowWindowUpdate; + ///When this packet was created + RakNet::TimeUS creationTime; + ///The resendNext time to take action on this packet + RakNet::TimeUS nextActionTime; + // For debugging + RakNet::TimeUS retransmissionTime; + // Size of the header when encoded into a bitstream + BitSize_t headerLength; + /// Buffer is a pointer to the actual data, assuming this packet has data at all + unsigned char *data; + /// How to alloc and delete the data member + enum AllocationScheme + { + /// Data is allocated using rakMalloc. Just free it + NORMAL, + + /// data points to a larger block of data, where the larger block is reference counted. internalPacketRefCountedData is used in this case + REF_COUNTED, + + /// If allocation scheme is STACK, data points to stackData and should not be deallocated + /// This is only used when sending. Received packets are deallocated in RakPeer + STACK + } allocationScheme; + InternalPacketRefCountedData *refCountedData; + /// How many attempts we made at sending this message + unsigned char timesSent; + /// The priority level of this packet + PacketPriority priority; + /// If the reliability type requires a receipt, then return this number with it + uint32_t sendReceiptSerial; + + // Used for the resend queue + // Linked list implementation so I can remove from the list via a pointer, without finding it in the list + InternalPacket *resendPrev, *resendNext,*unreliablePrev,*unreliableNext; + + unsigned char stackData[128]; +}; + +} // namespace RakNet + +#endif + diff --git a/include/raknet/Itoa.hpp b/include/raknet/Itoa.hpp new file mode 100644 index 0000000..31f9773 --- /dev/null +++ b/include/raknet/Itoa.hpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAK_ITOA_H +#define __RAK_ITOA_H + +#ifdef __cplusplus +extern "C" { +#endif + +char* Itoa( int value, char* result, int base ); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/include/raknet/Kbhit.hpp b/include/raknet/Kbhit.hpp new file mode 100644 index 0000000..44ffe4e --- /dev/null +++ b/include/raknet/Kbhit.hpp @@ -0,0 +1,84 @@ +/***************************************************************************** +kbhit() and getch() for Linux/UNIX +Chris Giese http://my.execpc.com/~geezer +Release date: ? +This code is public domain (no copyright). +You can do whatever you want with it. +*****************************************************************************/ +#if defined(_WIN32) +#include /* kbhit(), getch() */ + +#else +#include /* struct timeval, select() */ +/* ICANON, ECHO, TCSANOW, struct termios */ +#include /* tcgetattr(), tcsetattr() */ +#include /* atexit(), exit() */ +#include /* read() */ +#include /* printf() */ +#include /* memcpy */ + +static struct termios g_old_kbd_mode; +/***************************************************************************** +*****************************************************************************/ +static void cooked(void) +{ + tcsetattr(0, TCSANOW, &g_old_kbd_mode); +} +/***************************************************************************** +*****************************************************************************/ +static void raw(void) +{ + static char init; +/**/ + struct termios new_kbd_mode; + + if(init) + return; +/* put keyboard (stdin, actually) in raw, unbuffered mode */ + tcgetattr(0, &g_old_kbd_mode); + memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios)); + new_kbd_mode.c_lflag &= ~(ICANON /*| ECHO */ ); + new_kbd_mode.c_cc[VTIME] = 0; + new_kbd_mode.c_cc[VMIN] = 1; + tcsetattr(0, TCSANOW, &new_kbd_mode); +/* when we exit, go back to normal, "cooked" mode */ + atexit(cooked); + + init = 1; +} +/***************************************************************************** +*****************************************************************************/ +static int kbhit(void) +{ + struct timeval timeout; + fd_set read_handles; + int status; + + raw(); +/* check stdin (fd 0) for activity */ + FD_ZERO(&read_handles); + FD_SET(0, &read_handles); + timeout.tv_sec = timeout.tv_usec = 0; + status = select(0 + 1, &read_handles, NULL, NULL, &timeout); + if(status < 0) + { + printf("select() failed in kbhit()\n"); + exit(1); + } + return status; +} +/***************************************************************************** +*****************************************************************************/ +static int getch(void) +{ + unsigned char temp; + + raw(); +/* stdin = fd 0 */ + if(read(0, &temp, 1) != 1) + return 0; + return temp; +} +#endif + + diff --git a/include/raknet/LinuxStrings.hpp b/include/raknet/LinuxStrings.hpp new file mode 100644 index 0000000..67f9829 --- /dev/null +++ b/include/raknet/LinuxStrings.hpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef _GCC_WIN_STRINGS +#define _GCC_WIN_STRINGS + +#if defined(__native_client__) + #ifndef _stricmp + int _stricmp(const char* s1, const char* s2); + #endif + int _strnicmp(const char* s1, const char* s2, size_t n); + char *_strlwr(char * str ); + #define _vsnprintf vsnprintf +#else + #if (defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) ) && !defined(_WIN32) + #ifndef _stricmp + int _stricmp(const char* s1, const char* s2); + #endif + int _strnicmp(const char* s1, const char* s2, size_t n); + // http://www.jenkinssoftware.com/forum/index.php?topic=5010.msg20920#msg20920 + // #ifndef _vsnprintf + #define _vsnprintf vsnprintf + // #endif +#ifndef __APPLE__ + char *_strlwr(char * str ); //this won't compile on OSX for some reason +#endif + + + + #endif +#endif + +#endif // _GCC_WIN_STRINGS diff --git a/include/raknet/LocklessTypes.hpp b/include/raknet/LocklessTypes.hpp new file mode 100644 index 0000000..4b8104c --- /dev/null +++ b/include/raknet/LocklessTypes.hpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __LOCKLESS_TYPES_H +#define __LOCKLESS_TYPES_H + +#include "Export.hpp" +#include "NativeTypes.hpp" +#include "WindowsIncludes.hpp" +#if defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) +// __sync_fetch_and_add not supported apparently +#include "SimpleMutex.hpp" +#endif + +namespace RakNet +{ + +class RAK_DLL_EXPORT LocklessUint32_t +{ +public: + LocklessUint32_t(); + explicit LocklessUint32_t(uint32_t initial); + // Returns variable value after changing it + uint32_t Increment(void); + // Returns variable value after changing it + uint32_t Decrement(void); + uint32_t GetValue(void) const {return value;} + +protected: +#ifdef _WIN32 + volatile LONG value; +#elif defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) + // __sync_fetch_and_add not supported apparently + SimpleMutex mutex; + uint32_t value; +#else + volatile uint32_t value; +#endif +}; + +} + +#endif diff --git a/include/raknet/LogCommandParser.hpp b/include/raknet/LogCommandParser.hpp new file mode 100644 index 0000000..3239be4 --- /dev/null +++ b/include/raknet/LogCommandParser.hpp @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains LogCommandParser , Used to send logs to connected consoles +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_LogCommandParser==1 + +#ifndef __LOG_COMMAND_PARSER +#define __LOG_COMMAND_PARSER + +#include "CommandParserInterface.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \brief Adds the ability to send logging output to a remote console +class RAK_DLL_EXPORT LogCommandParser : public CommandParserInterface +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(LogCommandParser) + + LogCommandParser(); + ~LogCommandParser(); + + /// Given \a command with parameters \a parameterList , do whatever processing you wish. + /// \param[in] command The command to process + /// \param[in] numParameters How many parameters were passed along with the command + /// \param[in] parameterList The list of parameters. parameterList[0] is the first parameter and so on. + /// \param[in] transport The transport interface we can use to write to + /// \param[in] systemAddress The player that sent this command. + /// \param[in] originalString The string that was actually sent over the network, in case you want to do your own parsing + bool OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString); + + /// You are responsible for overriding this function and returning a static string, which will identifier your parser. + /// This should return a static string + /// \return The name that you return. + const char *GetName(void) const; + + /// A callback for when you are expected to send a brief description of your parser to \a systemAddress + /// \param[in] transport The transport interface we can use to write to + /// \param[in] systemAddress The player that requested help. + void SendHelp(TransportInterface *transport, const SystemAddress &systemAddress); + + /// All logs must be associated with a channel. This is a filter so that remote clients only get logs for a system they care about. + // If you call Log with a channel that is unknown, that channel will automatically be added + /// \param[in] channelName A persistent string naming the channel. Don't deallocate this string. + void AddChannel(const char *channelName); + + /// Write a log to a channel. + /// Logs are not buffered, so only remote consoles connected and subscribing at the time you write will get the output. + /// \param[in] format Same as RAKNET_DEBUG_PRINTF() + /// \param[in] ... Same as RAKNET_DEBUG_PRINTF() + void WriteLog(const char *channelName, const char *format, ...); + + /// A callback for when \a systemAddress has connected to us. + /// \param[in] systemAddress The player that has connected. + /// \param[in] transport The transport interface that sent us this information. Can be used to send messages to this or other players. + void OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport); + + /// A callback for when \a systemAddress has disconnected, either gracefully or forcefully + /// \param[in] systemAddress The player that has disconnected. + /// \param[in] transport The transport interface that sent us this information. + void OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport); + + /// This is called every time transport interface is registered. If you want to save a copy of the TransportInterface pointer + /// This is the place to do it + /// \param[in] transport The new TransportInterface + void OnTransportChange(TransportInterface *transport); +protected: + /// Sends the currently active channels to the user + /// \param[in] systemAddress The player to send to + /// \param[in] transport The transport interface to use to send the channels + void PrintChannels(const SystemAddress &systemAddress, TransportInterface *transport) const; + + /// Unsubscribe a user from a channel (or from all channels) + /// \param[in] systemAddress The player to unsubscribe to + /// \param[in] channelName If 0, then unsubscribe from all channels. Otherwise unsubscribe from the named channel + unsigned Unsubscribe(const SystemAddress &systemAddress, const char *channelName); + + /// Subscribe a user to a channel (or to all channels) + /// \param[in] systemAddress The player to subscribe to + /// \param[in] channelName If 0, then subscribe from all channels. Otherwise subscribe to the named channel + unsigned Subscribe(const SystemAddress &systemAddress, const char *channelName); + + /// Given the name of a channel, return the index into channelNames where it is located + /// \param[in] channelName The name of the channel + unsigned GetChannelIndexFromName(const char *channelName); + + /// One of these structures is created per player + struct SystemAddressAndChannel + { + /// The ID of the player + SystemAddress systemAddress; + + /// Bitwise representations of the channels subscribed to. If bit 0 is set, then we subscribe to channelNames[0] and so on. + unsigned channels; + }; + + /// The list of remote users. Added to when users subscribe, removed when they disconnect or unsubscribe + DataStructures::List remoteUsers; + + /// Names of the channels at each bit, or 0 for an unused channel + const char *channelNames[32]; + + /// This is so I can save the current transport provider, solely so I can use it without having the user pass it to Log + TransportInterface *trans; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/MTUSize.hpp b/include/raknet/MTUSize.hpp new file mode 100644 index 0000000..a63ffa6 --- /dev/null +++ b/include/raknet/MTUSize.hpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] Defines the default maximum transfer unit. +/// + + +#ifndef MAXIMUM_MTU_SIZE + +/// \li \em 17914 16 Mbit/Sec Token Ring +/// \li \em 4464 4 Mbits/Sec Token Ring +/// \li \em 4352 FDDI +/// \li \em 1500. The largest Ethernet packet size \b recommended. This is the typical setting for non-PPPoE, non-VPN connections. The default value for NETGEAR routers, adapters and switches. +/// \li \em 1492. The size PPPoE prefers. +/// \li \em 1472. Maximum size to use for pinging. (Bigger packets are fragmented.) +/// \li \em 1468. The size DHCP prefers. +/// \li \em 1460. Usable by AOL if you don't have large email attachments, etc. +/// \li \em 1430. The size VPN and PPTP prefer. +/// \li \em 1400. Maximum size for AOL DSL. +/// \li \em 576. Typical value to connect to dial-up ISPs. +/// The largest value for an UDP datagram + + + +#define MAXIMUM_MTU_SIZE 1492 + + +#define MINIMUM_MTU_SIZE 400 + +#endif diff --git a/include/raknet/MessageFilter.hpp b/include/raknet/MessageFilter.hpp new file mode 100644 index 0000000..4a1eeb7 --- /dev/null +++ b/include/raknet/MessageFilter.hpp @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Message filter plugin. Assigns systems to FilterSets. Each FilterSet limits what messages are allowed. This is a security related plugin. +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_MessageFilter==1 + +#ifndef __MESSAGE_FILTER_PLUGIN_H +#define __MESSAGE_FILTER_PLUGIN_H + +#include "RakNetTypes.hpp" +#include "PluginInterface2.hpp" +#include "DS_OrderedList.hpp" +#include "DS_Hash.hpp" +#include "Export.hpp" + +/// MessageIdentifier (ID_*) values shoudln't go higher than this. Change it if you do. +#define MESSAGE_FILTER_MAX_MESSAGE_ID 256 + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \internal Has to be public so some of the shittier compilers can use it. +int RAK_DLL_EXPORT MessageFilterStrComp( char *const &key,char *const &data ); + +/// \internal Has to be public so some of the shittier compilers can use it. +struct FilterSet +{ + bool banOnFilterTimeExceed; + bool kickOnDisallowedMessage; + bool banOnDisallowedMessage; + RakNet::TimeMS disallowedMessageBanTimeMS; + RakNet::TimeMS timeExceedBanTimeMS; + RakNet::TimeMS maxMemberTimeMS; + void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData, unsigned char messageID); + void *disallowedCallbackUserData; + void (*timeoutCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData); + void *timeoutUserData; + int filterSetID; + bool allowedIDs[MESSAGE_FILTER_MAX_MESSAGE_ID]; + DataStructures::OrderedList allowedRPC4; +}; + +/// \internal Has to be public so some of the shittier compilers can use it. +int RAK_DLL_EXPORT FilterSetComp( const int &key, FilterSet * const &data ); + +/// \internal Has to be public so some of the shittier compilers can use it. +struct FilteredSystem +{ + FilterSet *filter; + RakNet::TimeMS timeEnteredThisSet; +}; + +/// \defgroup MESSAGEFILTER_GROUP MessageFilter +/// \brief Remote incoming packets from unauthorized systems +/// \details +/// \ingroup PLUGINS_GROUP + +/// \brief Assigns systems to FilterSets. Each FilterSet limits what kinds of messages are allowed. +/// \details The MessageFilter plugin is used for security where you limit what systems can send what kind of messages.
+/// You implicitly define FilterSets, and add allowed message IDs to these FilterSets.
+/// You then add systems to these filters, such that those systems are limited to sending what the filters allows.
+/// You can automatically assign systems to a filter.
+/// You can automatically kick and possibly ban users that stay in a filter too long, or send the wrong message.
+/// Each system is a member of either zero or one filters.
+/// Add this plugin before any plugin you wish to filter (most likely just add this plugin before any other). +/// \ingroup MESSAGEFILTER_GROUP +class RAK_DLL_EXPORT MessageFilter : public PluginInterface2 +{ +public: + + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(MessageFilter) + + MessageFilter(); + virtual ~MessageFilter(); + + // -------------------------------------------------------------------------------------------- + // User functions + // -------------------------------------------------------------------------------------------- + + /// Automatically add all new systems to a particular filter + /// Defaults to -1 + /// \param[in] filterSetID Which filter to add new systems to. <0 for do not add. + void SetAutoAddNewConnectionsToFilter(int filterSetID); + + /// Allow a range of message IDs + /// Always allowed by default: ID_CONNECTION_REQUEST_ACCEPTED through ID_DOWNLOAD_PROGRESS + /// Usually you specify a range to make it easier to add new enumerations without having to constantly refer back to this function. + /// \param[in] allow True to allow this message ID, false to disallow. By default, all messageIDs except the noted types are disallowed. This includes messages from other plugins! + /// \param[in] messageIDStart The first ID_* message to allow in the range. Inclusive. + /// \param[in] messageIDEnd The last ID_* message to allow in the range. Inclusive. + /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. + void SetAllowMessageID(bool allow, int messageIDStart, int messageIDEnd,int filterSetID); + + /// Allow a specific RPC4 call + /// \pre MessageFilter must be attached before RPC4 + /// \param[in] uniqueID Identifier passed to RegisterFunction() + /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. + void SetAllowRPC4(bool allow, const char* uniqueID, int filterSetID); + + /// What action to take on a disallowed message. You can kick or not. You can add them to the ban list for some time + /// By default no action is taken. The message is simply ignored. + /// param[in] 0 for permanent ban, >0 for ban time in milliseconds. + /// \param[in] kickOnDisallowed kick the system that sent a disallowed message. + /// \param[in] banOnDisallowed ban the system that sent a disallowed message. See \a banTimeMS for the ban duration + /// \param[in] banTimeMS Passed to the milliseconds parameter of RakPeer::AddToBanList. + /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. + void SetActionOnDisallowedMessage(bool kickOnDisallowed, bool banOnDisallowed, RakNet::TimeMS banTimeMS, int filterSetID); + + /// Set a user callback to be called on an invalid message for a particular filterSet + /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. + /// \param[in] userData A pointer passed with the callback + /// \param[in] invalidMessageCallback A pointer to a C function to be called back with the specified parameters. + void SetDisallowedMessageCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID addressOrGUID, int filterSetID, void *userData, unsigned char messageID)); + + /// Set a user callback to be called when a user is disconnected due to SetFilterMaxTime + /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. + /// \param[in] userData A pointer passed with the callback + /// \param[in] invalidMessageCallback A pointer to a C function to be called back with the specified parameters. + void SetTimeoutCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID addressOrGUID, int filterSetID, void *userData)); + + /// Limit how long a connection can stay in a particular filterSetID. After this time, the connection is kicked and possibly banned. + /// By default there is no limit to how long a connection can stay in a particular filter set. + /// \param[in] allowedTimeMS How many milliseconds to allow a connection to stay in this filter set. + /// \param[in] banOnExceed True or false to ban the system, or not, when \a allowedTimeMS is exceeded + /// \param[in] banTimeMS Passed to the milliseconds parameter of RakPeer::AddToBanList. + /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. + void SetFilterMaxTime(int allowedTimeMS, bool banOnExceed, RakNet::TimeMS banTimeMS, int filterSetID); + + /// Get the filterSetID a system is using. Returns -1 for none. + /// \param[in] addressOrGUID The system we are referring to + int GetSystemFilterSet(AddressOrGUID addressOrGUID); + + /// Assign a system to a filter set. + /// Systems are automatically added to filter sets (or not) based on SetAutoAddNewConnectionsToFilter() + /// This function is used to change the filter set a system is using, to add it to a new filter set, or to remove it from all existin filter sets. + /// \param[in] addressOrGUID The system we are referring to + /// \param[in] filterSetID A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. If -1, the system will be removed from all filter sets. + void SetSystemFilterSet(AddressOrGUID addressOrGUID, int filterSetID); + + /// Returns the number of systems subscribed to a particular filter set + /// Using anything other than -1 for \a filterSetID is slow, so you should store the returned value. + /// \param[in] filterSetID The filter set to limit to. Use -1 for none (just returns the total number of filter systems in that case). + unsigned GetSystemCount(int filterSetID) const; + + /// Returns the total number of filter sets. + /// \return The total number of filter sets. + unsigned GetFilterSetCount(void) const; + + /// Returns the ID of a filter set, by index + /// \param[in] An index between 0 and GetFilterSetCount()-1 inclusive + int GetFilterSetIDByIndex(unsigned index); + + /// Delete a FilterSet. All systems formerly subscribed to this filter are now unrestricted. + /// \param[in] filterSetID The ID of the filter set to delete. + void DeleteFilterSet(int filterSetID); + + // -------------------------------------------------------------------------------------------- + // Packet handling functions + // -------------------------------------------------------------------------------------------- + virtual void Update(void); + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + +protected: + + void Clear(void); + void DeallocateFilterSet(FilterSet *filterSet); + FilterSet* GetFilterSetByID(int filterSetID); + void OnInvalidMessage(FilterSet *filterSet, AddressOrGUID systemAddress, unsigned char messageID); + + DataStructures::OrderedList filterList; + // Change to guid + DataStructures::Hash systemList; + + int autoAddNewConnectionsToFilter; + RakNet::Time whenLastTimeoutCheck; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/MessageIdentifiers.hpp b/include/raknet/MessageIdentifiers.hpp new file mode 100644 index 0000000..67c21ea --- /dev/null +++ b/include/raknet/MessageIdentifiers.hpp @@ -0,0 +1,437 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief All the message identifiers used by RakNet. Message identifiers comprise the first byte of any message. +/// + + +#ifndef __MESSAGE_IDENTIFIERS_H +#define __MESSAGE_IDENTIFIERS_H + +#if defined(RAKNET_USE_CUSTOM_PACKET_IDS) +#include "CustomPacketIdentifiers.hpp" +#else + +enum OutOfBandIdentifiers +{ + ID_NAT_ESTABLISH_UNIDIRECTIONAL, + ID_NAT_ESTABLISH_BIDIRECTIONAL, + ID_NAT_TYPE_DETECT, + ID_ROUTER_2_REPLY_TO_SENDER_PORT, + ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, + ID_ROUTER_2_MINI_PUNCH_REPLY, + ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE, + ID_XBOX_360_VOICE, + ID_XBOX_360_GET_NETWORK_ROOM, + ID_XBOX_360_RETURN_NETWORK_ROOM, + ID_NAT_PING, + ID_NAT_PONG, +}; + +/// You should not edit the file MessageIdentifiers.h as it is a part of RakNet static library +/// To define your own message id, define an enum following the code example that follows. +/// +/// \code +/// enum { +/// ID_MYPROJECT_MSG_1 = ID_USER_PACKET_ENUM, +/// ID_MYPROJECT_MSG_2, +/// ... +/// }; +/// \endcode +/// +/// \note All these enumerations should be casted to (unsigned char) before writing them to RakNet::BitStream +enum DefaultMessageIDTypes +{ + // + // RESERVED TYPES - DO NOT CHANGE THESE + // All types from RakPeer + // + /// These types are never returned to the user. + /// Ping from a connected system. Update timestamps (internal use only) + ID_CONNECTED_PING, + /// Ping from an unconnected system. Reply but do not update timestamps. (internal use only) + ID_UNCONNECTED_PING, + /// Ping from an unconnected system. Only reply if we have open connections. Do not update timestamps. (internal use only) + ID_UNCONNECTED_PING_OPEN_CONNECTIONS, + /// Pong from a connected system. Update timestamps (internal use only) + ID_CONNECTED_PONG, + /// A reliable packet to detect lost connections (internal use only) + ID_DETECT_LOST_CONNECTIONS, + /// C2S: Initial query: Header(1), OfflineMesageID(16), Protocol number(1), Pad(toMTU), sent with no fragment set. + /// If protocol fails on server, returns ID_INCOMPATIBLE_PROTOCOL_VERSION to client + ID_OPEN_CONNECTION_REQUEST_1, + /// S2C: Header(1), OfflineMesageID(16), server GUID(8), HasSecurity(1), Cookie(4, if HasSecurity) + /// , public key (if do security is true), MTU(2). If public key fails on client, returns ID_PUBLIC_KEY_MISMATCH + ID_OPEN_CONNECTION_REPLY_1, + /// C2S: Header(1), OfflineMesageID(16), Cookie(4, if HasSecurity is true on the server), clientSupportsSecurity(1 bit), + /// handshakeChallenge (if has security on both server and client), remoteBindingAddress(6), MTU(2), client GUID(8) + /// Connection slot allocated if cookie is valid, server is not full, GUID and IP not already in use. + ID_OPEN_CONNECTION_REQUEST_2, + /// S2C: Header(1), OfflineMesageID(16), server GUID(8), mtu(2), doSecurity(1 bit), handshakeAnswer (if do security is true) + ID_OPEN_CONNECTION_REPLY_2, + /// C2S: Header(1), GUID(8), Timestamp, HasSecurity(1), Proof(32) + ID_CONNECTION_REQUEST, + /// RakPeer - Remote system requires secure connections, pass a public key to RakPeerInterface::Connect() + ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY, + /// RakPeer - We passed a public key to RakPeerInterface::Connect(), but the other system did not have security turned on + ID_OUR_SYSTEM_REQUIRES_SECURITY, + /// RakPeer - Wrong public key passed to RakPeerInterface::Connect() + ID_PUBLIC_KEY_MISMATCH, + /// RakPeer - Same as ID_ADVERTISE_SYSTEM, but intended for internal use rather than being passed to the user. + /// Second byte indicates type. Used currently for NAT punchthrough for receiver port advertisement. See ID_NAT_ADVERTISE_RECIPIENT_PORT + ID_OUT_OF_BAND_INTERNAL, + /// If RakPeerInterface::Send() is called where PacketReliability contains _WITH_ACK_RECEIPT, then on a later call to + /// RakPeerInterface::Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS. The message will be 5 bytes long, + /// and bytes 1-4 inclusive will contain a number in native order containing a number that identifies this message. + /// This number will be returned by RakPeerInterface::Send() or RakPeerInterface::SendList(). ID_SND_RECEIPT_ACKED means that + /// the message arrived + ID_SND_RECEIPT_ACKED, + /// If RakPeerInterface::Send() is called where PacketReliability contains UNRELIABLE_WITH_ACK_RECEIPT, then on a later call to + /// RakPeerInterface::Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS. The message will be 5 bytes long, + /// and bytes 1-4 inclusive will contain a number in native order containing a number that identifies this message. This number + /// will be returned by RakPeerInterface::Send() or RakPeerInterface::SendList(). ID_SND_RECEIPT_LOSS means that an ack for the + /// message did not arrive (it may or may not have been delivered, probably not). On disconnect or shutdown, you will not get + /// ID_SND_RECEIPT_LOSS for unsent messages, you should consider those messages as all lost. + ID_SND_RECEIPT_LOSS, + + + // + // USER TYPES - DO NOT CHANGE THESE + // + + /// RakPeer - In a client/server environment, our connection request to the server has been accepted. + ID_CONNECTION_REQUEST_ACCEPTED, + /// RakPeer - Sent to the player when a connection request cannot be completed due to inability to connect. + ID_CONNECTION_ATTEMPT_FAILED, + /// RakPeer - Sent a connect request to a system we are currently connected to. + ID_ALREADY_CONNECTED, + /// RakPeer - A remote system has successfully connected. + ID_NEW_INCOMING_CONNECTION, + /// RakPeer - The system we attempted to connect to is not accepting new connections. + ID_NO_FREE_INCOMING_CONNECTIONS, + /// RakPeer - The system specified in Packet::systemAddress has disconnected from us. For the client, this would mean the + /// server has shutdown. + ID_DISCONNECTION_NOTIFICATION, + /// RakPeer - Reliable packets cannot be delivered to the system specified in Packet::systemAddress. The connection to that + /// system has been closed. + ID_CONNECTION_LOST, + /// RakPeer - We are banned from the system we attempted to connect to. + ID_CONNECTION_BANNED, + /// RakPeer - The remote system is using a password and has refused our connection because we did not set the correct password. + ID_INVALID_PASSWORD, + // RAKNET_PROTOCOL_VERSION in RakNetVersion.h does not match on the remote system what we have on our system + // This means the two systems cannot communicate. + // The 2nd byte of the message contains the value of RAKNET_PROTOCOL_VERSION for the remote system + ID_INCOMPATIBLE_PROTOCOL_VERSION, + // Means that this IP address connected recently, and can't connect again as a security measure. See + /// RakPeer::SetLimitIPConnectionFrequency() + ID_IP_RECENTLY_CONNECTED, + /// RakPeer - The sizeof(RakNetTime) bytes following this byte represent a value which is automatically modified by the difference + /// in system times between the sender and the recipient. Requires that you call SetOccasionalPing. + ID_TIMESTAMP, + /// RakPeer - Pong from an unconnected system. First byte is ID_UNCONNECTED_PONG, second sizeof(RakNet::TimeMS) bytes is the ping, + /// following bytes is system specific enumeration data. + /// Read using bitstreams + ID_UNCONNECTED_PONG, + /// RakPeer - Inform a remote system of our IP/Port. On the recipient, all data past ID_ADVERTISE_SYSTEM is whatever was passed to + /// the data parameter + ID_ADVERTISE_SYSTEM, + // RakPeer - Downloading a large message. Format is ID_DOWNLOAD_PROGRESS (MessageID), partCount (unsigned int), + /// partTotal (unsigned int), + /// partLength (unsigned int), first part data (length <= MAX_MTU_SIZE). See the three parameters partCount, partTotal + /// and partLength in OnFileProgress in FileListTransferCBInterface.h + ID_DOWNLOAD_PROGRESS, + + /// ConnectionGraph2 plugin - In a client/server environment, a client other than ourselves has disconnected gracefully. + /// Packet::systemAddress is modified to reflect the systemAddress of this client. + ID_REMOTE_DISCONNECTION_NOTIFICATION, + /// ConnectionGraph2 plugin - In a client/server environment, a client other than ourselves has been forcefully dropped. + /// Packet::systemAddress is modified to reflect the systemAddress of this client. + ID_REMOTE_CONNECTION_LOST, + /// ConnectionGraph2 plugin: Bytes 1-4 = count. for (count items) contains {SystemAddress, RakNetGUID, 2 byte ping} + ID_REMOTE_NEW_INCOMING_CONNECTION, + + /// FileListTransfer plugin - Setup data + ID_FILE_LIST_TRANSFER_HEADER, + /// FileListTransfer plugin - A file + ID_FILE_LIST_TRANSFER_FILE, + // Ack for reference push, to send more of the file + ID_FILE_LIST_REFERENCE_PUSH_ACK, + + /// DirectoryDeltaTransfer plugin - Request from a remote system for a download of a directory + ID_DDT_DOWNLOAD_REQUEST, + + /// RakNetTransport plugin - Transport provider message, used for remote console + ID_TRANSPORT_STRING, + + /// ReplicaManager plugin - Create an object + ID_REPLICA_MANAGER_CONSTRUCTION, + /// ReplicaManager plugin - Changed scope of an object + ID_REPLICA_MANAGER_SCOPE_CHANGE, + /// ReplicaManager plugin - Serialized data of an object + ID_REPLICA_MANAGER_SERIALIZE, + /// ReplicaManager plugin - New connection, about to send all world objects + ID_REPLICA_MANAGER_DOWNLOAD_STARTED, + /// ReplicaManager plugin - Finished downloading all serialized objects + ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE, + + /// RakVoice plugin - Open a communication channel + ID_RAKVOICE_OPEN_CHANNEL_REQUEST, + /// RakVoice plugin - Communication channel accepted + ID_RAKVOICE_OPEN_CHANNEL_REPLY, + /// RakVoice plugin - Close a communication channel + ID_RAKVOICE_CLOSE_CHANNEL, + /// RakVoice plugin - Voice data + ID_RAKVOICE_DATA, + + /// Autopatcher plugin - Get a list of files that have changed since a certain date + ID_AUTOPATCHER_GET_CHANGELIST_SINCE_DATE, + /// Autopatcher plugin - A list of files to create + ID_AUTOPATCHER_CREATION_LIST, + /// Autopatcher plugin - A list of files to delete + ID_AUTOPATCHER_DELETION_LIST, + /// Autopatcher plugin - A list of files to get patches for + ID_AUTOPATCHER_GET_PATCH, + /// Autopatcher plugin - A list of patches for a list of files + ID_AUTOPATCHER_PATCH_LIST, + /// Autopatcher plugin - Returned to the user: An error from the database repository for the autopatcher. + ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR, + /// Autopatcher plugin - Returned to the user: The server does not allow downloading unmodified game files. + ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES, + /// Autopatcher plugin - Finished getting all files from the autopatcher + ID_AUTOPATCHER_FINISHED_INTERNAL, + ID_AUTOPATCHER_FINISHED, + /// Autopatcher plugin - Returned to the user: You must restart the application to finish patching. + ID_AUTOPATCHER_RESTART_APPLICATION, + + /// NATPunchthrough plugin: internal + ID_NAT_PUNCHTHROUGH_REQUEST, + /// NATPunchthrough plugin: internal + //ID_NAT_GROUP_PUNCHTHROUGH_REQUEST, + /// NATPunchthrough plugin: internal + //ID_NAT_GROUP_PUNCHTHROUGH_REPLY, + /// NATPunchthrough plugin: internal + ID_NAT_CONNECT_AT_TIME, + /// NATPunchthrough plugin: internal + ID_NAT_GET_MOST_RECENT_PORT, + /// NATPunchthrough plugin: internal + ID_NAT_CLIENT_READY, + /// NATPunchthrough plugin: internal + //ID_NAT_GROUP_PUNCHTHROUGH_FAILURE_NOTIFICATION, + + /// NATPunchthrough plugin: Destination system is not connected to the server. Bytes starting at offset 1 contains the + /// RakNetGUID destination field of NatPunchthroughClient::OpenNAT(). + ID_NAT_TARGET_NOT_CONNECTED, + /// NATPunchthrough plugin: Destination system is not responding to ID_NAT_GET_MOST_RECENT_PORT. Possibly the plugin is not installed. + /// Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT(). + ID_NAT_TARGET_UNRESPONSIVE, + /// NATPunchthrough plugin: The server lost the connection to the destination system while setting up punchthrough. + /// Possibly the plugin is not installed. Bytes starting at offset 1 contains the RakNetGUID destination + /// field of NatPunchthroughClient::OpenNAT(). + ID_NAT_CONNECTION_TO_TARGET_LOST, + /// NATPunchthrough plugin: This punchthrough is already in progress. Possibly the plugin is not installed. + /// Bytes starting at offset 1 contains the RakNetGUID destination field of NatPunchthroughClient::OpenNAT(). + ID_NAT_ALREADY_IN_PROGRESS, + /// NATPunchthrough plugin: This message is generated on the local system, and does not come from the network. + /// packet::guid contains the destination field of NatPunchthroughClient::OpenNAT(). Byte 1 contains 1 if you are the sender, 0 if not + ID_NAT_PUNCHTHROUGH_FAILED, + /// NATPunchthrough plugin: Punchthrough succeeded. See packet::systemAddress and packet::guid. Byte 1 contains 1 if you are the sender, + /// 0 if not. You can now use RakPeer::Connect() or other calls to communicate with this system. + ID_NAT_PUNCHTHROUGH_SUCCEEDED, + + /// ReadyEvent plugin - Set the ready state for a particular system + /// First 4 bytes after the message contains the id + ID_READY_EVENT_SET, + /// ReadyEvent plugin - Unset the ready state for a particular system + /// First 4 bytes after the message contains the id + ID_READY_EVENT_UNSET, + /// All systems are in state ID_READY_EVENT_SET + /// First 4 bytes after the message contains the id + ID_READY_EVENT_ALL_SET, + /// \internal, do not process in your game + /// ReadyEvent plugin - Request of ready event state - used for pulling data when newly connecting + ID_READY_EVENT_QUERY, + + /// Lobby packets. Second byte indicates type. + ID_LOBBY_GENERAL, + + // RPC3, RPC4 error + ID_RPC_REMOTE_ERROR, + /// Plugin based replacement for RPC system + ID_RPC_PLUGIN, + + /// FileListTransfer transferring large files in chunks that are read only when needed, to save memory + ID_FILE_LIST_REFERENCE_PUSH, + /// Force the ready event to all set + ID_READY_EVENT_FORCE_ALL_SET, + + /// Rooms function + ID_ROOMS_EXECUTE_FUNC, + ID_ROOMS_LOGON_STATUS, + ID_ROOMS_HANDLE_CHANGE, + + /// Lobby2 message + ID_LOBBY2_SEND_MESSAGE, + ID_LOBBY2_SERVER_ERROR, + + /// Informs user of a new host GUID. Packet::Guid contains this new host RakNetGuid. The old host can be read out using BitStream->Read(RakNetGuid) starting on byte 1 + /// This is not returned until connected to a remote system + /// If the oldHost is UNASSIGNED_RAKNET_GUID, then this is the first time the host has been determined + ID_FCM2_NEW_HOST, + /// \internal For FullyConnectedMesh2 plugin + ID_FCM2_REQUEST_FCMGUID, + /// \internal For FullyConnectedMesh2 plugin + ID_FCM2_RESPOND_CONNECTION_COUNT, + /// \internal For FullyConnectedMesh2 plugin + ID_FCM2_INFORM_FCMGUID, + /// \internal For FullyConnectedMesh2 plugin + ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT, + /// A remote system (not necessarily the host) called FullyConnectedMesh2::StartVerifiedJoin() with our system as the client + /// Use FullyConnectedMesh2::GetVerifiedJoinRequiredProcessingList() to read systems + /// For each system, attempt NatPunchthroughClient::OpenNAT() and/or RakPeerInterface::Connect() + /// When this has been done for all systems, the remote system will automatically be informed of the results + /// \note Only the designated client gets this message + /// \note You won't get this message if you are already connected to all target systems + /// \note If you fail to connect to a system, this does not automatically mean you will get ID_FCM2_VERIFIED_JOIN_FAILED as that system may have been shutting down from the host too + /// \sa FullyConnectedMesh2::StartVerifiedJoin() + ID_FCM2_VERIFIED_JOIN_START, + /// \internal The client has completed processing for all systems designated in ID_FCM2_VERIFIED_JOIN_START + ID_FCM2_VERIFIED_JOIN_CAPABLE, + /// Client failed to connect to a required systems notified via FullyConnectedMesh2::StartVerifiedJoin() + /// RakPeerInterface::CloseConnection() was automatically called for all systems connected due to ID_FCM2_VERIFIED_JOIN_START + /// Programmer should inform the player via the UI that they cannot join this session, and to choose a different session + /// \note Server normally sends us this message, however if connection to the server was lost, message will be returned locally + /// \note Only the designated client gets this message + ID_FCM2_VERIFIED_JOIN_FAILED, + /// The system that called StartVerifiedJoin() got ID_FCM2_VERIFIED_JOIN_CAPABLE from the client and then called RespondOnVerifiedJoinCapable() with true + /// AddParticipant() has automatically been called for this system + /// Use GetVerifiedJoinAcceptedAdditionalData() to read any additional data passed to RespondOnVerifiedJoinCapable() + /// \note All systems in the mesh get this message + /// \sa RespondOnVerifiedJoinCapable() + ID_FCM2_VERIFIED_JOIN_ACCEPTED, + /// The system that called StartVerifiedJoin() got ID_FCM2_VERIFIED_JOIN_CAPABLE from the client and then called RespondOnVerifiedJoinCapable() with false + /// CloseConnection() has been automatically called for each system connected to since ID_FCM2_VERIFIED_JOIN_START. + /// The connection is NOT automatically closed to the original host that sent StartVerifiedJoin() + /// Use GetVerifiedJoinRejectedAdditionalData() to read any additional data passed to RespondOnVerifiedJoinCapable() + /// \note Only the designated client gets this message + /// \sa RespondOnVerifiedJoinCapable() + ID_FCM2_VERIFIED_JOIN_REJECTED, + + /// UDP proxy messages. Second byte indicates type. + ID_UDP_PROXY_GENERAL, + + /// SQLite3Plugin - execute + ID_SQLite3_EXEC, + /// SQLite3Plugin - Remote database is unknown + ID_SQLite3_UNKNOWN_DB, + /// Events happening with SQLiteClientLoggerPlugin + ID_SQLLITE_LOGGER, + + /// Sent to NatTypeDetectionServer + ID_NAT_TYPE_DETECTION_REQUEST, + /// Sent to NatTypeDetectionClient. Byte 1 contains the type of NAT detected. + ID_NAT_TYPE_DETECTION_RESULT, + + /// Used by the router2 plugin + ID_ROUTER_2_INTERNAL, + /// No path is available or can be established to the remote system + /// Packet::guid contains the endpoint guid that we were trying to reach + ID_ROUTER_2_FORWARDING_NO_PATH, + /// \brief You can now call connect, ping, or other operations to the destination system. + /// + /// Connect as follows: + /// + /// RakNet::BitStream bs(packet->data, packet->length, false); + /// bs.IgnoreBytes(sizeof(MessageID)); + /// RakNetGUID endpointGuid; + /// bs.Read(endpointGuid); + /// unsigned short sourceToDestPort; + /// bs.Read(sourceToDestPort); + /// char ipAddressString[32]; + /// packet->systemAddress.ToString(false, ipAddressString); + /// rakPeerInterface->Connect(ipAddressString, sourceToDestPort, 0,0); + ID_ROUTER_2_FORWARDING_ESTABLISHED, + /// The IP address for a forwarded connection has changed + /// Read endpointGuid and port as per ID_ROUTER_2_FORWARDING_ESTABLISHED + ID_ROUTER_2_REROUTED, + + /// \internal Used by the team balancer plugin + ID_TEAM_BALANCER_INTERNAL, + /// Cannot switch to the desired team because it is full. However, if someone on that team leaves, you will + /// get ID_TEAM_BALANCER_TEAM_ASSIGNED later. + /// For TeamBalancer: Byte 1 contains the team you requested to join. Following bytes contain NetworkID of which member + ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, + /// Cannot switch to the desired team because all teams are locked. However, if someone on that team leaves, + /// you will get ID_TEAM_BALANCER_SET_TEAM later. + /// For TeamBalancer: Byte 1 contains the team you requested to join. + ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, + ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED, + /// Team balancer plugin informing you of your team. Byte 1 contains the team you requested to join. Following bytes contain NetworkID of which member. + ID_TEAM_BALANCER_TEAM_ASSIGNED, + + /// Gamebryo Lightspeed integration + ID_LIGHTSPEED_INTEGRATION, + + /// XBOX integration + ID_XBOX_LOBBY, + + /// The password we used to challenge the other system passed, meaning the other system has called TwoWayAuthentication::AddPassword() with the same password we passed to TwoWayAuthentication::Challenge() + /// You can read the identifier used to challenge as follows: + /// RakNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(RakNet::MessageID)); RakNet::RakString password; bs.Read(password); + ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS, + ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS, + /// A remote system sent us a challenge using TwoWayAuthentication::Challenge(), and the challenge failed. + /// If the other system must pass the challenge to stay connected, you should call RakPeer::CloseConnection() to terminate the connection to the other system. + ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE, + /// The other system did not add the password we used to TwoWayAuthentication::AddPassword() + /// You can read the identifier used to challenge as follows: + /// RakNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); RakNet::RakString password; bs.Read(password); + ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE, + /// The other system did not respond within a timeout threshhold. Either the other system is not running the plugin or the other system was blocking on some operation for a long time. + /// You can read the identifier used to challenge as follows: + /// RakNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); RakNet::RakString password; bs.Read(password); + ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, + /// \internal + ID_TWO_WAY_AUTHENTICATION_NEGOTIATION, + + /// CloudClient / CloudServer + ID_CLOUD_POST_REQUEST, + ID_CLOUD_RELEASE_REQUEST, + ID_CLOUD_GET_REQUEST, + ID_CLOUD_GET_RESPONSE, + ID_CLOUD_UNSUBSCRIBE_REQUEST, + ID_CLOUD_SERVER_TO_SERVER_COMMAND, + ID_CLOUD_SUBSCRIPTION_NOTIFICATION, + + // LibVoice + ID_LIB_VOICE, + + ID_RELAY_PLUGIN, + ID_NAT_REQUEST_BOUND_ADDRESSES, + ID_NAT_RESPOND_BOUND_ADDRESSES, + ID_FCM2_UPDATE_USER_CONTEXT, + ID_RESERVED_3, + ID_RESERVED_4, + ID_RESERVED_5, + ID_RESERVED_6, + ID_RESERVED_7, + ID_RESERVED_8, + ID_RESERVED_9, + + // For the user to use. Start your first enumeration at this value. + ID_USER_PACKET_ENUM + //------------------------------------------------------------------------------------------------------------- + +}; + +#endif // RAKNET_USE_CUSTOM_PACKET_IDS + +#endif diff --git a/include/raknet/NatPunchthroughClient.hpp b/include/raknet/NatPunchthroughClient.hpp new file mode 100644 index 0000000..4bcc701 --- /dev/null +++ b/include/raknet/NatPunchthroughClient.hpp @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains the NAT-punchthrough plugin for the client. +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatPunchthroughClient==1 + +#ifndef __NAT_PUNCHTHROUGH_CLIENT_H +#define __NAT_PUNCHTHROUGH_CLIENT_H + +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "PluginInterface2.hpp" +#include "PacketPriority.hpp" +#include "SocketIncludes.hpp" +#include "DS_List.hpp" +#include "RakString.hpp" +#include "DS_Queue.hpp" + +// Trendnet TEW-632BRP sometimes starts at port 1024 and increments sequentially. +// Zonnet zsr1134we. Replies go out on the net, but are always absorbed by the remote router?? +// Dlink ebr2310 to Trendnet ok +// Trendnet TEW-652BRP to Trendnet 632BRP OK +// Trendnet TEW-632BRP to Trendnet 632BRP OK +// Buffalo WHR-HP-G54 OK +// Netgear WGR614 ok + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +struct Packet; +#if _RAKNET_SUPPORT_PacketLogger==1 +class PacketLogger; +#endif + +/// \ingroup NAT_PUNCHTHROUGH_GROUP +struct RAK_DLL_EXPORT PunchthroughConfiguration +{ + /// internal: (15 ms * 2 tries + 30 wait) * 5 ports * 8 players = 2.4 seconds + /// external: (50 ms * 8 sends + 200 wait) * 2 port * 8 players = 9.6 seconds + /// Total: 8 seconds + PunchthroughConfiguration() { + TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL=15; + TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL=50; + UDP_SENDS_PER_PORT_INTERNAL=2; + UDP_SENDS_PER_PORT_EXTERNAL=8; + INTERNAL_IP_WAIT_AFTER_ATTEMPTS=30; + MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK=5; /// set to 0 to not do lan connects + MAX_PREDICTIVE_PORT_RANGE=2; + EXTERNAL_IP_WAIT_BETWEEN_PORTS=200; + EXTERNAL_IP_WAIT_AFTER_FIRST_TTL=100; + EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS=EXTERNAL_IP_WAIT_BETWEEN_PORTS; + retryOnFailure=false; + } + + /// How much time between each UDP send + RakNet::Time TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL; + RakNet::Time TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL; + + /// How many tries for one port before giving up and going to the next port + int UDP_SENDS_PER_PORT_INTERNAL; + int UDP_SENDS_PER_PORT_EXTERNAL; + + /// After giving up on one internal port, how long to wait before trying the next port + int INTERNAL_IP_WAIT_AFTER_ATTEMPTS; + + /// How many external ports to try past the last known starting port + int MAX_PREDICTIVE_PORT_RANGE; + + /// After sending TTL, how long to wait until first punch attempt + int EXTERNAL_IP_WAIT_AFTER_FIRST_TTL; + + /// After giving up on one external port, how long to wait before trying the next port + int EXTERNAL_IP_WAIT_BETWEEN_PORTS; + + /// After trying all external ports, how long to wait before returning ID_NAT_PUNCHTHROUGH_FAILED + int EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS; + + /// Maximum number of internal IP address to try to connect to. + /// Cannot be greater than MAXIMUM_NUMBER_OF_INTERNAL_IDS + /// Should be high enough to try all internal IP addresses on the majority of computers + int MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK; + + /// If the first punchthrough attempt fails, try again + /// This sometimes works because the remote router was looking for an incoming message on a higher numbered port before responding to a lower numbered port from the other system + bool retryOnFailure; +}; + +/// \ingroup NAT_PUNCHTHROUGH_GROUP +struct RAK_DLL_EXPORT NatPunchthroughDebugInterface +{ + NatPunchthroughDebugInterface() {} + virtual ~NatPunchthroughDebugInterface() {} + virtual void OnClientMessage(const char *msg)=0; +}; + +/// \ingroup NAT_PUNCHTHROUGH_GROUP +struct RAK_DLL_EXPORT NatPunchthroughDebugInterface_Printf : public NatPunchthroughDebugInterface +{ + virtual void OnClientMessage(const char *msg); +}; + +#if _RAKNET_SUPPORT_PacketLogger==1 +/// \ingroup NAT_PUNCHTHROUGH_GROUP +struct RAK_DLL_EXPORT NatPunchthroughDebugInterface_PacketLogger : public NatPunchthroughDebugInterface +{ + // Set to non-zero to write to the packetlogger! + PacketLogger *pl; + + NatPunchthroughDebugInterface_PacketLogger() {pl=0;} + ~NatPunchthroughDebugInterface_PacketLogger() {} + virtual void OnClientMessage(const char *msg); +}; +#endif + +/// \brief Client code for NATPunchthrough +/// \details Maintain connection to NatPunchthroughServer to process incoming connection attempts through NatPunchthroughClient
+/// Client will send datagrams to port to estimate next port
+/// Will simultaneously connect with another client once ports are estimated. +/// \sa NatTypeDetectionClient +/// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html +/// \ingroup NAT_PUNCHTHROUGH_GROUP +class RAK_DLL_EXPORT NatPunchthroughClient : public PluginInterface2 +{ +public: + + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(NatPunchthroughClient) + + NatPunchthroughClient(); + ~NatPunchthroughClient(); + + /// If the instance of RakPeer running NATPunchthroughServer was bound to two IP addresses, then you can call FindRouterPortStride() + /// This will determine the stride that your router uses when assigning ports, if your router is full-cone + /// This function is also called automatically when you call OpenNAT - however, calling it earlier when you are connected to the facilitator will speed up the process + /// \param[in] destination The system to punch. Must already be connected to \a facilitator + void FindRouterPortStride(const SystemAddress &facilitator); + + /// Punchthrough a NAT. Doesn't connect, just tries to setup the routing table + /// \param[in] destination The system to punch. Must already be connected to \a facilitator + /// \param[in] facilitator A system we are already connected to running the NatPunchthroughServer plugin + /// \sa OpenNATGroup() + /// You will get ID_NAT_PUNCHTHROUGH_SUCCEEDED on success + /// You will get ID_NAT_TARGET_NOT_CONNECTED, ID_NAT_TARGET_UNRESPONSIVE, ID_NAT_CONNECTION_TO_TARGET_LOST, ID_NAT_ALREADY_IN_PROGRESS, or ID_NAT_PUNCHTHROUGH_FAILED on failures of various types + /// However, if you lose connection to the facilitator, you may not necessarily get above + bool OpenNAT(RakNetGUID destination, const SystemAddress &facilitator); + + /* + /// \deprecated See FullyConnectedMesh2::StartVerifiedJoin() which is more flexible + /// Same as calling OpenNAT for a list of systems, but reply is delayed until all systems pass. + /// This is useful for peer to peer games where you want to connect to every system in the remote session, not just one particular system + /// \note For cloud computing, all systems in the group must be connected to the same facilitator since we're only specifying one + /// You will get ID_NAT_GROUP_PUNCH_SUCCEEDED on success + /// You will get ID_NAT_TARGET_NOT_CONNECTED, ID_NAT_ALREADY_IN_PROGRESS, or ID_NAT_GROUP_PUNCH_FAILED on failures of various types + /// However, if you lose connection to the facilitator, you may not necessarily get above + bool OpenNATGroup(DataStructures::List destinationSystems, const SystemAddress &facilitator); + */ + + /// Modify the system configuration if desired + /// Don't modify the variables in the structure while punchthrough is in progress + PunchthroughConfiguration* GetPunchthroughConfiguration(void); + + /// Sets a callback to be called with debug messages + /// \param[in] i Pointer to an interface. The pointer is stored, so don't delete it while in progress. Pass 0 to clear. + void SetDebugInterface(NatPunchthroughDebugInterface *i); + + /// Get the port mappings you should pass to UPNP (for miniupnpc-1.6.20120410, for the function UPNP_AddPortMapping) + void GetUPNPPortMappings(char *externalPort, char *internalPort, const SystemAddress &natPunchthroughServerAddress); + + /// \internal For plugin handling + virtual void Update(void); + + /// \internal For plugin handling + virtual PluginReceiveResult OnReceive(Packet *packet); + + /// \internal For plugin handling + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + + /// \internal For plugin handling + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + + virtual void OnAttach(void); + virtual void OnDetach(void); + virtual void OnRakPeerShutdown(void); + void Clear(void); + + struct SendPing + { + RakNet::Time nextActionTime; + SystemAddress targetAddress; + SystemAddress facilitator; + SystemAddress internalIds[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; + RakNetGUID targetGuid; + bool weAreSender; + int attemptCount; + int retryCount; + int punchingFixedPortAttempts; // only used for TestMode::PUNCHING_FIXED_PORT + uint16_t sessionId; + bool sentTTL; + // Give priority to internal IP addresses because if we are on a LAN, we don't want to try to connect through the internet + enum TestMode + { + TESTING_INTERNAL_IPS, + WAITING_FOR_INTERNAL_IPS_RESPONSE, + //SEND_WITH_TTL, + TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT, + TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT, + TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024, + TESTING_EXTERNAL_IPS_1024_TO_1024, + WAITING_AFTER_ALL_ATTEMPTS, + + // The trendnet remaps the remote port to 1024. + // If you continue punching on a different port for the same IP it bans you and the communication becomes unidirectioal + PUNCHING_FIXED_PORT, + + // try port 1024-1028 + } testMode; + } sp; + +protected: + unsigned short mostRecentExternalPort; + //void OnNatGroupPunchthroughRequest(Packet *packet); + void OnFailureNotification(Packet *packet); + //void OnNatGroupPunchthroughReply(Packet *packet); + void OnGetMostRecentPort(Packet *packet); + void OnConnectAtTime(Packet *packet); + unsigned int GetPendingOpenNATIndex(RakNetGUID destination, const SystemAddress &facilitator); + void SendPunchthrough(RakNetGUID destination, const SystemAddress &facilitator); + void QueueOpenNAT(RakNetGUID destination, const SystemAddress &facilitator); + void SendQueuedOpenNAT(void); + void SendTTL(const SystemAddress &sa); + void SendOutOfBand(SystemAddress sa, MessageID oobId); + void OnPunchthroughFailure(void); + void OnReadyForNextPunchthrough(void); + void PushFailure(void); + bool RemoveFromFailureQueue(void); + void PushSuccess(void); + + PunchthroughConfiguration pc; + NatPunchthroughDebugInterface *natPunchthroughDebugInterface; + + // The first time we fail a NAT attempt, we add it to failedAttemptList and try again, since sometimes trying again later fixes the problem + // The second time we fail, we return ID_NAT_PUNCHTHROUGH_FAILED + struct AddrAndGuid + { + SystemAddress addr; + RakNetGUID guid; + }; + DataStructures::List failedAttemptList; + + struct DSTAndFac + { + RakNetGUID destination; + SystemAddress facilitator; + }; + DataStructures::Queue queuedOpenNat; + + void IncrementExternalAttemptCount(RakNet::Time time, RakNet::Time delta); + unsigned short portStride; + enum + { + HAS_PORT_STRIDE, + UNKNOWN_PORT_STRIDE, + CALCULATING_PORT_STRIDE, + INCAPABLE_PORT_STRIDE + } hasPortStride; + RakNet::Time portStrideCalTimeout; + + /* + struct TimeAndGuid + { + RakNet::Time time; + RakNetGUID guid; + }; + DataStructures::List groupRequestsInProgress; + + struct GroupPunchRequest + { + SystemAddress facilitator; + DataStructures::List pendingList; + DataStructures::List passedListGuid; + DataStructures::List passedListAddress; + DataStructures::List failedList; + DataStructures::List ignoredList; + }; + DataStructures::List groupPunchRequests; + void UpdateGroupPunchOnNatResult(SystemAddress facilitator, RakNetGUID targetSystem, SystemAddress targetSystemAddress, int result); // 0=failed, 1=success, 2=ignore + */ +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/NatPunchthroughServer.hpp b/include/raknet/NatPunchthroughServer.hpp new file mode 100644 index 0000000..c529c09 --- /dev/null +++ b/include/raknet/NatPunchthroughServer.hpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains the NAT-punchthrough plugin for the server. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatPunchthroughServer==1 + +#ifndef __NAT_PUNCHTHROUGH_SERVER_H +#define __NAT_PUNCHTHROUGH_SERVER_H + +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "PluginInterface2.hpp" +#include "PacketPriority.hpp" +#include "SocketIncludes.hpp" +#include "DS_OrderedList.hpp" +#include "RakString.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +struct Packet; +#if _RAKNET_SUPPORT_PacketLogger==1 +class PacketLogger; +#endif + +/// \defgroup NAT_PUNCHTHROUGH_GROUP NatPunchthrough +/// \brief Connect systems despite both systems being behind a router +/// \details +/// \ingroup PLUGINS_GROUP + +/// \ingroup NAT_PUNCHTHROUGH_GROUP +struct RAK_DLL_EXPORT NatPunchthroughServerDebugInterface +{ + NatPunchthroughServerDebugInterface() {} + virtual ~NatPunchthroughServerDebugInterface() {} + virtual void OnServerMessage(const char *msg)=0; +}; + +/// \ingroup NAT_PUNCHTHROUGH_GROUP +struct RAK_DLL_EXPORT NatPunchthroughServerDebugInterface_Printf : public NatPunchthroughServerDebugInterface +{ + virtual void OnServerMessage(const char *msg); +}; + +#if _RAKNET_SUPPORT_PacketLogger==1 +/// \ingroup NAT_PUNCHTHROUGH_GROUP +struct RAK_DLL_EXPORT NatPunchthroughServerDebugInterface_PacketLogger : public NatPunchthroughServerDebugInterface +{ + // Set to non-zero to write to the packetlogger! + PacketLogger *pl; + + NatPunchthroughServerDebugInterface_PacketLogger() {pl=0;} + ~NatPunchthroughServerDebugInterface_PacketLogger() {} + virtual void OnServerMessage(const char *msg); +}; +#endif + +/// \brief Server code for NATPunchthrough +/// \details Maintain connection to NatPunchthroughServer to process incoming connection attempts through NatPunchthroughClient
+/// Server maintains two sockets clients can connect to so as to estimate the next port choice
+/// Server tells other client about port estimate, current public port to the server, and a time to start connection attempts +/// \sa NatTypeDetectionClient +/// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html +/// \ingroup NAT_PUNCHTHROUGH_GROUP +class RAK_DLL_EXPORT NatPunchthroughServer : public PluginInterface2 +{ +public: + + STATIC_FACTORY_DECLARATIONS(NatPunchthroughServer) + + // Constructor + NatPunchthroughServer(); + + // Destructor + virtual ~NatPunchthroughServer(); + + /// Sets a callback to be called with debug messages + /// \param[in] i Pointer to an interface. The pointer is stored, so don't delete it while in progress. Pass 0 to clear. + void SetDebugInterface(NatPunchthroughServerDebugInterface *i); + + /// \internal For plugin handling + virtual void Update(void); + + /// \internal For plugin handling + virtual PluginReceiveResult OnReceive(Packet *packet); + + /// \internal For plugin handling + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + + // Each connected user has a ready state. Ready means ready for nat punchthrough. + struct User; + struct ConnectionAttempt + { + ConnectionAttempt() {sender=0; recipient=0; startTime=0; attemptPhase=NAT_ATTEMPT_PHASE_NOT_STARTED;} + User *sender, *recipient; + uint16_t sessionId; + RakNet::Time startTime; + enum + { + NAT_ATTEMPT_PHASE_NOT_STARTED, + NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS, + } attemptPhase; + }; + struct User + { + RakNetGUID guid; + SystemAddress systemAddress; + unsigned short mostRecentPort; + bool isReady; + DataStructures::OrderedList groupPunchthroughRequests; + + DataStructures::List connectionAttempts; + bool HasConnectionAttemptToUser(User *user); + void DerefConnectionAttempt(ConnectionAttempt *ca); + void DeleteConnectionAttempt(ConnectionAttempt *ca); + void LogConnectionAttempts(RakNet::RakString &rs); + }; + RakNet::Time lastUpdate; + static int NatPunchthroughUserComp( const RakNetGUID &key, User * const &data ); +protected: + void OnNATPunchthroughRequest(Packet *packet); + DataStructures::OrderedList users; + + void OnGetMostRecentPort(Packet *packet); + void OnClientReady(Packet *packet); + + void SendTimestamps(void); + void StartPendingPunchthrough(void); + void StartPunchthroughForUser(User*user); + uint16_t sessionId; + NatPunchthroughServerDebugInterface *natPunchthroughServerDebugInterface; + + SystemAddress boundAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; + unsigned char boundAddressCount; + +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/NatTypeDetectionClient.hpp b/include/raknet/NatTypeDetectionClient.hpp new file mode 100644 index 0000000..b5a7df2 --- /dev/null +++ b/include/raknet/NatTypeDetectionClient.hpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains the NAT-type detection code for the client +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatTypeDetectionClient==1 + +#ifndef __NAT_TYPE_DETECTION_CLIENT_H +#define __NAT_TYPE_DETECTION_CLIENT_H + +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "PluginInterface2.hpp" +#include "PacketPriority.hpp" +#include "SocketIncludes.hpp" +#include "DS_OrderedList.hpp" +#include "RakString.hpp" +#include "NatTypeDetectionCommon.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +struct Packet; + + /// \brief Client code for NatTypeDetection + /// \details See NatTypeDetectionServer.h for algorithm + /// To use, just connect to the server, and call DetectNAT + /// You will get back ID_NAT_TYPE_DETECTION_RESULT with one of the enumerated values of NATTypeDetectionResult found in NATTypeDetectionCommon.h + /// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html + /// \sa NatPunchthroughClient + /// \sa NatTypeDetectionServer + /// \ingroup NAT_TYPE_DETECTION_GROUP + class RAK_DLL_EXPORT NatTypeDetectionClient : public PluginInterface2, public RNS2EventHandler + { + public: + + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(NatTypeDetectionClient) + + // Constructor + NatTypeDetectionClient(); + + // Destructor + virtual ~NatTypeDetectionClient(); + + /// Send the message to the server to detect the nat type + /// Server must be running NatTypeDetectionServer + /// We must already be connected to the server + /// \param[in] serverAddress address of the server + void DetectNATType(SystemAddress _serverAddress); + + /// \internal For plugin handling + virtual void Update(void); + + /// \internal For plugin handling + virtual PluginReceiveResult OnReceive(Packet *packet); + + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnRakPeerShutdown(void); + virtual void OnDetach(void); + + virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct); + virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line); + virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line); + protected: + DataStructures::Queue bufferedPackets; + SimpleMutex bufferedPacketsMutex; + + RakNetSocket2* c2; + //unsigned short c2Port; + void Shutdown(void); + void OnCompletion(NATTypeDetectionResult result); + bool IsInProgress(void) const; + + void OnTestPortRestricted(Packet *packet); + SystemAddress serverAddress; + }; + + +} + + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/NatTypeDetectionCommon.hpp b/include/raknet/NatTypeDetectionCommon.hpp new file mode 100644 index 0000000..09d7305 --- /dev/null +++ b/include/raknet/NatTypeDetectionCommon.hpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \defgroup NAT_TYPE_DETECTION_GROUP NatTypeDetection +/// \brief Use a remote server with multiple IP addresses to determine what type of NAT your router is using +/// \details +/// \ingroup PLUGINS_GROUP + +#ifndef __NAT_TYPE_DETECTION_COMMON_H +#define __NAT_TYPE_DETECTION_COMMON_H + +#include "NativeFeatureIncludes.hpp" + +#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 + +#include "SocketIncludes.hpp" +#include "RakNetTypes.hpp" +#include "RakNetSocket2.hpp" + +namespace RakNet +{ + + /// All possible types of NATs (except NAT_TYPE_COUNT, which is an internal value) + enum NATTypeDetectionResult + { + /// Works with anyone + NAT_TYPE_NONE, + /// Accepts any datagrams to a port that has been previously used. Will accept the first datagram from the remote peer. + NAT_TYPE_FULL_CONE, + /// Accepts datagrams to a port as long as the datagram source IP address is a system we have already sent to. Will accept the first datagram if both systems send simultaneously. Otherwise, will accept the first datagram after we have sent one datagram. + NAT_TYPE_ADDRESS_RESTRICTED, + /// Same as address-restricted cone NAT, but we had to send to both the correct remote IP address and correct remote port. The same source address and port to a different destination uses the same mapping. + NAT_TYPE_PORT_RESTRICTED, + /// A different port is chosen for every remote destination. The same source address and port to a different destination uses a different mapping. Since the port will be different, the first external punchthrough attempt will fail. For this to work it requires port-prediction (MAX_PREDICTIVE_PORT_RANGE>1) and that the router chooses ports sequentially. + NAT_TYPE_SYMMETRIC, + /// Hasn't been determined. NATTypeDetectionClient does not use this, but other plugins might + NAT_TYPE_UNKNOWN, + /// In progress. NATTypeDetectionClient does not use this, but other plugins might + NAT_TYPE_DETECTION_IN_PROGRESS, + /// Didn't bother figuring it out, as we support UPNP, so it is equivalent to NAT_TYPE_NONE. NATTypeDetectionClient does not use this, but other plugins might + NAT_TYPE_SUPPORTS_UPNP, + /// \internal Must be last + NAT_TYPE_COUNT + }; + + /// \return Can one system with NATTypeDetectionResult \a type1 connect to \a type2 + bool RAK_DLL_EXPORT CanConnect(NATTypeDetectionResult type1, NATTypeDetectionResult type2); + + /// Return a technical string representin the enumeration + RAK_DLL_EXPORT const char * NATTypeDetectionResultToString(NATTypeDetectionResult type); + + /// Return a friendly string representing the enumeration + /// None and relaxed can connect to anything + /// Moderate can connect to moderate or less + /// Strict can connect to relaxed or less + RAK_DLL_EXPORT const char * NATTypeDetectionResultToStringFriendly(NATTypeDetectionResult type); + + /// \internal + RAK_DLL_EXPORT RakNetSocket2* CreateNonblockingBoundSocket(const char *bindAddr +#ifdef __native_client__ + ,_PP_Instance_ chromeInstance +#endif + , RNS2EventHandler *eventHandler + ); + + /// \internal + //int NatTypeRecvFrom(char *data, RakNetSocket2* socket, SystemAddress &sender, RNS2EventHandler *eventHandler); +} + +#endif // #if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 + +#endif diff --git a/include/raknet/NatTypeDetectionServer.hpp b/include/raknet/NatTypeDetectionServer.hpp new file mode 100644 index 0000000..71c8c44 --- /dev/null +++ b/include/raknet/NatTypeDetectionServer.hpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains the NAT-type detection code for the server +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 + +#ifndef __NAT_TYPE_DETECTION_SERVER_H +#define __NAT_TYPE_DETECTION_SERVER_H + +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "PluginInterface2.hpp" +#include "PacketPriority.hpp" +#include "SocketIncludes.hpp" +#include "DS_OrderedList.hpp" +#include "RakString.hpp" +#include "NatTypeDetectionCommon.hpp" + + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +struct Packet; + +/// \brief Server code for NatTypeDetection +/// \details +/// Sends to a remote system on certain ports and addresses to determine what type of router, if any, that client is behind +/// Requires that the server have 4 external IP addresses +///
    +///
  1. Server has 1 instance of RakNet. Server has four external ip addresses S1 to S4. Five ports are used in total P1 to P5. RakNet is bound to S1P1. Sockets are bound to S1P2, S2P3, S3P4, S4P5 +///
  2. Client with one port using RakNet (C1). Another port not using anything (C2). +///
  3. C1 connects to S1P1 for normal communication. +///
  4. S4P5 sends to C2. If arrived, no NAT. Done. (If didn't arrive, S4P5 potentially banned, do not use again). +///
  5. S2P3 sends to C1 (Different address, different port, to previously used port on client). If received, Full-cone nat. Done. (If didn't arrive, S2P3 potentially banned, do not use again). +///
  6. S1P2 sends to C1 (Same address, different port, to previously used port on client). If received, address-restricted cone nat. Done. +///
  7. Server via RakNet connection tells C1 to send to to S3P4. If address of C1 as seen by S3P4 is the same as the address of C1 as seen by S1P1 (RakNet connection), then port-restricted cone nat. Done +///
  8. Else symmetric nat. Done. +///
+/// See also http://www.jenkinssoftware.com/raknet/manual/natpunchthrough.html +/// \sa NatPunchthroughServer +/// \sa NatTypeDetectionClient +/// \ingroup NAT_TYPE_DETECTION_GROUP +class RAK_DLL_EXPORT NatTypeDetectionServer : public PluginInterface2, public RNS2EventHandler +{ +public: + + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(NatTypeDetectionServer) + + // Constructor + NatTypeDetectionServer(); + + // Destructor + virtual ~NatTypeDetectionServer(); + + /// Start the system, binding to 3 external IPs not already in useS + /// \param[in] nonRakNetIP2 First unused external IP + /// \param[in] nonRakNetIP3 Second unused external IP + /// \param[in] nonRakNetIP4 Third unused external IP + void Startup( + const char *nonRakNetIP2, + const char *nonRakNetIP3, + const char *nonRakNetIP4 +#ifdef __native_client__ + ,_PP_Instance_ chromeInstance +#endif + ); + + // Releases the sockets created in Startup(); + void Shutdown(void); + + /// \internal For plugin handling + virtual void Update(void); + + /// \internal For plugin handling + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + + enum NATDetectionState + { + STATE_NONE, + STATE_TESTING_NONE_1, + STATE_TESTING_NONE_2, + STATE_TESTING_FULL_CONE_1, + STATE_TESTING_FULL_CONE_2, + STATE_TESTING_ADDRESS_RESTRICTED_1, + STATE_TESTING_ADDRESS_RESTRICTED_2, + STATE_TESTING_PORT_RESTRICTED_1, + STATE_TESTING_PORT_RESTRICTED_2, + STATE_DONE, + }; + + struct NATDetectionAttempt + { + SystemAddress systemAddress; + NATDetectionState detectionState; + RakNet::TimeMS nextStateTime; + RakNet::TimeMS timeBetweenAttempts; + unsigned short c2Port; + RakNetGUID guid; + }; + + virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct); + virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line); + virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line); +protected: + DataStructures::Queue bufferedPackets; + SimpleMutex bufferedPacketsMutex; + + void OnDetectionRequest(Packet *packet); + DataStructures::List natDetectionAttempts; + unsigned int GetDetectionAttemptIndex(const SystemAddress &sa); + unsigned int GetDetectionAttemptIndex(RakNetGUID guid); + + // s1p1 is rakpeer itself + RakNetSocket2 *s1p2,*s2p3,*s3p4,*s4p5; + //unsigned short s1p2Port, s2p3Port, s3p4Port, s4p5Port; + char s3p4Address[64]; +}; +} + + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/NativeFeatureIncludes.hpp b/include/raknet/NativeFeatureIncludes.hpp new file mode 100644 index 0000000..1f61989 --- /dev/null +++ b/include/raknet/NativeFeatureIncludes.hpp @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +// If you want to change these defines, put them in NativeFeatureIncludesOverrides so your changes are not lost when updating RakNet +// The user should not edit this file +#include "NativeFeatureIncludesOverrides.hpp" + +#ifndef __NATIVE_FEATURE_INCLDUES_H +#define __NATIVE_FEATURE_INCLDUES_H + +// Uncomment below defines, and paste to NativeFeatureIncludesOverrides.h, to exclude plugins that you do not want to build into the static library, or DLL +// These are not all the plugins, only those that are in the core library +// Other plugins are located in DependentExtensions +// #define _RAKNET_SUPPORT_ConnectionGraph2 0 +// #define _RAKNET_SUPPORT_DirectoryDeltaTransfer 0 +// #define _RAKNET_SUPPORT_FileListTransfer 0 +// #define _RAKNET_SUPPORT_FullyConnectedMesh2 0 +// #define _RAKNET_SUPPORT_MessageFilter 0 +// #define _RAKNET_SUPPORT_NatPunchthroughClient 0 +// #define _RAKNET_SUPPORT_NatPunchthroughServer 0 +// #define _RAKNET_SUPPORT_NatTypeDetectionClient 0 +// #define _RAKNET_SUPPORT_NatTypeDetectionServer 0 +// #define _RAKNET_SUPPORT_PacketLogger 0 +// #define _RAKNET_SUPPORT_ReadyEvent 0 +// #define _RAKNET_SUPPORT_ReplicaManager3 0 +// #define _RAKNET_SUPPORT_Router2 0 +// #define _RAKNET_SUPPORT_RPC4Plugin 0 +// #define _RAKNET_SUPPORT_TeamBalancer 0 +// #define _RAKNET_SUPPORT_TeamManager 0 +// #define _RAKNET_SUPPORT_UDPProxyClient 0 +// #define _RAKNET_SUPPORT_UDPProxyCoordinator 0 +// #define _RAKNET_SUPPORT_UDPProxyServer 0 +// #define _RAKNET_SUPPORT_ConsoleServer 0 +// #define _RAKNET_SUPPORT_RakNetTransport 0 +// #define _RAKNET_SUPPORT_TelnetTransport 0 +// #define _RAKNET_SUPPORT_TCPInterface 0 +// #define _RAKNET_SUPPORT_LogCommandParser 0 +// #define _RAKNET_SUPPORT_RakNetCommandParser 0 +// #define _RAKNET_SUPPORT_EmailSender 0 +// #define _RAKNET_SUPPORT_HTTPConnection 0 +// #define _RAKNET_SUPPORT_HTTPConnection2 0 +// #define _RAKNET_SUPPORT_PacketizedTCP 0 +// #define _RAKNET_SUPPORT_TwoWayAuthentication 0 + +// SET DEFAULTS IF UNDEFINED +#ifndef LIBCAT_SECURITY +#define LIBCAT_SECURITY 0 +#endif +#ifndef _RAKNET_SUPPORT_ConnectionGraph2 +#define _RAKNET_SUPPORT_ConnectionGraph2 1 +#endif +#ifndef _RAKNET_SUPPORT_DirectoryDeltaTransfer +#define _RAKNET_SUPPORT_DirectoryDeltaTransfer 1 +#endif +#ifndef _RAKNET_SUPPORT_FileListTransfer +#define _RAKNET_SUPPORT_FileListTransfer 1 +#endif +#ifndef _RAKNET_SUPPORT_FullyConnectedMesh +#define _RAKNET_SUPPORT_FullyConnectedMesh 1 +#endif +#ifndef _RAKNET_SUPPORT_FullyConnectedMesh2 +#define _RAKNET_SUPPORT_FullyConnectedMesh2 1 +#endif +#ifndef _RAKNET_SUPPORT_MessageFilter +#define _RAKNET_SUPPORT_MessageFilter 1 +#endif +#ifndef _RAKNET_SUPPORT_NatPunchthroughClient +#define _RAKNET_SUPPORT_NatPunchthroughClient 1 +#endif +#ifndef _RAKNET_SUPPORT_NatPunchthroughServer +#define _RAKNET_SUPPORT_NatPunchthroughServer 1 +#endif +#ifndef _RAKNET_SUPPORT_NatTypeDetectionClient +#define _RAKNET_SUPPORT_NatTypeDetectionClient 1 +#endif +#ifndef _RAKNET_SUPPORT_NatTypeDetectionServer +#define _RAKNET_SUPPORT_NatTypeDetectionServer 1 +#endif +#ifndef _RAKNET_SUPPORT_PacketLogger +#define _RAKNET_SUPPORT_PacketLogger 1 +#endif +#ifndef _RAKNET_SUPPORT_ReadyEvent +#define _RAKNET_SUPPORT_ReadyEvent 1 +#endif +#ifndef _RAKNET_SUPPORT_ReplicaManager3 +#define _RAKNET_SUPPORT_ReplicaManager3 1 +#endif +#ifndef _RAKNET_SUPPORT_Router2 +#define _RAKNET_SUPPORT_Router2 1 +#endif +#ifndef _RAKNET_SUPPORT_RPC4Plugin +#define _RAKNET_SUPPORT_RPC4Plugin 1 +#endif +#ifndef _RAKNET_SUPPORT_TeamBalancer +#define _RAKNET_SUPPORT_TeamBalancer 1 +#endif +#ifndef _RAKNET_SUPPORT_TeamManager +#define _RAKNET_SUPPORT_TeamManager 1 +#endif +#ifndef _RAKNET_SUPPORT_UDPProxyClient +#define _RAKNET_SUPPORT_UDPProxyClient 1 +#endif +#ifndef _RAKNET_SUPPORT_UDPProxyCoordinator +#define _RAKNET_SUPPORT_UDPProxyCoordinator 1 +#endif +#ifndef _RAKNET_SUPPORT_UDPProxyServer +#define _RAKNET_SUPPORT_UDPProxyServer 1 +#endif +#ifndef _RAKNET_SUPPORT_ConsoleServer +#define _RAKNET_SUPPORT_ConsoleServer 1 +#endif +#ifndef _RAKNET_SUPPORT_RakNetTransport +#define _RAKNET_SUPPORT_RakNetTransport 1 +#endif +#ifndef _RAKNET_SUPPORT_TelnetTransport +#define _RAKNET_SUPPORT_TelnetTransport 1 +#endif +#ifndef _RAKNET_SUPPORT_TCPInterface +#define _RAKNET_SUPPORT_TCPInterface 1 +#endif +#ifndef _RAKNET_SUPPORT_LogCommandParser +#define _RAKNET_SUPPORT_LogCommandParser 1 +#endif +#ifndef _RAKNET_SUPPORT_RakNetCommandParser +#define _RAKNET_SUPPORT_RakNetCommandParser 1 +#endif +#ifndef _RAKNET_SUPPORT_EmailSender +#define _RAKNET_SUPPORT_EmailSender 1 +#endif +#ifndef _RAKNET_SUPPORT_HTTPConnection +#define _RAKNET_SUPPORT_HTTPConnection 1 +#endif +#ifndef _RAKNET_SUPPORT_HTTPConnection2 +#define _RAKNET_SUPPORT_HTTPConnection2 1 +#endif +#ifndef _RAKNET_SUPPORT_PacketizedTCP +#define _RAKNET_SUPPORT_PacketizedTCP 1 +#endif +#ifndef _RAKNET_SUPPORT_TwoWayAuthentication +#define _RAKNET_SUPPORT_TwoWayAuthentication 1 +#endif +#ifndef _RAKNET_SUPPORT_CloudClient +#define _RAKNET_SUPPORT_CloudClient 1 +#endif +#ifndef _RAKNET_SUPPORT_CloudServer +#define _RAKNET_SUPPORT_CloudServer 1 +#endif +#ifndef _RAKNET_SUPPORT_DynDNS +#define _RAKNET_SUPPORT_DynDNS 1 +#endif +#ifndef _RAKNET_SUPPORT_Rackspace +#define _RAKNET_SUPPORT_Rackspace 1 +#endif +#ifndef _RAKNET_SUPPORT_FileOperations +#define _RAKNET_SUPPORT_FileOperations 1 +#endif +#ifndef _RAKNET_SUPPORT_UDPForwarder +#define _RAKNET_SUPPORT_UDPForwarder 1 +#endif +#ifndef _RAKNET_SUPPORT_StatisticsHistory +#define _RAKNET_SUPPORT_StatisticsHistory 1 +#endif +#ifndef _RAKNET_SUPPORT_LibVoice +#define _RAKNET_SUPPORT_LibVoice 0 +#endif +#ifndef _RAKNET_SUPPORT_RelayPlugin +#define _RAKNET_SUPPORT_RelayPlugin 1 +#endif + +// Take care of dependencies +#if _RAKNET_SUPPORT_DirectoryDeltaTransfer==1 +#undef _RAKNET_SUPPORT_FileListTransfer +#define _RAKNET_SUPPORT_FileListTransfer 1 +#endif +#if _RAKNET_SUPPORT_FullyConnectedMesh2==1 +#undef _RAKNET_SUPPORT_ConnectionGraph2 +#define _RAKNET_SUPPORT_ConnectionGraph2 1 +#endif +#if _RAKNET_SUPPORT_TelnetTransport==1 +#undef _RAKNET_SUPPORT_PacketizedTCP +#define _RAKNET_SUPPORT_PacketizedTCP 1 +#endif +#if _RAKNET_SUPPORT_PacketizedTCP==1 || _RAKNET_SUPPORT_EmailSender==1 || _RAKNET_SUPPORT_HTTPConnection==1 +#undef _RAKNET_SUPPORT_TCPInterface +#define _RAKNET_SUPPORT_TCPInterface 1 +#endif + + + + + + + + + + + + +#endif // __NATIVE_FEATURE_INCLDUES_H diff --git a/include/raknet/NativeFeatureIncludesOverrides.hpp b/include/raknet/NativeFeatureIncludesOverrides.hpp new file mode 100644 index 0000000..345d5ff --- /dev/null +++ b/include/raknet/NativeFeatureIncludesOverrides.hpp @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +// USER EDITABLE FILE +// See NativeFeatureIncludes.h + +#ifndef __NATIVE_FEATURE_INCLDUES_OVERRIDES_H +#define __NATIVE_FEATURE_INCLDUES_OVERRIDES_H + +//#define LIBCAT_SECURITY 1 + +#endif diff --git a/include/raknet/NativeTypes.hpp b/include/raknet/NativeTypes.hpp new file mode 100644 index 0000000..f1aa478 --- /dev/null +++ b/include/raknet/NativeTypes.hpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __NATIVE_TYPES_H +#define __NATIVE_TYPES_H + +#if defined(__GNUC__) || defined(__GCCXML__) || defined(__SNC__) || defined(__S3E__) +#include +#elif !defined(_STDINT_H) && !defined(_SN_STDINT_H) && !defined(_SYS_STDINT_H_) && !defined(_STDINT) && !defined(_MACHTYPES_H_) && !defined(_STDINT_H_) + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned __int32 uint32_t; + typedef signed char int8_t; + typedef signed short int16_t; + typedef __int32 int32_t; + #if defined(_MSC_VER) && _MSC_VER < 1300 + typedef unsigned __int64 uint64_t; + typedef signed __int64 int64_t; + #else + typedef unsigned long long int uint64_t; + typedef signed long long int64_t; + #endif +#endif + + +#endif diff --git a/include/raknet/NetworkIDManager.hpp b/include/raknet/NetworkIDManager.hpp new file mode 100644 index 0000000..f59e7cc --- /dev/null +++ b/include/raknet/NetworkIDManager.hpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#ifndef __NETWORK_ID_MANAGER_H +#define __NETWORK_ID_MANAGER_H + +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "RakMemoryOverride.hpp" +#include "NetworkIDObject.hpp" +#include "Rand.hpp" + +namespace RakNet +{ + +/// Increase this value if you plan to have many persistent objects +/// This value must match on all systems +#define NETWORK_ID_MANAGER_HASH_LENGTH 1024 + +/// This class is simply used to generate a unique number for a group of instances of NetworkIDObject +/// An instance of this class is required to use the ObjectID to pointer lookup system +/// You should have one instance of this class per game instance. +/// Call SetIsNetworkIDAuthority before using any functions of this class, or of NetworkIDObject +class RAK_DLL_EXPORT NetworkIDManager +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(NetworkIDManager) + + NetworkIDManager(); + virtual ~NetworkIDManager(void); + + /// Returns the parent object, or this instance if you don't use a parent. + /// Supports NetworkIDObject anywhere in the inheritance hierarchy + /// \pre You must first call SetNetworkIDManager before using this function + template + returnType GET_OBJECT_FROM_ID(NetworkID x) { + NetworkIDObject *nio = GET_BASE_OBJECT_FROM_ID(x); + if (nio==0) + return 0; + if (nio->GetParent()) + return (returnType) nio->GetParent(); + return (returnType) nio; + } + + // Stop tracking all NetworkID objects + void Clear(void); + + /// \internal + NetworkIDObject *GET_BASE_OBJECT_FROM_ID(NetworkID x); + +protected: + /// \internal + void TrackNetworkIDObject(NetworkIDObject *networkIdObject); + void StopTrackingNetworkIDObject(NetworkIDObject *networkIdObject); + + friend class NetworkIDObject; + + NetworkIDObject *networkIdHash[NETWORK_ID_MANAGER_HASH_LENGTH]; + unsigned int NetworkIDToHashIndex(NetworkID networkId); + uint64_t startingOffset; + /// \internal + NetworkID GetNewNetworkID(void); + +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/NetworkIDObject.hpp b/include/raknet/NetworkIDObject.hpp new file mode 100644 index 0000000..306cc63 --- /dev/null +++ b/include/raknet/NetworkIDObject.hpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief A class you can derive from to make it easier to represent every networked object with an integer. This way you can refer to objects over the network. +/// + + +#if !defined(__NETWORK_ID_GENERATOR) +#define __NETWORK_ID_GENERATOR + +#include "RakNetTypes.hpp" +#include "RakMemoryOverride.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class NetworkIDManager; + +typedef uint32_t NetworkIDType; + +/// \brief Unique shared ids for each object instance +/// \details A class you can derive from to make it easier to represent every networked object with an integer. This way you can refer to objects over the network. +/// One system should return true for IsNetworkIDAuthority() and the rest should return false. When an object needs to be created, have the the one system create the object. +/// Then have that system send a message to all other systems, and include the value returned from GetNetworkID() in that packet. All other systems should then create the same +/// class of object, and call SetNetworkID() on that class with the NetworkID in the packet. +/// \see the manual for more information on this. +class RAK_DLL_EXPORT NetworkIDObject +{ +public: + // Constructor. NetworkIDs, if IsNetworkIDAuthority() is true, are created here. + NetworkIDObject(); + + // Destructor. Used NetworkIDs, if any, are freed here. + virtual ~NetworkIDObject(); + + /// Sets the manager class from which to request unique network IDs + /// Unlike previous versions, the NetworkIDObject relies on a manager class to provide IDs, rather than using statics, + /// So you can have more than one set of IDs on the same system. + virtual void SetNetworkIDManager( NetworkIDManager *manager); + + /// Returns what was passed to SetNetworkIDManager + virtual NetworkIDManager * GetNetworkIDManager( void ) const; + + /// Returns the NetworkID that you can use to refer to this object over the network. + /// \pre You must first call SetNetworkIDManager before using this function + /// \retval UNASSIGNED_NETWORK_ID UNASSIGNED_NETWORK_ID is returned IsNetworkIDAuthority() is false and SetNetworkID() was not previously called. This is also returned if you call this function in the constructor. + /// \retval 0-65534 Any other value is a valid NetworkID. NetworkIDs start at 0 and go to 65534, wrapping at that point. + virtual NetworkID GetNetworkID( void ); + + /// Sets the NetworkID for this instance. Usually this is called by the clients and determined from the servers. However, if you save multiplayer games you would likely use + /// This on load as well. + virtual void SetNetworkID( NetworkID id ); + + /// Your class does not have to derive from NetworkIDObject, although that is the easiest way to implement this. + /// If you want this to be a member object of another class, rather than inherit, then call SetParent() with a pointer to the parent class instance. + /// GET_OBJECT_FROM_ID will then return the parent rather than this instance. + virtual void SetParent( void *_parent ); + + /// Return what was passed to SetParent + /// \return The value passed to SetParent, or 0 if it was never called. + virtual void* GetParent( void ) const; + +protected: + + /// The network ID of this object + // networkID is assigned when networkIDManager is set. + NetworkID networkID; + NetworkIDManager *networkIDManager; + + /// The parent set by SetParent() + void *parent; + + /// \internal, used by NetworkIDManager + friend class NetworkIDManager; + NetworkIDObject *nextInstanceForNetworkIDManager; +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/PS3Includes.hpp b/include/raknet/PS3Includes.hpp new file mode 100644 index 0000000..1d60d89 --- /dev/null +++ b/include/raknet/PS3Includes.hpp @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/include/raknet/PS4Includes.hpp b/include/raknet/PS4Includes.hpp new file mode 100644 index 0000000..db9976f --- /dev/null +++ b/include/raknet/PS4Includes.hpp @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/include/raknet/PacketConsoleLogger.hpp b/include/raknet/PacketConsoleLogger.hpp new file mode 100644 index 0000000..990a6cd --- /dev/null +++ b/include/raknet/PacketConsoleLogger.hpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief This will write all incoming and outgoing network messages to the log command parser, which can be accessed through Telnet +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_LogCommandParser==1 && _RAKNET_SUPPORT_PacketLogger==1 + +#ifndef __PACKET_CONSOLE_LOGGER_H_ +#define __PACKET_CONSOLE_LOGGER_H_ + +#include "PacketLogger.hpp" + +namespace RakNet +{ +/// Forward declarations +class LogCommandParser; + +/// \ingroup PACKETLOGGER_GROUP +/// \brief Packetlogger that logs to a remote command console +class RAK_DLL_EXPORT PacketConsoleLogger : public PacketLogger +{ +public: + PacketConsoleLogger(); + // Writes to the command parser used for logging, which is accessed through a secondary communication layer (such as Telnet or RakNet) - See ConsoleServer.h + virtual void SetLogCommandParser(LogCommandParser *lcp); + virtual void WriteLog(const char *str); +protected: + LogCommandParser *logCommandParser; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/PacketFileLogger.hpp b/include/raknet/PacketFileLogger.hpp new file mode 100644 index 0000000..f2ff923 --- /dev/null +++ b/include/raknet/PacketFileLogger.hpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief This will write all incoming and outgoing network messages to a file +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 + +#ifndef __PACKET_FILE_LOGGER_H_ +#define __PACKET_FILE_LOGGER_H_ + +#include "PacketLogger.hpp" +#include + +namespace RakNet +{ + +/// \ingroup PACKETLOGGER_GROUP +/// \brief Packetlogger that outputs to a file +class RAK_DLL_EXPORT PacketFileLogger : public PacketLogger +{ +public: + PacketFileLogger(); + virtual ~PacketFileLogger(); + void StartLog(const char *filenamePrefix); + virtual void WriteLog(const char *str); +protected: + FILE *packetLogFile; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/PacketLogger.hpp b/include/raknet/PacketLogger.hpp new file mode 100644 index 0000000..2a319c3 --- /dev/null +++ b/include/raknet/PacketLogger.hpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief This will write all incoming and outgoing network messages to the local console screen. See derived functions for other outputs +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 + +#ifndef __PACKET_LOGGER_H +#define __PACKET_LOGGER_H + +#include "RakNetTypes.hpp" +#include "PluginInterface2.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \defgroup PACKETLOGGER_GROUP PacketLogger +/// \brief Print out incoming messages to a target destination +/// \details +/// \ingroup PLUGINS_GROUP + +/// \brief Writes incoming and outgoing messages to the screen. +/// This will write all incoming and outgoing messages to the console window, or to a file if you override it and give it this functionality. +/// \ingroup PACKETLOGGER_GROUP +class RAK_DLL_EXPORT PacketLogger : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(PacketLogger) + + PacketLogger(); + virtual ~PacketLogger(); + + // Translate the supplied parameters into an output line - overloaded version that takes a MessageIdentifier + // and translates it into a string (numeric or textual representation based on printId); this calls the + // second version which takes a const char* argument for the messageIdentifier + virtual void FormatLine(char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame + , unsigned char messageIdentifier, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, + unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex); + virtual void FormatLine(char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame + , const char* idToPrint, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, + unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex); + + /// Events on low level sends and receives. These functions may be called from different threads at the same time. + virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); + virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); + virtual void OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError); + virtual void OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, RakNet::TimeMS time, int isSend); + virtual void OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, RakNet::TimeMS time); + virtual void OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); + + /// Logs out a header for all the data + virtual void LogHeader(void); + + /// Override this to log strings to wherever. Log should be threadsafe + virtual void WriteLog(const char *str); + + // Write informational messages + virtual void WriteMiscellaneous(const char *type, const char *msg); + + + // Set to true to print ID_* instead of numbers + virtual void SetPrintID(bool print); + // Print or hide acks (clears up the screen not to print them but is worse for debugging) + virtual void SetPrintAcks(bool print); + + /// Prepend this string to output logs. + virtual void SetPrefix(const char *_prefix); + + /// Append this string to output logs. (newline is useful here) + virtual void SetSuffix(const char *_suffix); + static const char* BaseIDTOString(unsigned char Id); + + /// Log the direct sends and receives or not. Default true + void SetLogDirectMessages(bool send); +protected: + + virtual bool UsesReliabilityLayer(void) const {return true;} + const char* IDTOString(unsigned char Id); + virtual void AddToLog(const char *str); + // Users should override this + virtual const char* UserIDTOString(unsigned char Id); + void GetLocalTime(char buffer[128]); + bool logDirectMessages; + + bool printId, printAcks; + char prefix[256]; + char suffix[256]; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/PacketOutputWindowLogger.hpp b/include/raknet/PacketOutputWindowLogger.hpp new file mode 100644 index 0000000..c066d80 --- /dev/null +++ b/include/raknet/PacketOutputWindowLogger.hpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief This will write all incoming and outgoing network messages to a file +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 + +#ifndef __PACKET_OUTPUT_WINDOW_LOGGER_H_ +#define __PACKET_OUTPUT_WINDOW_LOGGER_H_ + +#include "PacketLogger.hpp" + +namespace RakNet +{ + +/// \ingroup PACKETLOGGER_GROUP +/// \brief Packetlogger that outputs to the output window in the debugger. Windows only. +class RAK_DLL_EXPORT PacketOutputWindowLogger : public PacketLogger +{ +public: + PacketOutputWindowLogger(); + virtual ~PacketOutputWindowLogger(); + virtual void WriteLog(const char *str); +protected: +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/PacketPool.hpp b/include/raknet/PacketPool.hpp new file mode 100644 index 0000000..b534cac --- /dev/null +++ b/include/raknet/PacketPool.hpp @@ -0,0 +1 @@ +// REMOVEME \ No newline at end of file diff --git a/include/raknet/PacketPriority.hpp b/include/raknet/PacketPriority.hpp new file mode 100644 index 0000000..973c304 --- /dev/null +++ b/include/raknet/PacketPriority.hpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief This file contains enumerations for packet priority and reliability enumerations. +/// + + + +#ifndef __PACKET_PRIORITY_H +#define __PACKET_PRIORITY_H + +/// These enumerations are used to describe when packets are delivered. +enum PacketPriority +{ + /// The highest possible priority. These message trigger sends immediately, and are generally not buffered or aggregated into a single datagram. + IMMEDIATE_PRIORITY, + + /// For every 2 IMMEDIATE_PRIORITY messages, 1 HIGH_PRIORITY will be sent. + /// Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control. + HIGH_PRIORITY, + + /// For every 2 HIGH_PRIORITY messages, 1 MEDIUM_PRIORITY will be sent. + /// Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control. + MEDIUM_PRIORITY, + + /// For every 2 MEDIUM_PRIORITY messages, 1 LOW_PRIORITY will be sent. + /// Messages at this priority and lower are buffered to be sent in groups at 10 millisecond intervals to reduce UDP overhead and better measure congestion control. + LOW_PRIORITY, + + /// \internal + NUMBER_OF_PRIORITIES +}; + +/// These enumerations are used to describe how packets are delivered. +/// \note Note to self: I write this with 3 bits in the stream. If I add more remember to change that +/// \note In ReliabilityLayer::WriteToBitStreamFromInternalPacket I assume there are 5 major types +/// \note Do not reorder, I check on >= UNRELIABLE_WITH_ACK_RECEIPT +enum PacketReliability +{ + /// Same as regular UDP, except that it will also discard duplicate datagrams. RakNet adds (6 to 17) + 21 bits of overhead, 16 of which is used to detect duplicate packets and 6 to 17 of which is used for message length. + UNRELIABLE, + + /// Regular UDP with a sequence counter. Out of order messages will be discarded. + /// Sequenced and ordered messages sent on the same channel will arrive in the order sent. + UNRELIABLE_SEQUENCED, + + /// The message is sent reliably, but not necessarily in any order. Same overhead as UNRELIABLE. + RELIABLE, + + /// This message is reliable and will arrive in the order you sent it. Messages will be delayed while waiting for out of order messages. Same overhead as UNRELIABLE_SEQUENCED. + /// Sequenced and ordered messages sent on the same channel will arrive in the order sent. + RELIABLE_ORDERED, + + /// This message is reliable and will arrive in the sequence you sent it. Out or order messages will be dropped. Same overhead as UNRELIABLE_SEQUENCED. + /// Sequenced and ordered messages sent on the same channel will arrive in the order sent. + RELIABLE_SEQUENCED, + + /// Same as UNRELIABLE, however the user will get either ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS based on the result of sending this message when calling RakPeerInterface::Receive(). Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. + UNRELIABLE_WITH_ACK_RECEIPT, + + /// Same as UNRELIABLE_SEQUENCED, however the user will get either ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS based on the result of sending this message when calling RakPeerInterface::Receive(). Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. + /// 05/04/10 You can't have sequenced and ack receipts, because you don't know if the other system discarded the message, meaning you don't know if the message was processed + // UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT, + + /// Same as RELIABLE. The user will also get ID_SND_RECEIPT_ACKED after the message is delivered when calling RakPeerInterface::Receive(). ID_SND_RECEIPT_ACKED is returned when the message arrives, not necessarily the order when it was sent. Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. This does not return ID_SND_RECEIPT_LOSS. + RELIABLE_WITH_ACK_RECEIPT, + + /// Same as RELIABLE_ORDERED_ACK_RECEIPT. The user will also get ID_SND_RECEIPT_ACKED after the message is delivered when calling RakPeerInterface::Receive(). ID_SND_RECEIPT_ACKED is returned when the message arrives, not necessarily the order when it was sent. Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. This does not return ID_SND_RECEIPT_LOSS. + RELIABLE_ORDERED_WITH_ACK_RECEIPT, + + /// Same as RELIABLE_SEQUENCED. The user will also get ID_SND_RECEIPT_ACKED after the message is delivered when calling RakPeerInterface::Receive(). Bytes 1-4 will contain the number returned from the Send() function. On disconnect or shutdown, all messages not previously acked should be considered lost. + /// 05/04/10 You can't have sequenced and ack receipts, because you don't know if the other system discarded the message, meaning you don't know if the message was processed + // RELIABLE_SEQUENCED_WITH_ACK_RECEIPT, + + /// \internal + NUMBER_OF_RELIABILITIES +}; + +#endif diff --git a/include/raknet/PacketizedTCP.hpp b/include/raknet/PacketizedTCP.hpp new file mode 100644 index 0000000..623b37c --- /dev/null +++ b/include/raknet/PacketizedTCP.hpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief A simple TCP based server allowing sends and receives. Can be connected by any TCP client, including telnet. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#ifndef __PACKETIZED_TCP +#define __PACKETIZED_TCP + +#include "TCPInterface.hpp" +#include "DS_ByteQueue.hpp" +#include "DS_Map.hpp" + +namespace RakNet +{ + +class RAK_DLL_EXPORT PacketizedTCP : public TCPInterface +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(PacketizedTCP) + + PacketizedTCP(); + virtual ~PacketizedTCP(); + + /// Stops the TCP server + void Stop(void); + + /// Sends a byte stream + void Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast ); + + // Sends a concatenated list of byte streams + bool SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ); + + /// Returns data received + Packet* Receive( void ); + + /// Disconnects a player/address + void CloseConnection( SystemAddress systemAddress ); + + /// Has a previous call to connect succeeded? + /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. + SystemAddress HasCompletedConnectionAttempt(void); + + /// Has a previous call to connect failed? + /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. + SystemAddress HasFailedConnectionAttempt(void); + + /// Queued events of new incoming connections + SystemAddress HasNewIncomingConnection(void); + + /// Queued events of lost connections + SystemAddress HasLostConnection(void); + +protected: + void ClearAllConnections(void); + void RemoveFromConnectionList(const SystemAddress &sa); + void AddToConnectionList(const SystemAddress &sa); + void PushNotificationsToQueues(void); + Packet *ReturnOutgoingPacket(void); + + // A single TCP recieve may generate multiple split packets. They are stored in the waitingPackets list until Receive is called + DataStructures::Queue waitingPackets; + DataStructures::Map connections; + + // Mirrors single producer / consumer, but processes them in Receive() before returning to user + DataStructures::Queue _newIncomingConnections, _lostConnections, _failedConnectionAttempts, _completedConnectionAttempts; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/PluginInterface2.hpp b/include/raknet/PluginInterface2.hpp new file mode 100644 index 0000000..a6e7f2e --- /dev/null +++ b/include/raknet/PluginInterface2.hpp @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b RakNet's plugin functionality system, version 2. You can derive from this to create your own plugins. +/// + + +#ifndef __PLUGIN_INTERFACE_2_H +#define __PLUGIN_INTERFACE_2_H + +#include "NativeFeatureIncludes.hpp" +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "PacketPriority.hpp" + +namespace RakNet { + +/// Forward declarations +class RakPeerInterface; +class TCPInterface; +struct Packet; +struct InternalPacket; + +/// \defgroup PLUGIN_INTERFACE_GROUP PluginInterface2 + +/// \defgroup PLUGINS_GROUP Plugins +/// \ingroup PLUGIN_INTERFACE_GROUP + +/// For each message that arrives on an instance of RakPeer, the plugins get an opportunity to process them first. This enumeration represents what to do with the message +/// \ingroup PLUGIN_INTERFACE_GROUP +enum PluginReceiveResult +{ + /// The plugin used this message and it shouldn't be given to the user. + RR_STOP_PROCESSING_AND_DEALLOCATE=0, + + /// This message will be processed by other plugins, and at last by the user. + RR_CONTINUE_PROCESSING, + + /// The plugin is going to hold on to this message. Do not deallocate it but do not pass it to other plugins either. + RR_STOP_PROCESSING +}; + +/// Reasons why a connection was lost +/// \ingroup PLUGIN_INTERFACE_GROUP +enum PI2_LostConnectionReason +{ + /// Called RakPeer::CloseConnection() + LCR_CLOSED_BY_USER, + + /// Got ID_DISCONNECTION_NOTIFICATION + LCR_DISCONNECTION_NOTIFICATION, + + /// GOT ID_CONNECTION_LOST + LCR_CONNECTION_LOST +}; + +/// Returns why a connection attempt failed +/// \ingroup PLUGIN_INTERFACE_GROUP +enum PI2_FailedConnectionAttemptReason +{ + FCAR_CONNECTION_ATTEMPT_FAILED, + FCAR_ALREADY_CONNECTED, + FCAR_NO_FREE_INCOMING_CONNECTIONS, + FCAR_SECURITY_PUBLIC_KEY_MISMATCH, + FCAR_CONNECTION_BANNED, + FCAR_INVALID_PASSWORD, + FCAR_INCOMPATIBLE_PROTOCOL, + FCAR_IP_RECENTLY_CONNECTED, + FCAR_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY, + FCAR_OUR_SYSTEM_REQUIRES_SECURITY, + FCAR_PUBLIC_KEY_MISMATCH +}; + +/// RakNet's plugin system. Each plugin processes the following events: +/// -Connection attempts +/// -The result of connection attempts +/// -Each incoming message +/// -Updates over time, when RakPeer::Receive() is called +/// +/// \ingroup PLUGIN_INTERFACE_GROUP +class RAK_DLL_EXPORT PluginInterface2 +{ +public: + PluginInterface2(); + virtual ~PluginInterface2(); + + /// Called when the interface is attached + virtual void OnAttach(void) {} + + /// Called when the interface is detached + virtual void OnDetach(void) {} + + /// Update is called every time a packet is checked for . + virtual void Update(void) {} + + /// OnReceive is called for every packet. + /// \param[in] packet the packet that is being returned to the user + /// \return True to allow the game and other plugins to get this message, false to absorb it + virtual PluginReceiveResult OnReceive(Packet *packet) {(void) packet; return RR_CONTINUE_PROCESSING;} + + /// Called when RakPeer is initialized + virtual void OnRakPeerStartup(void) {} + + /// Called when RakPeer is shutdown + virtual void OnRakPeerShutdown(void) {} + + /// Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system + /// \param[in] systemAddress The system whose connection was closed + /// \param[in] rakNetGuid The guid of the specified system + /// \param[in] lostConnectionReason How the connection was closed: manually, connection lost, or notification of disconnection + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ){(void) systemAddress; (void) rakNetGUID; (void) lostConnectionReason;} + + /// Called when we got a new connection + /// \param[in] systemAddress Address of the new connection + /// \param[in] rakNetGuid The guid of the specified system + /// \param[in] isIncoming If true, this is ID_NEW_INCOMING_CONNECTION, or the equivalent + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) {(void) systemAddress; (void) rakNetGUID; (void) isIncoming;} + + /// Called when a connection attempt fails + /// \param[in] packet Packet to be returned to the user + /// \param[in] failedConnectionReason Why the connection failed + virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) {(void) packet; (void) failedConnectionAttemptReason;} + + /// Queried when attached to RakPeer + /// Return true to call OnDirectSocketSend(), OnDirectSocketReceive(), OnReliabilityLayerNotification(), OnInternalPacket(), and OnAck() + /// If true, then you cannot call RakPeer::AttachPlugin() or RakPeer::DetachPlugin() for this plugin, while RakPeer is active + virtual bool UsesReliabilityLayer(void) const {return false;} + + /// Called on a send to the socket, per datagram, that does not go through the reliability layer + /// \pre To be called, UsesReliabilityLayer() must return true + /// \param[in] data The data being sent + /// \param[in] bitsUsed How many bits long \a data is + /// \param[in] remoteSystemAddress Which system this message is being sent to + virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) {(void) data; (void) bitsUsed; (void) remoteSystemAddress;} + + /// Called on a receive from the socket, per datagram, that does not go through the reliability layer + /// \pre To be called, UsesReliabilityLayer() must return true + /// \param[in] data The data being sent + /// \param[in] bitsUsed How many bits long \a data is + /// \param[in] remoteSystemAddress Which system this message is being sent to + virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) {(void) data; (void) bitsUsed; (void) remoteSystemAddress;} + + /// Called when the reliability layer rejects a send or receive + /// \pre To be called, UsesReliabilityLayer() must return true + /// \param[in] bitsUsed How many bits long \a data is + /// \param[in] remoteSystemAddress Which system this message is being sent to + virtual void OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError) {(void) errorMessage; (void) bitsUsed; (void) remoteSystemAddress; (void) isError;} + + /// Called on a send or receive of a message within the reliability layer + /// \pre To be called, UsesReliabilityLayer() must return true + /// \param[in] internalPacket The user message, along with all send data. + /// \param[in] frameNumber The number of frames sent or received so far for this player depending on \a isSend . Indicates the frame of this user message. + /// \param[in] remoteSystemAddress The player we sent or got this packet from + /// \param[in] time The current time as returned by RakNet::GetTimeMS() + /// \param[in] isSend Is this callback representing a send event or receive event? + virtual void OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, RakNet::TimeMS time, int isSend) {(void) internalPacket; (void) frameNumber; (void) remoteSystemAddress; (void) time; (void) isSend;} + + /// Called when we get an ack for a message we reliably sent + /// \pre To be called, UsesReliabilityLayer() must return true + /// \param[in] messageNumber The numerical identifier for which message this is + /// \param[in] remoteSystemAddress The player we sent or got this packet from + /// \param[in] time The current time as returned by RakNet::GetTimeMS() + virtual void OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, RakNet::TimeMS time) {(void) messageNumber; (void) remoteSystemAddress; (void) time;} + + /// System called RakPeerInterface::PushBackPacket + /// \param[in] data The data being sent + /// \param[in] bitsUsed How many bits long \a data is + /// \param[in] remoteSystemAddress The player we sent or got this packet from + virtual void OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) {(void) data; (void) bitsUsed; (void) remoteSystemAddress;} + + RakPeerInterface *GetRakPeerInterface(void) const {return rakPeerInterface;} + + RakNetGUID GetMyGUIDUnified(void) const; + + /// \internal + void SetRakPeerInterface( RakPeerInterface *ptr ); + +#if _RAKNET_SUPPORT_TCPInterface==1 + /// \internal + void SetTCPInterface( TCPInterface *ptr ); +#endif + +protected: + // Send through either rakPeerInterface or tcpInterface, whichever is available + void SendUnified( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); + void SendUnified( const char * data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); + bool SendListUnified( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); + + Packet *AllocatePacketUnified(unsigned dataSize); + void PushBackPacketUnified(Packet *packet, bool pushAtHead); + void DeallocPacketUnified(Packet *packet); + + // Filled automatically in when attached + RakPeerInterface *rakPeerInterface; +#if _RAKNET_SUPPORT_TCPInterface==1 + TCPInterface *tcpInterface; +#endif +}; + +} // namespace RakNet + +#endif + diff --git a/include/raknet/RPC4Plugin.hpp b/include/raknet/RPC4Plugin.hpp new file mode 100644 index 0000000..21a4511 --- /dev/null +++ b/include/raknet/RPC4Plugin.hpp @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Remote procedure call, supporting C functions only. No external dependencies required. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_RPC4Plugin==1 + +#ifndef __RPC_4_PLUGIN_H +#define __RPC_4_PLUGIN_H + +#include "PluginInterface2.hpp" +#include "PacketPriority.hpp" +#include "RakNetTypes.hpp" +#include "BitStream.hpp" +#include "RakString.hpp" +#include "NetworkIDObject.hpp" +#include "DS_Hash.hpp" +#include "DS_OrderedList.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +/// \defgroup RPC_PLUGIN_GROUP RPC +/// \brief Remote procedure calls, without external dependencies. +/// \details This should not be used at the same time as RPC3. This is a less functional version of RPC3, and is here for users that do not want the Boost dependency of RPC3. +/// \ingroup PLUGINS_GROUP + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; +class NetworkIDManager; + + /// \brief Error codes returned by a remote system as to why an RPC function call cannot execute + /// \details Error code follows packet ID ID_RPC_REMOTE_ERROR, that is packet->data[1]
+ /// Name of the function will be appended starting at packet->data[2] + /// \ingroup RPC_PLUGIN_GROUP + enum RPCErrorCodes + { + /// Named function was not registered with RegisterFunction(). Check your spelling. + RPC_ERROR_FUNCTION_NOT_REGISTERED, + }; + + /// \brief Instantiate this class globally if you want to register a function with RPC4 at the global space + class RAK_DLL_EXPORT RPC4GlobalRegistration + { + public: + /// \brief Queue a call to RPC4::RegisterFunction() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. + RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet )); + + /// \brief Queue a call to RPC4::RegisterSlot() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. + RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet ), int callPriority); + + /// \brief Queue a call to RPC4::RegisterBlockingFunction() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. + RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, RakNet::BitStream *returnData, Packet *packet )); + + /// \brief Queue a call to RPC4::RegisterLocalCallback() globally. Actual call occurs once RPC4 is attached to an instance of RakPeer or TCPInterface. + RPC4GlobalRegistration(const char* uniqueID, MessageID messageId); + }; + + /// \brief The RPC4 plugin is just an association between a C function pointer and a string. + /// \details It is for users that want to use RPC, but do not want to use boost. + /// You do not have the automatic serialization or other features of RPC3, and C++ member calls are not supported. + /// \note You cannot use RPC4 at the same time as RPC3Plugin + /// \ingroup RPC_PLUGIN_GROUP + class RAK_DLL_EXPORT RPC4 : public PluginInterface2 + { + public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(RPC4) + + // Constructor + RPC4(); + + // Destructor + virtual ~RPC4(); + + /// \deprecated Use RegisterSlot + /// \brief Register a function pointer to be callable from a remote system + /// \details The hash of the function name will be stored as an association with the function pointer + /// When a call is made to call this function from the \a Call() or CallLoopback() function, the function pointer will be invoked with the passed bitStream to Call() and the actual Packet that RakNet got. + /// \sa RegisterPacketCallback() + /// \param[in] uniqueID Identifier to be associated with \a functionPointer. If this identifier is already in use, the call will return false. + /// \param[in] functionPointer C function pointer to be called + /// \return True if the hash of uniqueID is not in use, false otherwise. + bool RegisterFunction(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet )); + + /// Register a slot, which is a function pointer to one or more implementations that supports this function signature + /// When a signal occurs, all slots with the same identifier are called. + /// \param[in] sharedIdentifier A string to identify the slot. Recommended to be the same as the name of the function. + /// \param[in] functionPtr Pointer to the function. For C, just pass the name of the function. For C++, use ARPC_REGISTER_CPP_FUNCTION + /// \param[in] callPriority Slots are called by order of the highest callPriority first. For slots with the same priority, they are called in the order they are registered + void RegisterSlot(const char *sharedIdentifier, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet ), int callPriority); + + /// \brief Same as \a RegisterFunction, but is called with CallBlocking() instead of Call() and returns a value to the caller + bool RegisterBlockingFunction(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, RakNet::BitStream *returnData, Packet *packet )); + + /// \deprecated Use RegisterSlot and invoke on self only when the packet you want arrives + /// When a RakNet Packet with the specified identifier is returned, execute CallLoopback() on a function previously registered with RegisterFunction() + /// For example, you could call "OnClosedConnection" whenever you get ID_DISCONNECTION_NOTIFICATION or ID_CONNECTION_LOST + /// \param[in] uniqueID Identifier passed to RegisterFunction() + /// \param[in] messageId What RakNet packet ID to call on, for example ID_DISCONNECTION_NOTIFICATION or ID_CONNECTION_LOST + void RegisterLocalCallback(const char* uniqueID, MessageID messageId); + + /// \brief Unregister a function pointer previously registered with RegisterFunction() + /// \param[in] Identifier originally passed to RegisterFunction() + /// \return True if the hash of uniqueID was in use, and hence removed. false otherwise. + bool UnregisterFunction(const char* uniqueID); + + /// \brief Same as UnregisterFunction, except for a blocking function + bool UnregisterBlockingFunction(const char* uniqueID); + + /// Remove the association created with RegisterPacketCallback() + /// \param[in] uniqueID Identifier passed as uniqueID to RegisterLocalCallback() + /// \param[in] messageId Identifier passed as messageId to RegisterLocalCallback() + /// \return True if the combination of uniqueID and messageId was in use, and hence removed + bool UnregisterLocalCallback(const char* uniqueID, MessageID messageId); + + /// Remove the association created with RegisterSlot() + /// \param[in] sharedIdentifier Identifier passed as sharedIdentifier to RegisterSlot() + bool UnregisterSlot(const char* sharedIdentifier); + + /// \deprecated Use RegisterSlot() and Signal() with your own RakNetGUID as the send target + /// Send to the attached instance of RakPeer. See RakPeerInterface::SendLoopback() + /// \param[in] Identifier originally passed to RegisterFunction() on the local system + /// \param[in] bitStream bitStream encoded data to send to the function callback + void CallLoopback( const char* uniqueID, RakNet::BitStream * bitStream ); + + /// \deprecated, use Signal() + /// Send to the specified remote instance of RakPeer. + /// \param[in] uniqueID Identifier originally passed to RegisterFunction() on the remote system(s) + /// \param[in] bitStream bitStream encoded data to send to the function callback + /// \param[in] priority See RakPeerInterface::Send() + /// \param[in] reliability See RakPeerInterface::Send() + /// \param[in] orderingChannel See RakPeerInterface::Send() + /// \param[in] systemIdentifier See RakPeerInterface::Send() + /// \param[in] broadcast See RakPeerInterface::Send() + void Call( const char* uniqueID, RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ); + + /// \brief Same as call, but don't return until the remote system replies. + /// Broadcasting parameter does not exist, this can only call one remote system + /// \note This function does not return until the remote system responds, disconnects, or was never connected to begin with + /// \param[in] Identifier originally passed to RegisterBlockingFunction() on the remote system(s) + /// \param[in] bitStream bitStream encoded data to send to the function callback + /// \param[in] priority See RakPeerInterface::Send() + /// \param[in] reliability See RakPeerInterface::Send() + /// \param[in] orderingChannel See RakPeerInterface::Send() + /// \param[in] systemIdentifier See RakPeerInterface::Send() + /// \param[out] returnData Written to by the function registered with RegisterBlockingFunction. + /// \return true if successfully called. False on disconnect, function not registered, or not connected to begin with + bool CallBlocking( const char* uniqueID, RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, RakNet::BitStream *returnData ); + + /// Calls zero or more functions identified by sharedIdentifier registered with RegisterSlot() + /// \param[in] sharedIdentifier parameter of the same name passed to RegisterSlot() on the remote system + /// \param[in] bitStream bitStream encoded data to send to the function callback + /// \param[in] priority See RakPeerInterface::Send() + /// \param[in] reliability See RakPeerInterface::Send() + /// \param[in] orderingChannel See RakPeerInterface::Send() + /// \param[in] systemIdentifier See RakPeerInterface::Send() + /// \param[in] broadcast See RakPeerInterface::Send() + /// \param[in] invokeLocal If true, also sends to self. + void Signal(const char *sharedIdentifier, RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool invokeLocal); + + /// If called while processing a slot, no further slots for the currently executing signal will be executed + void InterruptSignal(void); + + /// \internal + struct LocalCallback + { + MessageID messageId; + DataStructures::OrderedList functions; + }; + static int LocalCallbackComp(const MessageID &key, LocalCallback* const &data ); + + /// \internal + // Callable object, along with priority to call relative to other objects + struct LocalSlotObject + { + LocalSlotObject() {} + LocalSlotObject(unsigned int _registrationCount,int _callPriority, void ( *_functionPointer ) ( RakNet::BitStream *userData, Packet *packet )) + {registrationCount=_registrationCount;callPriority=_callPriority;functionPointer=_functionPointer;} + ~LocalSlotObject() {} + + // Used so slots are called in the order they are registered + unsigned int registrationCount; + int callPriority; + void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet ); + }; + + static int LocalSlotObjectComp( const LocalSlotObject &key, const LocalSlotObject &data ); + + /// \internal + struct LocalSlot + { + DataStructures::OrderedList slotObjects; + }; + DataStructures::Hash localSlots; + + protected: + + // -------------------------------------------------------------------------------------------- + // Packet handling functions + // -------------------------------------------------------------------------------------------- + virtual void OnAttach(void); + virtual PluginReceiveResult OnReceive(Packet *packet); + + DataStructures::Hash registeredNonblockingFunctions; + DataStructures::Hash registeredBlockingFunctions; + DataStructures::OrderedList localCallbacks; + + RakNet::BitStream blockingReturnValue; + bool gotBlockingReturnValue; + + DataStructures::HashIndex GetLocalSlotIndex(const char *sharedIdentifier); + + /// Used so slots are called in the order they are registered + unsigned int nextSlotRegistrationCount; + + bool interruptSignal; + + void InvokeSignal(DataStructures::HashIndex functionIndex, RakNet::BitStream *serializedParameters, Packet *packet); + }; + +} // End namespace + +#endif + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/Rackspace.hpp b/include/raknet/Rackspace.hpp new file mode 100644 index 0000000..54ba0cc --- /dev/null +++ b/include/raknet/Rackspace.hpp @@ -0,0 +1,413 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file Rackspace.h +/// \brief Helper to class to manage Rackspace servers +/// + + +#include "NativeFeatureIncludes.hpp" + +#if _RAKNET_SUPPORT_Rackspace==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#include "Export.hpp" +#include "DS_List.hpp" +#include "RakNetTypes.hpp" +#include "DS_Queue.hpp" +#include "RakString.hpp" + +#ifndef __RACKSPACE_H +#define __RACKSPACE_H + +namespace RakNet +{ + + class TCPInterface; + struct Packet; + + /// \brief Result codes for Rackspace commands + /// /sa Rackspace::EventTypeToString() + enum RackspaceEventType + { + RET_Success_200, + RET_Success_201, + RET_Success_202, + RET_Success_203, + RET_Success_204, + RET_Cloud_Servers_Fault_500, + RET_Service_Unavailable_503, + RET_Unauthorized_401, + RET_Bad_Request_400, + RET_Over_Limit_413, + RET_Bad_Media_Type_415, + RET_Item_Not_Found_404, + RET_Build_In_Progress_409, + RET_Resize_Not_Allowed_403, + RET_Connection_Closed_Without_Reponse, + RET_Unknown_Failure, + }; + + /// \internal + enum RackspaceOperationType + { + RO_CONNECT_AND_AUTHENTICATE, + RO_LIST_SERVERS, + RO_LIST_SERVERS_WITH_DETAILS, + RO_CREATE_SERVER, + RO_GET_SERVER_DETAILS, + RO_UPDATE_SERVER_NAME_OR_PASSWORD, + RO_DELETE_SERVER, + RO_LIST_SERVER_ADDRESSES, + RO_SHARE_SERVER_ADDRESS, + RO_DELETE_SERVER_ADDRESS, + RO_REBOOT_SERVER, + RO_REBUILD_SERVER, + RO_RESIZE_SERVER, + RO_CONFIRM_RESIZED_SERVER, + RO_REVERT_RESIZED_SERVER, + RO_LIST_FLAVORS, + RO_GET_FLAVOR_DETAILS, + RO_LIST_IMAGES, + RO_CREATE_IMAGE, + RO_GET_IMAGE_DETAILS, + RO_DELETE_IMAGE, + RO_LIST_SHARED_IP_GROUPS, + RO_LIST_SHARED_IP_GROUPS_WITH_DETAILS, + RO_CREATE_SHARED_IP_GROUP, + RO_GET_SHARED_IP_GROUP_DETAILS, + RO_DELETE_SHARED_IP_GROUP, + + RO_NONE, + }; + + /// \brief Callback interface to receive the results of operations + class RAK_DLL_EXPORT Rackspace2EventCallback + { + public: + Rackspace2EventCallback() {} + virtual ~Rackspace2EventCallback() {} + virtual void OnAuthenticationResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnListServersResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnListServersWithDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnCreateServerResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnGetServerDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnUpdateServerNameOrPassword(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnDeleteServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnListServerAddresses(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnShareServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnDeleteServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnRebootServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnRebuildServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnResizeServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnConfirmResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnRevertResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnListFlavorsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnGetFlavorDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnListImagesResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnCreateImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnGetImageDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnDeleteImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnListSharedIPGroups(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnListSharedIPGroupsWithDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnCreateSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnGetSharedIPGroupDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + virtual void OnDeleteSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo)=0; + + virtual void OnConnectionAttemptFailure(RackspaceOperationType operationType, const char *url)=0; + }; + + /// \brief Callback interface to receive the results of operations, with a default result + class RAK_DLL_EXPORT RackspaceEventCallback_Default : public Rackspace2EventCallback + { + public: + virtual void ExecuteDefault(const char *callbackName, RackspaceEventType eventType, const char *htmlAdditionalInfo) {(void) callbackName; (void) eventType; (void) htmlAdditionalInfo;} + + virtual void OnAuthenticationResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnAuthenticationResult", eventType, htmlAdditionalInfo);} + virtual void OnListServersResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListServersResult", eventType, htmlAdditionalInfo);} + virtual void OnListServersWithDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListServersWithDetailsResult", eventType, htmlAdditionalInfo);} + virtual void OnCreateServerResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnCreateServerResult", eventType, htmlAdditionalInfo);} + virtual void OnGetServerDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetServerDetails", eventType, htmlAdditionalInfo);} + virtual void OnUpdateServerNameOrPassword(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnUpdateServerNameOrPassword", eventType, htmlAdditionalInfo);} + virtual void OnDeleteServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteServer", eventType, htmlAdditionalInfo);} + virtual void OnListServerAddresses(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListServerAddresses", eventType, htmlAdditionalInfo);} + virtual void OnShareServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnShareServerAddress", eventType, htmlAdditionalInfo);} + virtual void OnDeleteServerAddress(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteServerAddress", eventType, htmlAdditionalInfo);} + virtual void OnRebootServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnRebootServer", eventType, htmlAdditionalInfo);} + virtual void OnRebuildServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnRebuildServer", eventType, htmlAdditionalInfo);} + virtual void OnResizeServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnResizeServer", eventType, htmlAdditionalInfo);} + virtual void OnConfirmResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnConfirmResizedServer", eventType, htmlAdditionalInfo);} + virtual void OnRevertResizedServer(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnRevertResizedServer", eventType, htmlAdditionalInfo);} + virtual void OnListFlavorsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListFlavorsResult", eventType, htmlAdditionalInfo);} + virtual void OnGetFlavorDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetFlavorDetailsResult", eventType, htmlAdditionalInfo);} + virtual void OnListImagesResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListImagesResult", eventType, htmlAdditionalInfo);} + virtual void OnCreateImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnCreateImageResult", eventType, htmlAdditionalInfo);} + virtual void OnGetImageDetailsResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetImageDetailsResult", eventType, htmlAdditionalInfo);} + virtual void OnDeleteImageResult(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteImageResult", eventType, htmlAdditionalInfo);} + virtual void OnListSharedIPGroups(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListSharedIPGroups", eventType, htmlAdditionalInfo);} + virtual void OnListSharedIPGroupsWithDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnListSharedIPGroupsWithDetails", eventType, htmlAdditionalInfo);} + virtual void OnCreateSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnCreateSharedIPGroup", eventType, htmlAdditionalInfo);} + virtual void OnGetSharedIPGroupDetails(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnGetSharedIPGroupDetails", eventType, htmlAdditionalInfo);} + virtual void OnDeleteSharedIPGroup(RackspaceEventType eventType, const char *htmlAdditionalInfo) {ExecuteDefault("OnDeleteSharedIPGroup", eventType, htmlAdditionalInfo);} + + virtual void OnConnectionAttemptFailure(RackspaceOperationType operationType, const char *url) {(void) operationType; (void) url;} + }; + + /// \brief Code that uses the TCPInterface class to communicate with the Rackspace API servers + /// \pre Compile RakNet with OPEN_SSL_CLIENT_SUPPORT set to 1 + /// \pre Packets returned from TCPInterface::OnReceive() must be passed to Rackspace::OnReceive() + /// \pre Packets returned from TCPInterface::HasLostConnection() must be passed to Rackspace::OnClosedConnection() + class RAK_DLL_EXPORT Rackspace + { + public: + Rackspace(); + ~Rackspace(); + + /// \brief Authenticate with Rackspace servers, required before executing any commands. + /// \details All requests to authenticate and operate against Cloud Servers are performed using SSL over HTTP (HTTPS) on TCP port 443. + /// Times out after 24 hours - if you get RET_Authenticate_Unauthorized in the RackspaceEventCallback callback, call again + /// \sa RackspaceEventCallback::OnAuthenticationResult() + /// \param[in] _tcpInterface An instance of TCPInterface, build with OPEN_SSL_CLIENT_SUPPORT 1 and already started + /// \param[in] _authenticationURL See http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf . US-based accounts authenticate through auth.api.rackspacecloud.com. UK-based accounts authenticate through lon.auth.api.rackspacecloud.com + /// \param[in] _rackspaceCloudUsername Username you registered with Rackspace on their website + /// \param[in] _apiAccessKey Obtain your API access key from the Rackspace Cloud Control Panel in the Your Account API Access section. + /// \return The address of the authentication server, or UNASSIGNED_SYSTEM_ADDRESS if the connection attempt failed + SystemAddress Authenticate(TCPInterface *_tcpInterface, const char *_authenticationURL, const char *_rackspaceCloudUsername, const char *_apiAccessKey); + + /// \brief Get a list of running servers + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnListServersResult() + void ListServers(void); + + /// \brief Get a list of running servers, with extended details on each server + /// \sa GetServerDetails() + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnListServersWithDetailsResult() + void ListServersWithDetails(void); + + /// \brief Create a server + /// \details Create a server with a given image (harddrive contents) and flavor (hardware configuration) + /// Get the available images with ListImages() + /// Get the available flavors with ListFlavors() + /// It is possible to configure the server in more detail. See the XML schema at http://docs.rackspacecloud.com/servers/api/v1.0 + /// You can execute such a custom command by calling AddOperation() manually. See the implementation of CreateServer for how to do so. + /// The server takes a while to build. Call GetServerDetails() to get the current build status. Server id to pass to GetServerDetails() is returned in the field + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnCreateServerResult() + /// \param[in] name Name of the server. Only alphanumeric characters, periods, and hyphens are valid. Server Name cannot start or end with a period or hyphen. + /// \param[in] imageId Which image (harddrive contents, including OS) to use + /// \param[in] flavorId Which flavor (hardware config) to use, primarily how much memory is available. + void CreateServer(RakNet::RakString name, RakNet::RakString imageId, RakNet::RakString flavorId); + + /// \brief Get details on a particular server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnGetServerDetailsResult() + /// \param[in] serverId Which server to get details on. You can call ListServers() to get the list of active servers. + void GetServerDetails(RakNet::RakString serverId); + + /// \brief Changes the name or password for a server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnUpdateServerNameOrPasswordResult() + /// \param[in] serverId Which server to get details on. You can call ListServers() to get the list of active servers. + /// \param[in] newName The new server name. Leave blank to leave unchanged. Only alphanumeric characters, periods, and hyphens are valid. Server Name cannot start or end with a period or hyphen. + /// \param[in] newPassword The new server password. Leave blank to leave unchanged. + void UpdateServerNameOrPassword(RakNet::RakString serverId, RakNet::RakString newName, RakNet::RakString newPassword); + + /// \brief Deletes a server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnDeleteServerResult() + /// \param[in] serverId Which server to get details on. You can call ListServers() to get the list of active servers. + void DeleteServer(RakNet::RakString serverId); + + /// \brief Lists the IP addresses available to a server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnListServerAddressesResult() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + void ListServerAddresses(RakNet::RakString serverId); + + /// \brief Shares an IP address with a server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnShareServerAddressResult() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + /// \param[in] ipAddress Which IP address. You can call ListServerAddresses() to get the list of addresses for the specified server + void ShareServerAddress(RakNet::RakString serverId, RakNet::RakString ipAddress); + + /// \brief Stops sharing an IP address with a server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnDeleteServerAddressResult() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + /// \param[in] ipAddress Which IP address. You can call ListServerAddresses() to get the list of addresses for the specified server + void DeleteServerAddress(RakNet::RakString serverId, RakNet::RakString ipAddress); + + /// \brief Reboots a server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnRebootServerResult() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + /// \param[in] rebootType Should be either "HARD" or "SOFT" + void RebootServer(RakNet::RakString serverId, RakNet::RakString rebootType); + + /// \brief Rebuilds a server with a different image (harddrive contents) + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnRebuildServerResult() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + /// \param[in] imageId Which image (harddrive contents, including OS) to use + void RebuildServer(RakNet::RakString serverId, RakNet::RakString imageId); + + /// \brief Changes the hardware configuration of a server. This does not take effect until you call ConfirmResizedServer() + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnResizeServerResult() + /// \sa RevertResizedServer() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + /// \param[in] flavorId Which flavor (hardware config) to use, primarily how much memory is available. + void ResizeServer(RakNet::RakString serverId, RakNet::RakString flavorId); + + /// \brief Confirm a resize for the specified server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnConfirmResizedServerResult() + /// \sa ResizeServer() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + void ConfirmResizedServer(RakNet::RakString serverId); + + /// \brief Reverts a resize for the specified server + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnRevertResizedServerResult() + /// \sa ResizeServer() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + void RevertResizedServer(RakNet::RakString serverId); + + /// \brief List all flavors (hardware configs, primarily memory) + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnListFlavorsResult() + void ListFlavors(void); + + /// \brief Get extended details about a specific flavor + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnGetFlavorDetailsResult() + /// \sa ListFlavors() + /// \param[in] flavorId Which flavor (hardware config) + void GetFlavorDetails(RakNet::RakString flavorId); + + /// \brief List all images (software configs, including operating systems), which includes images you create yourself + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnListImagesResult() + /// \sa CreateImage() + void ListImages(void); + + /// \brief Images a running server. This essentially copies the harddrive, and lets you start a server with the same harddrive contents later + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnCreateImageResult() + /// \sa ListImages() + /// \param[in] serverId Which server to operate on. You can call ListServers() to get the list of active servers. + /// \param[in] imageName What to call this image + void CreateImage(RakNet::RakString serverId, RakNet::RakString imageName); + + /// \brief Get extended details about a particular image + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnGetImageDetailsResult() + /// \sa ListImages() + /// \param[in] imageId Which image + void GetImageDetails(RakNet::RakString imageId); + + /// \brief Delete a custom image created with CreateImage() + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnDeleteImageResult() + /// \sa ListImages() + /// \param[in] imageId Which image + void DeleteImage(RakNet::RakString imageId); + + /// \brief List IP groups + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnListSharedIPGroupsResult() + void ListSharedIPGroups(void); + + /// \brief List IP groups with extended details + /// \sa http://docs.rackspacecloud.com/servers/api/v1.0/cs-devguide-20110112.pdf + /// \sa RackspaceEventCallback::OnListSharedIPGroupsWithDetailsResult() + void ListSharedIPGroupsWithDetails(void); + + // I don't know what this does + void CreateSharedIPGroup(RakNet::RakString name, RakNet::RakString optionalServerId); + // I don't know what this does + void GetSharedIPGroupDetails(RakNet::RakString groupId); + // I don't know what this does + void DeleteSharedIPGroup(RakNet::RakString groupId); + + /// \brief Adds a callback to the list of callbacks to be called when any of the above functions finish executing + /// The callbacks are called in the order they are added + void AddEventCallback(Rackspace2EventCallback *callback); + /// \brief Removes a callback from the list of callbacks to be called when any of the above functions finish executing + /// The callbacks are called in the order they are added + void RemoveEventCallback(Rackspace2EventCallback *callback); + /// \brief Removes all callbacks + void ClearEventCallbacks(void); + + /// Call this anytime TCPInterface returns a packet + void OnReceive(Packet *packet); + + /// Call this when TCPInterface returns something other than UNASSIGNED_SYSTEM_ADDRESS from HasLostConnection() + void OnClosedConnection(SystemAddress systemAddress); + + /// String representation of each RackspaceEventType + static const char * EventTypeToString(RackspaceEventType eventType); + + /// \brief Mostly for internal use, but you can use it to execute an operation with more complex xml if desired + /// See the Rackspace.cpp on how to use it + void AddOperation(RackspaceOperationType type, RakNet::RakString httpCommand, RakNet::RakString operation, RakNet::RakString xml); + protected: + + DataStructures::List eventCallbacks; + + struct RackspaceOperation + { + RackspaceOperationType type; + // RakNet::RakString stringInfo; + SystemAddress connectionAddress; + bool isPendingAuthentication; + RakNet::RakString incomingStream; + RakNet::RakString httpCommand; + RakNet::RakString operation; + RakNet::RakString xml; + }; + + TCPInterface *tcpInterface; + + // RackspaceOperationType currentOperation; + // DataStructures::Queue nextOperationQueue; + + DataStructures::List operations; + bool HasOperationOfType(RackspaceOperationType t); + unsigned int GetOperationOfTypeIndex(RackspaceOperationType t); + + RakNet::RakString serverManagementURL; + RakNet::RakString serverManagementDomain; + RakNet::RakString serverManagementPath; + RakNet::RakString storageURL; + RakNet::RakString storageDomain; + RakNet::RakString storagePath; + RakNet::RakString cdnManagementURL; + RakNet::RakString cdnManagementDomain; + RakNet::RakString cdnManagementPath; + + RakNet::RakString storageToken; + RakNet::RakString authToken; + RakNet::RakString rackspaceCloudUsername; + RakNet::RakString apiAccessKey; + + bool ExecuteOperation(RackspaceOperation &ro); + void ReadLine(const char *data, const char *stringStart, RakNet::RakString &output); + bool ConnectToServerManagementDomain(RackspaceOperation &ro); + + + }; + +} // namespace RakNet + +#endif // __RACKSPACE_API_H + +#endif // _RAKNET_SUPPORT_Rackspace diff --git a/include/raknet/RakAlloca.hpp b/include/raknet/RakAlloca.hpp new file mode 100644 index 0000000..62a199e --- /dev/null +++ b/include/raknet/RakAlloca.hpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#if defined(__FreeBSD__) +#include + + + + +#elif defined ( __APPLE__ ) || defined ( __APPLE_CC__ ) +#include +#include +#elif defined(_WIN32) +#include +#else +#include +// Alloca needed on Ubuntu apparently +#include +#endif diff --git a/include/raknet/RakAssert.hpp b/include/raknet/RakAssert.hpp new file mode 100644 index 0000000..b50fea5 --- /dev/null +++ b/include/raknet/RakAssert.hpp @@ -0,0 +1,12 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include +#include "RakNetDefines.hpp" diff --git a/include/raknet/RakMemoryOverride.hpp b/include/raknet/RakMemoryOverride.hpp new file mode 100644 index 0000000..ca1ce18 --- /dev/null +++ b/include/raknet/RakMemoryOverride.hpp @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief If _USE_RAK_MEMORY_OVERRIDE is defined, memory allocations go through rakMalloc, rakRealloc, and rakFree +/// + + + +#ifndef __RAK_MEMORY_H +#define __RAK_MEMORY_H + +#include "Export.hpp" +#include "RakNetDefines.hpp" +#include + + + + + + + +#include "RakAlloca.hpp" + +// #if _USE_RAK_MEMORY_OVERRIDE==1 +// #if defined(new) +// #pragma push_macro("new") +// #undef new +// #define RMO_NEW_UNDEF +// #endif +// #endif + + +// These pointers are statically and globally defined in RakMemoryOverride.cpp +// Change them to point to your own allocators if you want. +// Use the functions for a DLL, or just reassign the variable if using source +extern RAK_DLL_EXPORT void * (*rakMalloc) (size_t size); +extern RAK_DLL_EXPORT void * (*rakRealloc) (void *p, size_t size); +extern RAK_DLL_EXPORT void (*rakFree) (void *p); +extern RAK_DLL_EXPORT void * (*rakMalloc_Ex) (size_t size, const char *file, unsigned int line); +extern RAK_DLL_EXPORT void * (*rakRealloc_Ex) (void *p, size_t size, const char *file, unsigned int line); +extern RAK_DLL_EXPORT void (*rakFree_Ex) (void *p, const char *file, unsigned int line); +extern RAK_DLL_EXPORT void (*notifyOutOfMemory) (const char *file, const long line); +extern RAK_DLL_EXPORT void * (*dlMallocMMap) (size_t size); +extern RAK_DLL_EXPORT void * (*dlMallocDirectMMap) (size_t size); +extern RAK_DLL_EXPORT int (*dlMallocMUnmap) (void* ptr, size_t size); + +// Change to a user defined allocation function +void RAK_DLL_EXPORT SetMalloc( void* (*userFunction)(size_t size) ); +void RAK_DLL_EXPORT SetRealloc( void* (*userFunction)(void *p, size_t size) ); +void RAK_DLL_EXPORT SetFree( void (*userFunction)(void *p) ); +void RAK_DLL_EXPORT SetMalloc_Ex( void* (*userFunction)(size_t size, const char *file, unsigned int line) ); +void RAK_DLL_EXPORT SetRealloc_Ex( void* (*userFunction)(void *p, size_t size, const char *file, unsigned int line) ); +void RAK_DLL_EXPORT SetFree_Ex( void (*userFunction)(void *p, const char *file, unsigned int line) ); +// Change to a user defined out of memory function +void RAK_DLL_EXPORT SetNotifyOutOfMemory( void (*userFunction)(const char *file, const long line) ); +void RAK_DLL_EXPORT SetDLMallocMMap( void* (*userFunction)(size_t size) ); +void RAK_DLL_EXPORT SetDLMallocDirectMMap( void* (*userFunction)(size_t size) ); +void RAK_DLL_EXPORT SetDLMallocMUnmap( int (*userFunction)(void* ptr, size_t size) ); + +extern RAK_DLL_EXPORT void * (*GetMalloc()) (size_t size); +extern RAK_DLL_EXPORT void * (*GetRealloc()) (void *p, size_t size); +extern RAK_DLL_EXPORT void (*GetFree()) (void *p); +extern RAK_DLL_EXPORT void * (*GetMalloc_Ex()) (size_t size, const char *file, unsigned int line); +extern RAK_DLL_EXPORT void * (*GetRealloc_Ex()) (void *p, size_t size, const char *file, unsigned int line); +extern RAK_DLL_EXPORT void (*GetFree_Ex()) (void *p, const char *file, unsigned int line); +extern RAK_DLL_EXPORT void *(*GetDLMallocMMap())(size_t size); +extern RAK_DLL_EXPORT void *(*GetDLMallocDirectMMap())(size_t size); +extern RAK_DLL_EXPORT int (*GetDLMallocMUnmap())(void* ptr, size_t size); + +namespace RakNet +{ + + template + RAK_DLL_EXPORT Type* OP_NEW(const char *file, unsigned int line) + { +#if _USE_RAK_MEMORY_OVERRIDE==1 + char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); + Type *t = new (buffer) Type; + return t; +#else + (void) file; + (void) line; + return new Type; +#endif + } + + template + RAK_DLL_EXPORT Type* OP_NEW_1(const char *file, unsigned int line, const P1 &p1) + { +#if _USE_RAK_MEMORY_OVERRIDE==1 + char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); + Type *t = new (buffer) Type(p1); + return t; +#else + (void) file; + (void) line; + return new Type(p1); +#endif + } + + template + RAK_DLL_EXPORT Type* OP_NEW_2(const char *file, unsigned int line, const P1 &p1, const P2 &p2) + { +#if _USE_RAK_MEMORY_OVERRIDE==1 + char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); + Type *t = new (buffer) Type(p1, p2); + return t; +#else + (void) file; + (void) line; + return new Type(p1, p2); +#endif + } + + template + RAK_DLL_EXPORT Type* OP_NEW_3(const char *file, unsigned int line, const P1 &p1, const P2 &p2, const P3 &p3) + { +#if _USE_RAK_MEMORY_OVERRIDE==1 + char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); + Type *t = new (buffer) Type(p1, p2, p3); + return t; +#else + (void) file; + (void) line; + return new Type(p1, p2, p3); +#endif + } + + template + RAK_DLL_EXPORT Type* OP_NEW_4(const char *file, unsigned int line, const P1 &p1, const P2 &p2, const P3 &p3, const P4 &p4) + { +#if _USE_RAK_MEMORY_OVERRIDE==1 + char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line); + Type *t = new (buffer) Type(p1, p2, p3, p4); + return t; +#else + (void) file; + (void) line; + return new Type(p1, p2, p3, p4); +#endif + } + + + template + RAK_DLL_EXPORT Type* OP_NEW_ARRAY(const int count, const char *file, unsigned int line) + { + if (count==0) + return 0; + +#if _USE_RAK_MEMORY_OVERRIDE==1 +// Type *t; + char *buffer = (char *) (GetMalloc_Ex())(sizeof(int)+sizeof(Type)*count, file, line); + ((int*)buffer)[0]=count; + for (int i=0; i + RAK_DLL_EXPORT void OP_DELETE(Type *buff, const char *file, unsigned int line) + { +#if _USE_RAK_MEMORY_OVERRIDE==1 + if (buff==0) return; + buff->~Type(); + (GetFree_Ex())((char*)buff, file, line ); +#else + (void) file; + (void) line; + delete buff; +#endif + + } + + template + RAK_DLL_EXPORT void OP_DELETE_ARRAY(Type *buff, const char *file, unsigned int line) + { +#if _USE_RAK_MEMORY_OVERRIDE==1 + if (buff==0) + return; + + int count = ((int*)((char*)buff-sizeof(int)))[0]; + Type *t; + for (int i=0; i~Type(); + } + (GetFree_Ex())((char*)buff-sizeof(int), file, line ); +#else + (void) file; + (void) line; + delete [] buff; +#endif + + } + + void RAK_DLL_EXPORT * _RakMalloc (size_t size); + void RAK_DLL_EXPORT * _RakRealloc (void *p, size_t size); + void RAK_DLL_EXPORT _RakFree (void *p); + void RAK_DLL_EXPORT * _RakMalloc_Ex (size_t size, const char *file, unsigned int line); + void RAK_DLL_EXPORT * _RakRealloc_Ex (void *p, size_t size, const char *file, unsigned int line); + void RAK_DLL_EXPORT _RakFree_Ex (void *p, const char *file, unsigned int line); + void RAK_DLL_EXPORT * _DLMallocMMap (size_t size); + void RAK_DLL_EXPORT * _DLMallocDirectMMap (size_t size); + int RAK_DLL_EXPORT _DLMallocMUnmap (void *p, size_t size); + +} + +// Call to make RakNet allocate a large block of memory, and do all subsequent allocations in that memory block +// Initial and reallocations will be done through whatever function is pointed to by yourMMapFunction, and yourDirectMMapFunction (default is malloc) +// Allocations will be freed through whatever function is pointed to by yourMUnmapFunction (default free) +void UseRaknetFixedHeap(size_t initialCapacity, + void * (*yourMMapFunction) (size_t size) = RakNet::_DLMallocMMap, + void * (*yourDirectMMapFunction) (size_t size) = RakNet::_DLMallocDirectMMap, + int (*yourMUnmapFunction) (void *p, size_t size) = RakNet::_DLMallocMUnmap); + +// Free memory allocated from UseRaknetFixedHeap +void FreeRakNetFixedHeap(void); + +// #if _USE_RAK_MEMORY_OVERRIDE==1 +// #if defined(RMO_NEW_UNDEF) +// #pragma pop_macro("new") +// #undef RMO_NEW_UNDEF +// #endif +// #endif + +#endif diff --git a/include/raknet/RakNetCommandParser.hpp b/include/raknet/RakNetCommandParser.hpp new file mode 100644 index 0000000..c95aa22 --- /dev/null +++ b/include/raknet/RakNetCommandParser.hpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains RakNetCommandParser , used to send commands to an instance of RakPeer +/// + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_RakNetCommandParser==1 + +#ifndef __RAKNET_COMMAND_PARSER +#define __RAKNET_COMMAND_PARSER + +#include "CommandParserInterface.hpp" +#include "Export.hpp" + +namespace RakNet +{ +class RakPeerInterface; + +/// \brief This allows a console client to call most of the functions in RakPeer +class RAK_DLL_EXPORT RakNetCommandParser : public CommandParserInterface +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(RakNetCommandParser) + + RakNetCommandParser(); + ~RakNetCommandParser(); + + /// Given \a command with parameters \a parameterList , do whatever processing you wish. + /// \param[in] command The command to process + /// \param[in] numParameters How many parameters were passed along with the command + /// \param[in] parameterList The list of parameters. parameterList[0] is the first parameter and so on. + /// \param[in] transport The transport interface we can use to write to + /// \param[in] systemAddress The player that sent this command. + /// \param[in] originalString The string that was actually sent over the network, in case you want to do your own parsing + bool OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString); + + /// You are responsible for overriding this function and returning a static string, which will identifier your parser. + /// This should return a static string + /// \return The name that you return. + const char *GetName(void) const; + + /// A callback for when you are expected to send a brief description of your parser to \a systemAddress + /// \param[in] transport The transport interface we can use to write to + /// \param[in] systemAddress The player that requested help. + void SendHelp(TransportInterface *transport, const SystemAddress &systemAddress); + + /// Records the instance of RakPeer to perform the desired commands on + /// \param[in] rakPeer The RakPeer instance, or a derived class (e.g. RakPeer or RakPeer) + void SetRakPeerInterface(RakNet::RakPeerInterface *rakPeer); +protected: + + /// Which instance of RakPeer we are working on. Set from SetRakPeerInterface() + RakPeerInterface *peer; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/RakNetDefines.hpp b/include/raknet/RakNetDefines.hpp new file mode 100644 index 0000000..e45aa01 --- /dev/null +++ b/include/raknet/RakNetDefines.hpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAKNET_DEFINES_H +#define __RAKNET_DEFINES_H + +// If you want to change these defines, put them in RakNetDefinesOverrides so your changes are not lost when updating RakNet +// The user should not edit this file +#include "RakNetDefinesOverrides.hpp" + +/// Define __GET_TIME_64BIT to have RakNet::TimeMS use a 64, rather than 32 bit value. A 32 bit value will overflow after about 5 weeks. +/// However, this doubles the bandwidth use for sending times, so don't do it unless you have a reason to. +/// Comment out if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 +/// This must be the same on all systems, or they won't connect +#ifndef __GET_TIME_64BIT +#define __GET_TIME_64BIT 1 +#endif + +// Define _FILE_AND_LINE_ to "",0 if you want to strip out file and line info for memory tracking from the EXE +#ifndef _FILE_AND_LINE_ +#define _FILE_AND_LINE_ __FILE__,__LINE__ +#endif + +/// Define __BITSTREAM_NATIVE_END to NOT support endian swapping in the BitStream class. This is faster and is what you should use +/// unless you actually plan to have different endianness systems connect to each other +/// Enabled by default. +// #define __BITSTREAM_NATIVE_END + +/// Maximum (stack) size to use with _alloca before using new and delete instead. +#ifndef MAX_ALLOCA_STACK_ALLOCATION +#define MAX_ALLOCA_STACK_ALLOCATION 1048576 +#endif + +// Use WaitForSingleObject instead of sleep. +// Defining it plays nicer with other systems, and uses less CPU, but gives worse RakNet performance +// Undefining it uses more CPU time, but is more responsive and faster. +#ifndef _WIN32_WCE +#define USE_WAIT_FOR_MULTIPLE_EVENTS +#endif + +/// Uncomment to use RakMemoryOverride for custom memory tracking +/// See RakMemoryOverride.h. +#ifndef _USE_RAK_MEMORY_OVERRIDE +#define _USE_RAK_MEMORY_OVERRIDE 0 +#endif + +/// If defined, OpenSSL is enabled for the class TCPInterface +/// This is necessary to use the SendEmail class with Google POP servers +/// Note that OpenSSL carries its own license restrictions that you should be aware of. If you don't agree, don't enable this define +/// This also requires that you enable header search paths to DependentExtensions\openssl-1.0.0d +// #define OPEN_SSL_CLIENT_SUPPORT +#ifndef OPEN_SSL_CLIENT_SUPPORT +#define OPEN_SSL_CLIENT_SUPPORT 0 +#endif + +/// Threshold at which to do a malloc / free rather than pushing data onto a fixed stack for the bitstream class +/// Arbitrary size, just picking something likely to be larger than most packets +#ifndef BITSTREAM_STACK_ALLOCATION_SIZE +#define BITSTREAM_STACK_ALLOCATION_SIZE 256 +#endif + +// Redefine if you want to disable or change the target for debug RAKNET_DEBUG_PRINTF +#ifndef RAKNET_DEBUG_PRINTF +#define RAKNET_DEBUG_PRINTF printf +#endif + +// Maximum number of local IP addresses supported +#ifndef MAXIMUM_NUMBER_OF_INTERNAL_IDS +#define MAXIMUM_NUMBER_OF_INTERNAL_IDS 10 +#endif + +#ifndef RakAssert + + + +#if defined(__native_client__) +#define RakAssert(x) +#else +#if defined(_DEBUG) +#define RakAssert(x) assert(x); +#else +#define RakAssert(x) +#endif +#endif +#endif + +/// This controls the amount of memory used per connection. +/// This many datagrams are tracked by datagramNumber. If more than this many datagrams are sent, then an ack for an older datagram would be ignored +/// This results in an unnecessary resend in that case +#ifndef DATAGRAM_MESSAGE_ID_ARRAY_LENGTH +#define DATAGRAM_MESSAGE_ID_ARRAY_LENGTH 512 +#endif + +/// This is the maximum number of reliable user messages that can be on the wire at a time +/// If this is too low, then high ping connections with a large throughput will be underutilized +/// This will be evident because RakNetStatistics::messagesInSend buffer will increase over time, yet at the same time the outgoing bandwidth per second is less than your connection supports +#ifndef RESEND_BUFFER_ARRAY_LENGTH +#define RESEND_BUFFER_ARRAY_LENGTH 512 +#define RESEND_BUFFER_ARRAY_MASK 511 +#endif + +/// Uncomment if you want to link in the DLMalloc library to use with RakMemoryOverride +// #define _LINK_DL_MALLOC + +#ifndef GET_TIME_SPIKE_LIMIT +/// Workaround for http://support.microsoft.com/kb/274323 +/// If two calls between RakNet::GetTime() happen farther apart than this time in microseconds, this delta will be returned instead +/// Note: This will cause ID_TIMESTAMP to be temporarily inaccurate if you set a breakpoint that pauses the UpdateNetworkLoop() thread in RakPeer +/// Define in RakNetDefinesOverrides.h to enable (non-zero) or disable (0) +#define GET_TIME_SPIKE_LIMIT 0 +#endif + +// Use sliding window congestion control instead of ping based congestion control +#ifndef USE_SLIDING_WINDOW_CONGESTION_CONTROL +#define USE_SLIDING_WINDOW_CONGESTION_CONTROL 1 +#endif + +// When a large message is arriving, preallocate the memory for the entire block +// This results in large messages not taking up time to reassembly with memcpy, but is vulnerable to attackers causing the host to run out of memory +#ifndef PREALLOCATE_LARGE_MESSAGES +#define PREALLOCATE_LARGE_MESSAGES 0 +#endif + +#ifndef RAKNET_SUPPORT_IPV6 +#define RAKNET_SUPPORT_IPV6 0 +#endif + + + + + + + + + + + +#ifndef RAKSTRING_TYPE +#if defined(_UNICODE) +#define RAKSTRING_TYPE RakWString +#define RAKSTRING_TYPE_IS_UNICODE 1 +#else +#define RAKSTRING_TYPE RakString +#define RAKSTRING_TYPE_IS_UNICODE 0 +#endif +#endif + +#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS +#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS 48 +#endif + +#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH +#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH 48 +#endif + +#ifndef XBOX_BYPASS_SECURITY +#define XBOX_BYPASS_SECURITY 1 +#endif + +// Controls how many allocations occur at once for the memory pool of incoming datagrams waiting to be transferred between the recvfrom thread and the main update thread +// Has large effect on memory usage, per instance of RakPeer. Approximately MAXIMUM_MTU_SIZE*BUFFERED_PACKETS_PAGE_SIZE bytes, once after calling RakPeer::Startup() +#ifndef BUFFERED_PACKETS_PAGE_SIZE +#define BUFFERED_PACKETS_PAGE_SIZE 8 +#endif + +// Controls how many allocations occur at once for the memory pool of incoming or outgoing datagrams. +// Has small effect on memory usage per connection. Uses about 256 bytes*INTERNAL_PACKET_PAGE_SIZE per connection +#ifndef INTERNAL_PACKET_PAGE_SIZE +#define INTERNAL_PACKET_PAGE_SIZE 8 +#endif + +// If defined to 1, the user is responsible for calling RakPeer::RunUpdateCycle and RakPeer::RunRecvfrom +#ifndef RAKPEER_USER_THREADED +#define RAKPEER_USER_THREADED 0 +#endif + +#ifndef USE_ALLOCA +#define USE_ALLOCA 1 +#endif + + + + + + +//#define USE_THREADED_SEND + +#endif // __RAKNET_DEFINES_H diff --git a/include/raknet/RakNetDefinesOverrides.hpp b/include/raknet/RakNetDefinesOverrides.hpp new file mode 100644 index 0000000..00ad529 --- /dev/null +++ b/include/raknet/RakNetDefinesOverrides.hpp @@ -0,0 +1,12 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +// USER EDITABLE FILE + diff --git a/include/raknet/RakNetSmartPtr.hpp b/include/raknet/RakNetSmartPtr.hpp new file mode 100644 index 0000000..a4b123d --- /dev/null +++ b/include/raknet/RakNetSmartPtr.hpp @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAKNET_SMART_PTR_H +#define __RAKNET_SMART_PTR_H + +// From http://www.codeproject.com/KB/cpp/SmartPointers.aspx +// with bugs fixed + +#include "RakMemoryOverride.hpp" +#include "Export.hpp" + +//static int allocCount=0; +//static int deallocCount=0; + +namespace RakNet +{ + +class RAK_DLL_EXPORT ReferenceCounter +{ +private: + int refCount; + +public: + ReferenceCounter() {refCount=0;} + ~ReferenceCounter() {} + void AddRef() {refCount++;} + int Release() {return --refCount;} + int GetRefCount(void) const {return refCount;} +}; + +template < typename T > class RAK_DLL_EXPORT RakNetSmartPtr +{ +private: + T* ptr; // pointer + ReferenceCounter* reference; // Reference refCount + +public: + RakNetSmartPtr() : ptr(0), reference(0) + { + // Do not allocate by default, wasteful if we just have a list of preallocated and unassigend smart pointers + } + + RakNetSmartPtr(T* pValue) : ptr(pValue) + { + reference = RakNet::OP_NEW(_FILE_AND_LINE_); + reference->AddRef(); + +// allocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + + RakNetSmartPtr(const RakNetSmartPtr& sp) : ptr(sp.ptr), reference(sp.reference) + { + if (reference) + reference->AddRef(); + } + + ~RakNetSmartPtr() + { + if(reference && reference->Release() == 0) + { + RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); + RakNet::OP_DELETE(reference, _FILE_AND_LINE_); + +// deallocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + } + + bool IsNull(void) const + { + return ptr==0; + } + + void SetNull(void) + { + if(reference && reference->Release() == 0) + { + RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); + RakNet::OP_DELETE(reference, _FILE_AND_LINE_); + +// deallocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + ptr=0; + reference=0; + } + + bool IsUnique(void) const + { + return reference->GetRefCount()==1; + } + + // Allow you to change the values of the internal contents of the pointer, without changing what is pointed to by other instances of the smart pointer + void Clone(bool copyContents) + { + if (IsUnique()==false) + { + reference->Release(); + + reference = RakNet::OP_NEW(_FILE_AND_LINE_); + reference->AddRef(); + T* oldPtr=ptr; + ptr=RakNet::OP_NEW(_FILE_AND_LINE_); + if (copyContents) + *ptr=*oldPtr; + } + } + + int GetRefCount(void) const + { + return reference->GetRefCount(); + } + + T& operator* () + { + return *ptr; + } + + const T& operator* () const + { + return *ptr; + } + + T* operator-> () + { + return ptr; + } + + const T* operator-> () const + { + return ptr; + } + + bool operator == (const RakNetSmartPtr& sp) + { + return ptr == sp.ptr; + } + bool operator<( const RakNetSmartPtr &right ) {return ptr < right.ptr;} + bool operator>( const RakNetSmartPtr &right ) {return ptr > right.ptr;} + + bool operator != (const RakNetSmartPtr& sp) + { + return ptr != sp.ptr; + } + + RakNetSmartPtr& operator = (const RakNetSmartPtr& sp) + { + // Assignment operator + + if (this != &sp) // Avoid self assignment + { + if(reference && reference->Release() == 0) + { + RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); + RakNet::OP_DELETE(reference, _FILE_AND_LINE_); + +// deallocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + + ptr = sp.ptr; + reference = sp.reference; + if (reference) + reference->AddRef(); + } + return *this; + } + + +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/RakNetSocket.hpp b/include/raknet/RakNetSocket.hpp new file mode 100644 index 0000000..a98cb01 --- /dev/null +++ b/include/raknet/RakNetSocket.hpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/* +#ifndef __RAKNET_SOCKET_H +#define __RAKNET_SOCKET_H + +#include "RakNetTypes.hpp" +#include "RakNetDefines.hpp" +#include "Export.hpp" +#include "SocketIncludes.hpp" +#include "RakAssert.hpp" +#include "SocketDefines.hpp" +#include "MTUSize.hpp" + +namespace RakNet +{ + +struct RAK_DLL_EXPORT RakNetSocket +{ +public: + RakNetSocket(); + ~RakNetSocket(); + +// void Accept( +// struct sockaddr *addr, +// int *addrlen); + + inline int Connect( + const struct sockaddr *name, + int namelen) {return connect__(s,name,namelen);} + + static RakNetSocket* Create +#ifdef __native_client__ + (_PP_Instance_ _chromeInstance); +#else + (int af, + int type, + int protocol); +#endif + + int Bind( + const struct sockaddr *addr, + int namelen); + + inline int GetSockName( + struct sockaddr *name, + socklen_t * namelen) {return getsockname__(s,name,namelen);} + + inline int GetSockOpt ( + int level, + int optname, + char * optval, + socklen_t *optlen) {return getsockopt__(s,level,optname,optval,optlen);} + + + int IOCTLSocket( + long cmd, + unsigned long *argp); + + int Listen ( + int backlog); + + inline int Recv( + char * buf, + int len, + int flags) {return recv__(s,buf,len,flags);} + + inline int RecvFrom( + char * buf, + int len, + int flags, + struct sockaddr * from, + socklen_t * fromlen) {return recvfrom__(s,buf,len,flags,from,fromlen);} + +// inline int Select( +// int nfds, +// fd_set *readfds, +// fd_set *writefds, +// fd_set *exceptfds, +// struct timeval *timeout) {return select__(nfds,readfds,writefds,exceptfds,timeout);} + + inline int Send( + const char * buf, + int len, + int flags) {return send__(s,buf,len,flags);} + + inline int SendTo( + const char * buf, + int len, + int flags, + const struct sockaddr *to, + int tolen) {return sendto__(s,buf,len,flags,to,tolen);} + + #ifdef _WIN32 + #elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) || defined(SN_TARGET_PSP2) + #else + inline int Fcntl(int cmd, int arg) {return fcntl(s,cmd,arg);} + #endif + + +#if defined(_WIN32) && !defined(WINDOWS_STORE_RT) + inline int _WSASendTo( + LPWSABUF lpBuffers, + DWORD dwBufferCount, + LPDWORD lpNumberOfBytesSent, + DWORD dwFlags, + const struct sockaddr FAR * lpTo, + int iTolen, + LPWSAOVERLAPPED lpOverlapped, + LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine + ) + { return WSASendTo(s,lpBuffers,dwBufferCount,lpNumberOfBytesSent,dwFlags,lpTo,iTolen,lpOverlapped,lpCompletionRoutine);} + +#endif + + int SetSockOpt( + int level, + int optname, + const char * optval, + int optlen); + + int Shutdown( + int how); + + + inline void SetRemotePortRakNetWasStartedOn(unsigned short i) {remotePortRakNetWasStartedOn_PS3_PSP2=i;} + inline void SetUserConnectionSocketIndex(unsigned int i) {userConnectionSocketIndex=i;} + inline void SetBoundAddress(SystemAddress i) {boundAddress=i;} + inline void SetSocketFamily(unsigned short i) {socketFamily=i;} + inline void SetBlockingSocket(bool i) {blockingSocket=i;} + inline void SetExtraSocketOptions(unsigned int i) {extraSocketOptions=i;} + inline void SetChromeInstance(_PP_Instance_ i) {chromeInstance=i;} + inline void SetBoundAddressToLoopback(unsigned char ipVersion) {boundAddress.SetToLoopback(ipVersion);} + + inline SystemAddress GetBoundAddress(void) const {return boundAddress;} + inline unsigned short GetRemotePortRakNetWasStartedOn(void) const {return remotePortRakNetWasStartedOn_PS3_PSP2;} + inline bool GetBlockingSocket(void) {return blockingSocket;} + inline unsigned int GetExtraSocketOptions(void) const {return extraSocketOptions;} + inline unsigned short GetSocketFamily(void) const {return socketFamily;} + inline _PP_Instance_ GetChromeInstance(void) const {return chromeInstance;} + inline unsigned int GetUserConnectionSocketIndex(void) const { + RakAssert(userConnectionSocketIndex!=(unsigned int)-1); + return userConnectionSocketIndex;} + + +#ifdef __native_client__ + // Flag indicating if a SendTo is currently in progress + bool sendInProgress; + + // Data for next queued packet to send, if nextSendSize > 0 + char nextSendBuffer[MAXIMUM_MTU_SIZE]; + + // Size of next queued packet to send, or 0 if no queued packet + int nextSendSize; + + // Destination address of queued packet + PP_NetAddress_Private nextSendAddr; +#endif + + __UDPSOCKET__ s; + +protected: + +#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) + void* recvEvent; +#endif + + #if defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) || defined(SN_TARGET_PSP2) + /// PS3: Set for the PS3, when using signaling. + /// PS3: Connect with the port returned by signaling. Set this to whatever port RakNet was actually started on + /// PSP2: Set non-zero to use SCE_NET_SOCK_DGRAM_P2P. This should be done for ad-hoc or with + #endif + + unsigned short remotePortRakNetWasStartedOn_PS3_PSP2; + unsigned int userConnectionSocketIndex; + SystemAddress boundAddress; + unsigned short socketFamily; + bool blockingSocket; + unsigned int extraSocketOptions; + _PP_Instance_ chromeInstance; +}; + +} // namespace RakNet + +#endif +*/ diff --git a/include/raknet/RakNetSocket2.hpp b/include/raknet/RakNetSocket2.hpp new file mode 100644 index 0000000..983ff41 --- /dev/null +++ b/include/raknet/RakNetSocket2.hpp @@ -0,0 +1,453 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAKNET_SOCKET_2_H +#define __RAKNET_SOCKET_2_H + +#include "RakNetTypes.hpp" +#include "MTUSize.hpp" +#include "LocklessTypes.hpp" +#include "RakThread.hpp" +#include "DS_ThreadsafeAllocatingQueue.hpp" +#include "Export.hpp" + +// For CFSocket +// https://developer.apple.com/library/mac/#documentation/CoreFOundation/Reference/CFSocketRef/Reference/reference.html +// Reason: http://sourceforge.net/p/open-dis/discussion/683284/thread/0929d6a0 +#if defined(__APPLE__) +#import +#include +#include +#endif + +// #define TEST_NATIVE_CLIENT_ON_WINDOWS + +#ifdef TEST_NATIVE_CLIENT_ON_WINDOWS +#define __native_client__ +typedef int PP_Resource; +#endif + +namespace RakNet +{ + +class RakNetSocket2; +struct RNS2_BerkleyBindParameters; +struct RNS2_SendParameters; +typedef int RNS2Socket; + +enum RNS2BindResult +{ + BR_SUCCESS, + BR_REQUIRES_RAKNET_SUPPORT_IPV6_DEFINE, + BR_FAILED_TO_BIND_SOCKET, + BR_FAILED_SEND_TEST, +}; + +typedef int RNS2SendResult; + +enum RNS2Type +{ + RNS2T_WINDOWS_STORE_8, + RNS2T_PS3, + RNS2T_PS4, + RNS2T_CHROME, + RNS2T_VITA, + RNS2T_XBOX_360, + RNS2T_XBOX_720, + RNS2T_WINDOWS, + RNS2T_LINUX +}; + +struct RNS2_SendParameters +{ + RNS2_SendParameters() {ttl=0;} + char *data; + int length; + SystemAddress systemAddress; + int ttl; +}; + +struct RNS2RecvStruct +{ + + + + char data[MAXIMUM_MTU_SIZE]; + + int bytesRead; + SystemAddress systemAddress; + RakNet::TimeUS timeRead; + RakNetSocket2 *socket; +}; + +class RakNetSocket2Allocator +{ +public: + static RakNetSocket2* AllocRNS2(void); + static void DeallocRNS2(RakNetSocket2 *s); +}; + +class RAK_DLL_EXPORT RNS2EventHandler +{ +public: + RNS2EventHandler() {} + virtual ~RNS2EventHandler() {} + + // bufferedPackets.Push(recvFromStruct); + // quitAndDataEvents.SetEvent(); + virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct)=0; + virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line)=0; + virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line)=0; + + // recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); + // DataStructures::ThreadsafeAllocatingQueue bufferedPackets; +}; + +class RakNetSocket2 +{ +public: + RakNetSocket2(); + virtual ~RakNetSocket2(); + + // In order for the handler to trigger, some platforms must call PollRecvFrom, some platforms this create an internal thread. + void SetRecvEventHandler(RNS2EventHandler *_eventHandler); + virtual RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line )=0; + RNS2Type GetSocketType(void) const; + void SetSocketType(RNS2Type t); + bool IsBerkleySocket(void) const; + SystemAddress GetBoundAddress(void) const; + unsigned int GetUserConnectionSocketIndex(void) const; + void SetUserConnectionSocketIndex(unsigned int i); + RNS2EventHandler * GetEventHandler(void) const; + + // ----------- STATICS ------------ + static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); + static void DomainNameToIP( const char *domainName, char ip[65] ); + +protected: + RNS2EventHandler *eventHandler; + RNS2Type socketType; + SystemAddress boundAddress; + unsigned int userConnectionSocketIndex; +}; + +#if defined(WINDOWS_STORE_RT) + +ref class ListenerContext; + +// #include +//#include +#include "DS_List.hpp" +class RNS2_WindowsStore8 : public RakNetSocket2 +{ +public: + RNS2_WindowsStore8(); + ~RNS2_WindowsStore8(); + + virtual RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); + RNS2BindResult Bind( Platform::String ^localServiceName ); + // ----------- STATICS ------------ + static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); + static void DomainNameToIP( const char *domainName, char ip[65] ); + + static int WinRTInet_Addr(const char * cp); + + static int WinRTSetSockOpt(Windows::Networking::Sockets::DatagramSocket ^s, + int level, + int optname, + const char * optval, + socklen_t optlen); + + static int WinRTIOCTLSocket(Windows::Networking::Sockets::DatagramSocket ^s, + long cmd, + unsigned long *argp); + + static int WinRTGetSockName(Windows::Networking::Sockets::DatagramSocket ^s, + struct sockaddr *name, + socklen_t* namelen); + + static RNS2_WindowsStore8 *GetRNS2FromDatagramSocket(Windows::Networking::Sockets::DatagramSocket^ s); +protected: + static DataStructures::List rns2List; + static SimpleMutex rns2ListMutex; + + Windows::Networking::Sockets::DatagramSocket^ listener; + // Platform::Collections::Map ^outputStreamMap; + // Platform::Collections::Map^ m; + //std::map<> m; + ListenerContext^ listenerContext; +}; +#elif defined(__native_client__) +struct NativeClientBindParameters +{ + _PP_Instance_ nativeClientInstance; + unsigned short port; + const char *forceHostAddress; + bool is_ipv6; + RNS2EventHandler *eventHandler; +}; +class RNS2_NativeClient; +struct RNS2_SendParameters_NativeClient : public RNS2_SendParameters +{ + RNS2_NativeClient *socket2; +}; +class RNS2_NativeClient : public RakNetSocket2 +{ +public: + RNS2_NativeClient(); + virtual ~RNS2_NativeClient(); + RNS2BindResult Bind( NativeClientBindParameters *bindParameters, const char *file, unsigned int line ); + RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); + const NativeClientBindParameters *GetBindings(void) const; + + // ----------- STATICS ------------ + static bool IsPortInUse(unsigned short port, const char *hostAddress, unsigned short addressFamily, int type ); + static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); + + // RNS2_NativeClient doesn't automatically call recvfrom in a thread - user must call Update() from the main thread + // This causes buffered sends to send, until send is asynch pending + // It causes recvfrom events to trigger the callback, and push a message to the event handler + // + // Example: + // + // DataStructures::List< RakNet::RakNetSocket2* > sockets; + // rakPeerInterface->GetSockets(sockets); + // for (unsigned int i=0; i < sockets.Size(); i++) + // { + // ((RNS2_NativeClient*)sockets[i])->Update(); + // } + + void Update(void); +protected: + void ProcessBufferedSend(void); + static void SendImmediate(RNS2_SendParameters_NativeClient *sp); + static void DeallocSP(RNS2_SendParameters_NativeClient *sp); + static RNS2_SendParameters_NativeClient* CloneSP(RNS2_SendParameters *sp, RNS2_NativeClient *socket2, const char *file, unsigned int line); + static void onRecvFrom(void* pData, int32_t dataSize); + void IssueReceiveCall(void); + static void onSocketBound(void* pData, int32_t dataSize); + static void onSendTo(void* pData, int32_t dataSize); + void BufferSend( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); + PP_Resource rns2Socket; + NativeClientBindParameters binding; + bool sendInProgress; + SimpleMutex sendInProgressMutex; + + enum BindState + { + BS_UNBOUND, + BS_IN_PROGRESS, + BS_BOUND, + BS_FAILED + } bindState; + DataStructures::Queue bufferedSends; + SimpleMutex bufferedSendsMutex; +}; +#else // defined(WINDOWS_STORE_RT) + +struct RNS2_BerkleyBindParameters +{ + // Input parameters + unsigned short port; + char *hostAddress; + unsigned short addressFamily; // AF_INET or AF_INET6 + int type; // SOCK_DGRAM + int protocol; // 0 + bool nonBlockingSocket; + int setBroadcast; + int setIPHdrIncl; + int doNotFragment; + int pollingThreadPriority; + RNS2EventHandler *eventHandler; + unsigned short remotePortRakNetWasStartedOn_PS3_PS4_PSP2; +}; + +// Every platform except Windows Store 8 can use the Berkley sockets interface +class IRNS2_Berkley : public RakNetSocket2 +{ +public: + // ----------- STATICS ------------ + // For addressFamily, use AF_INET + // For type, use SOCK_DGRAM + static bool IsPortInUse(unsigned short port, const char *hostAddress, unsigned short addressFamily, int type ); + + // ----------- MEMBERS ------------ + virtual RNS2BindResult Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line )=0; +}; +// Every platform that uses Berkley sockets, except native client, can compile some common functions +class RNS2_Berkley : public IRNS2_Berkley +{ +public: + RNS2_Berkley(); + virtual ~RNS2_Berkley(); + int CreateRecvPollingThread(int threadPriority); + void SignalStopRecvPollingThread(void); + void BlockOnStopRecvPollingThread(void); + const RNS2_BerkleyBindParameters *GetBindings(void) const; + RNS2Socket GetSocket(void) const; + void SetDoNotFragment( int opt ); + +protected: + // Used by other classes + RNS2BindResult BindShared( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); + RNS2BindResult BindSharedIPV4( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); + RNS2BindResult BindSharedIPV4And6( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); + + static void GetSystemAddressIPV4 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ); + static void GetSystemAddressIPV4And6 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ); + + // Internal + void SetNonBlockingSocket(unsigned long nonblocking); + void SetSocketOptions(void); + void SetBroadcastSocket(int broadcast); + void SetIPHdrIncl(int ipHdrIncl); + void RecvFromBlocking(RNS2RecvStruct *recvFromStruct); + void RecvFromBlockingIPV4(RNS2RecvStruct *recvFromStruct); + void RecvFromBlockingIPV4And6(RNS2RecvStruct *recvFromStruct); + + RNS2Socket rns2Socket; + RNS2_BerkleyBindParameters binding; + + unsigned RecvFromLoopInt(void); + RakNet::LocklessUint32_t isRecvFromLoopThreadActive; + volatile bool endThreads; + // Constructor not called! + +#if defined(__APPLE__) + // http://sourceforge.net/p/open-dis/discussion/683284/thread/0929d6a0 + CFSocketRef _cfSocket; +#endif + + static RAK_THREAD_DECLARATION(RecvFromLoop); +}; + + + + + + + + + + + + + + + + + +#if defined(_WIN32) || defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) +class RNS2_Windows_Linux_360 +{ +public: +protected: + static RNS2SendResult Send_Windows_Linux_360NoVDP( RNS2Socket rns2Socket, RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); +}; +#endif + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#if defined(_WIN32) + +class RAK_DLL_EXPORT SocketLayerOverride +{ +public: + SocketLayerOverride() {} + virtual ~SocketLayerOverride() {} + + /// Called when SendTo would otherwise occur. + virtual int RakNetSendTo( const char *data, int length, const SystemAddress &systemAddress )=0; + + /// Called when RecvFrom would otherwise occur. Return number of bytes read. Write data into dataOut + // Return -1 to use RakNet's normal recvfrom, 0 to abort RakNet's normal recvfrom, and positive to return data + virtual int RakNetRecvFrom( char dataOut[ MAXIMUM_MTU_SIZE ], SystemAddress *senderOut, bool calledFromMainThread )=0; +}; + +class RNS2_Windows : public RNS2_Berkley, public RNS2_Windows_Linux_360 +{ +public: + RNS2_Windows(); + virtual ~RNS2_Windows(); + RNS2BindResult Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); + RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); + void SetSocketLayerOverride(SocketLayerOverride *_slo); + SocketLayerOverride* GetSocketLayerOverride(void); + // ----------- STATICS ------------ + static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); +protected: + static void GetMyIPIPV4( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); + static void GetMyIPIPV4And6( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); + SocketLayerOverride *slo; +}; + +#else +class RNS2_Linux : public RNS2_Berkley, public RNS2_Windows_Linux_360 +{ +public: + RNS2BindResult Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ); + RNS2SendResult Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ); + + // ----------- STATICS ------------ + static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); +protected: + static void GetMyIPIPV4( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); + static void GetMyIPIPV4And6( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); +}; + +#endif // Linux + +#endif // #elif !defined(WINDOWS_STORE_RT) + +} // namespace RakNet + +#endif // __RAKNET_SOCKET_2_H diff --git a/include/raknet/RakNetStatistics.hpp b/include/raknet/RakNetStatistics.hpp new file mode 100644 index 0000000..c2b400b --- /dev/null +++ b/include/raknet/RakNetStatistics.hpp @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief A structure that holds all statistical data returned by RakNet. +/// + + + +#ifndef __RAK_NET_STATISTICS_H +#define __RAK_NET_STATISTICS_H + +#include "PacketPriority.hpp" +#include "Export.hpp" +#include "RakNetTypes.hpp" + +namespace RakNet +{ + +enum RNSPerSecondMetrics +{ + /// How many bytes per pushed via a call to RakPeerInterface::Send() + USER_MESSAGE_BYTES_PUSHED, + + /// How many user message bytes were sent via a call to RakPeerInterface::Send(). This is less than or equal to USER_MESSAGE_BYTES_PUSHED. + /// A message would be pushed, but not yet sent, due to congestion control + USER_MESSAGE_BYTES_SENT, + + /// How many user message bytes were resent. A message is resent if it is marked as reliable, and either the message didn't arrive or the message ack didn't arrive. + USER_MESSAGE_BYTES_RESENT, + + /// How many user message bytes were received, and returned to the user successfully. + USER_MESSAGE_BYTES_RECEIVED_PROCESSED, + + /// How many user message bytes were received, but ignored due to data format errors. This will usually be 0. + USER_MESSAGE_BYTES_RECEIVED_IGNORED, + + /// How many actual bytes were sent, including per-message and per-datagram overhead, and reliable message acks + ACTUAL_BYTES_SENT, + + /// How many actual bytes were received, including overead and acks. + ACTUAL_BYTES_RECEIVED, + + /// \internal + RNS_PER_SECOND_METRICS_COUNT +}; + +/// \brief Network Statisics Usage +/// +/// Store Statistics information related to network usage +struct RAK_DLL_EXPORT RakNetStatistics +{ + /// For each type in RNSPerSecondMetrics, what is the value over the last 1 second? + uint64_t valueOverLastSecond[RNS_PER_SECOND_METRICS_COUNT]; + + /// For each type in RNSPerSecondMetrics, what is the total value over the lifetime of the connection? + uint64_t runningTotal[RNS_PER_SECOND_METRICS_COUNT]; + + /// When did the connection start? + /// \sa RakNet::GetTimeUS() + RakNet::TimeUS connectionStartTime; + + /// Is our current send rate throttled by congestion control? + /// This value should be true if you send more data per second than your bandwidth capacity + bool isLimitedByCongestionControl; + + /// If \a isLimitedByCongestionControl is true, what is the limit, in bytes per second? + uint64_t BPSLimitByCongestionControl; + + /// Is our current send rate throttled by a call to RakPeer::SetPerConnectionOutgoingBandwidthLimit()? + bool isLimitedByOutgoingBandwidthLimit; + + /// If \a isLimitedByOutgoingBandwidthLimit is true, what is the limit, in bytes per second? + uint64_t BPSLimitByOutgoingBandwidthLimit; + + /// For each priority level, how many messages are waiting to be sent out? + unsigned int messageInSendBuffer[NUMBER_OF_PRIORITIES]; + + /// For each priority level, how many bytes are waiting to be sent out? + double bytesInSendBuffer[NUMBER_OF_PRIORITIES]; + + /// How many messages are waiting in the resend buffer? This includes messages waiting for an ack, so should normally be a small value + /// If the value is rising over time, you are exceeding the bandwidth capacity. See BPSLimitByCongestionControl + unsigned int messagesInResendBuffer; + + /// How many bytes are waiting in the resend buffer. See also messagesInResendBuffer + uint64_t bytesInResendBuffer; + + /// Over the last second, what was our packetloss? This number will range from 0.0 (for none) to 1.0 (for 100%) + float packetlossLastSecond; + + /// What is the average total packetloss over the lifetime of the connection? + float packetlossTotal; + + RakNetStatistics& operator +=(const RakNetStatistics& other) + { + unsigned i; + for (i=0; i < NUMBER_OF_PRIORITIES; i++) + { + messageInSendBuffer[i]+=other.messageInSendBuffer[i]; + bytesInSendBuffer[i]+=other.bytesInSendBuffer[i]; + } + + for (i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) + { + valueOverLastSecond[i]+=other.valueOverLastSecond[i]; + runningTotal[i]+=other.runningTotal[i]; + } + + return *this; + } +}; + +/// Verbosity level currently supports 0 (low), 1 (medium), 2 (high) +/// \param[in] s The Statistical information to format out +/// \param[in] buffer The buffer containing a formated report +/// \param[in] verbosityLevel +/// 0 low +/// 1 medium +/// 2 high +/// 3 debugging congestion control +void RAK_DLL_EXPORT StatisticsToString( RakNetStatistics *s, char *buffer, int verbosityLevel ); + +} // namespace RakNet + +#endif diff --git a/include/raknet/RakNetTime.hpp b/include/raknet/RakNetTime.hpp new file mode 100644 index 0000000..df5aca7 --- /dev/null +++ b/include/raknet/RakNetTime.hpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAKNET_TIME_H +#define __RAKNET_TIME_H + +#include "NativeTypes.hpp" +#include "RakNetDefines.hpp" + +namespace RakNet { + +// Define __GET_TIME_64BIT if you want to use large types for GetTime (takes more bandwidth when you transmit time though!) +// You would want to do this if your system is going to run long enough to overflow the millisecond counter (over a month) +#if __GET_TIME_64BIT==1 +typedef uint64_t Time; +typedef uint32_t TimeMS; +typedef uint64_t TimeUS; +#else +typedef uint32_t Time; +typedef uint32_t TimeMS; +typedef uint64_t TimeUS; +#endif + +} // namespace RakNet + +#endif diff --git a/include/raknet/RakNetTransport2.hpp b/include/raknet/RakNetTransport2.hpp new file mode 100644 index 0000000..0f1f541 --- /dev/null +++ b/include/raknet/RakNetTransport2.hpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains RakNetTransportCommandParser and RakNetTransport used to provide a secure console connection. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TelnetTransport==1 + +#ifndef __RAKNET_TRANSPORT_2 +#define __RAKNET_TRANSPORT_2 + +#include "TransportInterface.hpp" +#include "DS_Queue.hpp" +#include "CommandParserInterface.hpp" +#include "PluginInterface2.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class BitStream; +class RakPeerInterface; +class RakNetTransport; + +/// \defgroup RAKNET_TRANSPORT_GROUP RakNetTransport +/// \brief UDP based transport implementation for the ConsoleServer +/// \details +/// \ingroup PLUGINS_GROUP + +/// \brief Use RakNetTransport if you need a secure connection between the client and the console server. +/// \details RakNetTransport automatically initializes security for the system. Use the project CommandConsoleClient to connect +/// To the ConsoleServer if you use RakNetTransport +/// \ingroup RAKNET_TRANSPORT_GROUP +class RAK_DLL_EXPORT RakNetTransport2 : public TransportInterface, public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(RakNetTransport2) + + RakNetTransport2(); + virtual ~RakNetTransport2(); + + /// Start the transport provider on the indicated port. + /// \param[in] port The port to start the transport provider on + /// \param[in] serverMode If true, you should allow incoming connections (I don't actually use this anywhere) + /// \return Return true on success, false on failure. + bool Start(unsigned short port, bool serverMode); + + /// Stop the transport provider. You can clear memory and shutdown threads here. + void Stop(void); + + /// Send a null-terminated string to \a systemAddress + /// If your transport method requires particular formatting of the outgoing data (e.g. you don't just send strings) you can do it here + /// and parse it out in Receive(). + /// \param[in] systemAddress The player to send the string to + /// \param[in] data format specifier - same as RAKNET_DEBUG_PRINTF + /// \param[in] ... format specification arguments - same as RAKNET_DEBUG_PRINTF + void Send( SystemAddress systemAddress, const char *data, ... ); + + /// Disconnect \a systemAddress . The binary address and port defines the SystemAddress structure. + /// \param[in] systemAddress The player/address to disconnect + void CloseConnection( SystemAddress systemAddress ); + + /// Return a string. The string should be allocated and written to Packet::data . + /// The byte length should be written to Packet::length . The player/address should be written to Packet::systemAddress + /// If your transport protocol adds special formatting to the data stream you should parse it out before returning it in the packet + /// and thus only return a string in Packet::data + /// \return The packet structure containing the result of Receive, or 0 if no data is available + Packet* Receive( void ); + + /// Deallocate the Packet structure returned by Receive + /// \param[in] The packet to deallocate + void DeallocatePacket( Packet *packet ); + + /// If a new system connects to you, you should queue that event and return the systemAddress/address of that player in this function. + /// \return The SystemAddress/address of the system + SystemAddress HasNewIncomingConnection(void); + + /// If a system loses the connection, you should queue that event and return the systemAddress/address of that player in this function. + /// \return The SystemAddress/address of the system + SystemAddress HasLostConnection(void); + + virtual CommandParserInterface* GetCommandParser(void) {return 0;} + + /// \internal + virtual PluginReceiveResult OnReceive(Packet *packet); + /// \internal + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + /// \internal + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); +protected: + DataStructures::Queue newConnections, lostConnections; + DataStructures::Queue packetQueue; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/RakNetTypes.hpp b/include/raknet/RakNetTypes.hpp new file mode 100644 index 0000000..7db2ce3 --- /dev/null +++ b/include/raknet/RakNetTypes.hpp @@ -0,0 +1,507 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Types used by RakNet, most of which involve user code. +/// + + +#ifndef __NETWORK_TYPES_H +#define __NETWORK_TYPES_H + + + + + +#include "RakNetDefines.hpp" +#include "NativeTypes.hpp" +#include "RakNetTime.hpp" +#include "Export.hpp" +#include "WindowsIncludes.hpp" +#include "XBox360Includes.hpp" +#include "SocketIncludes.hpp" + + + + + +namespace RakNet { +/// Forward declarations +class RakPeerInterface; +class BitStream; +struct Packet; + +enum StartupResult +{ + RAKNET_STARTED, + RAKNET_ALREADY_STARTED, + INVALID_SOCKET_DESCRIPTORS, + INVALID_MAX_CONNECTIONS, + SOCKET_FAMILY_NOT_SUPPORTED, + SOCKET_PORT_ALREADY_IN_USE, + SOCKET_FAILED_TO_BIND, + SOCKET_FAILED_TEST_SEND, + PORT_CANNOT_BE_ZERO, + FAILED_TO_CREATE_NETWORK_THREAD, + COULD_NOT_GENERATE_GUID, + STARTUP_OTHER_FAILURE +}; + + +enum ConnectionAttemptResult +{ + CONNECTION_ATTEMPT_STARTED, + INVALID_PARAMETER, + CANNOT_RESOLVE_DOMAIN_NAME, + ALREADY_CONNECTED_TO_ENDPOINT, + CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS, + SECURITY_INITIALIZATION_FAILED +}; + +/// Returned from RakPeerInterface::GetConnectionState() +enum ConnectionState +{ + /// Connect() was called, but the process hasn't started yet + IS_PENDING, + /// Processing the connection attempt + IS_CONNECTING, + /// Is connected and able to communicate + IS_CONNECTED, + /// Was connected, but will disconnect as soon as the remaining messages are delivered + IS_DISCONNECTING, + /// A connection attempt failed and will be aborted + IS_SILENTLY_DISCONNECTING, + /// No longer connected + IS_DISCONNECTED, + /// Was never connected, or else was disconnected long enough ago that the entry has been discarded + IS_NOT_CONNECTED +}; + +/// Given a number of bits, return how many bytes are needed to represent that. +#define BITS_TO_BYTES(x) (((x)+7)>>3) +#define BYTES_TO_BITS(x) ((x)<<3) + +/// \sa NetworkIDObject.h +typedef unsigned char UniqueIDType; +typedef unsigned short SystemIndex; +typedef unsigned char RPCIndex; +const int MAX_RPC_MAP_SIZE=((RPCIndex)-1)-1; +const int UNDEFINED_RPC_INDEX=((RPCIndex)-1); + +/// First byte of a network message +typedef unsigned char MessageID; + +typedef uint32_t BitSize_t; + +#if defined(_MSC_VER) && _MSC_VER > 0 +#define PRINTF_64_BIT_MODIFIER "I64" +#else +#define PRINTF_64_BIT_MODIFIER "ll" +#endif + +/// Used with the PublicKey structure +enum PublicKeyMode +{ + /// The connection is insecure. You can also just pass 0 for the pointer to PublicKey in RakPeerInterface::Connect() + PKM_INSECURE_CONNECTION, + + /// Accept whatever public key the server gives us. This is vulnerable to man in the middle, but does not require + /// distribution of the public key in advance of connecting. + PKM_ACCEPT_ANY_PUBLIC_KEY, + + /// Use a known remote server public key. PublicKey::remoteServerPublicKey must be non-zero. + /// This is the recommended mode for secure connections. + PKM_USE_KNOWN_PUBLIC_KEY, + + /// Use a known remote server public key AND provide a public key for the connecting client. + /// PublicKey::remoteServerPublicKey, myPublicKey and myPrivateKey must be all be non-zero. + /// The server must cooperate for this mode to work. + /// I recommend not using this mode except for server-to-server communication as it significantly increases the CPU requirements during connections for both sides. + /// Furthermore, when it is used, a connection password should be used as well to avoid DoS attacks. + PKM_USE_TWO_WAY_AUTHENTICATION +}; + +/// Passed to RakPeerInterface::Connect() +struct RAK_DLL_EXPORT PublicKey +{ + /// How to interpret the public key, see above + PublicKeyMode publicKeyMode; + + /// Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES. See the Encryption sample. + char *remoteServerPublicKey; + + /// (Optional) Pointer to a public key of length cat::EasyHandshake::PUBLIC_KEY_BYTES + char *myPublicKey; + + /// (Optional) Pointer to a private key of length cat::EasyHandshake::PRIVATE_KEY_BYTES + char *myPrivateKey; +}; + +/// Describes the local socket to use for RakPeer::Startup +struct RAK_DLL_EXPORT SocketDescriptor +{ + SocketDescriptor(); + SocketDescriptor(unsigned short _port, const char *_hostAddress); + + /// The local port to bind to. Pass 0 to have the OS autoassign a port. + unsigned short port; + + /// The local network card address to bind to, such as "127.0.0.1". Pass an empty string to use INADDR_ANY. + char hostAddress[32]; + + /// IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. + /// IPV6 is the newer internet protocol. Instead of addresses such as natpunch.jenkinssoftware.com, you may have an address such as fe80::7c:31f7:fec4:27de%14. + /// Encoding takes 16 bytes instead of 4, so IPV6 is less efficient for bandwidth. + /// On the positive side, NAT Punchthrough is not needed and should not be used with IPV6 because there are enough addresses that routers do not need to create address mappings. + /// RakPeer::Startup() will fail if this IP version is not supported. + /// \pre RAKNET_SUPPORT_IPV6 must be set to 1 in RakNetDefines.h for AF_INET6 + short socketFamily; + + + + + + + + + + unsigned short remotePortRakNetWasStartedOn_PS3_PSP2; + + // Required for Google chrome + _PP_Instance_ chromeInstance; + + // Set to true to use a blocking socket (default, do not change unless you have a reason to) + bool blockingSocket; + + /// XBOX only: set IPPROTO_VDP if you want to use VDP. If enabled, this socket does not support broadcast to 255.255.255.255 + unsigned int extraSocketOptions; +}; + +extern bool NonNumericHostString( const char *host ); + +/// \brief Network address for a system +/// \details Corresponds to a network address
+/// This is not necessarily a unique identifier. For example, if a system has both LAN and internet connections, the system may be identified by either one, depending on who is communicating
+/// Therefore, you should not transmit the SystemAddress over the network and expect it to identify a system, or use it to connect to that system, except in the case where that system is not behind a NAT (such as with a dedciated server) +/// Use RakNetGUID for a unique per-instance of RakPeer to identify systems +struct RAK_DLL_EXPORT SystemAddress +{ + /// Constructors + SystemAddress(); + SystemAddress(const char *str); + SystemAddress(const char *str, unsigned short port); + + + + + + + + + + + /// SystemAddress, with RAKNET_SUPPORT_IPV6 defined, holds both an sockaddr_in6 and a sockaddr_in + union// In6OrIn4 + { +#if RAKNET_SUPPORT_IPV6==1 + struct sockaddr_storage sa_stor; + sockaddr_in6 addr6; +#endif + + sockaddr_in addr4; + } address; + + /// This is not used internally, but holds a copy of the port held in the address union, so for debugging it's easier to check what port is being held + unsigned short debugPort; + + /// \internal Return the size to write to a bitStream + static int size(void); + + /// Hash the system address + static unsigned long ToInteger( const SystemAddress &sa ); + + /// Return the IP version, either IPV4 or IPV6 + /// \return Either 4 or 6 + unsigned char GetIPVersion(void) const; + + /// \internal Returns either IPPROTO_IP or IPPROTO_IPV6 + /// \sa GetIPVersion + unsigned int GetIPPROTO(void) const; + + /// Call SetToLoopback(), with whatever IP version is currently held. Defaults to IPV4 + void SetToLoopback(void); + + /// Call SetToLoopback() with a specific IP version + /// \param[in] ipVersion Either 4 for IPV4 or 6 for IPV6 + void SetToLoopback(unsigned char ipVersion); + + /// \return If was set to 127.0.0.1 or ::1 + bool IsLoopback(void) const; + + // Return the systemAddress as a string in the format | + // Returns a static string + // NOT THREADSAFE + // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f + const char *ToString(bool writePort=true, char portDelineator='|') const; + + // Return the systemAddress as a string in the format | + // dest must be large enough to hold the output + // portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f + // THREADSAFE + void ToString(bool writePort, char *dest, char portDelineator='|') const; + + /// Set the system address from a printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490" + /// You can write the port as well, using the portDelineator, for example "192.0.2.1|1234" + /// \param[in] str A printable IP string, for example "192.0.2.1" or "2001:db8:63b3:1::3490". Pass 0 for \a str to set to UNASSIGNED_SYSTEM_ADDRESS + /// \param[in] portDelineator if \a str contains a port, delineate the port with this character. portDelineator should not be '.', ':', '%', '-', '/', a number, or a-f + /// \param[in] ipVersion Only used if str is a pre-defined address in the wrong format, such as 127.0.0.1 but you want ip version 6, so you can pass 6 here to do the conversion + /// \note The current port is unchanged if a port is not specified in \a str + /// \return True on success, false on ipVersion does not match type of passed string + bool FromString(const char *str, char portDelineator='|', int ipVersion=0); + + /// Same as FromString(), but you explicitly set a port at the same time + bool FromStringExplicitPort(const char *str, unsigned short port, int ipVersion=0); + + /// Copy the port from another SystemAddress structure + void CopyPort( const SystemAddress& right ); + + /// Returns if two system addresses have the same IP (port is not checked) + bool EqualsExcludingPort( const SystemAddress& right ) const; + + /// Returns the port in host order (this is what you normally use) + unsigned short GetPort(void) const; + + /// \internal Returns the port in network order + unsigned short GetPortNetworkOrder(void) const; + + /// Sets the port. The port value should be in host order (this is what you normally use) + /// Renamed from SetPort because of winspool.h http://edn.embarcadero.com/article/21494 + void SetPortHostOrder(unsigned short s); + + /// \internal Sets the port. The port value should already be in network order. + void SetPortNetworkOrder(unsigned short s); + + /// Old version, for crap platforms that don't support newer socket functions + bool SetBinaryAddress(const char *str, char portDelineator=':'); + /// Old version, for crap platforms that don't support newer socket functions + void ToString_Old(bool writePort, char *dest, char portDelineator=':') const; + + /// \internal sockaddr_in6 requires extra data beyond just the IP and port. Copy that extra data from an existing SystemAddress that already has it + void FixForIPVersion(const SystemAddress &boundAddressToSocket); + + bool IsLANAddress(void); + + SystemAddress& operator = ( const SystemAddress& input ); + bool operator==( const SystemAddress& right ) const; + bool operator!=( const SystemAddress& right ) const; + bool operator > ( const SystemAddress& right ) const; + bool operator < ( const SystemAddress& right ) const; + + /// \internal Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this. + SystemIndex systemIndex; + + private: + +#if RAKNET_SUPPORT_IPV6==1 + void ToString_New(bool writePort, char *dest, char portDelineator) const; +#endif +}; + +/// Uniquely identifies an instance of RakPeer. Use RakPeer::GetGuidFromSystemAddress() and RakPeer::GetSystemAddressFromGuid() to go between SystemAddress and RakNetGUID +/// Use RakPeer::GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) to get your own GUID +struct RAK_DLL_EXPORT RakNetGUID +{ + RakNetGUID(); + explicit RakNetGUID(uint64_t _g) {g=_g; systemIndex=(SystemIndex)-1;} +// uint32_t g[6]; + uint64_t g; + + // Return the GUID as a string + // Returns a static string + // NOT THREADSAFE + const char *ToString(void) const; + + // Return the GUID as a string + // dest must be large enough to hold the output + // THREADSAFE + void ToString(char *dest) const; + + bool FromString(const char *source); + + static unsigned long ToUint32( const RakNetGUID &g ); + + RakNetGUID& operator = ( const RakNetGUID& input ) + { + g=input.g; + systemIndex=input.systemIndex; + return *this; + } + + // Used internally for fast lookup. Optional (use -1 to do regular lookup). Don't transmit this. + SystemIndex systemIndex; + static int size() {return (int) sizeof(uint64_t);} + + bool operator==( const RakNetGUID& right ) const; + bool operator!=( const RakNetGUID& right ) const; + bool operator > ( const RakNetGUID& right ) const; + bool operator < ( const RakNetGUID& right ) const; +}; + +/// Index of an invalid SystemAddress +//const SystemAddress UNASSIGNED_SYSTEM_ADDRESS = +//{ +// 0xFFFFFFFF, 0xFFFF +//}; +#ifndef SWIG +const SystemAddress UNASSIGNED_SYSTEM_ADDRESS; +const RakNetGUID UNASSIGNED_RAKNET_GUID((uint64_t)-1); +#endif +//{ +// {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF} +// 0xFFFFFFFFFFFFFFFF +//}; + + +struct RAK_DLL_EXPORT AddressOrGUID +{ + RakNetGUID rakNetGuid; + SystemAddress systemAddress; + + SystemIndex GetSystemIndex(void) const {if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) return rakNetGuid.systemIndex; else return systemAddress.systemIndex;} + bool IsUndefined(void) const {return rakNetGuid==UNASSIGNED_RAKNET_GUID && systemAddress==UNASSIGNED_SYSTEM_ADDRESS;} + void SetUndefined(void) {rakNetGuid=UNASSIGNED_RAKNET_GUID; systemAddress=UNASSIGNED_SYSTEM_ADDRESS;} + static unsigned long ToInteger( const AddressOrGUID &aog ); + const char *ToString(bool writePort=true) const; + void ToString(bool writePort, char *dest) const; + + AddressOrGUID() {} + AddressOrGUID( const AddressOrGUID& input ) + { + rakNetGuid=input.rakNetGuid; + systemAddress=input.systemAddress; + } + AddressOrGUID( const SystemAddress& input ) + { + rakNetGuid=UNASSIGNED_RAKNET_GUID; + systemAddress=input; + } + AddressOrGUID( Packet *packet ); + AddressOrGUID( const RakNetGUID& input ) + { + rakNetGuid=input; + systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + } + AddressOrGUID& operator = ( const AddressOrGUID& input ) + { + rakNetGuid=input.rakNetGuid; + systemAddress=input.systemAddress; + return *this; + } + + AddressOrGUID& operator = ( const SystemAddress& input ) + { + rakNetGuid=UNASSIGNED_RAKNET_GUID; + systemAddress=input; + return *this; + } + + AddressOrGUID& operator = ( const RakNetGUID& input ) + { + rakNetGuid=input; + systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + return *this; + } + + inline bool operator==( const AddressOrGUID& right ) const {return (rakNetGuid!=UNASSIGNED_RAKNET_GUID && rakNetGuid==right.rakNetGuid) || (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && systemAddress==right.systemAddress);} +}; + +typedef uint64_t NetworkID; + +/// This represents a user message from another system. +struct Packet +{ + /// The system that send this packet. + SystemAddress systemAddress; + + /// A unique identifier for the system that sent this packet, regardless of IP address (internal / external / remote system) + /// Only valid once a connection has been established (ID_CONNECTION_REQUEST_ACCEPTED, or ID_NEW_INCOMING_CONNECTION) + /// Until that time, will be UNASSIGNED_RAKNET_GUID + RakNetGUID guid; + + /// The length of the data in bytes + unsigned int length; + + /// The length of the data in bits + BitSize_t bitSize; + + /// The data from the sender + unsigned char* data; + + /// @internal + /// Indicates whether to delete the data, or to simply delete the packet. + bool deleteData; + + /// @internal + /// If true, this message is meant for the user, not for the plugins, so do not process it through plugins + bool wasGeneratedLocally; +}; + +/// Index of an unassigned player +const SystemIndex UNASSIGNED_PLAYER_INDEX = 65535; + +/// Unassigned object ID +const NetworkID UNASSIGNED_NETWORK_ID = (uint64_t) -1; + +const int PING_TIMES_ARRAY_SIZE = 5; + +struct RAK_DLL_EXPORT uint24_t +{ + uint32_t val; + + uint24_t() {} + inline operator uint32_t() { return val; } + inline operator uint32_t() const { return val; } + + inline uint24_t(const uint24_t& a) {val=a.val;} + inline uint24_t operator++() {++val; val&=0x00FFFFFF; return *this;} + inline uint24_t operator--() {--val; val&=0x00FFFFFF; return *this;} + inline uint24_t operator++(int) {uint24_t temp(val); ++val; val&=0x00FFFFFF; return temp;} + inline uint24_t operator--(int) {uint24_t temp(val); --val; val&=0x00FFFFFF; return temp;} + inline uint24_t operator&(const uint24_t& a) {return uint24_t(val&a.val);} + inline uint24_t& operator=(const uint24_t& a) { val=a.val; return *this; } + inline uint24_t& operator+=(const uint24_t& a) { val+=a.val; val&=0x00FFFFFF; return *this; } + inline uint24_t& operator-=(const uint24_t& a) { val-=a.val; val&=0x00FFFFFF; return *this; } + inline bool operator==( const uint24_t& right ) const {return val==right.val;} + inline bool operator!=( const uint24_t& right ) const {return val!=right.val;} + inline bool operator > ( const uint24_t& right ) const {return val>right.val;} + inline bool operator < ( const uint24_t& right ) const {return val ( const uint32_t& right ) const {return val>(right&0x00FFFFFF);} + inline bool operator < ( const uint32_t& right ) const {return val<(right&0x00FFFFFF);} + inline const uint24_t operator+( const uint32_t &other ) const { return uint24_t(val+other); } + inline const uint24_t operator-( const uint32_t &other ) const { return uint24_t(val-other); } + inline const uint24_t operator/( const uint32_t &other ) const { return uint24_t(val/other); } + inline const uint24_t operator*( const uint32_t &other ) const { return uint24_t(val*other); } +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/RakNetVersion.hpp b/include/raknet/RakNetVersion.hpp new file mode 100644 index 0000000..359a52b --- /dev/null +++ b/include/raknet/RakNetVersion.hpp @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#define RAKNET_VERSION "4.081" +#define RAKNET_VERSION_NUMBER 4.081 +#define RAKNET_VERSION_NUMBER_INT 4081 + +#define RAKNET_DATE "5/28/2014" + +// What compatible protocol version RakNet is using. When this value changes, it indicates this version of RakNet cannot connection to an older version. +// ID_INCOMPATIBLE_PROTOCOL_VERSION will be returned on connection attempt in this case +#define RAKNET_PROTOCOL_VERSION 6 diff --git a/include/raknet/RakPeer.hpp b/include/raknet/RakPeer.hpp new file mode 100644 index 0000000..ab4766c --- /dev/null +++ b/include/raknet/RakPeer.hpp @@ -0,0 +1,1034 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Declares RakPeer class. +/// + + +// TODO - RakNet 4 - Add network simulator +// TODO - RakNet 4 - Enable disabling flow control per connections + +#ifndef __RAK_PEER_H +#define __RAK_PEER_H + +#include "ReliabilityLayer.hpp" +#include "RakPeerInterface.hpp" +#include "BitStream.hpp" +#include "SingleProducerConsumer.hpp" +#include "SimpleMutex.hpp" +#include "DS_OrderedList.hpp" +#include "Export.hpp" +#include "RakString.hpp" +#include "RakThread.hpp" +//#include "RakNetSocket.hpp" +#include "RakNetSmartPtr.hpp" +#include "DS_ThreadsafeAllocatingQueue.hpp" +#include "SignaledEvent.hpp" +#include "NativeFeatureIncludes.hpp" +#include "SecureHandshake.hpp" +#include "LocklessTypes.hpp" +#include "DS_Queue.hpp" + +namespace RakNet { +/// Forward declarations +class HuffmanEncodingTree; +class PluginInterface2; + +// Sucks but this struct has to be outside the class. Inside and DevCPP won't let you refer to the struct as RakPeer::RemoteSystemIndex while GCC +// forces you to do RakPeer::RemoteSystemIndex +struct RemoteSystemIndex{unsigned index; RemoteSystemIndex *next;}; +//int RAK_DLL_EXPORT SystemAddressAndIndexComp( const SystemAddress &key, const RemoteSystemIndex &data ); // GCC requires RakPeer::RemoteSystemIndex or it won't compile + +///\brief Main interface for network communications. +/// \details It implements most of RakNet's functionality and is the primary interface for RakNet. +/// +/// Inherits RakPeerInterface. +/// +/// See the individual functions for what the class can do. +/// +class RAK_DLL_EXPORT RakPeer : public RakPeerInterface, public RNS2EventHandler +{ +public: + ///Constructor + RakPeer(); + + ///Destructor + virtual ~RakPeer(); + + // --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users-------------------------------------------------------------------------------------------- + /// \brief Starts the network threads and opens the listen port. + /// \details You must call this before calling Connect(). + /// \pre On the PS3, call Startup() after Client_Login() + /// \note Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown(). + /// \note Call SetMaximumIncomingConnections if you want to accept incoming connections. + /// \param[in] maxConnections Maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so that the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.A hybrid would set it to the sum of both types of connections. + /// \param[in] localPort The port to listen for connections on. On linux the system may be set up so thast ports under 1024 are restricted for everything but the root user. Use a higher port for maximum compatibility. + /// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); However, on the XBOX be sure to use IPPROTO_VDP + /// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass. + /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. + /// \return RAKNET_STARTED on success, otherwise appropriate failure enumeration. + StartupResult Startup( unsigned int maxConnections, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority=-99999 ); + + /// If you accept connections, you must call this or else security will not be enabled for incoming connections. + /// This feature requires more round trips, bandwidth, and CPU time for the connection handshake + /// x64 builds require under 25% of the CPU time of other builds + /// See the Encryption sample for example usage + /// \pre Must be called while offline + /// \pre LIBCAT_SECURITY must be defined to 1 in NativeFeatureIncludes.h for this function to have any effect + /// \param[in] publicKey A pointer to the public key for accepting new connections + /// \param[in] privateKey A pointer to the private key for accepting new connections + /// \param[in] bRequireClientKey: Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection + bool InitializeSecurity( const char *publicKey, const char *privateKey, bool bRequireClientKey = false ); + + /// Disables security for incoming connections. + /// \note Must be called while offline + void DisableSecurity( void ); + + /// \brief This is useful if you have a fixed-address internal server behind a LAN. + /// + /// Secure connections are determined by the recipient of an incoming connection. This has no effect if called on the system attempting to connect. + /// \note If secure connections are on, do not use secure connections for a specific IP address. + /// \param[in] ip IP address to add. * wildcards are supported. + void AddToSecurityExceptionList(const char *ip); + + /// \brief Remove a specific connection previously added via AddToSecurityExceptionList. + /// \param[in] ip IP address to remove. Pass 0 to remove all IP addresses. * wildcards are supported. + void RemoveFromSecurityExceptionList(const char *ip); + + /// \brief Checks to see if a given IP is in the security exception list. + /// \param[in] IP address to check. + /// \return True if the IP address is found in security exception list, else returns false. + bool IsInSecurityExceptionList(const char *ip); + + /// \brief Sets the maximum number of incoming connections allowed. + /// \details If the number of incoming connections is less than the number of players currently connected, + /// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed, + /// it will be reduced to the maximum number of peers allowed. + /// + /// Defaults to 0, meaning by default, nobody can connect to you + /// \param[in] numberAllowed Maximum number of incoming connections allowed. + void SetMaximumIncomingConnections( unsigned short numberAllowed ); + + /// \brief Returns the value passed to SetMaximumIncomingConnections(). + /// \return Maximum number of incoming connections, which is always <= maxConnections + unsigned int GetMaximumIncomingConnections( void ) const; + + /// \brief Returns how many open connections exist at this time. + /// \return Number of open connections. + unsigned short NumberOfConnections(void) const; + + /// \brief Sets the password for the incoming connections. + /// \details The password must match in the call to Connect (defaults to none). + /// Pass 0 to passwordData to specify no password. + /// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections. + /// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data + /// \param[in] passwordDataLength The length in bytes of passwordData + void SetIncomingPassword( const char* passwordData, int passwordDataLength ); + + /// \brief Gets the password passed to SetIncomingPassword + /// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword() + /// \param[in,out] passwordDataLength Maximum size of the passwordData array. Modified to hold the number of bytes actually written. + void GetIncomingPassword( char* passwordData, int *passwordDataLength ); + + /// \brief Connect to the specified host (ip or domain name) and server port. + /// \details Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. + /// Calling both acts as a true peer. + /// + /// This is a non-blocking connection. + /// + /// The connection is successful when GetConnectionState() returns IS_CONNECTED or Receive() gets a message with the type identifier ID_CONNECTION_REQUEST_ACCEPTED. + /// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen. + /// \pre Requires that you first call Startup(). + /// \param[in] host Either a dotted IP address or a domain name. + /// \param[in] remotePort Port to connect to on the remote machine. + /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword(). This can be a string or can be a stream of data. Use 0 for no password. + /// \param[in] passwordDataLength The length in bytes of passwordData. + /// \param[in] publicKey The public key the server is using. If 0, the server is not using security. If non-zero, the publicKeyMode member determines how to connect + /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to determine the one to send on. + /// \param[in] sendConnectionAttemptCount Number of datagrams to send to the other system to try to connect. + /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. + /// \param[in] timeoutTime Time to elapse before dropping the connection if a reliable message could not be sent. 0 to use the default value from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); + /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. + /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! + /// \note It is possible to immediately get back ID_CONNECTION_ATTEMPT_FAILED if you exceed the maxConnections parameter passed to Startup(). This could happen if you call CloseConnection() with sendDisconnectionNotificaiton true, then immediately call Connect() before the connection has closed. + ConnectionAttemptResult Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey=0, unsigned connectionSocketIndex=0, unsigned sendConnectionAttemptCount=6, unsigned timeBetweenSendConnectionAttemptsMS=1000, RakNet::TimeMS timeoutTime=0 ); + + /// \brief Connect to the specified host (ip or domain name) and server port. + /// \param[in] host Either a dotted IP address or a domain name. + /// \param[in] remotePort Which port to connect to on the remote machine. + /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword(). This can be a string or can be a stream of data. Use 0 for no password. + /// \param[in] passwordDataLength The length in bytes of passwordData. + /// \param[in] socket A bound socket returned by another instance of RakPeerInterface. + /// \param[in] sendConnectionAttemptCount Number of datagrams to send to the other system to try to connect. + /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned.. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. + /// \param[in] timeoutTime Time to elapse before dropping the connection if a reliable message could not be sent. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); + /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. + /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! + virtual ConnectionAttemptResult ConnectWithSocket(const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSocket2* socket, PublicKey *publicKey=0, unsigned sendConnectionAttemptCount=6, unsigned timeBetweenSendConnectionAttemptsMS=1000, RakNet::TimeMS timeoutTime=0); + + /* /// \brief Connect to the specified network ID (Platform specific console function) + /// \details Does built-in NAT traversal + /// \param[in] networkServiceId Network ID structure for the online service + /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword(). This can be a string or can be a stream of data. Use 0 for no password. + /// \param[in] passwordDataLength The length in bytes of passwordData. + //bool Console2LobbyConnect( void *networkServiceId, const char *passwordData, int passwordDataLength );*/ + + /// \brief Stops the network threads and closes all connections. + /// \param[in] blockDuration Wait time(milli seconds) for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all. + /// \param[in] orderingChannel Channel on which ID_DISCONNECTION_NOTIFICATION will be sent, if blockDuration > 0. + /// \param[in] disconnectionNotificationPriority Priority of sending ID_DISCONNECTION_NOTIFICATION. + /// If set to 0, the disconnection notification won't be sent. + void Shutdown( unsigned int blockDuration, unsigned char orderingChannel=0, PacketPriority disconnectionNotificationPriority=LOW_PRIORITY ); + + /// \brief Returns true if the network thread is running. + /// \return True if the network thread is running, False otherwise + bool IsActive( void ) const; + + /// \brief Fills the array remoteSystems with the SystemAddress of all the systems we are connected to. + /// \param[out] remoteSystems An array of SystemAddress structures, to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to get the number of systems we are connected to. + /// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array. + bool GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const; + + /// Returns the next uint32_t that Send() will return + /// \note If using RakPeer from multiple threads, this may not be accurate for your thread. Use IncrementNextSendReceipt() in that case. + /// \return The next uint32_t that Send() or SendList will return + virtual uint32_t GetNextSendReceipt(void); + + /// Returns the next uint32_t that Send() will return, and increments the value by one + /// \note If using RakPeer from multiple threads, pass this to forceReceipt in the send function + /// \return The next uint32_t that Send() or SendList will return + virtual uint32_t IncrementNextSendReceipt(void); + + /// \brief Sends a block of data to the specified system that you are connected to. + /// \note This function only works while connected. + /// \note The first byte should be a message identifier starting at ID_USER_PACKET_ENUM. + /// \param[in] data Block of data to send. + /// \param[in] length Size in bytes of the data to send. + /// \param[in] priority Priority level to send on. See PacketPriority.h + /// \param[in] reliability How reliably to send this data. See PacketPriority.h + /// \param[in] orderingChannel When using ordered or sequenced messages, the channel to order these on. Messages are only ordered relative to other messages on the same stream. + /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none + /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. + /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. + /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number + uint32_t Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 ); + + /// \brief "Send" to yourself rather than a remote system. + /// \details The message will be processed through the plugins and returned to the game as usual. + /// This function works anytime + /// \note The first byte should be a message identifier starting at ID_USER_PACKET_ENUM + /// \param[in] data Block of data to send. + /// \param[in] length Size in bytes of the data to send. + void SendLoopback( const char *data, const int length ); + + /// \brief Sends a block of data to the specified system that you are connected to. + /// + /// Same as the above version, but takes a BitStream as input. + /// \param[in] bitStream Bitstream to send + /// \param[in] priority Priority level to send on. See PacketPriority.h + /// \param[in] reliability How reliably to send this data. See PacketPriority.h + /// \param[in] orderingChannel Channel to order the messages on, when using ordered or sequenced messages. Messages are only ordered relative to other messages on the same stream. + /// \param[in] systemIdentifier System Address or RakNetGUID to send this packet to, or in the case of broadcasting, the address not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none. + /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. + /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. + /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number + /// \note COMMON MISTAKE: When writing the first byte, bitStream->Write((unsigned char) ID_MY_TYPE) be sure it is casted to a byte, and you are not writing a 4 byte enumeration. + uint32_t Send( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 ); + + /// \brief Sends multiple blocks of data, concatenating them automatically. + /// + /// This is equivalent to: + /// RakNet::BitStream bs; + /// bs.WriteAlignedBytes(block1, blockLength1); + /// bs.WriteAlignedBytes(block2, blockLength2); + /// bs.WriteAlignedBytes(block3, blockLength3); + /// Send(&bs, ...) + /// + /// This function only works when connected. + /// \param[in] data An array of pointers to blocks of data + /// \param[in] lengths An array of integers indicating the length of each block of data + /// \param[in] numParameters Length of the arrays data and lengths + /// \param[in] priority Priority level to send on. See PacketPriority.h + /// \param[in] reliability How reliably to send this data. See PacketPriority.h + /// \param[in] orderingChannel Channel to order the messages on, when using ordered or sequenced messages. Messages are only ordered relative to other messages on the same stream. + /// \param[in] systemIdentifier System Address or RakNetGUID to send this packet to, or in the case of broadcasting, the address not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none. + /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. + /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. + /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number + uint32_t SendList( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 ); + + /// \brief Gets a message from the incoming message queue. + /// \details Use DeallocatePacket() to deallocate the message after you are done with it. + /// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here. + /// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet. + /// \note COMMON MISTAKE: Be sure to call this in a loop, once per game tick, until it returns 0. If you only process one packet per game tick they will buffer up. + /// \sa RakNetTypes.h contains struct Packet. + Packet* Receive( void ); + + /// \brief Call this to deallocate a message returned by Receive() when you are done handling it. + /// \param[in] packet Message to deallocate. + void DeallocatePacket( Packet *packet ); + + /// \brief Return the total number of connections we are allowed. + /// \return Total number of connections allowed. + unsigned int GetMaximumNumberOfPeers( void ) const; + + // -------------------------------------------------------------------------------------------- Connection Management Functions-------------------------------------------------------------------------------------------- + /// \brief Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out). + /// \details This method closes the connection irrespective of who initiated the connection. + /// \param[in] target Which system to close the connection to. + /// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently. + /// \param[in] channel Which ordering channel to send the disconnection notification on, if any + /// \param[in] disconnectionNotificationPriority Priority to send ID_DISCONNECTION_NOTIFICATION on. + void CloseConnection( const AddressOrGUID target, bool sendDisconnectionNotification, unsigned char orderingChannel=0, PacketPriority disconnectionNotificationPriority=LOW_PRIORITY ); + + /// \brief Cancel a pending connection attempt. + /// \details If we are already connected, the connection stays open + /// \param[in] target Target system to cancel. + void CancelConnectionAttempt( const SystemAddress target ); + /// Returns if a system is connected, disconnected, connecting in progress, or various other states + /// \param[in] systemIdentifier The system we are referring to + /// \note This locks a mutex, do not call too frequently during connection attempts or the attempt will take longer and possibly even timeout + /// \return What state the remote system is in + ConnectionState GetConnectionState(const AddressOrGUID systemIdentifier); + + /// \brief Given \a systemAddress, returns its index into remoteSystemList. + /// \details Values range from 0 to the maximum number of players allowed - 1. + /// This includes systems which were formerly connected, but are now not connected. + /// \param[in] systemAddress The SystemAddress we are referring to + /// \return The index of this SystemAddress or -1 on system not found. + int GetIndexFromSystemAddress( const SystemAddress systemAddress ) const; + + /// \brief Given \a index into remoteSystemList, will return a SystemAddress. + /// This function is only useful for looping through all systems. + /// + /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. + /// \return The SystemAddress structure corresponding to \a index in remoteSystemList. + SystemAddress GetSystemAddressFromIndex( unsigned int index ); + + /// \brief Same as GetSystemAddressFromIndex but returns RakNetGUID + /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. + /// \return The RakNetGUID + RakNetGUID GetGUIDFromIndex( unsigned int index ); + + /// \brief Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient + /// Indices match each other, so \a addresses[0] and \a guids[0] refer to the same system + /// \param[out] addresses All system addresses. Size of the list is the number of connections. Size of the \a addresses list will match the size of the \a guids list. + /// \param[out] guids All guids. Size of the list is the number of connections. Size of the list will match the size of the \a addresses list. + void GetSystemList(DataStructures::List &addresses, DataStructures::List &guids) const; + + /// \brief Bans an IP from connecting. + /// \details Banned IPs persist between connections but are not saved on shutdown nor loaded on startup. + /// \param[in] IP Dotted IP address. You can use * for a wildcard address, such as 128.0.0. * will ban all IP addresses starting with 128.0.0. + /// \param[in] milliseconds Gives time in milli seconds for a temporary ban of the IP address. Use 0 for a permanent ban. + void AddToBanList( const char *IP, RakNet::TimeMS milliseconds=0 ); + + /// \brief Allows a previously banned IP to connect. + /// param[in] Dotted IP address. You can use * as a wildcard. An IP such as 128.0.0.* will ban all IP addresses starting with 128.0.0. + void RemoveFromBanList( const char *IP ); + + /// \brief Allows all previously banned IPs to connect. + void ClearBanList( void ); + + /// \brief Returns true or false indicating if a particular IP is banned. + /// \param[in] IP Dotted IP address. + /// \return True if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise. + bool IsBanned( const char *IP ); + + /// \brief Enable or disable allowing frequent connections from the same IP adderss + /// \details This is a security measure which is disabled by default, but can be set to true to prevent attackers from using up all connection slots. + /// \param[in] b True to limit connections from the same ip to at most 1 per 100 milliseconds. + void SetLimitIPConnectionFrequency(bool b); + + // --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism-------------------------------------------------------------------------------------------- + /// Send a ping to the specified connected system. + /// \pre The sender and recipient must already be started via a successful call to Startup() + /// \param[in] target Which system to ping + void Ping( const SystemAddress target ); + + /// \brief Send a ping to the specified unconnected system. + /// \details The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(RakNet::TimeMS) containing the system time the ping was sent. Default is 4 bytes - See __GET_TIME_64BIT in RakNetTypes.h + /// System should reply with ID_PONG if it is active + /// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast. + /// \param[in] remotePort Which port to connect to on the remote machine. + /// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections + /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. + /// \return true on success, false on failure (unknown hostname) + bool Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex=0 ); + + /// \brief Returns the average of all ping times read for the specific system or -1 if none read yet + /// \param[in] systemAddress Which system we are referring to + /// \return The ping time for this system, or -1 + int GetAveragePing( const AddressOrGUID systemIdentifier ); + + /// \brief Returns the last ping time read for the specific system or -1 if none read yet. + /// \param[in] systemAddress Which system we are referring to + /// \return The last ping time for this system, or -1. + int GetLastPing( const AddressOrGUID systemIdentifier ) const; + + /// \brief Returns the lowest ping time read or -1 if none read yet. + /// \param[in] systemIdentifier Which system we are referring to + /// \return The lowest ping time for this system, or -1. + int GetLowestPing( const AddressOrGUID systemIdentifier ) const; + + /// Ping the remote systems every so often, or not. Can be called anytime. + /// By default this is true. Recommended to leave on, because congestion control uses it to determine how often to resend lost packets. + /// It would be true by default to prevent timestamp drift, since in the event of a clock spike, the timestamp deltas would no longer be accurate + /// \param[in] doPing True to start occasional pings. False to stop them. + void SetOccasionalPing( bool doPing ); + + /// Return the clock difference between your system and the specified system + /// Subtract GetClockDifferential() from a time returned by the remote system to get that time relative to your own system + /// Returns 0 if the system is unknown + /// \param[in] systemIdentifier Which system we are referring to + RakNet::Time GetClockDifferential( const AddressOrGUID systemIdentifier ); + + // --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory-------------------------------------------------------------------------------------------- + /// \brief Sets the data to send along with a LAN server discovery or offline ping reply. + /// \param[in] data Block of data to send, or 0 for none + /// \param[in] length Length of the data in bytes, or 0 for none + /// \note \a length should be under 400 bytes, as a security measure against flood attacks + /// \sa Ping.cpp + void SetOfflinePingResponse( const char *data, const unsigned int length ); + + /// \brief Returns pointers to a copy of the \a data passed to SetOfflinePingResponse. + /// \param[out] data A pointer to a copy of the data passed to SetOfflinePingResponse() + /// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse() + /// \sa SetOfflinePingResponse + void GetOfflinePingResponse( char **data, unsigned int *length ); + + //--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general-------------------------------------------------------------------------------------------- + /// \brief Returns the unique address identifier that represents you or another system on the the network + /// \note Not supported by the XBOX + /// \param[in] systemAddress Use UNASSIGNED_SYSTEM_ADDRESS to get your behind-LAN address. Use a connected system to get their behind-LAN address. This does not return the port. + /// \param[in] index When you have multiple internal IDs, which index to return? Currently limited to MAXIMUM_NUMBER_OF_INTERNAL_IDS (so the maximum value of this variable is MAXIMUM_NUMBER_OF_INTERNAL_IDS-1) + /// \return Identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy. + SystemAddress GetInternalID( const SystemAddress systemAddress=UNASSIGNED_SYSTEM_ADDRESS, const int index=0 ) const; + + /// \brief Sets your internal IP address, for platforms that do not support reading it, or to override a value + /// \param[in] systemAddress. The address to set. Use SystemAddress::FromString() if you want to use a dotted string + /// \param[in] index When you have multiple internal IDs, which index to set? + void SetInternalID(SystemAddress systemAddress, int index=0); + + /// \brief Returns the unique address identifier that represents the target on the the network and is based on the target's external IP / port. + /// \param[in] target The SystemAddress of the remote system. Usually the same for all systems, unless you have two or more network cards. + SystemAddress GetExternalID( const SystemAddress target ) const; + + /// Return my own GUID + const RakNetGUID GetMyGUID(void) const; + + /// Return the address bound to a socket at the specified index + SystemAddress GetMyBoundAddress(const int socketIndex=0); + + /// \brief Given a connected system address, this method gives the unique GUID representing that instance of RakPeer. + /// This will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different. + /// Complexity is O(log2(n)). + /// If \a input is UNASSIGNED_SYSTEM_ADDRESS, will return your own GUID + /// \pre Call Startup() first, or the function will return UNASSIGNED_RAKNET_GUID + /// \param[in] input The system address of the target system we are connected to. + const RakNetGUID& GetGuidFromSystemAddress( const SystemAddress input ) const; + + /// \brief Gives the system address of a connected system, given its GUID. + /// The GUID will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different. + /// Currently O(log(n)), but this may be improved in the future + /// If \a input is UNASSIGNED_RAKNET_GUID, UNASSIGNED_SYSTEM_ADDRESS is returned. + /// \param[in] input The RakNetGUID of the target system. + SystemAddress GetSystemAddressFromGuid( const RakNetGUID input ) const; + + /// Given the SystemAddress of a connected system, get the public key they provided as an identity + /// Returns false if system address was not found or client public key is not known + /// \param[in] input The RakNetGUID of the system + /// \param[in] client_public_key The connected client's public key is copied to this address. Buffer must be cat::EasyHandshake::PUBLIC_KEY_BYTES bytes in length. + bool GetClientPublicKeyFromSystemAddress( const SystemAddress input, char *client_public_key ) const; + + /// \brief Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. + + /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. + /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. + /// Do not set different values for different computers that are connected to each other, or you won't be able to reconnect after ID_CONNECTION_LOST + /// \param[in] timeMS Time, in MS + /// \param[in] target SystemAddress structure of the target system. Pass UNASSIGNED_SYSTEM_ADDRESS for all systems. + void SetTimeoutTime( RakNet::TimeMS timeMS, const SystemAddress target ); + + /// \brief Returns the Timeout time for the given system. + /// \param[in] target Target system to get the TimeoutTime for. Pass UNASSIGNED_SYSTEM_ADDRESS to get the default value. + /// \return Timeout time for a given system. + RakNet::TimeMS GetTimeoutTime( const SystemAddress target ); + + /// \brief Returns the current MTU size + /// \param[in] target Which system to get MTU for. UNASSIGNED_SYSTEM_ADDRESS to get the default + /// \return The current MTU size of the target system. + int GetMTUSize( const SystemAddress target ) const; + + /// \brief Returns the number of IP addresses this system has internally. + /// \details Get the actual addresses from GetLocalIP() + unsigned GetNumberOfAddresses( void ); + + /// Returns an IP address at index 0 to GetNumberOfAddresses-1 in ipList array. + /// \param[in] index index into the list of IP addresses + /// \return The local IP address at this index + const char* GetLocalIP( unsigned int index ); + + /// Is this a local IP? + /// Checks if this ip is in the ipList array. + /// \param[in] An IP address to check, excluding the port. + /// \return True if this is one of the IP addresses returned by GetLocalIP + bool IsLocalIP( const char *ip ); + + /// \brief Allow or disallow connection responses from any IP. + /// \details Normally this should be false, but may be necessary when connecting to servers with multiple IP addresses. + /// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections. + void AllowConnectionResponseIPMigration( bool allow ); + + /// \brief Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system. + /// This will send our external IP outside the LAN along with some user data to the remote system. + /// \pre The sender and recipient must already be started via a successful call to Initialize + /// \param[in] host Either a dotted IP address or a domain name + /// \param[in] remotePort Which port to connect to on the remote machine. + /// \param[in] data Optional data to append to the packet. + /// \param[in] dataLength Length of data in bytes. Use 0 if no data. + /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. + /// \return False if IsActive()==false or the host is unresolvable. True otherwise. + bool AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex=0 ); + + /// \brief Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. + /// \details ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived. + /// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. + /// Defaults to 0 (never return this notification). + /// \param[in] interval How many messages to use as an interval before a download progress notification is returned. + void SetSplitMessageProgressInterval(int interval); + + /// \brief Returns what was passed to SetSplitMessageProgressInterval(). + /// \return Number of messages to be recieved before a download progress notification is returned. Default to 0. + int GetSplitMessageProgressInterval(void) const; + + /// \brief Set how long to wait before giving up on sending an unreliable message. + /// Useful if the network is clogged up. + /// Set to 0 or less to never timeout. Defaults to 0. + /// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message. + void SetUnreliableTimeout(RakNet::TimeMS timeoutMS); + + /// \brief Send a message to a host, with the IP socket option TTL set to 3. + /// \details This message will not reach the host, but will open the router. + /// \param[in] host The address of the remote host in dotted notation. + /// \param[in] remotePort The port number to send to. + /// \param[in] ttl Max hops of datagram, set to 3 + /// \param[in] connectionSocketIndex userConnectionSocketIndex. + /// \remarks Used for NAT-Punchthrough + void SendTTL( const char* host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex=0 ); + + // -------------------------------------------------------------------------------------------- Plugin Functions-------------------------------------------------------------------------------------------- + /// \brief Attaches a Plugin interface to an instance of the base class (RakPeer or PacketizedTCP) to run code automatically on message receipt in the Receive call. + /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. + /// \param[in] messageHandler Pointer to the plugin to attach. + void AttachPlugin( PluginInterface2 *plugin ); + + /// \brief Detaches a Plugin interface from the instance of the base class (RakPeer or PacketizedTCP) it is attached to. + /// \details This method disables the plugin code from running automatically on base class's updates or message receipt. + /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. + /// \param[in] messageHandler Pointer to a plugin to detach. + void DetachPlugin( PluginInterface2 *messageHandler ); + + // --------------------------------------------------------------------------------------------Miscellaneous Functions-------------------------------------------------------------------------------------------- + /// \brief Puts a message back in the receive queue in case you don't want to deal with it immediately. + /// \param[in] packet The pointer to the packet you want to push back. + /// \param[in] pushAtHead True to push the packet at the start of the queue so that the next receive call returns it. False to push it at the end of the queue. + /// \note Setting pushAtHead to false end makes the packets out of order. + void PushBackPacket( Packet *packet, bool pushAtHead ); + + /// \internal + /// \brief For a given system identified by \a guid, change the SystemAddress to send to. + /// \param[in] guid The connection we are referring to + /// \param[in] systemAddress The new address to send to + void ChangeSystemAddress(RakNetGUID guid, const SystemAddress &systemAddress); + + /// \brief Returns a packet for you to write to if you want to create a Packet for some reason. + /// You can add it to the receive buffer with PushBackPacket + /// \param[in] dataSize How many bytes to allocate for the buffer + /// \return A packet. + Packet* AllocatePacket(unsigned dataSize); + + /// \brief Get the socket used with a particular active connection. + /// The smart pointer reference counts the RakNetSocket object, so the socket will remain active as long as the smart pointer does, even if RakNet were to shutdown or close the connection. + /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. + /// \param[in] target Which system. + /// \return A smart pointer object containing the socket information about the target. Be sure to check IsNull() which is returned if the update thread is unresponsive, shutting down, or if this system is not connected. + virtual RakNetSocket2* GetSocket( const SystemAddress target ); + + /// \brief Gets all sockets in use. + /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. + /// \param[out] sockets List of RakNetSocket structures in use. + virtual void GetSockets( DataStructures::List &sockets ); + virtual void ReleaseSockets( DataStructures::List &sockets ); + + /// \internal + virtual void WriteOutOfBandHeader(RakNet::BitStream *bitStream); + + /// If you need code to run in the same thread as RakNet's update thread, this function can be used for that + /// \param[in] _userUpdateThreadPtr C callback function + /// \param[in] _userUpdateThreadData Passed to C callback function + virtual void SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface *, void *), void *_userUpdateThreadData); + + /// Set a C callback to be called whenever a datagram arrives + /// Return true from the callback to have RakPeer handle the datagram. Return false and RakPeer will ignore the datagram. + /// This can be used to filter incoming datagrams by system, or to share a recvfrom socket with RakPeer + /// RNS2RecvStruct will only remain valid for the duration of the call + virtual void SetIncomingDatagramEventHandler( bool (*_incomingDatagramEventHandler)(RNS2RecvStruct *) ); + + // --------------------------------------------------------------------------------------------Network Simulator Functions-------------------------------------------------------------------------------------------- + /// Adds simulated ping and packet loss to the outgoing data flow. + /// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and packetloss value on each. + /// You can exclude network simulator code with the _RELEASE #define to decrease code size + /// \deprecated Use http://www.jenkinssoftware.com/forum/index.php?topic=1671.0 instead. + /// \note Doesn't work past version 3.6201 + /// \param[in] packetloss Chance to lose a packet. Ranges from 0 to 1. + /// \param[in] minExtraPing The minimum time to delay sends. + /// \param[in] extraPingVariance The additional random time to delay sends. + virtual void ApplyNetworkSimulator( float packetloss, unsigned short minExtraPing, unsigned short extraPingVariance); + + /// Limits how much outgoing bandwidth can be sent per-connection. + /// This limit does not apply to the sum of all connections! + /// Exceeding the limit queues up outgoing traffic + /// \param[in] maxBitsPerSecond Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again. + virtual void SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond ); + + /// Returns if you previously called ApplyNetworkSimulator + /// \return If you previously called ApplyNetworkSimulator + virtual bool IsNetworkSimulatorActive( void ); + + // --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance-------------------------------------------------------------------------------------------- + + /// \brief Returns a structure containing a large set of network statistics for the specified system. + /// You can map this data to a string using the C style StatisticsToString() function + /// \param[in] systemAddress Which connected system to get statistics for. + /// \param[in] rns If you supply this structure,the network statistics will be written to it. Otherwise the method uses a static struct to write the data, which is not threadsafe. + /// \return 0 if the specified system can't be found. Otherwise a pointer to the struct containing the specified system's network statistics. + /// \sa RakNetStatistics.h + RakNetStatistics * GetStatistics( const SystemAddress systemAddress, RakNetStatistics *rns=0 ); + /// \brief Returns the network statistics of the system at the given index in the remoteSystemList. + /// \return True if the index is less than the maximum number of peers allowed and the system is active. False otherwise. + bool GetStatistics( const unsigned int index, RakNetStatistics *rns ); + /// \brief Returns the list of systems, and statistics for each of those systems + /// Each system has one entry in each of the lists, in the same order + /// \param[out] addresses SystemAddress for each connected system + /// \param[out] guids RakNetGUID for each connected system + /// \param[out] statistics Calculated RakNetStatistics for each connected system + virtual void GetStatisticsList(DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &statistics); + + /// \Returns how many messages are waiting when you call Receive() + virtual unsigned int GetReceiveBufferSize(void); + + // --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY-------------------------------------------------------------------------------------------- + + + /// \internal + // Call manually if RAKPEER_USER_THREADED==1 at least every 30 milliseconds. + // updateBitStream should be: + // BitStream updateBitStream( MAXIMUM_MTU_SIZE + // #if LIBCAT_SECURITY==1 + // + cat::AuthenticatedEncryption::OVERHEAD_BYTES + // #endif + // ); + bool RunUpdateCycle( BitStream &updateBitStream ); + + /// \internal + // Call manually if RAKPEER_USER_THREADED==1 at least every 30 milliseconds. + // Call in a loop until returns false if the socket is non-blocking + // remotePortRakNetWasStartedOn_PS3 and extraSocketOptions are from SocketDescriptor when the socket was created + // bool RunRecvFromOnce( RakNetSocket *s ); + + /// \internal + bool SendOutOfBand(const char *host, unsigned short remotePort, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex=0 ); + + // static Packet *AllocPacket(unsigned dataSize, const char *file, unsigned int line); + + /// \internal + /// \brief Holds the clock differences between systems, along with the ping + struct PingAndClockDifferential + { + unsigned short pingTime; + RakNet::Time clockDifferential; + }; + + /// \internal + /// \brief All the information representing a connected system + struct RemoteSystemStruct + { + bool isActive; // Is this structure in use? + SystemAddress systemAddress; /// Their external IP on the internet + SystemAddress myExternalSystemAddress; /// Your external IP on the internet, from their perspective + SystemAddress theirInternalSystemAddress[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; /// Their internal IP, behind the LAN + ReliabilityLayer reliabilityLayer; /// The reliability layer associated with this player + bool weInitiatedTheConnection; /// True if we started this connection via Connect. False if someone else connected to us. + PingAndClockDifferential pingAndClockDifferential[ PING_TIMES_ARRAY_SIZE ]; /// last x ping times and calculated clock differentials with it + RakNet::Time pingAndClockDifferentialWriteIndex; /// The index we are writing into the pingAndClockDifferential circular buffer + unsigned short lowestPing; ///The lowest ping value encountered + RakNet::Time nextPingTime; /// When to next ping this player + RakNet::Time lastReliableSend; /// When did the last reliable send occur. Reliable sends must occur at least once every timeoutTime/2 units to notice disconnects + RakNet::Time connectionTime; /// connection time, if active. +// int connectionSocketIndex; // index into connectionSockets to send back on. + RakNetGUID guid; + int MTUSize; + // Reference counted socket to send back on + RakNetSocket2* rakNetSocket; + SystemIndex remoteSystemIndex; + +#if LIBCAT_SECURITY==1 + // Cached answer used internally by RakPeer to prevent DoS attacks based on the connexion handshake + char answer[cat::EasyHandshake::ANSWER_BYTES]; + + // If the server has bRequireClientKey = true, then this is set to the validated public key of the connected client + // Valid after connectMode reaches HANDLING_CONNECTION_REQUEST + char client_public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; +#endif + + enum ConnectMode {NO_ACTION, DISCONNECT_ASAP, DISCONNECT_ASAP_SILENTLY, DISCONNECT_ON_NO_ACK, REQUESTED_CONNECTION, HANDLING_CONNECTION_REQUEST, UNVERIFIED_SENDER, CONNECTED} connectMode; + }; + + // DS_APR + //void ProcessChromePacket(RakNetSocket2 *s, const char *buffer, int dataSize, const SystemAddress& recvFromAddress, RakNet::TimeUS timeRead); + // /DS_APR +protected: + + friend RAK_THREAD_DECLARATION(UpdateNetworkLoop); + //friend RAK_THREAD_DECLARATION(RecvFromLoop); + friend RAK_THREAD_DECLARATION(UDTConnect); + + friend bool ProcessOfflineNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, bool *isOfflineMessage, RakNet::TimeUS timeRead ); + friend void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNet::TimeUS timeRead, BitStream &updateBitStream ); + friend void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, RakNet::TimeUS timeRead, BitStream &updateBitStream ); + + int GetIndexFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread ) const; + int GetIndexFromGuid( const RakNetGUID guid ); + + //void RemoveFromRequestedConnectionsList( const SystemAddress systemAddress ); + // Two versions needed because some buggy compilers strip the last parameter if unused, and crashes + ConnectionAttemptResult SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNet::TimeMS timeoutTime, RakNetSocket2* socket ); + ConnectionAttemptResult SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNet::TimeMS timeoutTime ); + ///Get the reliability layer associated with a systemAddress. + /// \param[in] systemAddress The player identifier + /// \return 0 if none + RemoteSystemStruct *GetRemoteSystemFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread, bool onlyActive ) const; + RakPeer::RemoteSystemStruct *GetRemoteSystem( const AddressOrGUID systemIdentifier, bool calledFromNetworkThread, bool onlyActive ) const; + void ValidateRemoteSystemLookup(void) const; + RemoteSystemStruct *GetRemoteSystemFromGUID( const RakNetGUID guid, bool onlyActive ) const; + ///Parse out a connection request packet + void ParseConnectionRequestPacket( RakPeer::RemoteSystemStruct *remoteSystem, const SystemAddress &systemAddress, const char *data, int byteSize); + void OnConnectionRequest( RakPeer::RemoteSystemStruct *remoteSystem, RakNet::Time incomingTimestamp ); + ///Send a reliable disconnect packet to this player and disconnect them when it is delivered + void NotifyAndFlagForShutdown( const SystemAddress systemAddress, bool performImmediate, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority ); + ///Returns how many remote systems initiated a connection to us + unsigned int GetNumberOfRemoteInitiatedConnections( void ) const; + /// \brief Get a free remote system from the list and assign our systemAddress to it. + /// \note Should only be called from the update thread - not the user thread. + /// \param[in] systemAddress systemAddress to be assigned + /// \param[in] connectionMode connection mode of the RemoteSystem. + /// \param[in] rakNetSocket + /// \param[in] thisIPConnectedRecently Is this IP connected recently? set to False; + /// \param[in] bindingAddress Address to be binded with the remote system + /// \param[in] incomingMTU MTU for the remote system + RemoteSystemStruct * AssignSystemAddressToRemoteSystemList( const SystemAddress systemAddress, RemoteSystemStruct::ConnectMode connectionMode, RakNetSocket2* incomingRakNetSocket, bool *thisIPConnectedRecently, SystemAddress bindingAddress, int incomingMTU, RakNetGUID guid, bool useSecurity ); + /// \brief Adjust the timestamp of the incoming packet to be relative to this system. + /// \param[in] data Data in the incoming packet. + /// \param[in] systemAddress Sender of the incoming packet. + void ShiftIncomingTimestamp( unsigned char *data, const SystemAddress &systemAddress ) const; + /// Get the most accurate clock differential for a certain player. + /// \param[in] systemAddress The player with whose clock the time difference is calculated. + /// \returns The clock differential for a certain player. + RakNet::Time GetBestClockDifferential( const SystemAddress systemAddress ) const; + + bool IsLoopbackAddress(const AddressOrGUID &systemIdentifier, bool matchPort) const; + SystemAddress GetLoopbackAddress(void) const; + + ///Set this to true to terminate the Peer thread execution + volatile bool endThreads; + ///true if the peer thread is active. + volatile bool isMainLoopThreadActive; + + // RakNet::LocklessUint32_t isRecvFromLoopThreadActive; + + + bool occasionalPing; /// Do we occasionally ping the other systems?*/ + ///Store the maximum number of peers allowed to connect + unsigned int maximumNumberOfPeers; + //05/02/06 Just using maximumNumberOfPeers instead + ///Store the maximum number of peers able to connect, including reserved connection slots for pings, etc. + //unsigned short remoteSystemListSize; + ///Store the maximum incoming connection allowed + unsigned int maximumIncomingConnections; + RakNet::BitStream offlinePingResponse; + ///Local Player ID + // SystemAddress mySystemAddress[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; + char incomingPassword[256]; + unsigned char incomingPasswordLength; + + /// This is an array of pointers to RemoteSystemStruct + /// This allows us to preallocate the list when starting, so we don't have to allocate or delete at runtime. + /// Another benefit is that is lets us add and remove active players simply by setting systemAddress + /// and moving elements in the list by copying pointers variables without affecting running threads, even if they are in the reliability layer + RemoteSystemStruct* remoteSystemList; + /// activeSystemList holds a list of pointers and is preallocated to be the same size as remoteSystemList. It is updated only by the network thread, but read by both threads + /// When the isActive member of RemoteSystemStruct is set to true or false, that system is added to this list of pointers + /// Threadsafe because RemoteSystemStruct is preallocated, and the list is only added to, not removed from + RemoteSystemStruct** activeSystemList; + unsigned int activeSystemListSize; + + // Use a hash, with binaryAddress plus port mod length as the index + RemoteSystemIndex **remoteSystemLookup; + unsigned int RemoteSystemLookupHashIndex(const SystemAddress &sa) const; + void ReferenceRemoteSystem(const SystemAddress &sa, unsigned int remoteSystemListIndex); + void DereferenceRemoteSystem(const SystemAddress &sa); + RemoteSystemStruct* GetRemoteSystem(const SystemAddress &sa) const; + unsigned int GetRemoteSystemIndex(const SystemAddress &sa) const; + void ClearRemoteSystemLookup(void); + DataStructures::MemoryPool remoteSystemIndexPool; + + void AddToActiveSystemList(unsigned int remoteSystemListIndex); + void RemoveFromActiveSystemList(const SystemAddress &sa); + +// unsigned int LookupIndexUsingHashIndex(const SystemAddress &sa) const; +// unsigned int RemoteSystemListIndexUsingHashIndex(const SystemAddress &sa) const; +// unsigned int FirstFreeRemoteSystemLookupIndex(const SystemAddress &sa) const; + + enum + { + // Only put these mutexes in user thread functions! + requestedConnectionList_Mutex, + offlinePingResponse_Mutex, + NUMBER_OF_RAKPEER_MUTEXES + }; + SimpleMutex rakPeerMutexes[ NUMBER_OF_RAKPEER_MUTEXES ]; + ///RunUpdateCycle is not thread safe but we don't need to mutex calls. Just skip calls if it is running already + + bool updateCycleIsRunning; + ///The list of people we have tried to connect to recently + + //DataStructures::Queue requestedConnectionsList; + ///Data that both the client and the server needs + + unsigned int bytesSentPerSecond, bytesReceivedPerSecond; + // bool isSocketLayerBlocking; + // bool continualPing,isRecvfromThreadActive,isMainLoopThreadActive, endThreads, isSocketLayerBlocking; + unsigned int validationInteger; + SimpleMutex incomingQueueMutex, banListMutex; //,synchronizedMemoryQueueMutex, automaticVariableSynchronizationMutex; + //DataStructures::Queue incomingpacketSingleProducerConsumer; //, synchronizedMemorypacketSingleProducerConsumer; + // BitStream enumerationData; + + struct BanStruct + { + char *IP; + RakNet::TimeMS timeout; // 0 for none + }; + + struct RequestedConnectionStruct + { + SystemAddress systemAddress; + RakNet::Time nextRequestTime; + unsigned char requestsMade; + char *data; + unsigned short dataLength; + char outgoingPassword[256]; + unsigned char outgoingPasswordLength; + unsigned socketIndex; + unsigned int extraData; + unsigned sendConnectionAttemptCount; + unsigned timeBetweenSendConnectionAttemptsMS; + RakNet::TimeMS timeoutTime; + PublicKeyMode publicKeyMode; + RakNetSocket2* socket; + enum {CONNECT=1, /*PING=2, PING_OPEN_CONNECTIONS=4,*/ /*ADVERTISE_SYSTEM=2*/} actionToTake; + +#if LIBCAT_SECURITY==1 + char handshakeChallenge[cat::EasyHandshake::CHALLENGE_BYTES]; + cat::ClientEasyHandshake *client_handshake; + char remote_public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; +// char remote_challenge[cat::EasyHandshake::CHALLENGE_BYTES]; + // char random[16]; +#endif + }; +#if LIBCAT_SECURITY==1 + bool GenerateConnectionRequestChallenge(RequestedConnectionStruct *rcs,PublicKey *publicKey); +#endif + + //DataStructures::List* > automaticVariableSynchronizationList; + DataStructures::List banList; + // Threadsafe, and not thread safe + DataStructures::List pluginListTS, pluginListNTS; + + DataStructures::Queue requestedConnectionQueue; + SimpleMutex requestedConnectionQueueMutex; + + // void RunMutexedUpdateCycle(void); + + struct BufferedCommandStruct + { + BitSize_t numberOfBitsToSend; + PacketPriority priority; + PacketReliability reliability; + char orderingChannel; + AddressOrGUID systemIdentifier; + bool broadcast; + RemoteSystemStruct::ConnectMode connectionMode; + NetworkID networkID; + bool blockingCommand; // Only used for RPC + char *data; + bool haveRakNetCloseSocket; + unsigned connectionSocketIndex; + unsigned short remotePortRakNetWasStartedOn_PS3; + unsigned int extraSocketOptions; + RakNetSocket2* socket; + unsigned short port; + uint32_t receipt; + enum {BCS_SEND, BCS_CLOSE_CONNECTION, BCS_GET_SOCKET, BCS_CHANGE_SYSTEM_ADDRESS,/* BCS_USE_USER_SOCKET, BCS_REBIND_SOCKET_ADDRESS, BCS_RPC, BCS_RPC_SHIFT,*/ BCS_DO_NOTHING} command; + }; + + // Single producer single consumer queue using a linked list + //BufferedCommandStruct* bufferedCommandReadIndex, bufferedCommandWriteIndex; + + DataStructures::ThreadsafeAllocatingQueue bufferedCommands; + + + // DataStructures::ThreadsafeAllocatingQueue bufferedPackets; + + DataStructures::Queue bufferedPacketsFreePool; + RakNet::SimpleMutex bufferedPacketsFreePoolMutex; + DataStructures::Queue bufferedPacketsQueue; + RakNet::SimpleMutex bufferedPacketsQueueMutex; + + virtual void DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line); + virtual RNS2RecvStruct *AllocRNS2RecvStruct(const char *file, unsigned int line); + void SetupBufferedPackets(void); + void PushBufferedPacket(RNS2RecvStruct * p); + RNS2RecvStruct *PopBufferedPacket(void); + + struct SocketQueryOutput + { + SocketQueryOutput() {} + ~SocketQueryOutput() {} + DataStructures::List sockets; + }; + + DataStructures::ThreadsafeAllocatingQueue socketQueryOutput; + + + bool AllowIncomingConnections(void) const; + + void PingInternal( const SystemAddress target, bool performImmediate, PacketReliability reliability ); + // This stores the user send calls to be handled by the update thread. This way we don't have thread contention over systemAddresss + void CloseConnectionInternal( const AddressOrGUID& systemIdentifier, bool sendDisconnectionNotification, bool performImmediate, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority ); + void SendBuffered( const char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ); + void SendBufferedList( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ); + bool SendImmediate( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool useCallerDataAllocation, RakNet::TimeUS currentTime, uint32_t receipt ); + //bool HandleBufferedRPC(BufferedCommandStruct *bcs, RakNet::TimeMS time); + void ClearBufferedCommands(void); + void ClearBufferedPackets(void); + void ClearSocketQueryOutput(void); + void ClearRequestedConnectionList(void); + void AddPacketToProducer(RakNet::Packet *p); + unsigned int GenerateSeedFromGuid(void); + RakNet::Time GetClockDifferentialInt(RemoteSystemStruct *remoteSystem) const; + SimpleMutex securityExceptionMutex; + + //DataStructures::AVLBalancedBinarySearchTree rpcTree; + int defaultMTUSize; + bool trackFrequencyTable; + + // Smart pointer so I can return the object to the user + DataStructures::List socketList; + void DerefAllSockets(void); + unsigned int GetRakNetSocketFromUserConnectionSocketIndex(unsigned int userIndex) const; + // Used for RPC replies + RakNet::BitStream *replyFromTargetBS; + SystemAddress replyFromTargetPlayer; + bool replyFromTargetBroadcast; + + RakNet::TimeMS defaultTimeoutTime; + + // Generate and store a unique GUID + void GenerateGUID(void); + unsigned int GetSystemIndexFromGuid( const RakNetGUID input ) const; + RakNetGUID myGuid; + + unsigned maxOutgoingBPS; + + // Nobody would use the internet simulator in a final build. +#ifdef _DEBUG + double _packetloss; + unsigned short _minExtraPing, _extraPingVariance; +#endif + + ///How long it has been since things were updated by a call to receiveUpdate thread uses this to determine how long to sleep for + //unsigned int lastUserUpdateCycle; + /// True to allow connection accepted packets from anyone. False to only allow these packets from servers we requested a connection to. + bool allowConnectionResponseIPMigration; + + SystemAddress firstExternalID; + int splitMessageProgressInterval; + RakNet::TimeMS unreliableTimeout; + + bool (*incomingDatagramEventHandler)(RNS2RecvStruct *); + + // Systems in this list will not go through the secure connection process, even when secure connections are turned on. Wildcards are accepted. + DataStructures::List securityExceptionList; + + SystemAddress ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ]; + + bool allowInternalRouting; + + void (*userUpdateThreadPtr)(RakPeerInterface *, void *); + void *userUpdateThreadData; + + + SignaledEvent quitAndDataEvents; + bool limitConnectionFrequencyFromTheSameIP; + + SimpleMutex packetAllocationPoolMutex; + DataStructures::MemoryPool packetAllocationPool; + + SimpleMutex packetReturnMutex; + DataStructures::Queue packetReturnQueue; + Packet *AllocPacket(unsigned dataSize, const char *file, unsigned int line); + Packet *AllocPacket(unsigned dataSize, unsigned char *data, const char *file, unsigned int line); + + /// This is used to return a number to the user when they call Send identifying the message + /// This number will be returned back with ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS and is only returned + /// with the reliability types that contain RECEIPT in the name + SimpleMutex sendReceiptSerialMutex; + uint32_t sendReceiptSerial; + void ResetSendReceipt(void); + void OnConnectedPong(RakNet::Time sendPingTime, RakNet::Time sendPongTime, RemoteSystemStruct *remoteSystem); + void CallPluginCallbacks(DataStructures::List &pluginList, Packet *packet); + +#if LIBCAT_SECURITY==1 + // Encryption and security + bool _using_security, _require_client_public_key; + char my_public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; + cat::ServerEasyHandshake *_server_handshake; + cat::CookieJar *_cookie_jar; + bool InitializeClientSecurity(RequestedConnectionStruct *rcs, const char *public_key); +#endif + + + + + + + virtual void OnRNS2Recv(RNS2RecvStruct *recvStruct); + void FillIPList(void); +} +// #if defined(SN_TARGET_PSP2) +// __attribute__((aligned(8))) +// #endif +; + +} // namespace RakNet + +#endif diff --git a/include/raknet/RakPeerInterface.hpp b/include/raknet/RakPeerInterface.hpp new file mode 100644 index 0000000..895b71f --- /dev/null +++ b/include/raknet/RakPeerInterface.hpp @@ -0,0 +1,616 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief An interface for RakPeer. Simply contains all user functions as pure virtuals. +/// + + + +#ifndef __RAK_PEER_INTERFACE_H +#define __RAK_PEER_INTERFACE_H + +#include "PacketPriority.hpp" +#include "RakNetTypes.hpp" +#include "RakMemoryOverride.hpp" +#include "Export.hpp" +#include "DS_List.hpp" +#include "RakNetSmartPtr.hpp" +#include "RakNetSocket2.hpp" + +namespace RakNet +{ +// Forward declarations +class BitStream; +class PluginInterface2; +struct RPCMap; +struct RakNetStatistics; +struct RakNetBandwidth; +class RouterInterface; +class NetworkIDManager; + +/// The primary interface for RakNet, RakPeer contains all major functions for the library. +/// See the individual functions for what the class can do. +/// \brief The main interface for network communications +class RAK_DLL_EXPORT RakPeerInterface +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(RakPeerInterface) + + ///Destructor + virtual ~RakPeerInterface() {} + + // --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users-------------------------------------------------------------------------------------------- + /// \brief Starts the network threads, opens the listen port. + /// \details You must call this before calling Connect(). + /// \pre On the PS3, call Startup() after Client_Login() + /// \pre On Android, add the necessary permission to your application's androidmanifest.xml: + /// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown(). + /// \note Call SetMaximumIncomingConnections if you want to accept incoming connections + /// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections + /// \param[in] localPort The port to listen for connections on. On linux the system may be set up so thast ports under 1024 are restricted for everything but the root user. Use a higher port for maximum compatibility. + /// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); However, on the XBOX be sure to use IPPROTO_VDP + /// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass. + /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. + /// \return RAKNET_STARTED on success, otherwise appropriate failure enumeration. + virtual StartupResult Startup( unsigned int maxConnections, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority=-99999 )=0; + + /// If you accept connections, you must call this or else security will not be enabled for incoming connections. + /// This feature requires more round trips, bandwidth, and CPU time for the connection handshake + /// x64 builds require under 25% of the CPU time of other builds + /// See the Encryption sample for example usage + /// \pre Must be called while offline + /// \pre LIBCAT_SECURITY must be defined to 1 in NativeFeatureIncludes.h for this function to have any effect + /// \param[in] publicKey A pointer to the public key for accepting new connections + /// \param[in] privateKey A pointer to the private key for accepting new connections + /// \param[in] bRequireClientKey: Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection + virtual bool InitializeSecurity( const char *publicKey, const char *privateKey, bool bRequireClientKey = false )=0; + + /// Disables security for incoming connections. + /// \note Must be called while offline + virtual void DisableSecurity( void )=0; + + /// If secure connections are on, do not use secure connections for a specific IP address. + /// This is useful if you have a fixed-address internal server behind a LAN. + /// \note Secure connections are determined by the recipient of an incoming connection. This has no effect if called on the system attempting to connect. + /// \param[in] ip IP address to add. * wildcards are supported. + virtual void AddToSecurityExceptionList(const char *ip)=0; + + /// Remove a specific connection previously added via AddToSecurityExceptionList + /// \param[in] ip IP address to remove. Pass 0 to remove all IP addresses. * wildcards are supported. + virtual void RemoveFromSecurityExceptionList(const char *ip)=0; + + /// Checks to see if a given IP is in the security exception list + /// \param[in] IP address to check. + virtual bool IsInSecurityExceptionList(const char *ip)=0; + + /// Sets how many incoming connections are allowed. If this is less than the number of players currently connected, + /// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed, + /// it will be reduced to the maximum number of peers allowed. + /// Defaults to 0, meaning by default, nobody can connect to you + /// \param[in] numberAllowed Maximum number of incoming connections allowed. + virtual void SetMaximumIncomingConnections( unsigned short numberAllowed )=0; + + /// Returns the value passed to SetMaximumIncomingConnections() + /// \return the maximum number of incoming connections, which is always <= maxConnections + virtual unsigned int GetMaximumIncomingConnections( void ) const=0; + + /// Returns how many open connections there are at this time + /// \return the number of open connections + virtual unsigned short NumberOfConnections(void) const=0; + + /// Sets the password incoming connections must match in the call to Connect (defaults to none). Pass 0 to passwordData to specify no password + /// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections + /// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data + /// \param[in] passwordDataLength The length in bytes of passwordData + virtual void SetIncomingPassword( const char* passwordData, int passwordDataLength )=0; + + /// Gets the password passed to SetIncomingPassword + /// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword() + /// \param[in,out] passwordDataLength Maximum size of the array passwordData. Modified to hold the number of bytes actually written + virtual void GetIncomingPassword( char* passwordData, int *passwordDataLength )=0; + + /// \brief Connect to the specified host (ip or domain name) and server port. + /// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. + /// Calling both acts as a true peer. This is a non-blocking connection. + /// You know the connection is successful when GetConnectionState() returns IS_CONNECTED or Receive() gets a message with the type identifier ID_CONNECTION_REQUEST_ACCEPTED. + /// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen. + /// \pre Requires that you first call Startup() + /// \param[in] host Either a dotted IP address or a domain name + /// \param[in] remotePort Which port to connect to on the remote machine. + /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. + /// \param[in] passwordDataLength The length in bytes of passwordData + /// \param[in] publicKey The public key the server is using. If 0, the server is not using security. If non-zero, the publicKeyMode member determines how to connect + /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. + /// \param[in] sendConnectionAttemptCount How many datagrams to send to the other system to try to connect. + /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. + /// \param[in] timeoutTime How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); + /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. + /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! + /// \note It is possible to immediately get back ID_CONNECTION_ATTEMPT_FAILED if you exceed the maxConnections parameter passed to Startup(). This could happen if you call CloseConnection() with sendDisconnectionNotificaiton true, then immediately call Connect() before the connection has closed. + virtual ConnectionAttemptResult Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey=0, unsigned connectionSocketIndex=0, unsigned sendConnectionAttemptCount=12, unsigned timeBetweenSendConnectionAttemptsMS=500, RakNet::TimeMS timeoutTime=0 )=0; + + /// \brief Connect to the specified host (ip or domain name) and server port, using a shared socket from another instance of RakNet + /// \param[in] host Either a dotted IP address or a domain name + /// \param[in] remotePort Which port to connect to on the remote machine. + /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. + /// \param[in] passwordDataLength The length in bytes of passwordData + /// \param[in] socket A bound socket returned by another instance of RakPeerInterface + /// \param[in] sendConnectionAttemptCount How many datagrams to send to the other system to try to connect. + /// \param[in] timeBetweenSendConnectionAttemptsMS Time to elapse before a datagram is sent to the other system to try to connect. After sendConnectionAttemptCount number of attempts, ID_CONNECTION_ATTEMPT_FAILED is returned. Under low bandwidth conditions with multiple simultaneous outgoing connections, this value should be raised to 1000 or higher, or else the MTU detection can overrun the available bandwidth. + /// \param[in] timeoutTime How long to keep the connection alive before dropping it on unable to send a reliable message. 0 to use the default from SetTimeoutTime(UNASSIGNED_SYSTEM_ADDRESS); + /// \return CONNECTION_ATTEMPT_STARTED on successful initiation. Otherwise, an appropriate enumeration indicating failure. + /// \note CONNECTION_ATTEMPT_STARTED does not mean you are already connected! + virtual ConnectionAttemptResult ConnectWithSocket(const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSocket2* socket, PublicKey *publicKey=0, unsigned sendConnectionAttemptCount=12, unsigned timeBetweenSendConnectionAttemptsMS=500, RakNet::TimeMS timeoutTime=0)=0; + + /// \brief Connect to the specified network ID (Platform specific console function) + /// \details Does built-in NAt traversal + /// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password. + /// \param[in] passwordDataLength The length in bytes of passwordData + //virtual bool Console2LobbyConnect( void *networkServiceId, const char *passwordData, int passwordDataLength )=0; + + /// \brief Stops the network threads and closes all connections. + /// \param[in] blockDuration How long, in milliseconds, you should wait for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all. + /// \param[in] orderingChannel If blockDuration > 0, ID_DISCONNECTION_NOTIFICATION will be sent on this channel + /// \param[in] disconnectionNotificationPriority Priority to send ID_DISCONNECTION_NOTIFICATION on. + /// If you set it to 0 then the disconnection notification won't be sent + virtual void Shutdown( unsigned int blockDuration, unsigned char orderingChannel=0, PacketPriority disconnectionNotificationPriority=LOW_PRIORITY )=0; + + /// Returns if the network thread is running + /// \return true if the network thread is running, false otherwise + virtual bool IsActive( void ) const=0; + + /// Fills the array remoteSystems with the SystemAddress of all the systems we are connected to + /// \param[out] remoteSystems An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to + /// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array + virtual bool GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const=0; + + /// Returns the next uint32_t that Send() will return + /// \note If using RakPeer from multiple threads, this may not be accurate for your thread. Use IncrementNextSendReceipt() in that case. + /// \return The next uint32_t that Send() or SendList will return + virtual uint32_t GetNextSendReceipt(void)=0; + + /// Returns the next uint32_t that Send() will return, and increments the value by one + /// \note If using RakPeer from multiple threads, pass this to forceReceipt in the send function + /// \return The next uint32_t that Send() or SendList will return + virtual uint32_t IncrementNextSendReceipt(void)=0; + + /// Sends a block of data to the specified system that you are connected to. + /// This function only works while connected + /// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM + /// \param[in] data The block of data to send + /// \param[in] length The size in bytes of the data to send + /// \param[in] priority What priority level to send on. See PacketPriority.h + /// \param[in] reliability How reliability to send this data. See PacketPriority.h + /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream + /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none + /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. + /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. + /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number + virtual uint32_t Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 )=0; + + /// "Send" to yourself rather than a remote system. The message will be processed through the plugins and returned to the game as usual + /// This function works anytime + /// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM + /// \param[in] data The block of data to send + /// \param[in] length The size in bytes of the data to send + virtual void SendLoopback( const char *data, const int length )=0; + + /// Sends a block of data to the specified system that you are connected to. Same as the above version, but takes a BitStream as input. + /// \param[in] bitStream The bitstream to send + /// \param[in] priority What priority level to send on. See PacketPriority.h + /// \param[in] reliability How reliability to send this data. See PacketPriority.h + /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream + /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none + /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. + /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. + /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number + /// \note COMMON MISTAKE: When writing the first byte, bitStream->Write((unsigned char) ID_MY_TYPE) be sure it is casted to a byte, and you are not writing a 4 byte enumeration. + virtual uint32_t Send( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 )=0; + + /// Sends multiple blocks of data, concatenating them automatically. + /// + /// This is equivalent to: + /// RakNet::BitStream bs; + /// bs.WriteAlignedBytes(block1, blockLength1); + /// bs.WriteAlignedBytes(block2, blockLength2); + /// bs.WriteAlignedBytes(block3, blockLength3); + /// Send(&bs, ...) + /// + /// This function only works while connected + /// \param[in] data An array of pointers to blocks of data + /// \param[in] lengths An array of integers indicating the length of each block of data + /// \param[in] numParameters Length of the arrays data and lengths + /// \param[in] priority What priority level to send on. See PacketPriority.h + /// \param[in] reliability How reliability to send this data. See PacketPriority.h + /// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream + /// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none + /// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. + /// \param[in] forceReceipt If 0, will automatically determine the receipt number to return. If non-zero, will return what you give it. + /// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number + virtual uint32_t SendList( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber=0 )=0; + + /// Gets a message from the incoming message queue. + /// Use DeallocatePacket() to deallocate the message after you are done with it. + /// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here. + /// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet. + /// \note COMMON MISTAKE: Be sure to call this in a loop, once per game tick, until it returns 0. If you only process one packet per game tick they will buffer up. + /// sa RakNetTypes.h contains struct Packet + virtual Packet* Receive( void )=0; + + /// Call this to deallocate a message returned by Receive() when you are done handling it. + /// \param[in] packet The message to deallocate. + virtual void DeallocatePacket( Packet *packet )=0; + + /// Return the total number of connections we are allowed + virtual unsigned int GetMaximumNumberOfPeers( void ) const=0; + + // -------------------------------------------------------------------------------------------- Connection Management Functions-------------------------------------------------------------------------------------------- + /// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out). + /// \param[in] target Which system to close the connection to. + /// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently. + /// \param[in] channel Which ordering channel to send the disconnection notification on, if any + /// \param[in] disconnectionNotificationPriority Priority to send ID_DISCONNECTION_NOTIFICATION on. + virtual void CloseConnection( const AddressOrGUID target, bool sendDisconnectionNotification, unsigned char orderingChannel=0, PacketPriority disconnectionNotificationPriority=LOW_PRIORITY )=0; + + /// Returns if a system is connected, disconnected, connecting in progress, or various other states + /// \param[in] systemIdentifier The system we are referring to + /// \note This locks a mutex, do not call too frequently during connection attempts or the attempt will take longer and possibly even timeout + /// \return What state the remote system is in + virtual ConnectionState GetConnectionState(const AddressOrGUID systemIdentifier)=0; + + /// Cancel a pending connection attempt + /// If we are already connected, the connection stays open + /// \param[in] target Which system to cancel + virtual void CancelConnectionAttempt( const SystemAddress target )=0; + + /// Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1. + /// \param[in] systemAddress The SystemAddress we are referring to + /// \return The index of this SystemAddress or -1 on system not found. + virtual int GetIndexFromSystemAddress( const SystemAddress systemAddress ) const=0; + + /// This function is only useful for looping through all systems + /// Given an index, will return a SystemAddress. + /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. + /// \return The SystemAddress + virtual SystemAddress GetSystemAddressFromIndex( unsigned int index )=0; + + /// Same as GetSystemAddressFromIndex but returns RakNetGUID + /// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. + /// \return The RakNetGUID + virtual RakNetGUID GetGUIDFromIndex( unsigned int index )=0; + + /// Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient + /// Indices match each other, so \a addresses[0] and \a guids[0] refer to the same system + /// \param[out] addresses All system addresses. Size of the list is the number of connections. Size of the list will match the size of the \a guids list. + /// \param[out] guids All guids. Size of the list is the number of connections. Size of the list will match the size of the \a addresses list. + virtual void GetSystemList(DataStructures::List &addresses, DataStructures::List &guids) const=0; + + /// Bans an IP from connecting. Banned IPs persist between connections but are not saved on shutdown nor loaded on startup. + /// param[in] IP Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban all IP addresses starting with 128.0.0 + /// \param[in] milliseconds how many ms for a temporary ban. Use 0 for a permanent ban + virtual void AddToBanList( const char *IP, RakNet::TimeMS milliseconds=0 )=0; + + /// Allows a previously banned IP to connect. + /// param[in] Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will banAll IP addresses starting with 128.0.0 + virtual void RemoveFromBanList( const char *IP )=0; + + /// Allows all previously banned IPs to connect. + virtual void ClearBanList( void )=0; + + /// Returns true or false indicating if a particular IP is banned. + /// \param[in] IP - Dotted IP address. + /// \return true if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise. + virtual bool IsBanned( const char *IP )=0; + + /// Enable or disable allowing frequent connections from the same IP adderss + /// This is a security measure which is disabled by default, but can be set to true to prevent attackers from using up all connection slots + /// \param[in] b True to limit connections from the same ip to at most 1 per 100 milliseconds. + virtual void SetLimitIPConnectionFrequency(bool b)=0; + + // --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism-------------------------------------------------------------------------------------------- + /// Send a ping to the specified connected system. + /// \pre The sender and recipient must already be started via a successful call to Startup() + /// \param[in] target Which system to ping + virtual void Ping( const SystemAddress target )=0; + + /// Send a ping to the specified unconnected system. The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(RakNet::TimeMS) containing the system time the ping was sent.(Default is 4 bytes - See __GET_TIME_64BIT in RakNetTypes.h + /// System should reply with ID_PONG if it is active + /// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast. + /// \param[in] remotePort Which port to connect to on the remote machine. + /// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections + /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. + /// \return true on success, false on failure (unknown hostname) + virtual bool Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex=0 )=0; + + /// Returns the average of all ping times read for the specific system or -1 if none read yet + /// \param[in] systemAddress Which system we are referring to + /// \return The ping time for this system, or -1 + virtual int GetAveragePing( const AddressOrGUID systemIdentifier )=0; + + /// Returns the last ping time read for the specific system or -1 if none read yet + /// \param[in] systemAddress Which system we are referring to + /// \return The last ping time for this system, or -1 + virtual int GetLastPing( const AddressOrGUID systemIdentifier ) const=0; + + /// Returns the lowest ping time read or -1 if none read yet + /// \param[in] systemAddress Which system we are referring to + /// \return The lowest ping time for this system, or -1 + virtual int GetLowestPing( const AddressOrGUID systemIdentifier ) const=0; + + /// Ping the remote systems every so often, or not. Can be called anytime. + /// By default this is true. Recommended to leave on, because congestion control uses it to determine how often to resend lost packets. + /// It would be true by default to prevent timestamp drift, since in the event of a clock spike, the timestamp deltas would no longer be accurate + /// \param[in] doPing True to start occasional pings. False to stop them. + virtual void SetOccasionalPing( bool doPing )=0; + + /// Return the clock difference between your system and the specified system + /// Subtract GetClockDifferential() from a time returned by the remote system to get that time relative to your own system + /// Returns 0 if the system is unknown + /// \param[in] systemIdentifier Which system we are referring to + virtual RakNet::Time GetClockDifferential( const AddressOrGUID systemIdentifier )=0; + + // --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory-------------------------------------------------------------------------------------------- + /// Sets the data to send along with a LAN server discovery or offline ping reply. + /// \a length should be under 400 bytes, as a security measure against flood attacks + /// \param[in] data a block of data to store, or 0 for none + /// \param[in] length The length of data in bytes, or 0 for none + /// \sa Ping.cpp + virtual void SetOfflinePingResponse( const char *data, const unsigned int length )=0; + + /// Returns pointers to a copy of the data passed to SetOfflinePingResponse + /// \param[out] data A pointer to a copy of the data passed to \a SetOfflinePingResponse() + /// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse() + /// \sa SetOfflinePingResponse + virtual void GetOfflinePingResponse( char **data, unsigned int *length )=0; + + //--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general-------------------------------------------------------------------------------------------- + /// Return the unique address identifier that represents you or another system on the the network and is based on your local IP / port. + /// \note Not supported by the XBOX + /// \param[in] systemAddress Use UNASSIGNED_SYSTEM_ADDRESS to get your behind-LAN address. Use a connected system to get their behind-LAN address + /// \param[in] index When you have multiple internal IDs, which index to return? Currently limited to MAXIMUM_NUMBER_OF_INTERNAL_IDS (so the maximum value of this variable is MAXIMUM_NUMBER_OF_INTERNAL_IDS-1) + /// \return the identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy + virtual SystemAddress GetInternalID( const SystemAddress systemAddress=UNASSIGNED_SYSTEM_ADDRESS, const int index=0 ) const=0; + + /// \brief Sets your internal IP address, for platforms that do not support reading it, or to override a value + /// \param[in] systemAddress. The address to set. Use SystemAddress::FromString() if you want to use a dotted string + /// \param[in] index When you have multiple internal IDs, which index to set? + virtual void SetInternalID(SystemAddress systemAddress, int index=0)=0; + + /// Return the unique address identifier that represents you on the the network and is based on your externalIP / port + /// (the IP / port the specified player uses to communicate with you) + /// \param[in] target Which remote system you are referring to for your external ID. Usually the same for all systems, unless you have two or more network cards. + virtual SystemAddress GetExternalID( const SystemAddress target ) const=0; + + /// Return my own GUID + virtual const RakNetGUID GetMyGUID(void) const=0; + + /// Return the address bound to a socket at the specified index + virtual SystemAddress GetMyBoundAddress(const int socketIndex=0)=0; + + /// Get a random number (to generate a GUID) + static uint64_t Get64BitUniqueRandomNumber(void); + + /// Given a connected system, give us the unique GUID representing that instance of RakPeer. + /// This will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different + /// Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won't change. + /// Returns UNASSIGNED_RAKNET_GUID if system address can't be found. + /// If \a input is UNASSIGNED_SYSTEM_ADDRESS, will return your own GUID + /// \pre Call Startup() first, or the function will return UNASSIGNED_RAKNET_GUID + /// \param[in] input The system address of the system we are connected to + virtual const RakNetGUID& GetGuidFromSystemAddress( const SystemAddress input ) const=0; + + /// Given the GUID of a connected system, give us the system address of that system. + /// The GUID will be the same on all systems connected to that instance of RakPeer, even if the external system addresses are different + /// Currently O(log(n)), but this may be improved in the future. If you use this frequently, you may want to cache the value as it won't change. + /// If \a input is UNASSIGNED_RAKNET_GUID, will return UNASSIGNED_SYSTEM_ADDRESS + /// \param[in] input The RakNetGUID of the system we are checking to see if we are connected to + virtual SystemAddress GetSystemAddressFromGuid( const RakNetGUID input ) const=0; + + /// Given the SystemAddress of a connected system, get the public key they provided as an identity + /// Returns false if system address was not found or client public key is not known + /// \param[in] input The RakNetGUID of the system + /// \param[in] client_public_key The connected client's public key is copied to this address. Buffer must be cat::EasyHandshake::PUBLIC_KEY_BYTES bytes in length. + virtual bool GetClientPublicKeyFromSystemAddress( const SystemAddress input, char *client_public_key ) const=0; + + /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message. + /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. + /// Do not set different values for different computers that are connected to each other, or you won't be able to reconnect after ID_CONNECTION_LOST + /// \param[in] timeMS Time, in MS + /// \param[in] target Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS for all systems. + virtual void SetTimeoutTime( RakNet::TimeMS timeMS, const SystemAddress target )=0; + + /// \param[in] target Which system to do this for. Pass UNASSIGNED_SYSTEM_ADDRESS to get the default value + /// \return timeoutTime for a given system. + virtual RakNet::TimeMS GetTimeoutTime( const SystemAddress target )=0; + + /// Returns the current MTU size + /// \param[in] target Which system to get this for. UNASSIGNED_SYSTEM_ADDRESS to get the default + /// \return The current MTU size + virtual int GetMTUSize( const SystemAddress target ) const=0; + + /// Returns the number of IP addresses this system has internally. Get the actual addresses from GetLocalIP() + virtual unsigned GetNumberOfAddresses( void )=0; + + /// Returns an IP address at index 0 to GetNumberOfAddresses-1 + /// \param[in] index index into the list of IP addresses + /// \return The local IP address at this index + virtual const char* GetLocalIP( unsigned int index )=0; + + /// Is this a local IP? + /// \param[in] An IP address to check, excluding the port + /// \return True if this is one of the IP addresses returned by GetLocalIP + virtual bool IsLocalIP( const char *ip )=0; + + /// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary + /// when connecting to servers with multiple IP addresses. + /// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections + virtual void AllowConnectionResponseIPMigration( bool allow )=0; + + /// Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system. + /// This will tell the remote system our external IP outside the LAN along with some user data. + /// \pre The sender and recipient must already be started via a successful call to Initialize + /// \param[in] host Either a dotted IP address or a domain name + /// \param[in] remotePort Which port to connect to on the remote machine. + /// \param[in] data Optional data to append to the packet. + /// \param[in] dataLength length of data in bytes. Use 0 if no data. + /// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. + /// \return false if IsActive()==false or the host is unresolvable. True otherwise + virtual bool AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex=0 )=0; + + /// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. + /// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived + /// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. + /// Defaults to 0 (never return this notification) + /// \param[in] interval How many messages to use as an interval + virtual void SetSplitMessageProgressInterval(int interval)=0; + + /// Returns what was passed to SetSplitMessageProgressInterval() + /// \return What was passed to SetSplitMessageProgressInterval(). Default to 0. + virtual int GetSplitMessageProgressInterval(void) const=0; + + /// Set how long to wait before giving up on sending an unreliable message + /// Useful if the network is clogged up. + /// Set to 0 or less to never timeout. Defaults to 0. + /// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message. + virtual void SetUnreliableTimeout(RakNet::TimeMS timeoutMS)=0; + + /// Send a message to host, with the IP socket option TTL set to 3 + /// This message will not reach the host, but will open the router. + /// Used for NAT-Punchthrough + virtual void SendTTL( const char* host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex=0 )=0; + + // -------------------------------------------------------------------------------------------- Plugin Functions-------------------------------------------------------------------------------------------- + /// \brief Attaches a Plugin interface to an instance of the base class (RakPeer or PacketizedTCP) to run code automatically on message receipt in the Receive call. + /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. + /// \param[in] messageHandler Pointer to the plugin to attach. + virtual void AttachPlugin( PluginInterface2 *plugin )=0; + + /// \brief Detaches a Plugin interface from the instance of the base class (RakPeer or PacketizedTCP) it is attached to. + /// \details This method disables the plugin code from running automatically on base class's updates or message receipt. + /// If the plugin returns false from PluginInterface::UsesReliabilityLayer(), which is the case for all plugins except PacketLogger, you can call AttachPlugin() and DetachPlugin() for this plugin while RakPeer is active. + /// \param[in] messageHandler Pointer to a plugin to detach. + virtual void DetachPlugin( PluginInterface2 *messageHandler )=0; + + // --------------------------------------------------------------------------------------------Miscellaneous Functions-------------------------------------------------------------------------------------------- + /// Put a message back at the end of the receive queue in case you don't want to deal with it immediately + /// \param[in] packet The packet you want to push back. + /// \param[in] pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order) + virtual void PushBackPacket( Packet *packet, bool pushAtHead )=0; + + /// \internal + /// \brief For a given system identified by \a guid, change the SystemAddress to send to. + /// \param[in] guid The connection we are referring to + /// \param[in] systemAddress The new address to send to + virtual void ChangeSystemAddress(RakNetGUID guid, const SystemAddress &systemAddress)=0; + + /// \returns a packet for you to write to if you want to create a Packet for some reason. + /// You can add it to the receive buffer with PushBackPacket + /// \param[in] dataSize How many bytes to allocate for the buffer + /// \return A packet you can write to + virtual Packet* AllocatePacket(unsigned dataSize)=0; + + /// Get the socket used with a particular active connection + /// The smart pointer reference counts the RakNetSocket2 object, so the socket will remain active as long as the smart pointer does, even if RakNet were to shutdown or close the connection. + /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. + /// \param[in] target Which system + /// \return A smart pointer object containing the socket information about the socket. Be sure to check IsNull() which is returned if the update thread is unresponsive, shutting down, or if this system is not connected + virtual RakNetSocket2* GetSocket( const SystemAddress target )=0; + + /// Get all sockets in use + /// \note This sends a query to the thread and blocks on the return value for up to one second. In practice it should only take a millisecond or so. + /// \param[out] sockets List of RakNetSocket2 structures in use. Sockets will not be closed until \a sockets goes out of scope + virtual void GetSockets( DataStructures::List &sockets )=0; + virtual void ReleaseSockets( DataStructures::List &sockets )=0; + + virtual void WriteOutOfBandHeader(RakNet::BitStream *bitStream)=0; + + /// If you need code to run in the same thread as RakNet's update thread, this function can be used for that + /// \param[in] _userUpdateThreadPtr C callback function + /// \param[in] _userUpdateThreadData Passed to C callback function + virtual void SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface *, void *), void *_userUpdateThreadData)=0; + + /// Set a C callback to be called whenever a datagram arrives + /// Return true from the callback to have RakPeer handle the datagram. Return false and RakPeer will ignore the datagram. + /// This can be used to filter incoming datagrams by system, or to share a recvfrom socket with RakPeer + /// RNS2RecvStruct will only remain valid for the duration of the call + /// If the incoming datagram is not from your game at all, it is a RakNet packet. + /// If the incoming datagram has an IP address that matches a known address from your game, then check the first byte of data. + /// For RakNet connected systems, the first bit is always 1. So for your own game packets, make sure the first bit is always 0. + virtual void SetIncomingDatagramEventHandler( bool (*_incomingDatagramEventHandler)(RNS2RecvStruct *) )=0; + + // --------------------------------------------------------------------------------------------Network Simulator Functions-------------------------------------------------------------------------------------------- + /// Adds simulated ping and packet loss to the outgoing data flow. + /// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and packetloss value on each. + /// You can exclude network simulator code with the _RELEASE #define to decrease code size + /// \deprecated Use http://www.jenkinssoftware.com/forum/index.php?topic=1671.0 instead. + /// \note Doesn't work past version 3.6201 + /// \param[in] packetloss Chance to lose a packet. Ranges from 0 to 1. + /// \param[in] minExtraPing The minimum time to delay sends. + /// \param[in] extraPingVariance The additional random time to delay sends. + virtual void ApplyNetworkSimulator( float packetloss, unsigned short minExtraPing, unsigned short extraPingVariance)=0; + + /// Limits how much outgoing bandwidth can be sent per-connection. + /// This limit does not apply to the sum of all connections! + /// Exceeding the limit queues up outgoing traffic + /// \param[in] maxBitsPerSecond Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again. + virtual void SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond )=0; + + /// Returns if you previously called ApplyNetworkSimulator + /// \return If you previously called ApplyNetworkSimulator + virtual bool IsNetworkSimulatorActive( void )=0; + + // --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance-------------------------------------------------------------------------------------------- + + /// Returns a structure containing a large set of network statistics for the specified system. + /// You can map this data to a string using the C style StatisticsToString() function + /// \param[in] systemAddress: Which connected system to get statistics for + /// \param[in] rns If you supply this structure, it will be written to it. Otherwise it will use a static struct, which is not threadsafe + /// \return 0 on can't find the specified system. A pointer to a set of data otherwise. + /// \sa RakNetStatistics.h + virtual RakNetStatistics * GetStatistics( const SystemAddress systemAddress, RakNetStatistics *rns=0 )=0; + /// \brief Returns the network statistics of the system at the given index in the remoteSystemList. + /// \return True if the index is less than the maximum number of peers allowed and the system is active. False otherwise. + virtual bool GetStatistics( const unsigned int index, RakNetStatistics *rns )=0; + /// \brief Returns the list of systems, and statistics for each of those systems + /// Each system has one entry in each of the lists, in the same order + /// \param[out] addresses SystemAddress for each connected system + /// \param[out] guids RakNetGUID for each connected system + /// \param[out] statistics Calculated RakNetStatistics for each connected system + virtual void GetStatisticsList(DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &statistics)=0; + + /// \Returns how many messages are waiting when you call Receive() + virtual unsigned int GetReceiveBufferSize(void)=0; + + // --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY-------------------------------------------------------------------------------------------- + + /// \internal + // Call manually if RAKPEER_USER_THREADED==1 at least every 30 milliseconds. + // updateBitStream should be: + // BitStream updateBitStream( MAXIMUM_MTU_SIZE + // #if LIBCAT_SECURITY==1 + // + cat::AuthenticatedEncryption::OVERHEAD_BYTES + // #endif + // ); + virtual bool RunUpdateCycle( BitStream &updateBitStream )=0; + + /// \internal + virtual bool SendOutOfBand(const char *host, unsigned short remotePort, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex=0 )=0; + +} +// #if defined(SN_TARGET_PSP2) +// __attribute__((aligned(8))) +// #endif +; + +} // namespace RakNet + +#endif diff --git a/include/raknet/RakSleep.hpp b/include/raknet/RakSleep.hpp new file mode 100644 index 0000000..5d6e8ea --- /dev/null +++ b/include/raknet/RakSleep.hpp @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAK_SLEEP_H +#define __RAK_SLEEP_H + +#include "Export.hpp" + +void RAK_DLL_EXPORT RakSleep(unsigned int ms); + +#endif diff --git a/include/raknet/RakString.hpp b/include/raknet/RakString.hpp new file mode 100644 index 0000000..c856689 --- /dev/null +++ b/include/raknet/RakString.hpp @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAK_STRING_H +#define __RAK_STRING_H + +#include "Export.hpp" +#include "DS_List.hpp" +#include "RakNetTypes.hpp" // int64_t +#include +#include "stdarg.h" + + +#ifdef _WIN32 + + + +#include "WindowsIncludes.hpp" +#endif + +namespace RakNet +{ +/// Forward declarations +class SimpleMutex; +class BitStream; + +/// \brief String class +/// \details Has the following improvements over std::string +/// -Reference counting: Suitable to store in lists +/// -Variadic assignment operator +/// -Doesn't cause linker errors +class RAK_DLL_EXPORT RakString +{ +public: + // Constructors + RakString(); + RakString(char input); + RakString(unsigned char input); + RakString(const unsigned char *format, ...); + RakString(const char *format, ...); + ~RakString(); + RakString( const RakString & rhs); + + /// Implicit return of const char* + operator const char* () const {return sharedString->c_str;} + + /// Same as std::string::c_str + const char *C_String(void) const {return sharedString->c_str;} + + // Lets you modify the string. Do not make the string longer - however, you can make it shorter, or change the contents. + // Pointer is only valid in the scope of RakString itself + char *C_StringUnsafe(void) {Clone(); return sharedString->c_str;} + + /// Assigment operators + RakString& operator = ( const RakString& rhs ); + RakString& operator = ( const char *str ); + RakString& operator = ( char *str ); + RakString& operator = ( const unsigned char *str ); + RakString& operator = ( char unsigned *str ); + RakString& operator = ( const char c ); + + /// Concatenation + RakString& operator +=( const RakString& rhs); + RakString& operator += ( const char *str ); + RakString& operator += ( char *str ); + RakString& operator += ( const unsigned char *str ); + RakString& operator += ( char unsigned *str ); + RakString& operator += ( const char c ); + + /// Character index. Do not use to change the string however. + unsigned char operator[] ( const unsigned int position ) const; + +#ifdef _WIN32 + // Return as Wide char + // Deallocate with DeallocWideChar + WCHAR * ToWideChar(void); + void DeallocWideChar(WCHAR * w); + + void FromWideChar(const wchar_t *source); + static RakNet::RakString FromWideChar_S(const wchar_t *source); +#endif + + /// String class find replacement + /// Searches the string for the content specified in stringToFind and returns the position of the first occurrence in the string. + /// Search only includes characters on or after position pos, ignoring any possible occurrences in previous locations. + /// \param[in] stringToFind The string to find inside of this object's string + /// \param[in] pos The position in the string to start the search + /// \return Returns the position of the first occurrence in the string. + size_t Find(const char *stringToFind,size_t pos = 0 ); + + /// Equality + bool operator==(const RakString &rhs) const; + bool operator==(const char *str) const; + bool operator==(char *str) const; + + // Comparison + bool operator < ( const RakString& right ) const; + bool operator <= ( const RakString& right ) const; + bool operator > ( const RakString& right ) const; + bool operator >= ( const RakString& right ) const; + + /// Inequality + bool operator!=(const RakString &rhs) const; + bool operator!=(const char *str) const; + bool operator!=(char *str) const; + + /// Change all characters to lowercase + const char * ToLower(void); + + /// Change all characters to uppercase + const char * ToUpper(void); + + /// Set the value of the string + void Set(const char *format, ...); + + /// Sets a copy of a substring of str as the new content. The substring is the portion of str + /// that begins at the character position pos and takes up to n characters + /// (it takes less than n if the end of str is reached before). + /// \param[in] str The string to copy in + /// \param[in] pos The position on str to start the copy + /// \param[in] n How many chars to copy + /// \return Returns the string, note that the current string is set to that value as well + RakString Assign(const char *str,size_t pos, size_t n ); + + /// Returns if the string is empty. Also, C_String() would return "" + bool IsEmpty(void) const; + + /// Returns the length of the string + size_t GetLength(void) const; + size_t GetLengthUTF8(void) const; + + /// Replace character(s) in starting at index, for count, with c + void Replace(unsigned index, unsigned count, unsigned char c); + + /// Replace character at index with c + void SetChar( unsigned index, unsigned char c ); + + /// Replace character at index with string s + void SetChar( unsigned index, RakNet::RakString s ); + + /// Make sure string is no longer than \a length + void Truncate(unsigned int length); + void TruncateUTF8(unsigned int length); + + // Gets the substring starting at index for count characters + RakString SubStr(unsigned int index, unsigned int count) const; + + /// Erase characters out of the string at index for count + void Erase(unsigned int index, unsigned int count); + + /// Set the first instance of c with a NULL terminator + void TerminateAtFirstCharacter(char c); + /// Set the last instance of c with a NULL terminator + void TerminateAtLastCharacter(char c); + + void StartAfterFirstCharacter(char c); + void StartAfterLastCharacter(char c); + + /// Returns how many occurances there are of \a c in the string + int GetCharacterCount(char c); + + /// Remove all instances of c + void RemoveCharacter(char c); + + /// Create a RakString with a value, without doing printf style parsing + /// Equivalent to assignment operator + static RakNet::RakString NonVariadic(const char *str); + + /// Hash the string into an unsigned int + static unsigned long ToInteger(const char *str); + static unsigned long ToInteger(const RakString &rs); + + /// \brief Read an integer out of a substring + /// \param[in] str The string + /// \param[in] pos The position on str where the integer starts + /// \param[in] n How many chars to copy + static int ReadIntFromSubstring(const char *str, size_t pos, size_t n); + + // Like strncat, but for a fixed length + void AppendBytes(const char *bytes, unsigned int count); + + /// Compare strings (case sensitive) + int StrCmp(const RakString &rhs) const; + + /// Compare strings (case sensitive), up to num characters + int StrNCmp(const RakString &rhs, size_t num) const; + + /// Compare strings (not case sensitive) + int StrICmp(const RakString &rhs) const; + + /// Clear the string + void Clear(void); + + /// Print the string to the screen + void Printf(void); + + /// Print the string to a file + void FPrintf(FILE *fp); + + /// Does the given IP address match the IP address encoded into this string, accounting for wildcards? + bool IPAddressMatch(const char *IP); + + /// Does the string contain non-printable characters other than spaces? + bool ContainsNonprintableExceptSpaces(void) const; + + /// Is this a valid email address? + bool IsEmailAddress(void) const; + + /// URL Encode the string. See http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029/ + RakNet::RakString& URLEncode(void); + + /// URL decode the string + RakNet::RakString& URLDecode(void); + + /// https://servers.api.rackspacecloud.com/v1.0 to https://, servers.api.rackspacecloud.com, /v1.0 + void SplitURI(RakNet::RakString &header, RakNet::RakString &domain, RakNet::RakString &path); + + /// Scan for quote, double quote, and backslash and prepend with backslash + RakNet::RakString& SQLEscape(void); + + /// Format as a POST command that can be sent to a webserver + /// \param[in] uri For example, masterserver2.raknet.com/testServer + /// \param[in] contentType For example, text/plain; charset=UTF-8 + /// \param[in] body Body of the post + /// \return Formatted string + static RakNet::RakString FormatForPOST(const char* uri, const char* contentType, const char* body, const char* extraHeaders=""); + static RakNet::RakString FormatForPUT(const char* uri, const char* contentType, const char* body, const char* extraHeaders=""); + + /// Format as a GET command that can be sent to a webserver + /// \param[in] uri For example, masterserver2.raknet.com/testServer?__gameId=comprehensivePCGame + /// \return Formatted string + static RakNet::RakString FormatForGET(const char* uri, const char* extraHeaders=""); + + /// Format as a DELETE command that can be sent to a webserver + /// \param[in] uri For example, masterserver2.raknet.com/testServer?__gameId=comprehensivePCGame&__rowId=1 + /// \return Formatted string + static RakNet::RakString FormatForDELETE(const char* uri, const char* extraHeaders=""); + + /// Fix to be a file path, ending with / + RakNet::RakString& MakeFilePath(void); + + /// RakString uses a freeList of old no-longer used strings + /// Call this function to clear this memory on shutdown + static void FreeMemory(void); + /// \internal + static void FreeMemoryNoMutex(void); + + /// Serialize to a bitstream, uncompressed (slightly faster) + /// \param[out] bs Bitstream to serialize to + void Serialize(BitStream *bs) const; + + /// Static version of the Serialize function + static void Serialize(const char *str, BitStream *bs); + + /// Serialize to a bitstream, compressed (better bandwidth usage) + /// \param[out] bs Bitstream to serialize to + /// \param[in] languageId languageId to pass to the StringCompressor class + /// \param[in] writeLanguageId encode the languageId variable in the stream. If false, 0 is assumed, and DeserializeCompressed will not look for this variable in the stream (saves bandwidth) + /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) + void SerializeCompressed(BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false) const; + + /// Static version of the SerializeCompressed function + static void SerializeCompressed(const char *str, BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false); + + /// Deserialize what was written by Serialize + /// \param[in] bs Bitstream to serialize from + /// \return true if the deserialization was successful + bool Deserialize(BitStream *bs); + + /// Static version of the Deserialize() function + static bool Deserialize(char *str, BitStream *bs); + + /// Deserialize compressed string, written by SerializeCompressed + /// \param[in] bs Bitstream to serialize from + /// \param[in] readLanguageId If true, looks for the variable langaugeId in the data stream. Must match what was passed to SerializeCompressed + /// \return true if the deserialization was successful + /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) + bool DeserializeCompressed(BitStream *bs, bool readLanguageId=false); + + /// Static version of the DeserializeCompressed() function + static bool DeserializeCompressed(char *str, BitStream *bs, bool readLanguageId=false); + + static const char *ToString(int64_t i); + static const char *ToString(uint64_t i); + + /// \internal + static size_t GetSizeToAllocate(size_t bytes) + { + const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; + if (bytes<=smallStringSize) + return smallStringSize; + else + return bytes*2; + } + + /// \internal + struct SharedString + { + SimpleMutex *refCountMutex; + unsigned int refCount; + size_t bytesUsed; + char *bigString; + char *c_str; + char smallString[128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2]; + }; + + /// \internal + RakString( SharedString *_sharedString ); + + /// \internal + SharedString *sharedString; + +// static SimpleMutex poolMutex; +// static DataStructures::MemoryPool pool; + /// \internal + static SharedString emptyString; + + //static SharedString *sharedStringFreeList; + //static unsigned int sharedStringFreeListAllocationCount; + /// \internal + /// List of free objects to reduce memory reallocations + static DataStructures::List freeList; + + static int RakStringComp( RakString const &key, RakString const &data ); + + static void LockMutex(void); + static void UnlockMutex(void); + +protected: + static RakNet::RakString FormatForPUTOrPost(const char* type, const char* uri, const char* contentType, const char* body, const char* extraHeaders); + void Allocate(size_t len); + void Assign(const char *str); + void Assign(const char *str, va_list ap); + + void Clone(void); + void Free(void); + unsigned char ToLower(unsigned char c); + unsigned char ToUpper(unsigned char c); + void Realloc(SharedString *sharedString, size_t bytes); +}; + +} + +const RakNet::RakString RAK_DLL_EXPORT operator+(const RakNet::RakString &lhs, const RakNet::RakString &rhs); + + +#endif diff --git a/include/raknet/RakThread.hpp b/include/raknet/RakThread.hpp new file mode 100644 index 0000000..3387dbe --- /dev/null +++ b/include/raknet/RakThread.hpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAK_THREAD_H +#define __RAK_THREAD_H + +#if defined(_WIN32_WCE) +#include "WindowsIncludes.hpp" +#endif + + + + + +#include "Export.hpp" + + + + + + +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) +#include "../DependentExtensions/WinPhone8/ThreadEmulation.hpp" +using namespace ThreadEmulation; +#endif + +namespace RakNet +{ +/// To define a thread, use RAK_THREAD_DECLARATION(functionName); +#if defined(_WIN32_WCE) || defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) +#define RAK_THREAD_DECLARATION(functionName) DWORD WINAPI functionName(LPVOID arguments) + + +#elif defined(_WIN32) +#define RAK_THREAD_DECLARATION(functionName) unsigned __stdcall functionName( void* arguments ) + + +#else +#define RAK_THREAD_DECLARATION(functionName) void* functionName( void* arguments ) +#endif + +class RAK_DLL_EXPORT RakThread +{ +public: + + + + + /// Create a thread, simplified to be cross platform without all the extra junk + /// To then start that thread, call RakCreateThread(functionName, arguments); + /// \param[in] start_address Function you want to call + /// \param[in] arglist Arguments to pass to the function + /// \return 0=success. >0 = error code + + /* + nice value Win32 Priority + -20 to -16 THREAD_PRIORITY_HIGHEST + -15 to -6 THREAD_PRIORITY_ABOVE_NORMAL + -5 to +4 THREAD_PRIORITY_NORMAL + +5 to +14 THREAD_PRIORITY_BELOW_NORMAL + +15 to +19 THREAD_PRIORITY_LOWEST + */ +#if defined(_WIN32_WCE) || defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) + static int Create( LPTHREAD_START_ROUTINE start_address, void *arglist, int priority=0); + + +#elif defined(_WIN32) + static int Create( unsigned __stdcall start_address( void* ), void *arglist, int priority=0); + + + +#else + static int Create( void* start_address( void* ), void *arglist, int priority=0); +#endif + + + + + + + + + + + + + + + + + + + + +}; + +} + +#endif diff --git a/include/raknet/RakWString.hpp b/include/raknet/RakWString.hpp new file mode 100644 index 0000000..29380f0 --- /dev/null +++ b/include/raknet/RakWString.hpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __RAK_W_STRING_H +#define __RAK_W_STRING_H + +#include "Export.hpp" +#include "RakNetTypes.hpp" // int64_t +#include "RakString.hpp" + +#ifdef _WIN32 + + + +#include "WindowsIncludes.hpp" +#endif + +namespace RakNet +{ + /// \brief String class for Unicode + class RAK_DLL_EXPORT RakWString + { + public: + // Constructors + RakWString(); + RakWString( const RakString &right ); + RakWString( const wchar_t *input ); + RakWString( const RakWString & right); + RakWString( const char *input ); + ~RakWString(); + + /// Implicit return of wchar_t* + operator wchar_t* () const {if (c_str) return c_str; return (wchar_t*) L"";} + + /// Same as std::string::c_str + const wchar_t* C_String(void) const {if (c_str) return c_str; return (const wchar_t*) L"";} + + /// Assignment operators + RakWString& operator = ( const RakWString& right ); + RakWString& operator = ( const RakString& right ); + RakWString& operator = ( const wchar_t * const str ); + RakWString& operator = ( wchar_t *str ); + RakWString& operator = ( const char * const str ); + RakWString& operator = ( char *str ); + + /// Concatenation + RakWString& operator +=( const RakWString& right); + RakWString& operator += ( const wchar_t * const right ); + RakWString& operator += ( wchar_t *right ); + + /// Equality + bool operator==(const RakWString &right) const; + + // Comparison + bool operator < ( const RakWString& right ) const; + bool operator <= ( const RakWString& right ) const; + bool operator > ( const RakWString& right ) const; + bool operator >= ( const RakWString& right ) const; + + /// Inequality + bool operator!=(const RakWString &right) const; + + /// Set the value of the string + void Set( wchar_t *str ); + + /// Returns if the string is empty. Also, C_String() would return "" + bool IsEmpty(void) const; + + /// Returns the length of the string + size_t GetLength(void) const; + + /// Has the string into an unsigned int + static unsigned long ToInteger(const RakWString &rs); + + /// Compare strings (case sensitive) + int StrCmp(const RakWString &right) const; + + /// Compare strings (not case sensitive) + int StrICmp(const RakWString &right) const; + + /// Clear the string + void Clear(void); + + /// Print the string to the screen + void Printf(void); + + /// Print the string to a file + void FPrintf(FILE *fp); + + /// Serialize to a bitstream, uncompressed (slightly faster) + /// \param[out] bs Bitstream to serialize to + void Serialize(BitStream *bs) const; + + /// Static version of the Serialize function + static void Serialize(const wchar_t * const str, BitStream *bs); + + /// Deserialize what was written by Serialize + /// \param[in] bs Bitstream to serialize from + /// \return true if the deserialization was successful + bool Deserialize(BitStream *bs); + + /// Static version of the Deserialize() function + static bool Deserialize(wchar_t *str, BitStream *bs); + + + protected: + wchar_t* c_str; + size_t c_strCharLength; + }; + +} + +const RakNet::RakWString RAK_DLL_EXPORT operator+(const RakNet::RakWString &lhs, const RakNet::RakWString &rhs); + + +#endif diff --git a/include/raknet/Rand.hpp b/include/raknet/Rand.hpp new file mode 100644 index 0000000..884e0ec --- /dev/null +++ b/include/raknet/Rand.hpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] Random number generator +/// + + + +#ifndef __RAND_H +#define __RAND_H + +#include "Export.hpp" + +/// Initialise seed for Random Generator +/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread +/// \param[in] seed The seed value for the random number generator. +extern void RAK_DLL_EXPORT seedMT( unsigned int seed ); + +/// \internal +/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread +extern unsigned int RAK_DLL_EXPORT reloadMT( void ); + +/// Gets a random unsigned int +/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread +/// \return an integer random value. +extern unsigned int RAK_DLL_EXPORT randomMT( void ); + +/// Gets a random float +/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread +/// \return 0 to 1.0f, inclusive +extern float RAK_DLL_EXPORT frandomMT( void ); + +/// Randomizes a buffer +/// \note not threadSafe, use an instance of RakNetRandom if necessary per thread +extern void RAK_DLL_EXPORT fillBufferMT( void *buffer, unsigned int bytes ); + +namespace RakNet { + +// Same thing as above functions, but not global +class RAK_DLL_EXPORT RakNetRandom +{ +public: + RakNetRandom(); + ~RakNetRandom(); + void SeedMT( unsigned int seed ); + unsigned int ReloadMT( void ); + unsigned int RandomMT( void ); + float FrandomMT( void ); + void FillBufferMT( void *buffer, unsigned int bytes ); + +protected: + unsigned int state[ 624 + 1 ]; + unsigned int *next; + int left; +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/RandSync.hpp b/include/raknet/RandSync.hpp new file mode 100644 index 0000000..2a0c77a --- /dev/null +++ b/include/raknet/RandSync.hpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] Random number generator +/// + + + +#ifndef __RAND_SYNC_H +#define __RAND_SYNC_H + +#include "Export.hpp" +#include "Rand.hpp" +#include "DS_Queue.hpp" +#include "NativeTypes.hpp" + +namespace RakNet { + +class BitStream; + +class RAK_DLL_EXPORT RakNetRandomSync +{ +public: + RakNetRandomSync(); + virtual ~RakNetRandomSync(); + void SeedMT( uint32_t _seed ); + void SeedMT( uint32_t _seed, uint32_t skipValues ); + float FrandomMT( void ); + unsigned int RandomMT( void ); + uint32_t GetSeed( void ) const; + uint32_t GetCallCount( void ) const; + void SetCallCount( uint32_t i ); + + virtual void SerializeConstruction(RakNet::BitStream *constructionBitstream); + virtual bool DeserializeConstruction(RakNet::BitStream *constructionBitstream); + virtual void Serialize(RakNet::BitStream *outputBitstream); + virtual void Deserialize(RakNet::BitStream *outputBitstream); + +protected: + void Skip( uint32_t count ); + DataStructures::Queue usedValues; + uint32_t seed; + uint32_t callCount; + uint32_t usedValueBufferCount; + RakNetRandom rnr; +}; +} // namespace RakNet + + +#endif diff --git a/include/raknet/ReadyEvent.hpp b/include/raknet/ReadyEvent.hpp new file mode 100644 index 0000000..e4cb243 --- /dev/null +++ b/include/raknet/ReadyEvent.hpp @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Ready event plugin. This enables a set of systems to create a signal event, set this signal as ready or unready, and to trigger the event when all systems are ready +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_ReadyEvent==1 + +#ifndef __READY_EVENT_H +#define __READY_EVENT_H + +#include "PluginInterface2.hpp" +#include "DS_OrderedList.hpp" + +namespace RakNet { + +class RakPeerInterface; + +/// \defgroup READY_EVENT_GROUP ReadyEvent +/// \brief Peer to peer synchronized ready and unready events +/// \details +/// \ingroup PLUGINS_GROUP + +/// \ingroup READY_EVENT_GROUP +/// Returns the status of a remote system when querying with ReadyEvent::GetReadyStatus +enum ReadyEventSystemStatus +{ + /// ----------- Normal states --------------- + /// The remote system is not in the wait list, and we have never gotten a ready or complete message from it. + /// This is the default state for valid events + RES_NOT_WAITING, + /// We are waiting for this remote system to call SetEvent(thisEvent,true). + RES_WAITING, + /// The remote system called SetEvent(thisEvent,true), but it still waiting for other systems before completing the ReadyEvent. + RES_READY, + /// The remote system called SetEvent(thisEvent,true), and is no longer waiting for any other systems. + /// This remote system has completed the ReadyEvent + RES_ALL_READY, + + /// Error code, we couldn't look up the system because the event was unknown + RES_UNKNOWN_EVENT, +}; + +/// \brief Peer to peer synchronized ready and unready events +/// \details For peer to peer networks in a fully connected mesh.
+/// Solves the problem of how to tell if all peers, relative to all other peers, are in a certain ready state.
+/// For example, if A is connected to B and C, A may see that B and C are ready, but does not know if B is ready to C, or vice-versa.
+/// This plugin uses two stages to solve that problem, first, everyone I know about is ready. Second, everyone I know about is ready to everyone they know about.
+/// The user will get ID_READY_EVENT_SET and ID_READY_EVENT_UNSET as the signal flag is set or unset
+/// The user will get ID_READY_EVENT_ALL_SET when all systems are done waiting for all other systems, in which case the event is considered complete, and no longer tracked.
+/// \sa FullyConnectedMesh2 +/// \ingroup READY_EVENT_GROUP +class ReadyEvent : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(ReadyEvent) + + // Constructor + ReadyEvent(); + + // Destructor + virtual ~ReadyEvent(); + + // -------------------------------------------------------------------------------------------- + // User functions + // -------------------------------------------------------------------------------------------- + /// Sets or updates the initial ready state for our local system. + /// If eventId is an unknown event the event is created. + /// If eventId was previously used and you want to reuse it, call DeleteEvent first, or else you will keep the same event signals from before + /// Systems previously or later added through AddToWaitList() with the same \a eventId when isReady=true will get ID_READY_EVENT_SET + /// Systems previously added through AddToWaitList with the same \a eventId will get ID_READY_EVENT_UNSET + /// For both ID_READY_EVENT_SET and ID_READY_EVENT_UNSET, eventId is encoded in bytes 1 through 1+sizeof(int) + /// \param[in] eventId A user-defined identifier to wait on. This can be a sequence counter, an event identifier, or anything else you want. + /// \param[in] isReady True to signal we are ready to proceed with this event, false to unsignal + /// \return False if event status is ID_READY_EVENT_FORCE_ALL_SET, or if we are setting to a status we are already in (no change). Otherwise true + bool SetEvent(int eventId, bool isReady); + + /// When systems can call SetEvent() with isReady==false, it is possible for one system to return true from IsEventCompleted() while the other systems return false + /// This can occur if a system SetEvent() with isReady==false while the completion message is still being transmitted. + /// If your game has the situation where some action should be taken on all systems when IsEventCompleted() is true for any system, then call ForceCompletion() when the action begins. + /// This will force all systems to return true from IsEventCompleted(). + /// \param[in] eventId A user-defined identifier to immediately set as completed + void ForceCompletion(int eventId); + + /// Deletes an event. We will no longer wait for this event, and any systems that we know have set the event will be forgotten. + /// Call this to clear memory when events are completed and you know you will never need them again. + /// \param[in] eventId A user-defined identifier + /// \return True on success. False (failure) on unknown eventId + bool DeleteEvent(int eventId); + + /// Returns what was passed to SetEvent() + /// \return The value of isReady passed to SetEvent(). Also returns false on unknown event. + bool IsEventSet(int eventId); + + /// Returns if the event is about to be ready and we are negotiating the final packets. + /// This will usually only be true for a very short time, after which IsEventCompleted should return true. + /// While this is true you cannot add to the wait list, or SetEvent() isReady to false anymore. + /// \param[in] eventId A user-defined identifier + /// \return True if any other system has completed processing. Will always be true if IsEventCompleted() is true + bool IsEventCompletionProcessing(int eventId) const; + + /// Returns if the wait list is a subset of the completion list. + /// Call this after all systems you want to wait for have been added with AddToWaitList + /// If you are waiting for a specific number of systems (such as players later connecting), also check GetRemoteWaitListSize(eventId) to be equal to 1 less than the total number of participants. + /// \param[in] eventId A user-defined identifier + /// \return True on completion. False (failure) on unknown eventId, or the set is not completed. + bool IsEventCompleted(int eventId) const; + + /// Returns if this is a known event. + /// Events may be known even if we never ourselves referenced them with SetEvent, because other systems created them via ID_READY_EVENT_SET. + /// \param[in] eventId A user-defined identifier + /// \return true if we have this event, false otherwise + bool HasEvent(int eventId); + + /// Returns the total number of events stored in the system. + /// \return The total number of events stored in the system. + unsigned GetEventListSize(void) const; + + /// Returns the event ID stored at a particular index. EventIDs are stored sorted from least to greatest. + /// \param[in] index Index into the array, from 0 to GetEventListSize() + /// \return The event ID stored at a particular index + int GetEventAtIndex(unsigned index) const; + + /// Adds a system to wait for to signal an event before considering the event complete and returning ID_READY_EVENT_ALL_SET. + /// As we add systems, if this event was previously set to true with SetEvent, these systems will get ID_READY_EVENT_SET. + /// As these systems disconnect (directly or indirectly through the router) they are removed. + /// \note If the event completion process has already started, you cannot add more systems, as this would cause the completion process to fail + /// \param[in] eventId A user-defined number previously passed to SetEvent that has not yet completed + /// \param[in] guid An address to wait for event replies from. Pass UNASSIGNED_SYSTEM_ADDRESS for all currently connected systems. Until all systems in this list have called SetEvent with this ID and true, and have this system in the list, we won't get ID_READY_EVENT_COMPLETE + /// \return True on success, false on unknown eventId (this should be considered an error) + bool AddToWaitList(int eventId, RakNetGUID guid); + + /// Removes systems from the wait list, which should have been previously added with AddToWaitList + /// \note Systems that directly or indirectly disconnect from us are automatically removed from the wait list + /// \param[in] guid The system to remove from the wait list. Pass UNASSIGNED_RAKNET_GUID for all currently connected systems. + /// \return True on success, false on unknown eventId (this should be considered an error) + bool RemoveFromWaitList(int eventId, RakNetGUID guid); + + /// Returns if a particular system is waiting on a particular event. + /// \param[in] eventId A user-defined identifier + /// \param[in] guid The system we are checking up on + /// \return True if this system is waiting on this event, false otherwise. + bool IsInWaitList(int eventId, RakNetGUID guid); + + /// Returns the total number of systems we are waiting on for this event. + /// Does not include yourself + /// \param[in] eventId A user-defined identifier + /// \return The total number of systems we are waiting on for this event. + unsigned GetRemoteWaitListSize(int eventId) const; + + /// Returns the system address of a system at a particular index, for this event. + /// \param[in] eventId A user-defined identifier + /// \param[in] index Index into the array, from 0 to GetWaitListSize() + /// \return The system address of a system at a particular index, for this event. + RakNetGUID GetFromWaitListAtIndex(int eventId, unsigned index) const; + + /// For a remote system, find out what their ready status is (waiting, signaled, complete). + /// \param[in] eventId A user-defined identifier + /// \param[in] guid Which system we are checking up on + /// \return The status of this system, for this particular event. \sa ReadyEventSystemStatus + ReadyEventSystemStatus GetReadyStatus(int eventId, RakNetGUID guid); + + /// This channel will be used for all RakPeer::Send calls + /// \param[in] newChannel The channel to use for internal RakPeer::Send calls from this system. Defaults to 0. + void SetSendChannel(unsigned char newChannel); + + // ---------------------------- ALL INTERNAL AFTER HERE ---------------------------- + /// \internal + /// Status of a remote system + struct RemoteSystem + { + MessageID lastSentStatus, lastReceivedStatus; + RakNetGUID rakNetGuid; + }; + static int RemoteSystemCompByGuid( const RakNetGUID &key, const RemoteSystem &data ); + /// \internal + /// An event, with a set of systems we are waiting for, a set of systems that are signaled, and a set of systems with completed events + struct ReadyEventNode + { + int eventId; // Sorted on this + MessageID eventStatus; + DataStructures::OrderedList systemList; + }; + static int ReadyEventNodeComp( const int &key, ReadyEvent::ReadyEventNode * const &data ); + + +protected: + // -------------------------------------------------------------------------------------------- + // Packet handling functions + // -------------------------------------------------------------------------------------------- + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnRakPeerShutdown(void); + + void Clear(void); + /* + bool AnyWaitersCompleted(unsigned eventIndex) const; + bool AllWaitersCompleted(unsigned eventIndex) const; + bool AllWaitersReady(unsigned eventIndex) const; + void SendAllReady(unsigned eventId, RakNetGUID guid); + void BroadcastAllReady(unsigned eventIndex); + void SendReadyStateQuery(unsigned eventId, RakNetGUID guid); + void BroadcastReadyUpdate(unsigned eventIndex); + bool AddToWaitListInternal(unsigned eventIndex, RakNetGUID guid); + bool IsLocked(unsigned eventIndex) const; + bool IsAllReadyByIndex(unsigned eventIndex) const; + */ + + void SendReadyStateQuery(unsigned eventId, RakNetGUID guid); + void SendReadyUpdate(unsigned eventIndex, unsigned systemIndex, bool forceIfNotDefault); + void BroadcastReadyUpdate(unsigned eventIndex, bool forceIfNotDefault); + void RemoveFromAllLists(RakNetGUID guid); + void OnReadyEventQuery(Packet *packet); + void PushCompletionPacket(unsigned eventId); + bool AddToWaitListInternal(unsigned eventIndex, RakNetGUID guid); + void OnReadyEventForceAllSet(Packet *packet); + void OnReadyEventPacketUpdate(Packet *packet); + void UpdateReadyStatus(unsigned eventIndex); + bool IsEventCompletedByIndex(unsigned eventIndex) const; + unsigned CreateNewEvent(int eventId, bool isReady); + bool SetEventByIndex(int eventIndex, bool isReady); + + DataStructures::OrderedList readyEventNodeList; + unsigned char channel; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/RefCountedObj.hpp b/include/raknet/RefCountedObj.hpp new file mode 100644 index 0000000..7bedd09 --- /dev/null +++ b/include/raknet/RefCountedObj.hpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b Reference counted object. Very simple class for quick and dirty uses. +/// + + + +#ifndef __REF_COUNTED_OBJ_H +#define __REF_COUNTED_OBJ_H + +#include "RakMemoryOverride.hpp" + +/// World's simplest class :) +class RefCountedObj +{ + public: + RefCountedObj() {refCount=1;} + virtual ~RefCountedObj() {} + void AddRef(void) {refCount++;} + void Deref(void) {if (--refCount==0) RakNet::OP_DELETE(this, _FILE_AND_LINE_);} + int refCount; +}; + +#endif diff --git a/include/raknet/RelayPlugin.hpp b/include/raknet/RelayPlugin.hpp new file mode 100644 index 0000000..4de271f --- /dev/null +++ b/include/raknet/RelayPlugin.hpp @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains the class RelayPlugin +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_RelayPlugin==1 + +#ifndef __RELAY_PLUGIN_H +#define __RELAY_PLUGIN_H + +#include "PluginInterface2.hpp" +#include "RakString.hpp" +#include "DS_Hash.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +/// \defgroup RELAY_PLUGIN_GROUP RelayPlugin +/// \brief A simple class to relay messages from one system to another through an intermediary +/// \ingroup PLUGINS_GROUP + +namespace RakNet +{ + +/// Forward declarations +class RakPeerInterface; + +enum RelayPluginEnums +{ + // Server handled messages + RPE_MESSAGE_TO_SERVER_FROM_CLIENT, + RPE_ADD_CLIENT_REQUEST_FROM_CLIENT, + RPE_REMOVE_CLIENT_REQUEST_FROM_CLIENT, + RPE_GROUP_MESSAGE_FROM_CLIENT, + RPE_JOIN_GROUP_REQUEST_FROM_CLIENT, + RPE_LEAVE_GROUP_REQUEST_FROM_CLIENT, + RPE_GET_GROUP_LIST_REQUEST_FROM_CLIENT, + // Client handled messages + RPE_MESSAGE_TO_CLIENT_FROM_SERVER, + RPE_ADD_CLIENT_NOT_ALLOWED, + RPE_ADD_CLIENT_TARGET_NOT_CONNECTED, + RPE_ADD_CLIENT_NAME_ALREADY_IN_USE, + RPE_ADD_CLIENT_SUCCESS, + RPE_USER_ENTERED_ROOM, + RPE_USER_LEFT_ROOM, + RPE_GROUP_MSG_FROM_SERVER, + RPE_GET_GROUP_LIST_REPLY_FROM_SERVER, + RPE_JOIN_GROUP_SUCCESS, + RPE_JOIN_GROUP_FAILURE, +}; + +/// \brief A simple class to relay messages from one system to another, identifying remote systems by a string. +/// \ingroup RELAY_PLUGIN_GROUP +class RAK_DLL_EXPORT RelayPlugin : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(RelayPlugin) + + /// Constructor + RelayPlugin(); + + /// Destructor + virtual ~RelayPlugin(); + + /// \brief Forward messages from any system, to the system specified by the combination of key and guid. The sending system only needs to know the key. + /// \param[in] key A string to identify the target's RakNetGUID. This is so the sending system does not need to know the RakNetGUID of the target system. The key should be unique among all guids added. If the key is not unique, only one system will be sent to (at random). + /// \param[in] guid The RakNetGuid of the system to send to. If this system disconnects, it is removed from the internal hash + /// \return RPE_ADD_CLIENT_TARGET_NOT_CONNECTED, RPE_ADD_CLIENT_NAME_ALREADY_IN_USE, or RPE_ADD_CLIENT_OK + RelayPluginEnums AddParticipantOnServer(const RakString &key, const RakNetGUID &guid); + + /// \brief Remove a chat participant + void RemoveParticipantOnServer(const RakNetGUID &guid); + + /// \brief If true, then if the client calls AddParticipantRequestFromClient(), the server will call AddParticipantOnServer() automatically + /// Defaults to false + /// \param[in] accept true to accept, false to not. + void SetAcceptAddParticipantRequests(bool accept); + + /// \brief Request from the client for the server to call AddParticipantOnServer() + /// \pre The server must have called SetAcceptAddParticipantRequests(true) or the request will be ignored + /// \param[in] key A string to identify out system. Passed to \a key on AddParticipantOnServer() + /// \param[in] relayPluginServerGuid the RakNetGUID of the system running RelayPlugin + void AddParticipantRequestFromClient(const RakString &key, const RakNetGUID &relayPluginServerGuid); + + /// \brief Remove yourself as a participant + void RemoveParticipantRequestFromClient(const RakNetGUID &relayPluginServerGuid); + + /// \brief Request that the server relay \a bitStream to the system designated by \a key + /// \param[in] relayPluginServerGuid the RakNetGUID of the system running RelayPlugin + /// \param[in] destinationGuid The key value passed to AddParticipant() earlier on the server. If this was not done, the server will not relay the message (it will be silently discarded). + /// \param[in] bitStream The data to relay + /// \param[in] priority See the parameter of the same name in RakPeerInterface::Send() + /// \param[in] reliability See the parameter of the same name in RakPeerInterface::Send() + /// \param[in] orderingChannel See the parameter of the same name in RakPeerInterface::Send() + void SendToParticipant(const RakNetGUID &relayPluginServerGuid, const RakString &destinationGuid, BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel); + + void SendGroupMessage(const RakNetGUID &relayPluginServerGuid, BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel); + void JoinGroupRequest(const RakNetGUID &relayPluginServerGuid, RakString groupName); + void LeaveGroup(const RakNetGUID &relayPluginServerGuid); + void GetGroupList(const RakNetGUID &relayPluginServerGuid); + + /// \internal + virtual PluginReceiveResult OnReceive(Packet *packet); + /// \internal + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + + struct StrAndGuidAndRoom + { + RakString str; + RakNetGUID guid; + RakString currentRoom; + }; + + struct StrAndGuid + { + RakString str; + RakNetGUID guid; + }; + + struct RP_Group + { + RakString roomName; + DataStructures::List usersInRoom; + }; + +protected: + + RelayPlugin::RP_Group* JoinGroup(RakNetGUID userGuid, RakString roomName); + RelayPlugin::RP_Group* JoinGroup(RP_Group* room, StrAndGuidAndRoom **strAndGuidSender); + void LeaveGroup(StrAndGuidAndRoom **strAndGuidSender); + void NotifyUsersInRoom(RP_Group *room, int msg, const RakString& message); + void SendMessageToRoom(StrAndGuidAndRoom **strAndGuidSender, BitStream* message); + void SendChatRoomsList(RakNetGUID target); + void OnGroupMessageFromClient(Packet *packet); + void OnJoinGroupRequestFromClient(Packet *packet); + void OnLeaveGroupRequestFromClient(Packet *packet); + + DataStructures::Hash strToGuidHash; + DataStructures::Hash guidToStrHash; + DataStructures::List chatRooms; + bool acceptAddParticipantRequests; + +}; + +} // End namespace + +#endif + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/ReliabilityLayer.hpp b/include/raknet/ReliabilityLayer.hpp new file mode 100644 index 0000000..651f673 --- /dev/null +++ b/include/raknet/ReliabilityLayer.hpp @@ -0,0 +1,596 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence. +/// + + +#ifndef __RELIABILITY_LAYER_H +#define __RELIABILITY_LAYER_H + +#include "RakMemoryOverride.hpp" +#include "MTUSize.hpp" +#include "DS_LinkedList.hpp" +#include "DS_List.hpp" +#include "SocketLayer.hpp" +#include "PacketPriority.hpp" +#include "DS_Queue.hpp" +#include "BitStream.hpp" +#include "InternalPacket.hpp" +#include "RakNetStatistics.hpp" +#include "DR_SHA1.hpp" +#include "DS_OrderedList.hpp" +#include "DS_RangeList.hpp" +#include "DS_BPlusTree.hpp" +#include "DS_MemoryPool.hpp" +#include "RakNetDefines.hpp" +#include "DS_Heap.hpp" +#include "BitStream.hpp" +#include "NativeFeatureIncludes.hpp" +#include "SecureHandshake.hpp" +#include "PluginInterface2.hpp" +#include "Rand.hpp" +#include "RakNetSocket2.hpp" + +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 +#include "CCRakNetUDT.hpp" +#define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 1 +#else +#include "CCRakNetSlidingWindow.hpp" +#define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 0 +#endif + +/// Number of ordered streams available. You can use up to 32 ordered streams +#define NUMBER_OF_ORDERED_STREAMS 32 // 2^5 + +#define RESEND_TREE_ORDER 32 + +namespace RakNet { + + /// Forward declarations +class PluginInterface2; +class RakNetRandom; +typedef uint64_t reliabilityHeapWeightType; + +// int SplitPacketIndexComp( SplitPacketIndexType const &key, InternalPacket* const &data ); +struct SplitPacketChannel// +{ + CCTimeType lastUpdateTime; + + DataStructures::List splitPacketList; + +#if PREALLOCATE_LARGE_MESSAGES==1 + InternalPacket *returnedPacket; + bool gotFirstPacket; + unsigned int stride; + unsigned int splitPacketsArrived; +#else + // This is here for progress notifications, since progress notifications return the first packet data, if available + InternalPacket *firstPacket; +#endif + +}; +int RAK_DLL_EXPORT SplitPacketChannelComp( SplitPacketIdType const &key, SplitPacketChannel* const &data ); + +// Helper class +struct BPSTracker +{ + BPSTracker(); + ~BPSTracker(); + void Reset(const char *file, unsigned int line); + inline void Push1(CCTimeType time, uint64_t value1) {dataQueue.Push(TimeAndValue2(time,value1),_FILE_AND_LINE_); total1+=value1; lastSec1+=value1;} +// void Push2(RakNet::TimeUS time, uint64_t value1, uint64_t value2); + inline uint64_t GetBPS1(CCTimeType time) {(void) time; return lastSec1;} + inline uint64_t GetBPS1Threadsafe(CCTimeType time) {(void) time; return lastSec1;} +// uint64_t GetBPS2(RakNetTimeUS time); +// void GetBPS1And2(RakNetTimeUS time, uint64_t &out1, uint64_t &out2); + uint64_t GetTotal1(void) const; +// uint64_t GetTotal2(void) const; + + struct TimeAndValue2 + { + TimeAndValue2(); + ~TimeAndValue2(); + TimeAndValue2(CCTimeType t, uint64_t v1); + // TimeAndValue2(RakNet::TimeUS t, uint64_t v1, uint64_t v2); + // uint64_t value1, value2; + uint64_t value1; + CCTimeType time; + }; + + uint64_t total1, lastSec1; +// uint64_t total2, lastSec2; + DataStructures::Queue dataQueue; + void ClearExpired1(CCTimeType time); +// void ClearExpired2(RakNet::TimeUS time); +}; + +/// Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence. +class ReliabilityLayer// +{ +public: + + // Constructor + ReliabilityLayer(); + + // Destructor + ~ReliabilityLayer(); + + /// Resets the layer for reuse + void Reset( bool resetVariables, int MTUSize, bool _useSecurity ); + + /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable packet + /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. + /// \param[in] time Time, in MS + void SetTimeoutTime( RakNet::TimeMS time ); + + /// Returns the value passed to SetTimeoutTime. or the default if it was never called + /// \param[out] the value passed to SetTimeoutTime + RakNet::TimeMS GetTimeoutTime(void); + + /// Packets are read directly from the socket layer and skip the reliability layer because unconnected players do not use the reliability layer + /// This function takes packet data after a player has been confirmed as connected. + /// \param[in] buffer The socket data + /// \param[in] length The length of the socket data + /// \param[in] systemAddress The player that this data is from + /// \param[in] messageHandlerList A list of registered plugins + /// \param[in] MTUSize maximum datagram size + /// \retval true Success + /// \retval false Modified packet + bool HandleSocketReceiveFromConnectedPlayer( + const char *buffer, unsigned int length, SystemAddress &systemAddress, DataStructures::List &messageHandlerList, int MTUSize, + RakNetSocket2 *s, RakNetRandom *rnr, CCTimeType timeRead, BitStream &updateBitStream); + + /// This allocates bytes and writes a user-level message to those bytes. + /// \param[out] data The message + /// \return Returns number of BITS put into the buffer + BitSize_t Receive( unsigned char**data ); + + /// Puts data on the send queue + /// \param[in] data The data to send + /// \param[in] numberOfBitsToSend The length of \a data in bits + /// \param[in] priority The priority level for the send + /// \param[in] reliability The reliability type for the send + /// \param[in] orderingChannel 0 to 31. Specifies what channel to use, for relational ordering and sequencing of packets. + /// \param[in] makeDataCopy If true \a data will be copied. Otherwise, only a pointer will be stored. + /// \param[in] MTUSize maximum datagram size + /// \param[in] currentTime Current time, as per RakNet::GetTimeMS() + /// \param[in] receipt This number will be returned back with ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS and is only returned with the reliability types that contain RECEIPT in the name + /// \return True or false for success or failure. + bool Send( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, unsigned char orderingChannel, bool makeDataCopy, int MTUSize, CCTimeType currentTime, uint32_t receipt ); + + /// Call once per game cycle. Handles internal lists and actually does the send. + /// \param[in] s the communication end point + /// \param[in] systemAddress The Unique Player Identifier who shouldhave sent some packets + /// \param[in] MTUSize maximum datagram size + /// \param[in] time current system time + /// \param[in] maxBitsPerSecond if non-zero, enforces that outgoing bandwidth does not exceed this amount + /// \param[in] messageHandlerList A list of registered plugins + void Update( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, + unsigned bitsPerSecondLimit, + DataStructures::List &messageHandlerList, + RakNetRandom *rnr, BitStream &updateBitStream); + + /// Were you ever unable to deliver a packet despite retries? + /// \return true means the connection has been lost. Otherwise not. + bool IsDeadConnection( void ) const; + + /// Causes IsDeadConnection to return true + void KillConnection(void); + + /// Get Statistics + /// \return A pointer to a static struct, filled out with current statistical information. + RakNetStatistics * GetStatistics( RakNetStatistics *rns ); + + ///Are we waiting for any data to be sent out or be processed by the player? + bool IsOutgoingDataWaiting(void); + bool AreAcksWaiting(void); + + // Set outgoing lag and packet loss properties + void ApplyNetworkSimulator( double _maxSendBPS, RakNet::TimeMS _minExtraPing, RakNet::TimeMS _extraPingVariance ); + + /// Returns if you previously called ApplyNetworkSimulator + /// \return If you previously called ApplyNetworkSimulator + bool IsNetworkSimulatorActive( void ); + + void SetSplitMessageProgressInterval(int interval); + void SetUnreliableTimeout(RakNet::TimeMS timeoutMS); + /// Has a lot of time passed since the last ack + bool AckTimeout(RakNet::Time curTime); + CCTimeType GetNextSendTime(void) const; + CCTimeType GetTimeBetweenPackets(void) const; +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + CCTimeType GetAckPing(void) const; +#endif + RakNet::TimeMS GetTimeLastDatagramArrived(void) const {return timeLastDatagramArrived;} + + // If true, will update time between packets quickly based on ping calculations + //void SetDoFastThroughputReactions(bool fast); + + // Encoded as numMessages[unsigned int], message1BitLength[unsigned int], message1Data (aligned), ... + //void GetUndeliveredMessages(RakNet::BitStream *messages, int MTUSize); + +private: + /// Send the contents of a bitstream to the socket + /// \param[in] s The socket used for sending data + /// \param[in] systemAddress The address and port to send to + /// \param[in] bitStream The data to send. + void SendBitStream( RakNetSocket2 *s, SystemAddress &systemAddress, RakNet::BitStream *bitStream, RakNetRandom *rnr, CCTimeType currentTime); + + ///Parse an internalPacket and create a bitstream to represent this data + /// \return Returns number of bits used + BitSize_t WriteToBitStreamFromInternalPacket( RakNet::BitStream *bitStream, const InternalPacket *const internalPacket, CCTimeType curTime ); + + + /// Parse a bitstream and create an internal packet to represent this data + InternalPacket* CreateInternalPacketFromBitStream( RakNet::BitStream *bitStream, CCTimeType time ); + + /// Does what the function name says + unsigned RemovePacketFromResendListAndDeleteOlderReliableSequenced( const MessageNumberType messageNumber, CCTimeType time, DataStructures::List &messageHandlerList, const SystemAddress &systemAddress ); + + /// Acknowledge receipt of the packet with the specified messageNumber + void SendAcknowledgementPacket( const DatagramSequenceNumberType messageNumber, CCTimeType time); + + /// This will return true if we should not send at this time + bool IsSendThrottled( int MTUSize ); + + /// We lost a packet + void UpdateWindowFromPacketloss( CCTimeType time ); + + /// Increase the window size + void UpdateWindowFromAck( CCTimeType time ); + + /// Parse an internalPacket and figure out how many header bits would be written. Returns that number + BitSize_t GetMaxMessageHeaderLengthBits( void ); + BitSize_t GetMessageHeaderLengthBits( const InternalPacket *const internalPacket ); + + /// Get the SHA1 code + void GetSHA1( unsigned char * const buffer, unsigned int nbytes, char code[ SHA1_LENGTH ] ); + + /// Check the SHA1 code + bool CheckSHA1( char code[ SHA1_LENGTH ], unsigned char * const buffer, unsigned int nbytes ); + + /// Search the specified list for sequenced packets on the specified ordering channel, optionally skipping those with splitPacketId, and delete them +// void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::List&theList, int splitPacketId = -1 ); + + /// Search the specified list for sequenced packets with a value less than orderingIndex and delete them +// void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::Queue&theList ); + + /// Returns true if newPacketOrderingIndex is older than the waitingForPacketOrderingIndex + bool IsOlderOrderedPacket( OrderingIndexType newPacketOrderingIndex, OrderingIndexType waitingForPacketOrderingIndex ); + + /// Split the passed packet into chunks under MTU_SIZE bytes (including headers) and save those new chunks + void SplitPacket( InternalPacket *internalPacket ); + + /// Insert a packet into the split packet list + void InsertIntoSplitPacketList( InternalPacket * internalPacket, CCTimeType time ); + + /// Take all split chunks with the specified splitPacketId and try to reconstruct a packet. If we can, allocate and return it. Otherwise return 0 + InternalPacket * BuildPacketFromSplitPacketList( SplitPacketIdType splitPacketId, CCTimeType time, + RakNetSocket2 *s, SystemAddress &systemAddress, RakNetRandom *rnr, BitStream &updateBitStream); + InternalPacket * BuildPacketFromSplitPacketList( SplitPacketChannel *splitPacketChannel, CCTimeType time ); + + /// Delete any unreliable split packets that have long since expired + //void DeleteOldUnreliableSplitPackets( CCTimeType time ); + + /// Creates a copy of the specified internal packet with data copied from the original starting at dataByteOffset for dataByteLength bytes. + /// Does not copy any split data parameters as that information is always generated does not have any reason to be copied + InternalPacket * CreateInternalPacketCopy( InternalPacket *original, int dataByteOffset, int dataByteLength, CCTimeType time ); + + /// Get the specified ordering list + // DataStructures::LinkedList *GetOrderingListAtOrderingStream( unsigned char orderingChannel ); + + /// Add the internal packet to the ordering list in order based on order index + // void AddToOrderingList( InternalPacket * internalPacket ); + + /// Inserts a packet into the resend list in order + void InsertPacketIntoResendList( InternalPacket *internalPacket, CCTimeType time, bool firstResend, bool modifyUnacknowledgedBytes ); + + /// Memory handling + void FreeMemory( bool freeAllImmediately ); + + /// Memory handling + void FreeThreadSafeMemory( void ); + + // Initialize the variables + void InitializeVariables( void ); + + /// Given the current time, is this time so old that we should consider it a timeout? + bool IsExpiredTime(unsigned int input, CCTimeType currentTime) const; + + // Make it so we don't do resends within a minimum threshold of time + void UpdateNextActionTime(void); + + + /// Does this packet number represent a packet that was skipped (out of order?) + //unsigned int IsReceivedPacketHole(unsigned int input, RakNet::TimeMS currentTime) const; + + /// Skip an element in the received packets list + //unsigned int MakeReceivedPacketHole(unsigned int input) const; + + /// How many elements are waiting to be resent? + unsigned int GetResendListDataSize(void) const; + + /// Update all memory which is not threadsafe + void UpdateThreadedMemory(void); + + void CalculateHistogramAckSize(void); + + // Used ONLY for RELIABLE_ORDERED + // RELIABLE_SEQUENCED just returns the newest one + // DataStructures::List*> orderingList; + DataStructures::Queue outputQueue; + int splitMessageProgressInterval; + CCTimeType unreliableTimeout; + + struct MessageNumberNode + { + DatagramSequenceNumberType messageNumber; + MessageNumberNode *next; + }; + struct DatagramHistoryNode + { + DatagramHistoryNode() {} + DatagramHistoryNode(MessageNumberNode *_head, CCTimeType ts + ) : + head(_head), timeSent(ts) + {} + MessageNumberNode *head; + CCTimeType timeSent; + }; + // Queue length is programmatically restricted to DATAGRAM_MESSAGE_ID_ARRAY_LENGTH + // This is essentially an O(1) lookup to get a DatagramHistoryNode given an index + // datagramHistory holds a linked list of MessageNumberNode. Each MessageNumberNode refers to one element in resendList which can be cleared on an ack. + DataStructures::Queue datagramHistory; + DataStructures::MemoryPool datagramHistoryMessagePool; + + struct UnreliableWithAckReceiptNode + { + UnreliableWithAckReceiptNode() {} + UnreliableWithAckReceiptNode(DatagramSequenceNumberType _datagramNumber, uint32_t _sendReceiptSerial, RakNet::TimeUS _nextActionTime) : + datagramNumber(_datagramNumber), sendReceiptSerial(_sendReceiptSerial), nextActionTime(_nextActionTime) + {} + DatagramSequenceNumberType datagramNumber; + uint32_t sendReceiptSerial; + RakNet::TimeUS nextActionTime; + }; + DataStructures::List unreliableWithAckReceiptHistory; + + void RemoveFromDatagramHistory(DatagramSequenceNumberType index); + MessageNumberNode* GetMessageNumberNodeByDatagramIndex(DatagramSequenceNumberType index, CCTimeType *timeSent); + void AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, CCTimeType timeSent); + MessageNumberNode* AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, DatagramSequenceNumberType messageNumber, CCTimeType timeSent); + MessageNumberNode* AddSubsequentToDatagramHistory(MessageNumberNode *messageNumberNode, DatagramSequenceNumberType messageNumber); + DatagramSequenceNumberType datagramHistoryPopCount; + + DataStructures::MemoryPool internalPacketPool; + // DataStructures::BPlusTree resendTree; + InternalPacket *resendBuffer[RESEND_BUFFER_ARRAY_LENGTH]; + InternalPacket *resendLinkedListHead; + InternalPacket *unreliableLinkedListHead; + void RemoveFromUnreliableLinkedList(InternalPacket *internalPacket); + void AddToUnreliableLinkedList(InternalPacket *internalPacket); +// unsigned int numPacketsOnResendBuffer; + //unsigned int blockWindowIncreaseUntilTime; + // DataStructures::RangeList acknowlegements; + // Resend list is a tree of packets we need to resend + + // Set to the current time when the resend queue is no longer empty + // Set to zero when it becomes empty + // Set to the current time if it is not zero, and we get incoming data + // If the current time - timeResendQueueNonEmpty is greater than a threshold, we are disconnected +// CCTimeType timeResendQueueNonEmpty; + RakNet::TimeMS timeLastDatagramArrived; + + + // If we backoff due to packetloss, don't remeasure until all waiting resends have gone out or else we overcount +// bool packetlossThisSample; +// int backoffThisSample; +// unsigned packetlossThisSampleResendCount; +// CCTimeType lastPacketlossTime; + + //DataStructures::Queue sendPacketSet[ NUMBER_OF_PRIORITIES ]; + DataStructures::Heap outgoingPacketBuffer; + reliabilityHeapWeightType outgoingPacketBufferNextWeights[NUMBER_OF_PRIORITIES]; + void InitHeapWeights(void); + reliabilityHeapWeightType GetNextWeight(int priorityLevel); +// unsigned int messageInSendBuffer[NUMBER_OF_PRIORITIES]; +// double bytesInSendBuffer[NUMBER_OF_PRIORITIES]; + + + DataStructures::OrderedList splitPacketChannelList; + + MessageNumberType sendReliableMessageNumberIndex; + MessageNumberType internalOrderIndex; + //unsigned int windowSize; + //RakNet::BitStream updateBitStream; + bool deadConnection, cheater; + SplitPacketIdType splitPacketId; + RakNet::TimeMS timeoutTime; // How long to wait in MS before timing someone out + //int MAX_AVERAGE_PACKETS_PER_SECOND; // Name says it all +// int RECEIVED_PACKET_LOG_LENGTH, requestedReceivedPacketLogLength; // How big the receivedPackets array is +// unsigned int *receivedPackets; + RakNetStatistics statistics; + + // Algorithm for blending ordered and sequenced on the same channel: + // 1. Each ordered message transmits OrderingIndexType orderedWriteIndex. There are NUMBER_OF_ORDERED_STREAMS independent values of these. The value + // starts at 0. Every time an ordered message is sent, the value increments by 1 + // 2. Each sequenced message contains the current value of orderedWriteIndex for that channel, and additionally OrderingIndexType sequencedWriteIndex. + // sequencedWriteIndex resets to 0 every time orderedWriteIndex increments. It increments by 1 every time a sequenced message is sent. + // 3. The receiver maintains the next expected value for the orderedWriteIndex, stored in orderedReadIndex. + // 4. As messages arrive: + // If a message has the current ordering index, and is sequenced, and is < the current highest sequence value, discard + // If a message has the current ordering index, and is sequenced, and is >= the current highest sequence value, return immediately + // If a message has a greater ordering index, and is sequenced or ordered, buffer it + // If a message has the current ordering index, and is ordered, buffer, then push off messages from buffer + // 5. Pushing off messages from buffer: + // Messages in buffer are put in a minheap. The value of each node is calculated such that messages are returned: + // A. (lowest ordering index, lowest sequence index) + // B. (lowest ordering index, no sequence index) + // Messages are pushed off until the heap is empty, or the next message to be returned does not preserve the ordered index + // For an empty heap, the heap weight should start at the lowest value based on the next expected ordering index, to avoid variable overflow + + // Sender increments this by 1 for every ordered message sent + OrderingIndexType orderedWriteIndex[NUMBER_OF_ORDERED_STREAMS]; + // Sender increments by 1 for every sequenced message sent. Resets to 0 when an ordered message is sent + OrderingIndexType sequencedWriteIndex[NUMBER_OF_ORDERED_STREAMS]; + // Next expected index for ordered messages. + OrderingIndexType orderedReadIndex[NUMBER_OF_ORDERED_STREAMS]; + // Highest value received for sequencedWriteIndex for the current value of orderedReadIndex on the same channel. + OrderingIndexType highestSequencedReadIndex[NUMBER_OF_ORDERED_STREAMS]; + DataStructures::Heap orderingHeaps[NUMBER_OF_ORDERED_STREAMS]; + OrderingIndexType heapIndexOffsets[NUMBER_OF_ORDERED_STREAMS]; + + + + + + + +// CCTimeType histogramStart; +// unsigned histogramBitsSent; + + + /// Memory-efficient receivedPackets algorithm: + /// receivedPacketsBaseIndex is the packet number we are expecting + /// Everything under receivedPacketsBaseIndex is a packet we already got + /// Everything over receivedPacketsBaseIndex is stored in hasReceivedPacketQueue + /// It stores the time to stop waiting for a particular packet number, where the packet number is receivedPacketsBaseIndex + the index into the queue + /// If 0, we got got that packet. Otherwise, the time to give up waiting for that packet. + /// If we get a packet number where (receivedPacketsBaseIndex-packetNumber) is less than half the range of receivedPacketsBaseIndex then it is a duplicate + /// Otherwise, it is a duplicate packet (and ignore it). + // DataStructures::Queue hasReceivedPacketQueue; + DataStructures::Queue hasReceivedPacketQueue; + DatagramSequenceNumberType receivedPacketsBaseIndex; + bool resetReceivedPackets; + + CCTimeType lastUpdateTime; + CCTimeType timeBetweenPackets, nextSendTime; +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + CCTimeType ackPing; +#endif +// CCTimeType ackPingSamples[ACK_PING_SAMPLES_SIZE]; // Must be range of unsigned char to wrap ackPingIndex properly + CCTimeType ackPingSum; + unsigned char ackPingIndex; + //CCTimeType nextLowestPingReset; + RemoteSystemTimeType remoteSystemTime; +// bool continuousSend; +// CCTimeType lastTimeBetweenPacketsIncrease,lastTimeBetweenPacketsDecrease; + // Limit changes in throughput to once per ping - otherwise even if lag starts we don't know about it + // In the meantime the connection is flooded and overrun. + CCTimeType nextAllowedThroughputSample; + bool bandwidthExceededStatistic; + + // If Update::maxBitsPerSecond > 0, then throughputCapCountdown is used as a timer to prevent sends for some amount of time after each send, depending on + // the amount of data sent + long long throughputCapCountdown; + + unsigned receivePacketCount; + +#ifdef _DEBUG + struct DataAndTime// + { + RakNetSocket2 *s; + char data[ MAXIMUM_MTU_SIZE ]; + unsigned int length; + RakNet::TimeMS sendTime; + // SystemAddress systemAddress; + unsigned short remotePortRakNetWasStartedOn_PS3; + unsigned int extraSocketOptions; + }; + DataStructures::Queue delayList; + + // Internet simulator + double packetloss; + RakNet::TimeMS minExtraPing, extraPingVariance; +#endif + + CCTimeType elapsedTimeSinceLastUpdate; + + CCTimeType nextAckTimeToSend; + + +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1 + RakNet::CCRakNetSlidingWindow congestionManager; +#else + RakNet::CCRakNetUDT congestionManager; +#endif + + + uint32_t unacknowledgedBytes; + + bool ResendBufferOverflow(void) const; + void ValidateResendList(void) const; + void ResetPacketsAndDatagrams(void); + void PushPacket(CCTimeType time, InternalPacket *internalPacket, bool isReliable); + void PushDatagram(void); + bool TagMostRecentPushAsSecondOfPacketPair(void); + void ClearPacketsAndDatagrams(void); + void MoveToListHead(InternalPacket *internalPacket); + void RemoveFromList(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes); + void AddToListTail(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes); + void PopListHead(bool modifyUnacknowledgedBytes); + bool IsResendQueueEmpty(void) const; + void SortSplitPacketList(DataStructures::List &data, unsigned int leftEdge, unsigned int rightEdge) const; + void SendACKs(RakNetSocket2 *s, SystemAddress &systemAddress, CCTimeType time, RakNetRandom *rnr, BitStream &updateBitStream); + + DataStructures::List packetsToSendThisUpdate; + DataStructures::List packetsToDeallocThisUpdate; + // boundary is in packetsToSendThisUpdate, inclusive + DataStructures::List packetsToSendThisUpdateDatagramBoundaries; + DataStructures::List datagramsToSendThisUpdateIsPair; + DataStructures::List datagramSizesInBytes; + BitSize_t datagramSizeSoFar; + BitSize_t allDatagramSizesSoFar; + double totalUserDataBytesAcked; + CCTimeType timeOfLastContinualSend; + CCTimeType timeToNextUnreliableCull; + + // This doesn't need to be a member, but I do it to avoid reallocations + DataStructures::RangeList incomingAcks; + + // Every 16 datagrams, we make sure the 17th datagram goes out the same update tick, and is the same size as the 16th + int countdownToNextPacketPair; + InternalPacket* AllocateFromInternalPacketPool(void); + void ReleaseToInternalPacketPool(InternalPacket *ip); + + DataStructures::RangeList acknowlegements; + DataStructures::RangeList NAKs; + bool remoteSystemNeedsBAndAS; + + unsigned int GetMaxDatagramSizeExcludingMessageHeaderBytes(void); + BitSize_t GetMaxDatagramSizeExcludingMessageHeaderBits(void); + + // ourOffset refers to a section within externallyAllocatedPtr. Do not deallocate externallyAllocatedPtr until all references are lost + void AllocInternalPacketData(InternalPacket *internalPacket, InternalPacketRefCountedData **refCounter, unsigned char *externallyAllocatedPtr, unsigned char *ourOffset); + // Set the data pointer to externallyAllocatedPtr, do not allocate + void AllocInternalPacketData(InternalPacket *internalPacket, unsigned char *externallyAllocatedPtr); + // Allocate new + void AllocInternalPacketData(InternalPacket *internalPacket, unsigned int numBytes, bool allowStack, const char *file, unsigned int line); + void FreeInternalPacketData(InternalPacket *internalPacket, const char *file, unsigned int line); + DataStructures::MemoryPool refCountedDataPool; + + BPSTracker bpsMetrics[RNS_PER_SECOND_METRICS_COUNT]; + CCTimeType lastBpsClear; + +#if LIBCAT_SECURITY==1 +public: + cat::AuthenticatedEncryption* GetAuthenticatedEncryption(void) { return &auth_enc; } + +protected: + cat::AuthenticatedEncryption auth_enc; + bool useSecurity; +#endif // LIBCAT_SECURITY +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/ReplicaEnums.hpp b/include/raknet/ReplicaEnums.hpp new file mode 100644 index 0000000..1cd771a --- /dev/null +++ b/include/raknet/ReplicaEnums.hpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains enumerations used by the ReplicaManager system. This file is a lightweight header, so you can include it without worrying about linking in lots of other crap +/// + + + +#ifndef __REPLICA_ENUMS_H +#define __REPLICA_ENUMS_H + +/// Replica interface flags, used to enable and disable function calls on the Replica object +/// Passed to ReplicaManager::EnableReplicaInterfaces and ReplicaManager::DisableReplicaInterfaces +enum +{ + REPLICA_RECEIVE_DESTRUCTION=1<<0, + REPLICA_RECEIVE_SERIALIZE=1<<1, + REPLICA_RECEIVE_SCOPE_CHANGE=1<<2, + REPLICA_SEND_CONSTRUCTION=1<<3, + REPLICA_SEND_DESTRUCTION=1<<4, + REPLICA_SEND_SCOPE_CHANGE=1<<5, + REPLICA_SEND_SERIALIZE=1<<6, + REPLICA_SET_ALL = 0xFF // Allow all of the above +}; + +enum ReplicaReturnResult +{ + /// This means call the function again later, with the same parameters + REPLICA_PROCESS_LATER, + /// This means we are done processing (the normal result to return) + REPLICA_PROCESSING_DONE, + /// This means cancel the processing - don't send any network messages and don't change the current state. + REPLICA_CANCEL_PROCESS, + /// Same as REPLICA_PROCESSING_DONE, where a message is sent, but does not clear the send bit. + /// Useful for multi-part sends with different reliability levels. + /// Only currently used by Replica::Serialize + REPLICA_PROCESS_AGAIN, + /// Only returned from the Replica::SendConstruction interface, means act as if the other system had this object but don't actually + /// Send a construction packet. This way you will still send scope and serialize packets to that system + REPLICA_PROCESS_IMPLICIT +}; + +#endif diff --git a/include/raknet/ReplicaManager3.hpp b/include/raknet/ReplicaManager3.hpp new file mode 100644 index 0000000..67d694b --- /dev/null +++ b/include/raknet/ReplicaManager3.hpp @@ -0,0 +1,1137 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains the third iteration of the ReplicaManager class. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_ReplicaManager3==1 + +#ifndef __REPLICA_MANAGER_3 +#define __REPLICA_MANAGER_3 + +#include "RakNetTypes.hpp" +#include "RakNetTime.hpp" +#include "BitStream.hpp" +#include "PacketPriority.hpp" +#include "PluginInterface2.hpp" +#include "NetworkIDObject.hpp" +#include "DS_OrderedList.hpp" +#include "DS_Queue.hpp" + +/// \defgroup REPLICA_MANAGER_GROUP3 ReplicaManager3 +/// \brief Third implementation of object replication +/// \details +/// \ingroup PLUGINS_GROUP + +namespace RakNet +{ +class Connection_RM3; +class Replica3; + +/// \ingroup REPLICA_MANAGER_GROUP3 +/// Used for multiple worlds. World 0 is created automatically by default +typedef uint8_t WorldId; + + +/// \internal +/// \ingroup REPLICA_MANAGER_GROUP3 +struct PRO +{ + /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketPriority(). + PacketPriority priority; + + /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketReliability(). + PacketReliability reliability; + + /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultOrderingChannel(). + char orderingChannel; + + /// Passed to RakPeerInterface::Send(). Defaults to 0. + uint32_t sendReceipt; + + bool operator==( const PRO& right ) const; + bool operator!=( const PRO& right ) const; +}; + + +/// \brief System to help automate game object construction, destruction, and serialization +/// \details ReplicaManager3 tracks your game objects and automates the networking for replicating them across the network
+/// As objects are created, destroyed, or serialized differently, those changes are pushed out to other systems.
+/// To use:
+///
    +///
  1. Derive from Connection_RM3 and implement Connection_RM3::AllocReplica(). This is a factory function where given a user-supplied identifier for a class (such as name) return an instance of that class. Should be able to return any networked object in your game. +///
  2. Derive from ReplicaManager3 and implement AllocConnection() and DeallocConnection() to return the class you created in step 1. +///
  3. Derive your networked game objects from Replica3. All pure virtuals have to be implemented, however defaults are provided for Replica3::QueryConstruction(), Replica3::QueryRemoteConstruction(), and Replica3::QuerySerialization() depending on your network architecture. +///
  4. When a new game object is created on the local system, pass it to ReplicaManager3::Reference(). +///
  5. When a game object is destroyed on the local system, and you want other systems to know about it, call Replica3::BroadcastDestruction() +///
+///
+/// At this point, all new connections will automatically download, get construction messages, get destruction messages, and update serialization automatically. +/// \ingroup REPLICA_MANAGER_GROUP3 +class RAK_DLL_EXPORT ReplicaManager3 : public PluginInterface2 +{ +public: + ReplicaManager3(); + virtual ~ReplicaManager3(); + + /// \brief Implement to return a game specific derivation of Connection_RM3 + /// \details The connection object represents a remote system connected to you that is using the ReplicaManager3 system.
+ /// It has functions to perform operations per-connection.
+ /// AllocConnection() and DeallocConnection() are factory functions to create and destroy instances of the connection object.
+ /// It is used if autoCreate is true via SetAutoManageConnections() (true by default). Otherwise, the function is not called, and you will have to call PushConnection() manually
+ /// \note If you do not want a new network connection to immediately download game objects, SetAutoManageConnections() and PushConnection() are how you do this. + /// \sa SetAutoManageConnections() + /// \param[in] systemAddress Address of the system you are adding + /// \param[in] rakNetGUID GUID of the system you are adding. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress() + /// \return The new connection instance. + virtual Connection_RM3* AllocConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID) const=0; + + /// \brief Implement to destroy a class instanced returned by AllocConnection() + /// \details Most likely just implement as {delete connection;}
+ /// It is used if autoDestroy is true via SetAutoManageConnections() (true by default). Otherwise, the function is not called and you would then be responsible for deleting your own connection objects. + /// \param[in] connection The pointer instance to delete + virtual void DeallocConnection(Connection_RM3 *connection) const=0; + + /// \brief Enable or disable automatically assigning connections to new instances of Connection_RM3 + /// \details ReplicaManager3 can automatically create and/or destroy Connection_RM3 as systems connect or disconnect from RakPeerInterface.
+ /// By default this is on, to make the system easier to learn and setup.
+ /// If you don't want all connections to take part in the game, or you want to delay when a connection downloads the game, set \a autoCreate to false.
+ /// If you want to delay deleting a connection that has dropped, set \a autoDestroy to false. If you do this, then you must call PopConnection() to remove that connection from being internally tracked. You'll also have to delete the connection instance on your own.
+ /// \param[in] autoCreate Automatically call ReplicaManager3::AllocConnection() for each new connection. Defaults to true. Also see AutoCreateConnectionList() + /// \param[in] autoDestroy Automatically call ReplicaManager3::DeallocConnection() for each dropped connection. Defaults to true. + void SetAutoManageConnections(bool autoCreate, bool autoDestroy); + + /// \return What was passed to the autoCreate parameter of SetAutoManageConnections() + bool GetAutoCreateConnections(void) const; + + /// \return What was passed to the autoDestroy parameter of SetAutoManageConnections() + bool GetAutoDestroyConnections(void) const; + + /// \brief Call AllocConnection() and PushConnection() for each connection in \a participantList + /// \param[in] participantListIn The list of connections to allocate + /// \param[in] participantListOut The connections allocated, if any + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void AutoCreateConnectionList( + DataStructures::List &participantListIn, + DataStructures::List &participantListOut, + WorldId worldId=0); + + /// \brief Track a new Connection_RM3 instance + /// \details If \a autoCreate is false for SetAutoManageConnections(), then you need this function to add new instances of Connection_RM3 yourself.
+ /// You don't need to track this pointer yourself, you can get it with GetConnectionAtIndex(), GetConnectionByGUID(), or GetConnectionBySystemAddress().
+ /// \param[in] newConnection The new connection instance to track. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + bool PushConnection(RakNet::Connection_RM3 *newConnection, WorldId worldId=0); + + /// \brief Stop tracking a connection + /// \details On call, for each replica returned by GetReplicasCreatedByGuid(), QueryActionOnPopConnection() will be called. Depending on the return value, this may delete the corresponding replica.
+ /// If autoDestroy is true in the call to SetAutoManageConnections() (true by default) then this is called automatically when the connection is lost. In that case, the returned connection instance is deleted.
+ /// \param[in] guid of the connection to get. Passed to ReplicaManager3::AllocConnection() originally. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + RakNet::Connection_RM3 * PopConnection(RakNetGUID guid, WorldId worldId=0); + + /// \brief Adds a replicated object to the system. + /// \details Anytime you create a new object that derives from Replica3, and you want ReplicaManager3 to use it, pass it to Reference().
+ /// Remote systems already connected will potentially download this object the next time ReplicaManager3::Update() is called, which happens every time you call RakPeerInterface::Receive().
+ /// You can also call ReplicaManager3::Update() manually to send referenced objects right away + /// \param[in] replica3 The object to start tracking + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void Reference(RakNet::Replica3 *replica3, WorldId worldId=0); + + /// \brief Removes a replicated object from the system. + /// \details The object is not deallocated, it is up to the caller to do so.
+ /// This is called automatically from the destructor of Replica3, so you don't need to call it manually unless you want to stop tracking an object before it is destroyed. + /// \param[in] replica3 The object to stop tracking + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void Dereference(RakNet::Replica3 *replica3, WorldId worldId=0); + + /// \brief Removes multiple replicated objects from the system. + /// \details Same as Dereference(), but for a list of objects.
+ /// Useful with the lists returned by GetReplicasCreatedByGuid(), GetReplicasCreatedByMe(), or GetReferencedReplicaList().
+ /// \param[in] replicaListIn List of objects + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void DereferenceList(DataStructures::List &replicaListIn, WorldId worldId=0); + + /// \brief Returns all objects originally created by a particular system + /// \details Originally created is defined as the value of Replica3::creatingSystemGUID, which is automatically assigned in ReplicaManager3::Reference().
+ /// You do not have to be directly connected to that system to get the objects originally created by that system.
+ /// \param[in] guid GUID of the system we are referring to. Originally passed as the \a guid parameter to ReplicaManager3::AllocConnection() + /// \param[out] List of Replica3 instances to be returned + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void GetReplicasCreatedByGuid(RakNetGUID guid, DataStructures::List &replicaListOut, WorldId worldId=0); + + /// \brief Returns all objects originally created by your system + /// \details Calls GetReplicasCreatedByGuid() for your own system guid. + /// \param[out] List of Replica3 instances to be returned + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void GetReplicasCreatedByMe(DataStructures::List &replicaListOut, WorldId worldId=0); + + /// \brief Returns the entire list of Replicas that we know about. + /// \details This is all Replica3 instances passed to Reference, as well as instances we downloaded and created via Connection_RM3::AllocReference() + /// \param[out] List of Replica3 instances to be returned + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void GetReferencedReplicaList(DataStructures::List &replicaListOut, WorldId worldId=0); + + /// \brief Returns the number of replicas known about + /// \details Returns the size of the list that would be returned by GetReferencedReplicaList() + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \return How many replica objects are in the list of replica objects + unsigned GetReplicaCount(WorldId worldId=0) const; + + /// \brief Returns a replica by index + /// \details Returns one of the items in the list that would be returned by GetReferencedReplicaList() + /// \param[in] index An index, from 0 to GetReplicaCount()-1. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \return A Replica3 instance + Replica3 *GetReplicaAtIndex(unsigned index, WorldId worldId=0); + + /// \brief Returns the number of connections + /// \details Returns the number of connections added with ReplicaManager3::PushConnection(), minus the number removed with ReplicaManager3::PopConnection() + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \return The number of registered connections + unsigned int GetConnectionCount(WorldId worldId=0) const; + + /// \brief Returns a connection pointer previously added with PushConnection() + /// \param[in] index An index, from 0 to GetConnectionCount()-1. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \return A Connection_RM3 pointer + Connection_RM3* GetConnectionAtIndex(unsigned index, WorldId worldId=0) const; + + /// \brief Returns a connection pointer previously added with PushConnection() + /// \param[in] sa The system address of the connection to return + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \return A Connection_RM3 pointer, or 0 if not found + Connection_RM3* GetConnectionBySystemAddress(const SystemAddress &sa, WorldId worldId=0) const; + + /// \brief Returns a connection pointer previously added with PushConnection.() + /// \param[in] guid The guid of the connection to return + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \return A Connection_RM3 pointer, or 0 if not found + Connection_RM3* GetConnectionByGUID(RakNetGUID guid, WorldId worldId=0) const; + + /// \param[in] Default ordering channel to use for object creation, destruction, and serializations + void SetDefaultOrderingChannel(char def); + + /// \param[in] Default packet priority to use for object creation, destruction, and serializations + void SetDefaultPacketPriority(PacketPriority def); + + /// \param[in] Default packet reliability to use for object creation, destruction, and serializations + void SetDefaultPacketReliability(PacketReliability def); + + /// \details Every \a intervalMS milliseconds, Connection_RM3::OnAutoserializeInterval() will be called.
+ /// Defaults to 30.
+ /// Pass with <0 to disable. Pass 0 to Serialize() every time RakPeer::Recieve() is called
+ /// If you want to control the update interval with more granularity, use the return values from Replica3::Serialize().
+ /// \param[in] intervalMS How frequently to autoserialize all objects. This controls the maximum number of game object updates per second. + void SetAutoSerializeInterval(RakNet::Time intervalMS); + + /// \brief Return the connections that we think have an instance of the specified Replica3 instance + /// \details This can be wrong, for example if that system locally deleted the outside the scope of ReplicaManager3, if QueryRemoteConstruction() returned false, or if DeserializeConstruction() returned false. + /// \param[in] replica The replica to check against. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \param[out] connectionsThatHaveConstructedThisReplica Populated with connection instances that we believe have \a replica allocated + void GetConnectionsThatHaveReplicaConstructed(Replica3 *replica, DataStructures::List &connectionsThatHaveConstructedThisReplica, WorldId worldId=0); + + /// \brief Returns if GetDownloadWasCompleted() returns true for all connections + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + /// \return True when all downloads have been completed + bool GetAllConnectionDownloadsCompleted(WorldId worldId=0) const; + + /// \brief ReplicaManager3 can support multiple worlds, where each world has a separate NetworkIDManager, list of connections, replicas, etc + /// A world with id 0 is created automatically. If you want multiple worlds, use this function, and ReplicaManager3::SetNetworkIDManager() to have a different NetworkIDManager instance per world + /// \param[in] worldId A unique identifier for this world. User-defined + void AddWorld(WorldId worldId); + + /// \brief Deallocate a world added with AddWorld, or the default world with id 0 + /// Deallocating a world will also stop tracking and updating all connections and replicas associated with that world. + /// \param[in] worldId A \a worldId value previously added with AddWorld() + void RemoveWorld(WorldId worldId); + + /// \brief Get one of the WorldId values added with AddWorld() + /// \details WorldId 0 is created by default. Worlds will not necessarily be in the order added with AddWorld(). Edit RemoveWorld() changing RemoveAtIndexFast() to RemoveAtIndex() to preserve order. + /// \param[in] index A value between 0 and GetWorldCount()-1 + /// \return One of the WorldId values added with AddWorld() + WorldId GetWorldIdAtIndex(unsigned int index); + + /// \brief Returns the number of world id specifiers in memory, added with AddWorld() and removed with RemoveWorld() + /// \return The number of worlds added + unsigned int GetWorldCount(void) const; + + /// \details Sets the networkIDManager instance that this plugin relys upon.
+ /// Uses whatever instance is attached to RakPeerInterface if unset.
+ /// To support multiple worlds, you should set it to a different manager for each instance of the plugin + /// \param[in] _networkIDManager The externally allocated NetworkIDManager instance for this plugin to use. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void SetNetworkIDManager(NetworkIDManager *_networkIDManager, WorldId worldId=0); + + /// Returns what was passed to SetNetworkIDManager(), or the instance on RakPeerInterface if unset. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + NetworkIDManager *GetNetworkIDManager(WorldId worldId=0) const; + + /// \details Send a network command to destroy one or more Replica3 instances + /// Usually you won't need this, but use Replica3::BroadcastDestruction() instead. + /// The objects are unaffected locally + /// \param[in] replicaList List of Replica3 objects to tell other systems to destroy. + /// \param[in] exclusionAddress Which system to not send to. UNASSIGNED_SYSTEM_ADDRESS to send to all. + /// \param[in] worldId Used for multiple worlds. World 0 is created automatically by default. See AddWorld() + void BroadcastDestructionList(DataStructures::List &replicaListSource, const SystemAddress &exclusionAddress, WorldId worldId=0); + + /// \internal + /// \details Tell other systems that have this replica to destroy this replica.
+ /// You shouldn't need to call this, as it happens in the Replica3 destructor + void BroadcastDestruction(Replica3 *replica, const SystemAddress &exclusionAddress); + + /// \internal + /// \details Frees internal lists.
+ /// \param[in] deleteWorlds True to also delete the worlds added with AddWorld() + /// Externally allocated pointers are not deallocated + void Clear(bool deleteWorlds=false); + + /// \internal + PRO GetDefaultSendParameters(void) const; + + /// Call interfaces, send data + virtual void Update(void); + + /// \internal + struct RM3World + { + RM3World(); + void Clear(ReplicaManager3 *replicaManager3); + + DataStructures::List connectionList; + DataStructures::List userReplicaList; + WorldId worldId; + NetworkIDManager *networkIDManager; + }; +protected: + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + virtual void OnRakPeerShutdown(void); + virtual void OnDetach(void); + + PluginReceiveResult OnConstruction(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId); + PluginReceiveResult OnSerialize(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, RakNet::Time timestamp, unsigned char packetDataOffset, WorldId worldId); + PluginReceiveResult OnDownloadStarted(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId); + PluginReceiveResult OnDownloadComplete(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId); + + void DeallocReplicaNoBroadcastDestruction(RakNet::Connection_RM3 *connection, RakNet::Replica3 *replica3); + RakNet::Connection_RM3 * PopConnection(unsigned int index, WorldId worldId); + Replica3* GetReplicaByNetworkID(NetworkID networkId, WorldId worldId); + unsigned int ReferenceInternal(RakNet::Replica3 *replica3, WorldId worldId); + + PRO defaultSendParameters; + RakNet::Time autoSerializeInterval; + RakNet::Time lastAutoSerializeOccurance; + bool autoCreateConnections, autoDestroyConnections; + Replica3 *currentlyDeallocatingReplica; + // Set on the first call to ReferenceInternal(), and should never be changed after that + // Used to lookup in Replica3LSRComp. I don't want to rely on GetNetworkID() in case it changes at runtime + uint32_t nextReferenceIndex; + + // For O(1) lookup + RM3World *worldsArray[255]; + // For fast traversal + DataStructures::List worldsList; + + friend class Connection_RM3; +}; + +static const int RM3_NUM_OUTPUT_BITSTREAM_CHANNELS=16; + +/// \ingroup REPLICA_MANAGER_GROUP3 +struct LastSerializationResultBS +{ + RakNet::BitStream bitStream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; +}; + +/// Represents the serialized data for an object the last time it was sent. Used by Connection_RM3::OnAutoserializeInterval() and Connection_RM3::SendSerializeIfChanged() +/// \ingroup REPLICA_MANAGER_GROUP3 +struct LastSerializationResult +{ + LastSerializationResult(); + ~LastSerializationResult(); + + /// The replica instance we serialized + /// \note replica MUST be the first member of this struct because I cast from replica to LastSerializationResult in Update() + RakNet::Replica3 *replica; + //bool neverSerialize; +// bool isConstructed; + RakNet::Time whenLastSerialized; + + void AllocBS(void); + LastSerializationResultBS* lastSerializationResultBS; +}; + +/// Parameters passed to Replica3::Serialize() +/// \ingroup REPLICA_MANAGER_GROUP3 +struct SerializeParameters +{ + /// Write your output for serialization here + /// If nothing is written, the serialization will not occur + /// Write to any or all of the NUM_OUTPUT_BITSTREAM_CHANNELS channels available. Channels can hold independent data + RakNet::BitStream outputBitstream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + + /// Last bitstream we sent for this replica to this system. + /// Read, but DO NOT MODIFY + RakNet::BitStream* lastSentBitstream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + + /// Set to non-zero to transmit a timestamp with this message. + /// Defaults to 0 + /// Use RakNet::GetTime() for this + RakNet::Time messageTimestamp; + + /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketPriority(). + /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultPacketReliability(). + /// Passed to RakPeerInterface::Send(). Defaults to ReplicaManager3::SetDefaultOrderingChannel(). + PRO pro[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + + /// Passed to RakPeerInterface::Send(). + RakNet::Connection_RM3 *destinationConnection; + + /// For prior serializations this tick, for the same connection, how many bits have we written so far? + /// Use this to limit how many objects you send to update per-tick if desired + BitSize_t bitsWrittenSoFar; + + /// When this object was last serialized to the connection + /// 0 means never + RakNet::Time whenLastSerialized; + + /// Current time, in milliseconds. + /// curTime - whenLastSerialized is how long it has been since this object was last sent + RakNet::Time curTime; +}; + +/// \ingroup REPLICA_MANAGER_GROUP3 +struct DeserializeParameters +{ + RakNet::BitStream serializationBitstream[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + bool bitstreamWrittenTo[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + RakNet::Time timeStamp; + RakNet::Connection_RM3 *sourceConnection; +}; + +/// \ingroup REPLICA_MANAGER_GROUP3 +enum SendSerializeIfChangedResult +{ + SSICR_SENT_DATA, + SSICR_DID_NOT_SEND_DATA, + SSICR_NEVER_SERIALIZE, +}; + +/// \brief Each remote system is represented by Connection_RM3. Used to allocate Replica3 and track which instances have been allocated +/// \details Important function: AllocReplica() - must be overridden to create an object given an identifier for that object, which you define for all objects in your game +/// \ingroup REPLICA_MANAGER_GROUP3 +class RAK_DLL_EXPORT Connection_RM3 +{ +public: + + Connection_RM3(const SystemAddress &_systemAddress, RakNetGUID _guid); + virtual ~Connection_RM3(); + + /// \brief Class factory to create a Replica3 instance, given a user-defined identifier + /// \details Identifier is returned by Replica3::WriteAllocationID() for what type of class to create.
+ /// This is called when you download a replica from another system.
+ /// See Replica3::Dealloc for the corresponding destruction message.
+ /// Return 0 if unable to create the intended object. Note, in that case the other system will still think we have the object and will try to serialize object updates to us. Generally, you should not send objects the other system cannot create.
+ /// \sa Replica3::WriteAllocationID(). + /// Sample implementation:
+ /// {RakNet::RakString typeName; allocationIdBitstream->Read(typeName); if (typeName=="Soldier") return new Soldier; return 0;}
+ /// \param[in] allocationIdBitstream user-defined bitstream uniquely identifying a game object type + /// \param[in] replicaManager3 Instance of ReplicaManager3 that controls this connection + /// \return The new replica instance + virtual Replica3 *AllocReplica(RakNet::BitStream *allocationIdBitstream, ReplicaManager3 *replicaManager3)=0; + + /// \brief Get list of all replicas that are constructed for this connection + /// \param[out] objectsTheyDoHave Destination list. Returned in sorted ascending order, sorted on the value of the Replica3 pointer. + virtual void GetConstructedReplicas(DataStructures::List &objectsTheyDoHave); + + /// Returns true if we think this remote connection has this replica constructed + /// \param[in] replica3 Which replica we are querying + /// \return True if constructed, false othewise + bool HasReplicaConstructed(RakNet::Replica3 *replica); + + /// When a new connection connects, before sending any objects, SerializeOnDownloadStarted() is called + /// \param[out] bitStream Passed to DeserializeOnDownloadStarted() + virtual void SerializeOnDownloadStarted(RakNet::BitStream *bitStream) {(void) bitStream;} + + /// Receives whatever was written in SerializeOnDownloadStarted() + /// \param[in] bitStream Written in SerializeOnDownloadStarted() + virtual void DeserializeOnDownloadStarted(RakNet::BitStream *bitStream) {(void) bitStream;} + + /// When a new connection connects, after constructing and serialization all objects, SerializeOnDownloadComplete() is called + /// \param[out] bitStream Passed to DeserializeOnDownloadComplete() + virtual void SerializeOnDownloadComplete(RakNet::BitStream *bitStream) {(void) bitStream;} + + /// Receives whatever was written in DeserializeOnDownloadComplete() + /// \param[in] bitStream Written in SerializeOnDownloadComplete() + virtual void DeserializeOnDownloadComplete(RakNet::BitStream *bitStream) {(void) bitStream;} + + /// \return The system address passed to the constructor of this object + SystemAddress GetSystemAddress(void) const {return systemAddress;} + + /// \return Returns the RakNetGUID passed to the constructor of this object + RakNetGUID GetRakNetGUID(void) const {return guid;} + + /// \return True if ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE arrived for this connection + bool GetDownloadWasCompleted(void) const {return gotDownloadComplete;} + + /// List of enumerations for how to get the list of valid objects for other systems + enum ConstructionMode + { + /// For every object that does not exist on the remote system, call Replica3::QueryConstruction() every tick. + /// Do not call Replica3::QueryDestruction() + /// Do not call Connection_RM3::QueryReplicaList() + QUERY_REPLICA_FOR_CONSTRUCTION, + + /// For every object that does not exist on the remote system, call Replica3::QueryConstruction() every tick. Based on the call, the object may be sent to the other system. + /// For every object that does exist on the remote system, call Replica3::QueryDestruction() every tick. Based on the call, the object may be deleted on the other system. + /// Do not call Connection_RM3::QueryReplicaList() + QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION, + + /// Do not call Replica3::QueryConstruction() or Replica3::QueryDestruction() + /// Call Connection_RM3::QueryReplicaList() to determine which objects exist on remote systems + /// This can be faster than QUERY_REPLICA_FOR_CONSTRUCTION and QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION for large worlds + /// See GridSectorizer.h under /Source for code that can help with this + QUERY_CONNECTION_FOR_REPLICA_LIST + }; + + /// \brief Return whether or not downloads to our system should all be processed the same tick (call to RakPeer::Receive() ) + /// \details Normally the system will send ID_REPLICA_MANAGER_DOWNLOAD_STARTED, ID_REPLICA_MANAGER_CONSTRUCTION for all downloaded objects, + /// ID_REPLICA_MANAGER_SERIALIZE for each downloaded object, and lastly ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE. + /// This enables the application to show a downloading splash screen on ID_REPLICA_MANAGER_DOWNLOAD_STARTED, a progress bar, and to close the splash screen and activate all objects on ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE + /// However, if the application was not set up for this then it would result in incomplete objects spread out over time, and cause problems + /// If you return true from QueryGroupDownloadMessages(), then these messages will be returned all in one tick, returned only when the download is complete + /// \note ID_REPLICA_MANAGER_DOWNLOAD_STARTED calls the callback DeserializeOnDownloadStarted() + /// \note ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE calls the callback DeserializeOnDownloadComplete() + virtual bool QueryGroupDownloadMessages(void) const {return false;} + + /// \brief Queries how to get the list of objects that exist on remote systems + /// \details The default of calling QueryConstruction for every known object is easy to use, but not efficient, especially for large worlds where many objects are outside of the player's circle of influence.
+ /// QueryDestruction is also not necessarily useful or efficient, as object destruction tends to happen in known cases, and can be accomplished by calling Replica3::BroadcastDestruction() + /// QueryConstructionMode() allows you to specify more efficient algorithms than the default when overriden. + /// \return How to get the list of objects that exist on the remote system. You should always return the same value for a given connection + virtual ConstructionMode QueryConstructionMode(void) const {return QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION;} + + /// \brief Callback used when QueryConstructionMode() returns QUERY_CONNECTION_FOR_REPLICA_LIST + /// \details This advantage of this callback is if that there are many objects that a particular connection does not have, then we do not have to iterate through those + /// objects calling QueryConstruction() for each of them.
+ ///
+ /// See GridSectorizer in the Source directory as a method to find all objects within a certain radius in a fast way.
+ ///
+ /// \param[out] newReplicasToCreate Anything in this list will be created on the remote system + /// \param[out] existingReplicasToDestroy Anything in this list will be destroyed on the remote system + virtual void QueryReplicaList( + DataStructures::List &newReplicasToCreate, + DataStructures::List &existingReplicasToDestroy) {(void) newReplicasToCreate; (void) existingReplicasToDestroy;} + + /// \brief Override which replicas to serialize and in what order for a connection for a ReplicaManager3::Update() cycle + /// \details By default, Connection_RM3 will iterate through queryToSerializeReplicaList and call QuerySerialization() on each Replica in that list + /// queryToSerializeReplicaList is populated in the order in which ReplicaManager3::Reference() is called for those objects. + /// If you write to to \a replicasToSerialize and return true, you can control in what order and for which replicas to call QuerySerialization() + /// Example use case: + /// We have more data to send then the bandwidth supports, so want to prioritize sends. For example enemies shooting are more important than animation effects + /// When QuerySerializationList(), sort objects by priority, and write the list to \a replicasToSerialize, optionally skipping objects with a lower serialization frequency + /// If you hit your bandwidth limit when checking SerializeParameters::bitsWrittenSoFar, you can return RM3SR_DO_NOT_SERIALIZE for all remaining items + /// \note Only replicas written to replicasToSerialize are transmitted. Even if you returned RM3SR_SERIALIZED_ALWAYS a prior ReplicaManager3::Update() cycle, the replica will not be transmitted if it is not in replicasToSerialize + /// \note If you do not know what objects are candidates for serialization, you can use queryToSerializeReplicaList as a source for your filtering or sorting operations + /// \param[in] replicasToSerialize List of replicas to call QuerySerialization() on + /// \return Return true to use replicasToSerialize (replicasToSerialize may be empty if desired). Otherwise return false. + virtual bool QuerySerializationList(DataStructures::List &replicasToSerialize) {(void) replicasToSerialize; return false;} + + /// \internal This is used internally - however, you can also call it manually to send a data update for a remote replica.
+ /// \brief Sends over a serialization update for \a replica.
+ /// NetworkID::GetNetworkID() is written automatically, serializationData is the object data.
+ /// \param[in] replica Which replica to serialize + /// \param[in] serializationData Serialized object data + /// \param[in] timestamp 0 means no timestamp. Otherwise message is prepended with ID_TIMESTAMP + /// \param[in] sendParameters Parameters on how to send + /// \param[in] rakPeer Instance of RakPeerInterface to send on + /// \param[in] worldId Which world, see ReplicaManager3::AddWorld() + /// \param[in] curTime The current time + virtual SendSerializeIfChangedResult SendSerialize(RakNet::Replica3 *replica, bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakNet::BitStream serializationData[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakNet::Time timestamp, PRO sendParameters[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakNet::RakPeerInterface *rakPeer, unsigned char worldId, RakNet::Time curTime); + + /// \internal + /// \details Calls Connection_RM3::SendSerialize() if Replica3::Serialize() returns a different result than what is contained in \a lastSerializationResult.
+ /// Used by autoserialization in Connection_RM3::OnAutoserializeInterval() + /// \param[in] lsr Item in the queryToSerializeReplicaList + /// \param[in] sp Controlling parameters over the serialization + /// \param[in] rakPeer Instance of RakPeerInterface to send on + /// \param[in] worldId Which world, see ReplicaManager3::AddWorld() + /// \param[in] curTime The current time + virtual SendSerializeIfChangedResult SendSerializeIfChanged(LastSerializationResult *lsr, SerializeParameters *sp, RakNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager, RakNet::Time curTime); + + /// \internal + /// \brief Given a list of objects that were created and destroyed, serialize and send them to another system. + /// \param[in] newObjects Objects to serialize construction + /// \param[in] deletedObjects Objects to serialize destruction + /// \param[in] sendParameters Controlling parameters over the serialization + /// \param[in] rakPeer Instance of RakPeerInterface to send on + /// \param[in] worldId Which world, see ReplicaManager3::AddWorld() + /// \param[in] replicaManager3 ReplicaManager3 instance + virtual void SendConstruction(DataStructures::List &newObjects, DataStructures::List &deletedObjects, PRO sendParameters, RakNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager3); + + /// \internal + void SendValidation(RakNet::RakPeerInterface *rakPeer, WorldId worldId); + + /// \internal + void AutoConstructByQuery(ReplicaManager3 *replicaManager3, WorldId worldId); + + + // Internal - does the other system have this connection too? Validated means we can now use it + bool isValidated; + // Internal - Used to see if we should send download started + bool isFirstConstruction; + + static int Replica3LSRComp( Replica3 * const &replica3, LastSerializationResult * const &data ); + + // Internal + void ClearDownloadGroup(RakPeerInterface *rakPeerInterface); +protected: + + SystemAddress systemAddress; + RakNetGUID guid; + + /* + Operations: + + Locally reference a new replica: + Add to queryToConstructReplicaList for all objects + + Add all objects to queryToConstructReplicaList + + Download: + Add to constructedReplicaList for connection that send the object to us + Add to queryToSerializeReplicaList for connection that send the object to us + Add to queryToConstructReplicaList for all other connections + + Never construct for this connection: + Remove from queryToConstructReplicaList + + Construct to this connection + Remove from queryToConstructReplicaList + Add to constructedReplicaList for this connection + Add to queryToSerializeReplicaList for this connection + + Serialize: + Iterate through queryToSerializeReplicaList + + Never serialize for this connection + Remove from queryToSerializeReplicaList + + Reference (this system has this object already) + Remove from queryToConstructReplicaList + Add to constructedReplicaList for this connection + Add to queryToSerializeReplicaList for this connection + + Downloaded an existing object + if replica is in queryToConstructReplicaList, OnConstructToThisConnection() + else ignore + + Send destruction from query + Remove from queryToDestructReplicaList + Remove from queryToSerializeReplicaList + Remove from constructedReplicaList + Add to queryToConstructReplicaList + + Do not query destruction again + Remove from queryToDestructReplicaList + */ + void OnLocalReference(Replica3* replica3, ReplicaManager3 *replicaManager); + void OnDereference(Replica3* replica3, ReplicaManager3 *replicaManager); + void OnDownloadFromThisSystem(Replica3* replica3, ReplicaManager3 *replicaManager); + void OnDownloadFromOtherSystem(Replica3* replica3, ReplicaManager3 *replicaManager); + void OnNeverConstruct(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager); + void OnConstructToThisConnection(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager); + void OnConstructToThisConnection(Replica3 *replica, ReplicaManager3 *replicaManager); + void OnNeverSerialize(LastSerializationResult *lsr, ReplicaManager3 *replicaManager); + void OnReplicaAlreadyExists(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager); + void OnDownloadExisting(Replica3* replica3, ReplicaManager3 *replicaManager); + void OnSendDestructionFromQuery(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager); + void OnDoNotQueryDestruction(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager); + void ValidateLists(ReplicaManager3 *replicaManager) const; + void SendSerializeHeader(RakNet::Replica3 *replica, RakNet::Time timestamp, RakNet::BitStream *bs, WorldId worldId); + + // The list of objects that our local system and this remote system both have + // Either we sent this object to them, or they sent this object to us + // A given Replica can be either in queryToConstructReplicaList or constructedReplicaList but not both at the same time + DataStructures::OrderedList constructedReplicaList; + + // Objects that we have, but this system does not, and we will query each tick to see if it should be sent to them + // If we do send it to them, the replica is moved to constructedReplicaList + // A given Replica can be either in queryToConstructReplicaList or constructedReplicaList but not both at the same time + DataStructures::List queryToConstructReplicaList; + + // Objects that this system has constructed are added at the same time to queryToSerializeReplicaList + // This list is used to serialize all objects that this system has to this connection + DataStructures::List queryToSerializeReplicaList; + + // Objects that are constructed on this system are also queried if they should be destroyed to this system + DataStructures::List queryToDestructReplicaList; + + // Working lists + DataStructures::List constructedReplicasCulled, destroyedReplicasCulled; + + // This is used if QueryGroupDownloadMessages() returns true when ID_REPLICA_MANAGER_DOWNLOAD_STARTED arrives + // Packets will be gathered and not returned until ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE arrives + bool groupConstructionAndSerialize; + DataStructures::Queue downloadGroup; + + // Stores if we got download complete for this connection + bool gotDownloadComplete; + + friend class ReplicaManager3; +private: + Connection_RM3() {}; + + ConstructionMode constructionMode; +}; + +/// \brief Return codes for Connection_RM3::GetConstructionState() and Replica3::QueryConstruction() +/// \details Indicates what state the object should be in for the remote system +/// \ingroup REPLICA_MANAGER_GROUP3 +enum RM3ConstructionState +{ + /// This object should exist on the remote system. Send a construction message if necessary + /// If the NetworkID is already in use, it will not do anything + /// If it is not in use, it will create the object, and then call DeserializeConstruction + RM3CS_SEND_CONSTRUCTION, + + /// This object should exist on the remote system. + /// The other system already has the object, and the object will never be deleted. + /// This is true of objects that are loaded with the level, for example. + /// Treat it as if it existed, without sending a construction message. + /// Will call Serialize() and SerializeConstructionExisting() to the object on the remote system + RM3CS_ALREADY_EXISTS_REMOTELY, + + /// Same as RM3CS_ALREADY_EXISTS_REMOTELY but does not call SerializeConstructionExisting() + RM3CS_ALREADY_EXISTS_REMOTELY_DO_NOT_CONSTRUCT, + + /// This object will never be sent to the target system + /// This object will never be serialized from this system to the target system + RM3CS_NEVER_CONSTRUCT, + + /// Don't do anything this tick. Will query again next tick + RM3CS_NO_ACTION, + + /// Max enum + RM3CS_MAX, +}; + +/// If this object already exists for this system, should it be removed? +/// \ingroup REPLICA_MANAGER_GROUP3 +enum RM3DestructionState +{ + /// This object should not exist on the remote system. Send a destruction message if necessary. + RM3DS_SEND_DESTRUCTION, + + /// This object will never be destroyed by a per-tick query. Don't call again + RM3DS_DO_NOT_QUERY_DESTRUCTION, + + /// Don't do anything this tick. Will query again next tick + RM3DS_NO_ACTION, + + /// Max enum + RM3DS_MAX, +}; + +/// Return codes when constructing an object +/// \ingroup REPLICA_MANAGER_GROUP3 +enum RM3SerializationResult +{ + /// This object serializes identically no matter who we send to + /// We also send it to every connection (broadcast). + /// Efficient for memory, speed, and bandwidth but only if the object is always broadcast identically. + RM3SR_BROADCAST_IDENTICALLY, + + /// Same as RM3SR_BROADCAST_IDENTICALLY, but assume the object needs to be serialized, do not check with a memcmp + /// Assume the object changed, and serialize it + /// Use this if you know exactly when your object needs to change. Can be faster than RM3SR_BROADCAST_IDENTICALLY. + /// An example of this is if every member variable has an accessor, changing a member sets a flag, and you check that flag in Replica3::QuerySerialization() + /// The opposite of this is RM3SR_DO_NOT_SERIALIZE, in case the object did not change + RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION, + + /// Either this object serializes differently depending on who we send to or we send it to some systems and not others. + /// Inefficient for memory and speed, but efficient for bandwidth + /// However, if you don't know what to return, return this + RM3SR_SERIALIZED_UNIQUELY, + + /// Do not compare against last sent value. Just send even if the data is the same as the last tick + /// If the data is always changing anyway, or you want to send unreliably, this is a good method of serialization + /// Can send unique data per connection if desired. If same data is sent to all connections, use RM3SR_SERIALIZED_ALWAYS_IDENTICALLY for even better performance + /// Efficient for memory and speed, but not necessarily bandwidth + RM3SR_SERIALIZED_ALWAYS, + + /// \deprecated, use RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION + RM3SR_SERIALIZED_ALWAYS_IDENTICALLY, + + /// Do not serialize this object this tick, for this connection. Will query again next autoserialize timer + RM3SR_DO_NOT_SERIALIZE, + + /// Never serialize this object for this connection + /// Useful for objects that are downloaded, and never change again + /// Efficient + RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION, + + /// Max enum + RM3SR_MAX, +}; + +/// First pass at topology to see if an object should be serialized +/// \ingroup REPLICA_MANAGER_GROUP3 +enum RM3QuerySerializationResult +{ + /// Call Serialize() to see if this object should be serializable for this connection + RM3QSR_CALL_SERIALIZE, + /// Do not call Serialize() this tick to see if this object should be serializable for this connection + RM3QSR_DO_NOT_CALL_SERIALIZE, + /// Never call Serialize() for this object and connection. This system will not serialize this object for this topology + RM3QSR_NEVER_CALL_SERIALIZE, + /// Max enum + RM3QSR_MAX, +}; + +/// \ingroup REPLICA_MANAGER_GROUP3 +enum RM3ActionOnPopConnection +{ + RM3AOPC_DO_NOTHING, + RM3AOPC_DELETE_REPLICA, + RM3AOPC_DELETE_REPLICA_AND_BROADCAST_DESTRUCTION, + RM3AOPC_MAX, +}; + +/// \ingroup REPLICA_MANAGER_GROUP3 +/// Used for Replica3::QueryConstruction_PeerToPeer() and Replica3::QuerySerialization_PeerToPeer() to describe how the object replicates between hosts +enum Replica3P2PMode +{ + /// The Replica3 instance is constructed and serialized by one system only. + /// Example: Your avatar. No other player serializes or can create your avatar. + R3P2PM_SINGLE_OWNER, + /// The Replica3 instance is constructed and/or serialized by different systems + /// This system is currently in charge of construction and/or serialization + /// Example: A pickup. When an avatar holds it, that avatar controls it. When it is on the ground, the host controls it. + R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE, + /// The Replica3 instance is constructed and/or serialized by different systems + /// Another system is in charge of construction and/or serialization, but this system may be in charge at a later time + /// Example: A pickup held by another player. That player sends creation of that object to new connections, and serializes it until it is dropped. + R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE, + /// The Replica3 instance is a static object (already exists on the remote system). + /// This system is currently in charge of construction and/or serialization + R3P2PM_STATIC_OBJECT_CURRENTLY_AUTHORITATIVE, + /// The Replica3 instance is a static object (already exists on the remote system). + /// Another system is in charge of construction and/or serialization, but this system may be in charge at a later time + R3P2PM_STATIC_OBJECT_NOT_CURRENTLY_AUTHORITATIVE, + +}; + +/// \brief Base class for your replicated objects for the ReplicaManager3 system. +/// \details To use, derive your class, or a member of your class, from Replica3.
+/// \ingroup REPLICA_MANAGER_GROUP3 +class RAK_DLL_EXPORT Replica3 : public NetworkIDObject +{ +public: + Replica3(); + + /// Before deleting a local instance of Replica3, call Replica3::BroadcastDestruction() for the deletion notification to go out on the network. + /// It is not necessary to call ReplicaManager3::Dereference(), as this happens automatically in the destructor + virtual ~Replica3(); + + /// \brief Write a unique identifer that can be read on a remote system to create an object of this same class. + /// \details The value written to \a allocationIdBitstream will be passed to Connection_RM3::AllocReplica().
+ /// Sample implementation:
+ /// {allocationIdBitstream->Write(RakNet::RakString("Soldier");}
+ /// \param[out] allocationIdBitstream Bitstream for the user to write to, to identify this class + virtual void WriteAllocationID(RakNet::Connection_RM3 *destinationConnection, RakNet::BitStream *allocationIdBitstream) const=0; + + /// \brief Ask if this object, which does not exist on \a destinationConnection should (now) be sent to that system. + /// \details If ReplicaManager3::QueryConstructionMode() returns QUERY_CONNECTION_FOR_REPLICA_LIST or QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION (default), + /// then QueyrConstruction() is called once per tick from ReplicaManager3::Update() to determine if an object should exist on a given system.
+ /// Based on the return value, a network message may be sent to the other system to create the object.
+ /// If QueryConstructionMode() is overriden to return QUERY_CONNECTION_FOR_REPLICA_LIST, this function is unused.
+ /// \note Defaults are provided: QueryConstruction_PeerToPeer(), QueryConstruction_ServerConstruction(), QueryConstruction_ClientConstruction(). Return one of these functions for a working default for the relevant topology. + /// \param[in] destinationConnection Which system we will send to + /// \param[in] replicaManager3 Plugin instance for this Replica3 + /// \return What action to take + virtual RM3ConstructionState QueryConstruction(RakNet::Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3)=0; + + /// \brief Ask if this object, which does exist on \a destinationConnection should be removed from the remote system + /// \details If ReplicaManager3::QueryConstructionMode() returns QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION (default), + /// then QueryDestruction() is called once per tick from ReplicaManager3::Update() to determine if an object that exists on a remote system should be destroyed for a given system.
+ /// Based on the return value, a network message may be sent to the other system to destroy the object.
+ /// Note that you can also destroy objects with BroadcastDestruction(), so this function is not useful unless you plan to delete objects for only a particular connection.
+ /// If QueryConstructionMode() is overriden to return QUERY_CONNECTION_FOR_REPLICA_LIST, this function is unused.
+ /// \param[in] destinationConnection Which system we will send to + /// \param[in] replicaManager3 Plugin instance for this Replica3 + /// \return What action to take. Only RM3CS_SEND_DESTRUCTION does anything at this time. + virtual RM3DestructionState QueryDestruction(RakNet::Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3) {(void) destinationConnection; (void) replicaManager3; return RM3DS_DO_NOT_QUERY_DESTRUCTION;} + + /// \brief We're about to call DeserializeConstruction() on this Replica3. If QueryRemoteConstruction() returns false, this object is deleted instead. + /// \details By default, QueryRemoteConstruction_ServerConstruction() does not allow clients to create objects. The client will get Replica3::DeserializeConstructionRequestRejected().
+ /// If you want the client to be able to potentially create objects for client/server, override accordingly.
+ /// Other variants of QueryRemoteConstruction_* just return true. + /// \note Defaults are provided: QueryRemoteConstruction_PeerToPeer(), QueryRemoteConstruction_ServerConstruction(), QueryRemoteConstruction_ClientConstruction(). Return one of these functions for a working default for the relevant topology. + /// \param[in] sourceConnection Which system sent us the object creation request message. + /// \return True to allow the object to pass onto DeserializeConstruction() (where it may also be rejected), false to immediately reject the remote construction request + virtual bool QueryRemoteConstruction(RakNet::Connection_RM3 *sourceConnection)=0; + + /// \brief We got a message from a connection to destroy this replica + /// Return true to automatically relay the destruction message to all our other connections + /// For a client in client/server, it does not matter what this funtion returns + /// For a server in client/server, this should normally return true + /// For a peer in peer to peer, you can normally return false since the original destroying peer would have told all other peers about the destruction + /// If a system gets a destruction command for an object that was already destroyed, the destruction message is ignored + virtual bool QueryRelayDestruction(Connection_RM3 *sourceConnection) const {(void) sourceConnection; return true;} + + /// \brief Write data to be sent only when the object is constructed on a remote system. + /// \details SerializeConstruction is used to write out data that you need to create this object in the context of your game, such as health, score, name. Use it for data you only need to send when the object is created.
+ /// After SerializeConstruction() is called, Serialize() will be called immediately thereafter. However, they are sent in different messages, so Serialize() may arrive a later frame than SerializeConstruction() + /// For that reason, the object should be valid after a call to DeserializeConstruction() for at least a short time.
+ /// \note The object's NetworkID and allocation id are handled by the system automatically, you do not need to write these values to \a constructionBitstream + /// \param[out] constructionBitstream Destination bitstream to write your data to + /// \param[in] destinationConnection System that will receive this network message. + virtual void SerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection)=0; + + /// \brief Read data written by Replica3::SerializeConstruction() + /// \details Reads whatever data was written to \a constructionBitstream in Replica3::SerializeConstruction() + /// \param[out] constructionBitstream Bitstream written to in Replica3::SerializeConstruction() + /// \param[in] sourceConnection System that sent us this network message. + /// \return true to accept construction of the object. false to reject, in which case the object will be deleted via Replica3::DeallocReplica() + virtual bool DeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection)=0; + + /// Same as SerializeConstruction(), but for an object that already exists on the remote system. + /// Used if you return RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction + virtual void SerializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) {(void) constructionBitstream; (void) destinationConnection;}; + + /// Same as DeserializeConstruction(), but for an object that already exists on the remote system. + /// Used if you return RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction + virtual void DeserializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) {(void) constructionBitstream; (void) sourceConnection;}; + + /// \brief Write extra data to send with the object deletion event, if desired + /// \details Replica3::SerializeDestruction() will be called to write any object destruction specific data you want to send with this event. + /// \a destructionBitstream can be read in DeserializeDestruction() + /// \param[out] destructionBitstream Bitstream for you to write to + /// \param[in] destinationConnection System that will receive this network message. + virtual void SerializeDestruction(RakNet::BitStream *destructionBitstream, RakNet::Connection_RM3 *destinationConnection)=0; + + /// \brief Read data written by Replica3::SerializeDestruction() + /// \details Return true to delete the object. BroadcastDestruction() will be called automatically, followed by ReplicaManager3::Dereference.
+ /// Return false to not delete it. If you delete it at a later point, you are responsible for calling BroadcastDestruction() yourself. + virtual bool DeserializeDestruction(RakNet::BitStream *destructionBitstream, RakNet::Connection_RM3 *sourceConnection)=0; + + /// \brief The system is asking what to do with this replica when the connection is dropped + /// \details Return QueryActionOnPopConnection_Client, QueryActionOnPopConnection_Server, or QueryActionOnPopConnection_PeerToPeer + virtual RakNet::RM3ActionOnPopConnection QueryActionOnPopConnection(RakNet::Connection_RM3 *droppedConnection) const=0; + + /// Notification called for each of our replicas when a connection is popped + virtual void OnPoppedConnection(RakNet::Connection_RM3 *droppedConnection) {(void) droppedConnection;} + + /// \brief Override with {delete this;} + /// \details + ///
    + ///
  1. Got a remote message to delete this object which passed DeserializeDestruction(), OR + ///
  2. ReplicaManager3::SetAutoManageConnections() was called autoDestroy true (which is the default setting), and a remote system that owns this object disconnected) OR + /// <\OL> + ///
    + /// Override with {delete this;} to actually delete the object (and any other processing you wish).
    + /// If you don't want to delete the object, just do nothing, however, the system will not know this. You may wish to call Dereference() if the object should no longer be networked, but remain in memory. You are responsible for deleting it yoruself later.
    + /// destructionBitstream may be 0 if the object was deleted locally + virtual void DeallocReplica(RakNet::Connection_RM3 *sourceConnection)=0; + + /// \brief Implement with QuerySerialization_ClientSerializable(), QuerySerialization_ServerSerializable(), or QuerySerialization_PeerToPeer() + /// \details QuerySerialization() is a first pass query to check if a given object should serializable to a given system. The intent is that the user implements with one of the defaults for client, server, or peer to peer.
    + /// Without this function, a careless implementation would serialize an object anytime it changed to all systems. This would give you feedback loops as the sender gets the same message back from the recipient it just sent to.
    + /// If more than one system can serialize the same object then you will need to override to return true, and control the serialization result from Replica3::Serialize(). Be careful not to send back the same data to the system that just sent to you! + /// \return True to allow calling Replica3::Serialize() for this connection, false to not call. + virtual RakNet::RM3QuerySerializationResult QuerySerialization(RakNet::Connection_RM3 *destinationConnection)=0; + + /// \brief Called for each replica owned by the user, once per Serialization tick, before Serialize() is called. + /// If you want to do some kind of operation on the Replica objects that you own, just before Serialization(), then overload this function + virtual void OnUserReplicaPreSerializeTick(void) {} + + /// \brief Serialize our class to a bitstream + /// \details User should implement this function to write the contents of this class to SerializationParamters::serializationBitstream.
    + /// If data only needs to be written once, you can write it to SerializeConstruction() instead for efficiency.
    + /// Transmitted over the network if it changed from the last time we called Serialize().
    + /// Called every time the time interval to ReplicaManager3::SetAutoSerializeInterval() elapses and ReplicaManager3::Update is subsequently called. + /// \param[in/out] serializeParameters Parameters controlling the serialization, including destination bitstream to write to + /// \return Whether to serialize, and if so, how to optimize the results + virtual RM3SerializationResult Serialize(RakNet::SerializeParameters *serializeParameters)=0; + + /// \brief Called when the class is actually transmitted via Serialize() + /// \details Use to track how much bandwidth this class it taking + virtual void OnSerializeTransmission(RakNet::BitStream *bitStream, RakNet::Connection_RM3 *destinationConnection, BitSize_t bitsPerChannel[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakNet::Time curTime) {(void) bitStream; (void) destinationConnection; (void) bitsPerChannel; (void) curTime;} + + /// \brief Read what was written in Serialize() + /// \details Reads the contents of the class from SerializationParamters::serializationBitstream.
    + /// Called whenever Serialize() is called with different data from the last send. + /// \param[in] serializationBitstream Bitstream passed to Serialize() + /// \param[in] timeStamp 0 if unused, else contains the time the message originated on the remote system + /// \param[in] sourceConnection Which system sent to us + virtual void Deserialize(RakNet::DeserializeParameters *deserializeParameters)=0; + + /// \brief Called after SerializeConstruction completes for all objects in a given update tick.
    + /// Writes to PostDeserializeConstruction(), which is called after all objects are created for a given Construction tick(). + /// Override to send data to PostDeserializeConstruction(), such as the NetworkID of other objects to resolve pointers to + virtual void PostSerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) {(void) constructionBitstream; (void) destinationConnection;} + + /// Called after DeserializeConstruction completes for all objects in a given update tick.
    + /// This is used to resolve dependency chains, where two objects would refer to each other in DeserializeConstruction, yet one had not been constructed yet + /// In PostDeserializeConstruction(), you know that all objects have already been created, so can resolve NetworkIDs to pointers safely. + /// You can also use it to trigger some sort of event when you know the object has completed deserialization. + /// \param[in] constructionBitstream BitStream written in PostSerializeConstruction() + /// \param[in] sourceConnection System that sent us this network message. + virtual void PostDeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) {(void) constructionBitstream; (void) sourceConnection;} + + /// Same as PostSerializeConstruction(), but for objects that returned RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction + virtual void PostSerializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) {(void) constructionBitstream; (void) destinationConnection;} + + /// Same as PostDeserializeConstruction(), but for objects that returned RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction + virtual void PostDeserializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) {(void) constructionBitstream; (void) sourceConnection;} + + /// Called after DeserializeDestruction completes for the object successfully, but obviously before the object is deleted.
    + /// Override to trigger some sort of event when you know the object has completed destruction. + /// \param[in] sourceConnection System that sent us this network message. + virtual void PreDestruction(RakNet::Connection_RM3 *sourceConnection) {(void) sourceConnection;} + + /// \brief Default call for QueryConstruction(). + /// \details Both the client and the server is allowed to create this object. The network topology is client/server + /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] isThisTheServer True if this system is the server, false if not. + virtual RM3ConstructionState QueryConstruction_ClientConstruction(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer); + + /// Default call for QueryRemoteConstruction(). + /// \details Both the client and the server is allowed to create this object. The network topology is client/server + /// The code means on the client or the server, allow creation of Replica3 instances + /// \param[in] sourceConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] isThisTheServer True if this system is the server, false if not. + virtual bool QueryRemoteConstruction_ClientConstruction(RakNet::Connection_RM3 *sourceConnection, bool isThisTheServer); + + /// \brief Default call for QueryConstruction(). + /// \details Only the server is allowed to create this object. The network topology is client/server + /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] isThisTheServer True if this system is the server, false if not. + virtual RM3ConstructionState QueryConstruction_ServerConstruction(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer); + + /// \brief Default call for QueryRemoteConstruction(). Allow the server to create this object, but not the client. + /// \details Only the server is allowed to create this object. The network topology is client/server + /// The code means if this is the server, and I got a command to create a Replica3 to ignore it. If this is the client, to allow it. + /// \param[in] sourceConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] isThisTheServer True if this system is the server, false if not. + virtual bool QueryRemoteConstruction_ServerConstruction(RakNet::Connection_RM3 *sourceConnection, bool isThisTheServer); + + /// \brief Default call for QueryConstruction(). + /// \details All clients are allowed to create all objects. The object is not relayed when remotely created + /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] p2pMode If controlled only by this system ever, pass R3P2PM_SINGLE_OWNER. Otherwise pass R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE or R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE + virtual RM3ConstructionState QueryConstruction_PeerToPeer(RakNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode=R3P2PM_SINGLE_OWNER); + /// \brief Default call for QueryRemoteConstruction(). + /// \details All clients are allowed to create all objects. The object is not relayed when remotely created + /// \param[in] sourceConnection destinationConnection parameter passed to QueryConstruction() + virtual bool QueryRemoteConstruction_PeerToPeer(RakNet::Connection_RM3 *sourceConnection); + + /// \brief Default call for QuerySerialization(). + /// \details Use if the values you are serializing are generated by the client that owns the object. The serialization will be relayed through the server to the other clients. + /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] isThisTheServer True if this system is the server, false if not. + virtual RakNet::RM3QuerySerializationResult QuerySerialization_ClientSerializable(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer); + /// \brief Default call for QuerySerialization(). + /// \details Use if the values you are serializing are generated only by the server. The serialization will be sent to all clients, but the clients will not send back to the server. + /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] isThisTheServer True if this system is the server, false if not. + virtual RakNet::RM3QuerySerializationResult QuerySerialization_ServerSerializable(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer); + /// \brief Default call for QuerySerialization(). + /// \details Use if the values you are serializing are on a peer to peer network. The peer that owns the object will send to all. Remote peers will not send. + /// \param[in] destinationConnection destinationConnection parameter passed to QueryConstruction() + /// \param[in] p2pMode If controlled only by this system ever, pass R3P2PM_SINGLE_OWNER. Otherwise pass R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE or R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE + virtual RakNet::RM3QuerySerializationResult QuerySerialization_PeerToPeer(RakNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode=R3P2PM_SINGLE_OWNER); + + /// Default: If we are a client, and the connection is lost, delete the server's objects + virtual RM3ActionOnPopConnection QueryActionOnPopConnection_Client(RakNet::Connection_RM3 *droppedConnection) const; + /// Default: If we are a server, and the connection is lost, delete the client's objects and broadcast the destruction + virtual RM3ActionOnPopConnection QueryActionOnPopConnection_Server(RakNet::Connection_RM3 *droppedConnection) const; + /// Default: If we are a peer, and the connection is lost, delete the peer's objects + virtual RM3ActionOnPopConnection QueryActionOnPopConnection_PeerToPeer(RakNet::Connection_RM3 *droppedConnection) const; + + /// Call to send a network message to delete this object on other systems.
    + /// Call it before deleting the object + virtual void BroadcastDestruction(void); + + /// creatingSystemGUID is set the first time Reference() is called, or if we get the object from another system + /// \return System that originally created this object + RakNetGUID GetCreatingSystemGUID(void) const; + + /// \return If ReplicaManager3::Reference() was called on this object. + bool WasReferenced(void) const {return replicaManager!=0;} + + /// GUID of the system that first called Reference() on this object. + /// Transmitted automatically when the object is constructed + RakNetGUID creatingSystemGUID; + /// GUID of the system that caused the item to send a deletion command over the network + RakNetGUID deletingSystemGUID; + + /// \internal + /// ReplicaManager3 plugin associated with this object + ReplicaManager3 *replicaManager; + + LastSerializationResultBS lastSentSerialization; + bool forceSendUntilNextUpdate; + LastSerializationResult *lsr; + uint32_t referenceIndex; +}; + +/// \brief Use Replica3 through composition instead of inheritance by containing an instance of this templated class +/// Calls to parent class for all functions +/// Parent class must still define and functions though! +/// \pre Parent class must call SetCompositeOwner() on this object +template +class RAK_DLL_EXPORT Replica3Composite : public Replica3 +{ +protected: + parent_type *r3CompositeOwner; +public: + void SetCompositeOwner(parent_type *p) {r3CompositeOwner=p;} + parent_type* GetCompositeOwner(void) const {return r3CompositeOwner;}; + virtual void WriteAllocationID(RakNet::Connection_RM3 *destinationConnection, RakNet::BitStream *allocationIdBitstream) const {r3CompositeOwner->WriteAllocationID(destinationConnection, allocationIdBitstream);} + virtual RakNet::RM3ConstructionState QueryConstruction(RakNet::Connection_RM3 *destinationConnection, RakNet::ReplicaManager3 *replicaManager3) {return r3CompositeOwner->QueryConstruction(destinationConnection, replicaManager3);} + virtual RakNet::RM3DestructionState QueryDestruction(RakNet::Connection_RM3 *destinationConnection, RakNet::ReplicaManager3 *replicaManager3) {return r3CompositeOwner->QueryDestruction(destinationConnection, replicaManager3);} + virtual bool QueryRemoteConstruction(RakNet::Connection_RM3 *sourceConnection) {return r3CompositeOwner->QueryRemoteConstruction(sourceConnection);} + virtual bool QueryRelayDestruction(RakNet::Connection_RM3 *sourceConnection) const {return r3CompositeOwner->QueryRelayDestruction(sourceConnection);} + virtual void SerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->SerializeConstruction(constructionBitstream, destinationConnection);} + virtual bool DeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) {return r3CompositeOwner->DeserializeConstruction(constructionBitstream, sourceConnection);} + virtual void SerializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->SerializeConstructionExisting(constructionBitstream, destinationConnection);} + virtual void DeserializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->DeserializeConstructionExisting(constructionBitstream, sourceConnection);} + virtual void SerializeDestruction(RakNet::BitStream *destructionBitstream, RakNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->SerializeDestruction(destructionBitstream, destinationConnection);} + virtual bool DeserializeDestruction(RakNet::BitStream *destructionBitstream, RakNet::Connection_RM3 *sourceConnection) {return r3CompositeOwner->DeserializeDestruction(destructionBitstream, sourceConnection);} + virtual RakNet::RM3ActionOnPopConnection QueryActionOnPopConnection(RakNet::Connection_RM3 *droppedConnection) const {return r3CompositeOwner->QueryActionOnPopConnection(droppedConnection);} + virtual void OnPoppedConnection(RakNet::Connection_RM3 *droppedConnection) {r3CompositeOwner->OnPoppedConnection(droppedConnection);} + virtual void DeallocReplica(RakNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->DeallocReplica(sourceConnection);} + virtual RakNet::RM3QuerySerializationResult QuerySerialization(RakNet::Connection_RM3 *destinationConnection) {return r3CompositeOwner->QuerySerialization(destinationConnection);} + virtual void OnUserReplicaPreSerializeTick(void) {r3CompositeOwner->OnUserReplicaPreSerializeTick();} + virtual RakNet::RM3SerializationResult Serialize(RakNet::SerializeParameters *serializeParameters) {return r3CompositeOwner->Serialize(serializeParameters);} + virtual void OnSerializeTransmission(RakNet::BitStream *bitStream, RakNet::Connection_RM3 *destinationConnection, RakNet::BitSize_t bitsPerChannel[RakNet::RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakNet::Time curTime) {r3CompositeOwner->OnSerializeTransmission(bitStream, destinationConnection, bitsPerChannel, curTime);} + virtual void Deserialize(RakNet::DeserializeParameters *deserializeParameters) {r3CompositeOwner->Deserialize(deserializeParameters);} + virtual void PostSerializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->PostSerializeConstruction(constructionBitstream, destinationConnection);} + virtual void PostDeserializeConstruction(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->PostDeserializeConstruction(constructionBitstream, sourceConnection);} + virtual void PostSerializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *destinationConnection) {r3CompositeOwner->PostSerializeConstructionExisting(constructionBitstream, destinationConnection);} + virtual void PostDeserializeConstructionExisting(RakNet::BitStream *constructionBitstream, RakNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->PostDeserializeConstructionExisting(constructionBitstream, sourceConnection);} + virtual void PreDestruction(RakNet::Connection_RM3 *sourceConnection) {r3CompositeOwner->PreDestruction(sourceConnection);} +}; + +} // namespace RakNet + + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/Router2.hpp b/include/raknet/Router2.hpp new file mode 100644 index 0000000..2fa9987 --- /dev/null +++ b/include/raknet/Router2.hpp @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Router2 plugin. Allows you to connect to a system by routing packets through another system that is connected to both you and the destination. Useful for getting around NATs. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_Router2==1 && _RAKNET_SUPPORT_UDPForwarder==1 + +#ifndef __ROUTER_2_PLUGIN_H +#define __ROUTER_2_PLUGIN_H + +#include "RakNetTypes.hpp" +#include "PluginInterface2.hpp" +#include "PacketPriority.hpp" +#include "Export.hpp" +#include "UDPForwarder.hpp" +#include "MessageIdentifiers.hpp" +#include "DS_List.hpp" +#include "SimpleMutex.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +struct Router2DebugInterface +{ + Router2DebugInterface() {} + virtual ~Router2DebugInterface() {} + virtual void ShowFailure(const char *message); + virtual void ShowDiagnostic(const char *message); +}; + +/// \defgroup ROUTER_2_GROUP Router2 +/// \brief Part of the NAT punchthrough solution, allowing you to connect to systems by routing through a shared connection. +/// \details Router2 routes datagrams between two systems that are not directly connected by using the bandwidth of a third system, to which the other two systems were connected +/// It is of benefit when a fully connected mesh topology is desired, but could not be completely established due to routers and/or firewalls +/// As the system address of a remote system will be the system address of the intermediary, it is necessary to use the RakNetGUID object to refer to systems, including with other plugins +/// \ingroup PLUGINS_GROUP + +/// \ingroup ROUTER_2_GROUP +/// \brief Class interface for the Router2 system +/// \details +class RAK_DLL_EXPORT Router2 : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(Router2) + + Router2(); + virtual ~Router2(); + + /// Sets the socket family to use, either IPV4 or IPV6 + /// \param[in] socketFamily For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. + void SetSocketFamily(unsigned short _socketFamily); + + /// \brief Query all connected systems to connect through them to a third system. + /// System will return ID_ROUTER_2_FORWARDING_NO_PATH if unable to connect. + /// Else you will get ID_ROUTER_2_FORWARDING_ESTABLISHED + /// + /// On ID_ROUTER_2_FORWARDING_ESTABLISHED, EstablishRouting as follows: + /// + /// RakNet::BitStream bs(packet->data, packet->length, false); + /// bs.IgnoreBytes(sizeof(MessageID)); + /// RakNetGUID endpointGuid; + /// bs.Read(endpointGuid); + /// unsigned short sourceToDestPort; + /// bs.Read(sourceToDestPort); + /// char ipAddressString[32]; + /// packet->systemAddress.ToString(false, ipAddressString); + /// rakPeerInterface->EstablishRouting(ipAddressString, sourceToDestPort, 0,0); + /// + /// \note The SystemAddress for a connection should not be used - always use RakNetGuid as the address can change at any time. + /// When the address changes, you will get ID_ROUTER_2_REROUTED + void EstablishRouting(RakNetGUID endpointGuid); + + /// Set the maximum number of bidirectional connections this system will support + /// Defaults to 0 + void SetMaximumForwardingRequests(int max); + + /// For testing and debugging + void SetDebugInterface(Router2DebugInterface *_debugInterface); + + /// Get the pointer passed to SetDebugInterface() + Router2DebugInterface *GetDebugInterface(void) const; + + // -------------------------------------------------------------------------------------------- + // Packet handling functions + // -------------------------------------------------------------------------------------------- + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void Update(void); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason); + virtual void OnRakPeerShutdown(void); + + + enum Router2RequestStates + { + R2RS_REQUEST_STATE_QUERY_FORWARDING, + REQUEST_STATE_REQUEST_FORWARDING, + }; + + struct ConnectionRequestSystem + { + RakNetGUID guid; + int pingToEndpoint; + unsigned short usedForwardingEntries; + }; + + struct ConnnectRequest + { + ConnnectRequest(); + ~ConnnectRequest(); + + DataStructures::List connectionRequestSystems; + SimpleMutex connectionRequestSystemsMutex; + Router2RequestStates requestState; + RakNet::TimeMS pingTimeout; + RakNetGUID endpointGuid; + RakNetGUID lastRequestedForwardingSystem; + bool returnConnectionLostOnFailure; + unsigned int GetGuidIndex(RakNetGUID guid); + }; + + unsigned int GetConnectionRequestIndex(RakNetGUID endpointGuid); + + struct MiniPunchRequest + { + RakNetGUID endpointGuid; + SystemAddress endpointAddress; + bool gotReplyFromEndpoint; + RakNetGUID sourceGuid; + SystemAddress sourceAddress; + bool gotReplyFromSource; + RakNet::TimeMS timeout; + RakNet::TimeMS nextAction; + unsigned short forwardingPort; + __UDPSOCKET__ forwardingSocket; + }; + + struct ForwardedConnection + { + RakNetGUID endpointGuid; + RakNetGUID intermediaryGuid; + SystemAddress intermediaryAddress; + bool returnConnectionLostOnFailure; + bool weInitiatedForwarding; + }; + +protected: + + bool UpdateForwarding(ConnnectRequest* connectionRequest); + void RemoveConnectionRequest(unsigned int connectionRequestIndex); + void RequestForwarding(ConnnectRequest* connectionRequest); + void OnQueryForwarding(Packet *packet); + void OnQueryForwardingReply(Packet *packet); + void OnRequestForwarding(Packet *packet); + void OnRerouted(Packet *packet); + void OnMiniPunchReply(Packet *packet); + void OnMiniPunchReplyBounce(Packet *packet); + bool OnForwardingSuccess(Packet *packet); + int GetLargestPingAmongConnectedSystems(void) const; + void ReturnToUser(MessageID messageId, RakNetGUID endpointGuid, const SystemAddress &systemAddress, bool wasGeneratedLocally); + bool ConnectInternal(RakNetGUID endpointGuid, bool returnConnectionLostOnFailure); + + UDPForwarder *udpForwarder; + int maximumForwardingRequests; + SimpleMutex connectionRequestsMutex, miniPunchesInProgressMutex, forwardedConnectionListMutex; + DataStructures::List connectionRequests; + DataStructures::List miniPunchesInProgress; + // Forwarding we have initiated + DataStructures::List forwardedConnectionList; + + void ClearConnectionRequests(void); + void ClearMinipunches(void); + void ClearForwardedConnections(void); + void ClearAll(void); + int ReturnFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid); + void SendFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid); + void SendForwardingSuccess(MessageID messageId, RakNetGUID sourceGuid, RakNetGUID endpointGuid, unsigned short sourceToDstPort); + void SendOOBFromRakNetPort(OutOfBandIdentifiers oob, BitStream *extraData, SystemAddress sa); + void SendOOBFromSpecifiedSocket(OutOfBandIdentifiers oob, SystemAddress sa, __UDPSOCKET__ socket); + void SendOOBMessages(MiniPunchRequest *mpr); + + Router2DebugInterface *debugInterface; + unsigned short socketFamily; +}; + +} + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/SecureHandshake.hpp b/include/raknet/SecureHandshake.hpp new file mode 100644 index 0000000..8a5dfcf --- /dev/null +++ b/include/raknet/SecureHandshake.hpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#ifndef SECURE_HANDSHAKE_H +#define SECURE_HANDSHAKE_H + +#include "NativeFeatureIncludes.hpp" + +#if LIBCAT_SECURITY==1 + +// If building a RakNet DLL, be sure to tweak the CAT_EXPORT macro meaning +#if !defined(_RAKNET_LIB) && defined(_RAKNET_DLL) +# define CAT_BUILD_DLL +#else +# define CAT_NEUTER_EXPORT +#endif + +// Include DependentExtensions in your path to include this +#include "cat/AllTunnel.hpp" + +#endif // LIBCAT_SECURITY + +#endif // SECURE_HANDSHAKE_H diff --git a/include/raknet/SendToThread.hpp b/include/raknet/SendToThread.hpp new file mode 100644 index 0000000..5df911d --- /dev/null +++ b/include/raknet/SendToThread.hpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __SENDTO_THREAD +#define __SENDTO_THREAD + +#include "RakNetDefines.hpp" + +#ifdef USE_THREADED_SEND + +#include "InternalPacket.hpp" +#include "SocketLayer.hpp" +#include "DS_ThreadsafeAllocatingQueue.hpp" +#include "ThreadPool.hpp" + +namespace RakNet +{ +class SendToThread +{ +public: + SendToThread(); + ~SendToThread(); + + struct SendToThreadBlock + { + SOCKET s; + SystemAddress systemAddress; + unsigned short remotePortRakNetWasStartedOn_PS3; + unsigned int extraSocketOptions; + char data[MAXIMUM_MTU_SIZE]; + unsigned short dataWriteOffset; + }; + + static SendToThreadBlock* AllocateBlock(void); + static void ProcessBlock(SendToThreadBlock* threadedSend); + + static void AddRef(void); + static void Deref(void); + static DataStructures::ThreadsafeAllocatingQueue objectQueue; +protected: + static int refCount; + static ThreadPool threadPool; + +}; +} + + +#endif + +#endif diff --git a/include/raknet/SignaledEvent.hpp b/include/raknet/SignaledEvent.hpp new file mode 100644 index 0000000..0d46199 --- /dev/null +++ b/include/raknet/SignaledEvent.hpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __SIGNALED_EVENT_H +#define __SIGNALED_EVENT_H + + + +#if defined(_WIN32) +#include "WindowsIncludes.hpp" + + + +#else + #include + #include + #include "SimpleMutex.hpp" + + + + +#endif + +#include "Export.hpp" + +namespace RakNet +{ + +class RAK_DLL_EXPORT SignaledEvent +{ +public: + SignaledEvent(); + ~SignaledEvent(); + + void InitEvent(void); + void CloseEvent(void); + void SetEvent(void); + void WaitOnEvent(int timeoutMs); + +protected: +#ifdef _WIN32 + HANDLE eventList; + + + + + +#else + SimpleMutex isSignaledMutex; + bool isSignaled; +#if !defined(ANDROID) + pthread_condattr_t condAttr; +#endif + pthread_cond_t eventList; + pthread_mutex_t hMutex; + pthread_mutexattr_t mutexAttr; +#endif +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/SimpleMutex.hpp b/include/raknet/SimpleMutex.hpp new file mode 100644 index 0000000..5b99e68 --- /dev/null +++ b/include/raknet/SimpleMutex.hpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] Encapsulates a mutex +/// + + + +#ifndef __SIMPLE_MUTEX_H +#define __SIMPLE_MUTEX_H + +#include "RakMemoryOverride.hpp" + + +#if defined(_WIN32) +#include "WindowsIncludes.hpp" + + +#else +#include +#include +#endif +#include "Export.hpp" + +namespace RakNet +{ + +/// \brief An easy to use mutex. +/// +/// I wrote this because the version that comes with Windows is too complicated and requires too much code to use. +/// @remark Previously I used this everywhere, and in fact for a year or two RakNet was totally threadsafe. While doing profiling, I saw that this function was incredibly slow compared to the blazing performance of everything else, so switched to single producer / consumer everywhere. Now the user thread of RakNet is not threadsafe, but it's 100X faster than before. +class RAK_DLL_EXPORT SimpleMutex +{ +public: + + // Constructor + SimpleMutex(); + + // Destructor + ~SimpleMutex(); + + // Locks the mutex. Slow! + void Lock(void); + + // Unlocks the mutex. + void Unlock(void); + + + + + + + +private: + void Init(void); +#ifdef _WIN32 + CRITICAL_SECTION criticalSection; /// Docs say this is faster than a mutex for single process access + + +#else + pthread_mutex_t hMutex; +#endif + // Not threadsafe + // bool isInitialized; +}; + +} // namespace RakNet + +#endif + diff --git a/include/raknet/SimpleTCPServer.hpp b/include/raknet/SimpleTCPServer.hpp new file mode 100644 index 0000000..1181cd0 --- /dev/null +++ b/include/raknet/SimpleTCPServer.hpp @@ -0,0 +1 @@ +// Eraseme \ No newline at end of file diff --git a/include/raknet/SingleProducerConsumer.hpp b/include/raknet/SingleProducerConsumer.hpp new file mode 100644 index 0000000..6dde659 --- /dev/null +++ b/include/raknet/SingleProducerConsumer.hpp @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b [Internal] Passes queued data between threads using a circular buffer with read and write pointers +/// + + + +#ifndef __SINGLE_PRODUCER_CONSUMER_H +#define __SINGLE_PRODUCER_CONSUMER_H + +#include "RakAssert.hpp" + +static const int MINIMUM_LIST_SIZE=8; + +#include "RakMemoryOverride.hpp" +#include "Export.hpp" + +/// The namespace DataStructures was only added to avoid compiler errors for commonly named data structures +/// As these data structures are stand-alone, you can use them outside of RakNet for your own projects if you wish. +namespace DataStructures +{ + /// \brief A single producer consumer implementation without critical sections. + template + class RAK_DLL_EXPORT SingleProducerConsumer + { + public: + // Constructor + SingleProducerConsumer(); + + // Destructor + ~SingleProducerConsumer(); + + /// WriteLock must be immediately followed by WriteUnlock. These two functions must be called in the same thread. + /// \return A pointer to a block of data you can write to. + SingleProducerConsumerType* WriteLock(void); + + /// Call if you don't want to write to a block of data from WriteLock() after all. + /// Cancelling locks cancels all locks back up to the data passed. So if you lock twice and cancel using the first lock, the second lock is ignored + /// \param[in] cancelToLocation Which WriteLock() to cancel. + void CancelWriteLock(SingleProducerConsumerType* cancelToLocation); + + /// Call when you are done writing to a block of memory returned by WriteLock() + void WriteUnlock(void); + + /// ReadLock must be immediately followed by ReadUnlock. These two functions must be called in the same thread. + /// \retval 0 No data is availble to read + /// \retval Non-zero The data previously written to, in another thread, by WriteLock followed by WriteUnlock. + SingleProducerConsumerType* ReadLock(void); + + // Cancelling locks cancels all locks back up to the data passed. So if you lock twice and cancel using the first lock, the second lock is ignored + /// param[in] Which ReadLock() to cancel. + void CancelReadLock(SingleProducerConsumerType* cancelToLocation); + + /// Signals that we are done reading the the data from the least recent call of ReadLock. + /// At this point that pointer is no longer valid, and should no longer be read. + void ReadUnlock(void); + + /// Clear is not thread-safe and none of the lock or unlock functions should be called while it is running. + void Clear(void); + + /// This function will estimate how many elements are waiting to be read. It's threadsafe enough that the value returned is stable, but not threadsafe enough to give accurate results. + /// \return An ESTIMATE of how many data elements are waiting to be read + int Size(void) const; + + /// Make sure that the pointer we done reading for the call to ReadUnlock is the right pointer. + /// param[in] A previous pointer returned by ReadLock() + bool CheckReadUnlockOrder(const SingleProducerConsumerType* data) const; + + /// Returns if ReadUnlock was called before ReadLock + /// \return If the read is locked + bool ReadIsLocked(void) const; + + private: + struct DataPlusPtr + { + DataPlusPtr () {readyToRead=false;} + SingleProducerConsumerType object; + + // Ready to read is so we can use an equality boolean comparison, in case the writePointer var is trashed while context switching. + volatile bool readyToRead; + volatile DataPlusPtr *next; + }; + volatile DataPlusPtr *readAheadPointer; + volatile DataPlusPtr *writeAheadPointer; + volatile DataPlusPtr *readPointer; + volatile DataPlusPtr *writePointer; + unsigned readCount, writeCount; + }; + + template + SingleProducerConsumer::SingleProducerConsumer() + { + // Preallocate + readPointer = RakNet::OP_NEW( _FILE_AND_LINE_ ); + writePointer=readPointer; + readPointer->next = RakNet::OP_NEW( _FILE_AND_LINE_ ); + int listSize; +#ifdef _DEBUG + RakAssert(MINIMUM_LIST_SIZE>=3); +#endif + for (listSize=2; listSize < MINIMUM_LIST_SIZE; listSize++) + { + readPointer=readPointer->next; + readPointer->next = RakNet::OP_NEW( _FILE_AND_LINE_ ); + } + readPointer->next->next=writePointer; // last to next = start + readPointer=writePointer; + readAheadPointer=readPointer; + writeAheadPointer=writePointer; + readCount=writeCount=0; + } + + template + SingleProducerConsumer::~SingleProducerConsumer() + { + volatile DataPlusPtr *next; + readPointer=writeAheadPointer->next; + while (readPointer!=writeAheadPointer) + { + next=readPointer->next; + RakNet::OP_DELETE((char*) readPointer, _FILE_AND_LINE_); + readPointer=next; + } + RakNet::OP_DELETE((char*) readPointer, _FILE_AND_LINE_); + } + + template + SingleProducerConsumerType* SingleProducerConsumer::WriteLock( void ) + { + if (writeAheadPointer->next==readPointer || + writeAheadPointer->next->readyToRead==true) + { + volatile DataPlusPtr *originalNext=writeAheadPointer->next; + writeAheadPointer->next=RakNet::OP_NEW(_FILE_AND_LINE_); + RakAssert(writeAheadPointer->next); + writeAheadPointer->next->next=originalNext; + } + + volatile DataPlusPtr *last; + last=writeAheadPointer; + writeAheadPointer=writeAheadPointer->next; + + return (SingleProducerConsumerType*) last; + } + + template + void SingleProducerConsumer::CancelWriteLock( SingleProducerConsumerType* cancelToLocation ) + { + writeAheadPointer=(DataPlusPtr *)cancelToLocation; + } + + template + void SingleProducerConsumer::WriteUnlock( void ) + { + // DataPlusPtr *dataContainer = (DataPlusPtr *)structure; + +#ifdef _DEBUG + RakAssert(writePointer->next!=readPointer); + RakAssert(writePointer!=writeAheadPointer); +#endif + + writeCount++; + // User is done with the data, allow send by updating the write pointer + writePointer->readyToRead=true; + writePointer=writePointer->next; + } + + template + SingleProducerConsumerType* SingleProducerConsumer::ReadLock( void ) + { + if (readAheadPointer==writePointer || + readAheadPointer->readyToRead==false) + { + return 0; + } + + volatile DataPlusPtr *last; + last=readAheadPointer; + readAheadPointer=readAheadPointer->next; + return (SingleProducerConsumerType*)last; + } + + template + void SingleProducerConsumer::CancelReadLock( SingleProducerConsumerType* cancelToLocation ) + { +#ifdef _DEBUG + RakAssert(readPointer!=writePointer); +#endif + readAheadPointer=(DataPlusPtr *)cancelToLocation; + } + + template + void SingleProducerConsumer::ReadUnlock( void ) + { +#ifdef _DEBUG + RakAssert(readAheadPointer!=readPointer); // If hits, then called ReadUnlock before ReadLock + RakAssert(readPointer!=writePointer); // If hits, then called ReadUnlock when Read returns 0 +#endif + readCount++; + + // Allow writes to this memory block + readPointer->readyToRead=false; + readPointer=readPointer->next; + } + + template + void SingleProducerConsumer::Clear( void ) + { + // Shrink the list down to MINIMUM_LIST_SIZE elements + volatile DataPlusPtr *next; + writePointer=readPointer->next; + + int listSize=1; + next=readPointer->next; + while (next!=readPointer) + { + listSize++; + next=next->next; + } + + while (listSize-- > MINIMUM_LIST_SIZE) + { + next=writePointer->next; +#ifdef _DEBUG + RakAssert(writePointer!=readPointer); +#endif + RakNet::OP_DELETE((char*) writePointer, _FILE_AND_LINE_); + writePointer=next; + } + + readPointer->next=writePointer; + writePointer=readPointer; + readAheadPointer=readPointer; + writeAheadPointer=writePointer; + readCount=writeCount=0; + } + + template + int SingleProducerConsumer::Size( void ) const + { + return writeCount-readCount; + } + + template + bool SingleProducerConsumer::CheckReadUnlockOrder(const SingleProducerConsumerType* data) const + { + return const_cast(&readPointer->object) == data; + } + + + template + bool SingleProducerConsumer::ReadIsLocked(void) const + { + return readAheadPointer!=readPointer; + } +} + +#endif diff --git a/include/raknet/SocketDefines.hpp b/include/raknet/SocketDefines.hpp new file mode 100644 index 0000000..ab975ed --- /dev/null +++ b/include/raknet/SocketDefines.hpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __SOCKET_DEFINES_H +#define __SOCKET_DEFINES_H + +/// Internal + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#if defined(WINDOWS_STORE_RT) + #include "WinRTSocketAdapter.hpp" + #define accept__ WinRTAccept + #define connect__ WinRTConnect + #define closesocket__ WinRTClose + #define socket__ WinRTCreateDatagramSocket + #define bind__ WinRTBind + #define getsockname__ RNS2_WindowsStore8::WinRTGetSockName + #define getsockopt__ WinRTGetSockOpt + #define inet_addr__ RNS2_WindowsStore8::WinRTInet_Addr + #define ioctlsocket__ RNS2_WindowsStore8::WinRTIOCTLSocket + #define listen__ WinRTListen + #define recv__ WinRTRecv + #define recvfrom__ WinRTRecvFrom + #define select__ WinRTSelect + #define send__ WinRTSend + #define sendto__ WinRTSendTo + #define setsockopt__ RNS2_WindowsStore8::WinRTSetSockOpt + #define shutdown__ WinRTShutdown + #define WSASendTo__ WinRTSendTo +#else + + + + + + + #if defined(_WIN32) + #define closesocket__ closesocket + #define select__ select + #elif defined(__native_client__) + // namespace RakNet { void CloseSocket(SOCKET s); } + // #define closesocket__ RakNet::CloseSocket + #define select__ select + #else + #define closesocket__ close + #define select__ select + #endif + #define accept__ accept + #define connect__ connect + + + + #define socket__ socket + + #define bind__ bind + #define getsockname__ getsockname + #define getsockopt__ getsockopt + + + + #define inet_addr__ inet_addr + + #define ioctlsocket__ ioctlsocket + #define listen__ listen + #define recv__ recv + #define recvfrom__ recvfrom + + + + #define sendto__ sendto + + #define send__ send + + + + #define setsockopt__ setsockopt + + #define shutdown__ shutdown + #define WSASendTo__ WSASendTo +#endif + +#endif diff --git a/include/raknet/SocketIncludes.hpp b/include/raknet/SocketIncludes.hpp new file mode 100644 index 0000000..cddcc3c --- /dev/null +++ b/include/raknet/SocketIncludes.hpp @@ -0,0 +1,98 @@ +#ifndef RAKNET_SOCKETINCLUDES_H +#define RAKNET_SOCKETINCLUDES_H + +// All this crap just to include type SOCKET + +#ifdef __native_client__ +#define _PP_Instance_ PP_Instance +#else +#define _PP_Instance_ int +#endif + + + + + + + + + + + + + + + + + + + + +#if defined(WINDOWS_STORE_RT) + #include + #include "WinRTSockAddr.hpp" + typedef Windows::Networking::Sockets::DatagramSocket^ __UDPSOCKET__; + typedef Windows::Networking::Sockets::StreamSocket^ __TCPSOCKET__; + typedef unsigned int socklen_t; + #define FORMAT_MESSAGE_ALLOCATE_BUFFER 0 + #define FIONBIO 0 + #define LocalFree(x) + // using Windows.Networking; + // using Windows.Networking.Sockets; + // See http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets.datagramsocketcontrol +#elif defined(_WIN32) + // IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib + // winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly + // WinRT: http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets + // Sample code: http://stackoverflow.com/questions/10290945/correct-use-of-udp-datagramsocket + #include + typedef SOCKET __UDPSOCKET__; + typedef SOCKET __TCPSOCKET__; + typedef int socklen_t; +#else + #define closesocket close + #include + #include + #include + #include + #include + #include + #include + + #ifdef __native_client__ + #include "ppapi/cpp/private/net_address_private.hpp" + #include "ppapi/c/pp_bool.hpp" + #include "ppapi/c/pp_errors.hpp" + #include "ppapi/cpp/completion_callback.hpp" + #include "ppapi/cpp/instance_handle.hpp" + #include "ppapi/cpp/module.hpp" + #include "ppapi/cpp/module_impl.hpp" + #include "ppapi/c/pp_errors.hpp" + #include "ppapi/c/pp_module.hpp" + #include "ppapi/c/pp_var.hpp" + #include "ppapi/c/pp_resource.hpp" + #include "ppapi/c/ppb.hpp" + #include "ppapi/c/ppb_instance.hpp" + #include "ppapi/c/ppb_messaging.hpp" + #include "ppapi/c/ppb_var.hpp" + #include "ppapi/c/ppp.hpp" + #include "ppapi/c/ppb_core.hpp" + #include "ppapi/c/ppp_instance.hpp" + #include "ppapi/c/ppp_messaging.hpp" + #include "ppapi/c/pp_input_event.hpp" + #include "ppapi/c/pp_completion_callback.hpp" + //UDP specific - the 'private' folder was copied from the chromium src/ppapi/c headers folder + #include "ppapi/c/private/ppb_udp_socket_private.hpp" + #include "ppapi/cpp/private/net_address_private.hpp" + typedef PP_Resource __UDPSOCKET__; + typedef PP_Resource __TCPSOCKET__; + #else + //#include "RakMemoryOverride.hpp" + /// Unix/Linux uses ints for sockets + typedef int __UDPSOCKET__; + typedef int __TCPSOCKET__; +#endif + +#endif + +#endif // RAKNET_SOCKETINCLUDES_H diff --git a/include/raknet/SocketLayer.hpp b/include/raknet/SocketLayer.hpp new file mode 100644 index 0000000..fcefafa --- /dev/null +++ b/include/raknet/SocketLayer.hpp @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief SocketLayer class implementation +/// + + + + +#ifndef __SOCKET_LAYER_H +#define __SOCKET_LAYER_H + +#include "RakMemoryOverride.hpp" +#include "RakNetTypes.hpp" +#include "RakNetSmartPtr.hpp" +//#include "RakNetSocket.hpp" +#include "Export.hpp" +#include "MTUSize.hpp" +#include "RakString.hpp" + +//#include "ClientContextStruct.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeer; + +/* +class RAK_DLL_EXPORT SocketLayerOverride +{ +public: + SocketLayerOverride() {} + virtual ~SocketLayerOverride() {} + + /// Called when SendTo would otherwise occur. + virtual int RakNetSendTo( const char *data, int length, const SystemAddress &systemAddress )=0; + + /// Called when RecvFrom would otherwise occur. Return number of bytes read. Write data into dataOut + // Return -1 to use RakNet's normal recvfrom, 0 to abort RakNet's normal recvfrom, and positive to return data + virtual int RakNetRecvFrom( char dataOut[ MAXIMUM_MTU_SIZE ], SystemAddress *senderOut, bool calledFromMainThread )=0; +}; +*/ + +// A platform independent implementation of Berkeley sockets, with settings used by RakNet +class RAK_DLL_EXPORT SocketLayer +{ + +public: + + /// Default Constructor + SocketLayer(); + + // Destructor + ~SocketLayer(); + + /* + /// Creates a bound socket to listen for incoming connections on the specified port + /// \param[in] port the port number + /// \param[in] blockingSocket + /// \return A new socket used for accepting clients + static RakNetSocket* CreateBoundSocket( RakPeer *peer, unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048, unsigned int extraSocketOptions, unsigned short socketFamily, _PP_Instance_ chromeInstance ); +#if defined(WINDOWS_STORE_RT) + static RakNetSocket* CreateWindowsStore8Socket( RakPeer *peer, unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048, unsigned int extraSocketOptions, _PP_Instance_ chromeInstance ); +#endif + static RakNetSocket* CreateBoundSocket_IPV4( RakPeer *peer, unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048, unsigned int extraSocketOptions, _PP_Instance_ chromeInstance ); + #if RAKNET_SUPPORT_IPV6==1 + static RakNetSocket* CreateBoundSocket_SupportIPV4And6( RakPeer *peer, unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048, unsigned int extraSocketOptions, unsigned short socketFamily, _PP_Instance_ chromeInstance ); + #endif + static RakNetSocket* CreateBoundSocket_PS3Lobby( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned short socketFamily ); + static RakNetSocket* CreateBoundSocket_PSP2( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned short socketFamily ); + */ + + /* +#ifndef WINDOWS_STORE_RT + /// Returns if this specified port is in use, for UDP + /// \param[in] port the port number + /// \return If this port is already in use + //static bool IsPortInUse_Old(unsigned short port, const char *hostAddress); + //static bool IsPortInUse(unsigned short port, const char *hostAddress, unsigned short socketFamily ); + static bool IsSocketFamilySupported(const char *hostAddress, unsigned short socketFamily); +#endif + */ + +// static const char* DomainNameToIP_Old( const char *domainName ); +// static const char* DomainNameToIP( const char *domainName ); + + /// Write \a data of length \a length to \a writeSocket + /// \param[in] writeSocket The socket to write to + /// \param[in] data The data to write + /// \param[in] length The length of \a data + // static void Write( RakNetSocket*writeSocket, const char* data, const int length ); + + /// Read data from a socket + /// \param[in] s the socket + /// \param[in] rakPeer The instance of rakPeer containing the recvFrom C callback + /// \param[in] errorCode An error code if an error occured . + /// \param[in] connectionSocketIndex Which of the sockets in RakPeer we are using + /// \return Returns true if you successfully read data, false on error. +// static void RecvFromBlocking_IPV4( RakNetSocket *s, RakPeer *rakPeer, char *dataOut, int *bytesReadOut, SystemAddress *systemAddressOut, RakNet::TimeUS *timeRead ); +// #if RAKNET_SUPPORT_IPV6==1 +// static void RecvFromBlockingIPV4And6( RakNetSocket *s, RakPeer *rakPeer, char *dataOut, int *bytesReadOut, SystemAddress *systemAddressOut, RakNet::TimeUS *timeRead ); +// #endif +// static void RecvFromBlocking( RakNetSocket *s, RakPeer *rakPeer, char *dataOut, int *bytesReadOut, SystemAddress *systemAddressOut, RakNet::TimeUS *timeRead ); +#if defined(WINDOWS_STORE_RT) +// static void RecvFromBlocking_WindowsStore8( RakNetSocket *s, RakPeer *rakPeer, char *dataOut, int *bytesReadOut, SystemAddress *systemAddressOut, RakNet::TimeUS *timeRead ); +#endif + + /// Given a socket and IP, retrieves the subnet mask, on linux the socket is unused + /// \param[in] inSock the socket + /// \param[in] inIpString The ip of the interface you wish to retrieve the subnet mask from + /// \return Returns the ip dotted subnet mask if successful, otherwise returns empty string ("") + static RakNet::RakString GetSubNetForSocketAndIp(__UDPSOCKET__ inSock, RakNet::RakString inIpString); + + + /// Sets the socket flags to nonblocking + /// \param[in] listenSocket the socket to set +// static void SetNonBlocking( RakNetSocket* listenSocket); + + + /// Retrieve all local IP address in a string format. + /// \param[in] s The socket whose port we are referring to + /// \param[in] ipList An array of ip address in dotted notation. + static void GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ); + + + /// Call sendto (UDP obviously) + /// \param[in] s the socket + /// \param[in] data The byte buffer to send + /// \param[in] length The length of the \a data in bytes + /// \param[in] ip The address of the remote host in dotted notation. + /// \param[in] port The port number to send to. + /// \return 0 on success, nonzero on failure. +// static int SendTo( UDPSOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port, unsigned short remotePortRakNetWasStartedOn_PS3, unsigned int extraSocketOptions, const char *file, const long line ); + + /// Call sendto' (UDP obviously) + /// It won't reach the recipient, except on a LAN + /// However, this is good for opening routers / firewalls + /// \param[in] s the socket + /// \param[in] data The byte buffer to send + /// \param[in] length The length of the \a data in bytes + /// \param[in] ip The address of the remote host in dotted notation. + /// \param[in] port The port number to send to. + /// \param[in] ttl Max hops of datagram + /// \return 0 on success, nonzero on failure. +// static int SendToTTL( RakNetSocket *s, const char *data, int length, SystemAddress &systemAddress, int ttl ); + + /// Call sendto (UDP obviously) + /// \param[in] s the socket + /// \param[in] data The byte buffer to send + /// \param[in] length The length of the \a data in bytes + /// \param[in] binaryAddress The address of the remote host in binary format. + /// \param[in] port The port number to send to. + /// \return 0 on success, nonzero on failure. +// static int SendTo( RakNetSocket *s, const char *data, int length, SystemAddress systemAddress, const char *file, const long line ); + +// static unsigned short GetLocalPort(RakNetSocket *s); + static unsigned short GetLocalPort( __UDPSOCKET__ s); +// static void GetSystemAddress_Old ( RakNetSocket *s, SystemAddress *systemAddressOut ); + static void GetSystemAddress_Old ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ); +// static void GetSystemAddress ( RakNetSocket *s, SystemAddress *systemAddressOut ); + static void GetSystemAddress ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ); + +// static void SetSocketLayerOverride(SocketLayerOverride *_slo); +// static SocketLayerOverride* GetSocketLayerOverride(void) {return slo;} + +// static int SendTo_PS3Lobby( RakNetSocket *s, const char *data, int length, const SystemAddress &systemAddress ); +// static int SendTo_PSP2( RakNetSocket *s, const char *data, int length, const SystemAddress &systemAddress ); +// static int SendTo_360( RakNetSocket *s, const char *data, int length, const char *voiceData, int voiceLength, const SystemAddress &systemAddress ); +// static int SendTo_PC( RakNetSocket *s, const char *data, int length, const SystemAddress &systemAddress, const char *file, const long line ); +// #if defined(WINDOWS_STORE_RT) +// static int SendTo_WindowsStore8( RakNetSocket *s, const char *data, int length, const SystemAddress &systemAddress, const char *file, const long line ); +// #endif +// +// static void SetDoNotFragment( RakNetSocket* listenSocket, int opt ); +// static void SetSocketOptions( RakNetSocket* listenSocket, bool blockingSocket, bool setBroadcast); + static void SetSocketOptions( __UDPSOCKET__ listenSocket, bool blockingSocket, bool setBroadcast); + + + // AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. + static bool GetFirstBindableIP(char firstBindable[128], int ipProto); + +private: + +// static SocketLayerOverride *slo; +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/StatisticsHistory.hpp b/include/raknet/StatisticsHistory.hpp new file mode 100644 index 0000000..73d19da --- /dev/null +++ b/include/raknet/StatisticsHistory.hpp @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file StatisticsHistory.h +/// \brief Input numerical values over time. Get sum, average, highest, lowest, standard deviation on recent or all-time values + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_StatisticsHistory==1 + +#ifndef __STATISTICS_HISTORY_H +#define __STATISTICS_HISTORY_H + +#include "PluginInterface2.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" +#include "DS_List.hpp" +#include "RakNetTypes.hpp" +#include "DS_OrderedList.hpp" +#include "RakString.hpp" +#include "DS_Queue.hpp" +#include "DS_Hash.hpp" +#include + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +// Type used to track values. If needed, change to double and recompile +typedef double SHValueType; +#define SH_TYPE_MAX DBL_MAX + +/// \brief Input numerical values over time. Get sum, average, highest, lowest, standard deviation on recent or all-time values +class RAK_DLL_EXPORT StatisticsHistory +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(StatisticsHistory) + + enum SHErrorCode + { + SH_OK, + SH_UKNOWN_OBJECT, + SH_UKNOWN_KEY, + SH_INVALID_PARAMETER, + }; + + enum SHSortOperation + { + SH_DO_NOT_SORT, + + SH_SORT_BY_RECENT_SUM_ASCENDING, + SH_SORT_BY_RECENT_SUM_DESCENDING, + SH_SORT_BY_LONG_TERM_SUM_ASCENDING, + SH_SORT_BY_LONG_TERM_SUM_DESCENDING, + SH_SORT_BY_RECENT_SUM_OF_SQUARES_ASCENDING, + SH_SORT_BY_RECENT_SUM_OF_SQUARES_DESCENDING, + SH_SORT_BY_RECENT_AVERAGE_ASCENDING, + SH_SORT_BY_RECENT_AVERAGE_DESCENDING, + SH_SORT_BY_LONG_TERM_AVERAGE_ASCENDING, + SH_SORT_BY_LONG_TERM_AVERAGE_DESCENDING, + SH_SORT_BY_RECENT_HIGHEST_ASCENDING, + SH_SORT_BY_RECENT_HIGHEST_DESCENDING, + SH_SORT_BY_RECENT_LOWEST_ASCENDING, + SH_SORT_BY_RECENT_LOWEST_DESCENDING, + SH_SORT_BY_LONG_TERM_HIGHEST_ASCENDING, + SH_SORT_BY_LONG_TERM_HIGHEST_DESCENDING, + SH_SORT_BY_LONG_TERM_LOWEST_ASCENDING, + SH_SORT_BY_LONG_TERM_LOWEST_DESCENDING, + }; + + enum SHDataCategory + { + /// Insert values from one set into the other set, in time order + /// Values at the same time end up in the final set twice + /// Use when you have additional data points to add to a graph + DC_DISCRETE, + + /// Add values from one set to values from the other set, at corresponding times + /// If value at time t does not exist in the other set, linearly extrapolate value for other set based on nearest two data points + /// longTerm* values are unknown using this method + /// Use to add two graphs together + DC_CONTINUOUS + }; + + struct TimeAndValue; + struct TimeAndValueQueue; + + struct TrackedObjectData + { + TrackedObjectData(); + TrackedObjectData(uint64_t _objectId, int _objectType, void *_userData); + uint64_t objectId; + int objectType; + void *userData; + }; + + StatisticsHistory(); + virtual ~StatisticsHistory(); + void SetDefaultTimeToTrack(Time defaultTimeToTrack); + Time GetDefaultTimeToTrack(void) const; + bool AddObject(TrackedObjectData tod); + bool RemoveObject(uint64_t objectId, void **userData); + void RemoveObjectAtIndex(unsigned int index); + void Clear(void); + unsigned int GetObjectCount(void) const; + StatisticsHistory::TrackedObjectData * GetObjectAtIndex(unsigned int index) const; + unsigned int GetObjectIndex(uint64_t objectId) const; + bool AddValueByObjectID(uint64_t objectId, RakString key, SHValueType val, Time curTime, bool combineEqualTimes); + void AddValueByIndex(unsigned int index, RakString key, SHValueType val, Time curTime, bool combineEqualTimes); + SHErrorCode GetHistoryForKey(uint64_t objectId, RakString key, TimeAndValueQueue **values, Time curTime) const; + bool GetHistorySorted(uint64_t objectId, SHSortOperation sortType, DataStructures::List &values) const; + void MergeAllObjectsOnKey(RakString key, TimeAndValueQueue *tavqOutput, SHDataCategory dataCategory) const; + void GetUniqueKeyList(DataStructures::List &keys); + + struct TimeAndValue + { + Time time; + SHValueType val; + }; + + struct TimeAndValueQueue + { + TimeAndValueQueue(); + ~TimeAndValueQueue(); + + DataStructures::Queue values; + + Time timeToTrackValues; + RakString key; + + SHValueType recentSum; + SHValueType recentSumOfSquares; + SHValueType longTermSum; + SHValueType longTermCount; + SHValueType longTermLowest; + SHValueType longTermHighest; + + void SetTimeToTrackValues(Time t); + Time GetTimeToTrackValues(void) const; + SHValueType GetRecentSum(void) const; + SHValueType GetRecentSumOfSquares(void) const; + SHValueType GetLongTermSum(void) const; + SHValueType GetRecentAverage(void) const; + SHValueType GetRecentLowest(void) const; + SHValueType GetRecentHighest(void) const; + SHValueType GetRecentStandardDeviation(void) const; + SHValueType GetLongTermAverage(void) const; + SHValueType GetLongTermLowest(void) const; + SHValueType GetLongTermHighest(void) const; + SHValueType GetSumSinceTime(Time t) const; + Time GetTimeRange(void) const; + + // Merge two sets to output + static void MergeSets( const TimeAndValueQueue *lhs, SHDataCategory lhsDataCategory, const TimeAndValueQueue *rhs, SHDataCategory rhsDataCategory, TimeAndValueQueue *output ); + + // Shrink or expand a sample set to the approximate number given + // DC_DISCRETE will produce a histogram (sum) while DC_CONTINUOUS will produce an average + void ResizeSampleSet( int approximateSamples, DataStructures::Queue &blendedSamples, SHDataCategory dataCategory, Time timeClipStart=0, Time timeClipEnd=0 ); + + // Clear out all values + void Clear(void); + + TimeAndValueQueue& operator = ( const TimeAndValueQueue& input ); + + /// \internal + void CullExpiredValues(Time curTime); + /// \internal + static SHValueType Interpolate(TimeAndValue t1, TimeAndValue t2, Time time); + /// \internal + SHValueType sortValue; + }; + +protected: + struct TrackedObject; +public: + static int TrackedObjectComp( const uint64_t &key, TrackedObject* const &data ); +protected: + + struct TrackedObject + { + TrackedObject(); + ~TrackedObject(); + TrackedObjectData trackedObjectData; + DataStructures::Hash dataQueues; + }; + + DataStructures::OrderedList objects; + + Time timeToTrack; +}; + +/// \brief Input numerical values over time. Get sum, average, highest, lowest, standard deviation on recent or all-time values +/// \ingroup PLUGINS_GROUP +class RAK_DLL_EXPORT StatisticsHistoryPlugin : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(StatisticsHistoryPlugin) + + StatisticsHistory statistics; + + StatisticsHistoryPlugin(); + virtual ~StatisticsHistoryPlugin(); + void SetTrackConnections(bool _addNewConnections, int newConnectionsObjectType, bool _removeLostConnections); + +protected: + virtual void Update(void); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + + // Too slow +// virtual bool UsesReliabilityLayer(void) const {return true;} +// virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); +// virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress); + + + bool addNewConnections; + bool removeLostConnections; + int newConnectionsObjectType; +}; + +} // namespace RakNet + +#endif // __STATISTICS_HISTORY_H + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/StringCompressor.hpp b/include/raknet/StringCompressor.hpp new file mode 100644 index 0000000..b77f6fe --- /dev/null +++ b/include/raknet/StringCompressor.hpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief \b Compresses/Decompresses ASCII strings and writes/reads them to BitStream class instances. You can use this to easily serialize and deserialize your own strings. +/// + + + +#ifndef __STRING_COMPRESSOR_H +#define __STRING_COMPRESSOR_H + +#include "Export.hpp" +#include "DS_Map.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" + +#ifdef _STD_STRING_COMPRESSOR +#include +#endif + +/// Forward declaration +namespace RakNet +{ + class BitStream; + class RakString; +}; + + +namespace RakNet +{ +/// Forward declarations +class HuffmanEncodingTree; + +/// \brief Writes and reads strings to and from bitstreams. +/// +/// Only works with ASCII strings. The default compression is for English. +/// You can call GenerateTreeFromStrings to compress and decompress other languages efficiently as well. +class RAK_DLL_EXPORT StringCompressor +{ +public: + + // Destructor + ~StringCompressor(); + + /// static function because only static functions can access static members + /// The RakPeer constructor adds a reference to this class, so don't call this until an instance of RakPeer exists, or unless you call AddReference yourself. + /// \return the unique instance of the StringCompressor + static StringCompressor* Instance(void); + + /// Given an array of strings, such as a chat log, generate the optimal encoding tree for it. + /// This function is optional and if it is not called a default tree will be used instead. + /// \param[in] input An array of bytes which should point to text. + /// \param[in] inputLength Length of \a input + /// \param[in] languageID An identifier for the language / string table to generate the tree for. English is automatically created with ID 0 in the constructor. + void GenerateTreeFromStrings( unsigned char *input, unsigned inputLength, uint8_t languageId ); + + /// Writes input to output, compressed. Takes care of the null terminator for you. + /// \param[in] input Pointer to an ASCII string + /// \param[in] maxCharsToWrite The max number of bytes to write of \a input. Use 0 to mean no limit. + /// \param[out] output The bitstream to write the compressed string to + /// \param[in] languageID Which language to use + void EncodeString( const char *input, int maxCharsToWrite, RakNet::BitStream *output, uint8_t languageId=0 ); + + /// Writes input to output, uncompressed. Takes care of the null terminator for you. + /// \param[out] output A block of bytes to receive the output + /// \param[in] maxCharsToWrite Size, in bytes, of \a output . A NULL terminator will always be appended to the output string. If the maxCharsToWrite is not large enough, the string will be truncated. + /// \param[in] input The bitstream containing the compressed string + /// \param[in] languageID Which language to use + bool DecodeString( char *output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId=0 ); + +#ifdef _CSTRING_COMPRESSOR + void EncodeString( const CString &input, int maxCharsToWrite, RakNet::BitStream *output, uint8_t languageId=0 ); + bool DecodeString( CString &output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId=0 ); +#endif + +#ifdef _STD_STRING_COMPRESSOR + void EncodeString( const std::string &input, int maxCharsToWrite, RakNet::BitStream *output, uint8_t languageId=0 ); + bool DecodeString( std::string *output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId=0 ); +#endif + + void EncodeString( const RakNet::RakString *input, int maxCharsToWrite, RakNet::BitStream *output, uint8_t languageId=0 ); + bool DecodeString( RakNet::RakString *output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId=0 ); + + /// Used so I can allocate and deallocate this singleton at runtime + static void AddReference(void); + + /// Used so I can allocate and deallocate this singleton at runtime + static void RemoveReference(void); + + StringCompressor(); + +private: + + /// Singleton instance + static StringCompressor *instance; + + /// Pointer to the huffman encoding trees. + DataStructures::Map huffmanEncodingTrees; + + static int referenceCount; +}; + +} // namespace RakNet + +#endif diff --git a/include/raknet/StringTable.hpp b/include/raknet/StringTable.hpp new file mode 100644 index 0000000..9960340 --- /dev/null +++ b/include/raknet/StringTable.hpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief A simple class to encode and decode known strings based on a lookup table. Similar to the StringCompressor class. +/// + + + +#ifndef __STRING_TABLE_H +#define __STRING_TABLE_H + +#include "DS_OrderedList.hpp" +#include "Export.hpp" +#include "RakMemoryOverride.hpp" + +/// Forward declaration +namespace RakNet +{ + class BitStream; +}; + +/// StringTableType should be the smallest type possible, or else it defeats the purpose of the StringTable class, which is to save bandwidth. +typedef unsigned char StringTableType; + +/// The string plus a bool telling us if this string was copied or not. +struct StrAndBool +{ + char *str; + bool b; +}; + +namespace RakNet +{ + int RAK_DLL_EXPORT StrAndBoolComp( char *const &key, const StrAndBool &data ); + + /// \details This is an even more efficient alternative to StringCompressor in that it writes a single byte from a lookup table and only does compression.
    + /// if the string does not already exist in the table.
    + /// All string tables must match on all systems - hence you must add all the strings in the same order on all systems.
    + /// Furthermore, this must be done before sending packets that use this class, since the strings are ordered for fast lookup. Adding after that time would mess up all the indices so don't do it.
    + /// Don't use this class to write strings which were not previously registered with AddString, since you just waste bandwidth then. Use StringCompressor instead. + /// \brief Writes a string index, instead of the whole string + class RAK_DLL_EXPORT StringTable + { + public: + + // Destructor + ~StringTable(); + + /// static function because only static functions can access static members + /// The RakPeer constructor adds a reference to this class, so don't call this until an instance of RakPeer exists, or unless you call AddReference yourself. + /// \return the unique instance of the StringTable + static StringTable* Instance(void); + + /// Add a string to the string table. + /// \param[in] str The string to add to the string table + /// \param[in] copyString true to make a copy of the passed string (takes more memory), false to not do so (if your string is in static memory). + void AddString(const char *str, bool copyString); + + /// Writes input to output, compressed. Takes care of the null terminator for you. + /// Relies on the StringCompressor class, which is automatically reference counted in the constructor and destructor in RakPeer. You can call the reference counting functions yourself if you wish too. + /// \param[in] input Pointer to an ASCII string + /// \param[in] maxCharsToWrite The size of \a input + /// \param[out] output The bitstream to write the compressed string to + void EncodeString( const char *input, int maxCharsToWrite, RakNet::BitStream *output ); + + /// Writes input to output, uncompressed. Takes care of the null terminator for you. + /// Relies on the StringCompressor class, which is automatically reference counted in the constructor and destructor in RakPeer. You can call the reference counting functions yourself if you wish too. + /// \param[out] output A block of bytes to receive the output + /// \param[in] maxCharsToWrite Size, in bytes, of \a output . A NULL terminator will always be appended to the output string. If the maxCharsToWrite is not large enough, the string will be truncated. + /// \param[in] input The bitstream containing the compressed string + bool DecodeString( char *output, int maxCharsToWrite, RakNet::BitStream *input ); + + /// Used so I can allocate and deallocate this singleton at runtime + static void AddReference(void); + + /// Used so I can allocate and deallocate this singleton at runtime + static void RemoveReference(void); + + /// Private Constructor + StringTable(); + + protected: + /// Called when you mess up and send a string using this class that was not registered with AddString + /// \param[in] maxCharsToWrite Size, in bytes, of \a output . A NULL terminator will always be appended to the output string. If the maxCharsToWrite is not large enough, the string will be truncated. + void LogStringNotFound(const char *strName); + + /// Singleton instance + static StringTable *instance; + static int referenceCount; + + DataStructures::OrderedList orderedStringList; + }; +} + + +#endif diff --git a/include/raknet/SuperFastHash.hpp b/include/raknet/SuperFastHash.hpp new file mode 100644 index 0000000..d473756 --- /dev/null +++ b/include/raknet/SuperFastHash.hpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __SUPER_FAST_HASH_H +#define __SUPER_FAST_HASH_H + +#include +#include "NativeTypes.hpp" + +// From http://www.azillionmonkeys.com/qed/hash.html +// Author of main code is Paul Hsieh +// I just added some convenience functions +// Also note http://burtleburtle.net/bob/hash/doobs.html, which shows that this is 20% faster than the one on that page but has more collisions + +uint32_t SuperFastHash (const char * data, int length); +uint32_t SuperFastHashIncremental (const char * data, int len, unsigned int lastHash ); +uint32_t SuperFastHashFile (const char * filename); +uint32_t SuperFastHashFilePtr (FILE *fp); + +#endif diff --git a/include/raknet/TCPInterface.hpp b/include/raknet/TCPInterface.hpp new file mode 100644 index 0000000..c1cdd45 --- /dev/null +++ b/include/raknet/TCPInterface.hpp @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief A simple TCP based server allowing sends and receives. Can be connected by any TCP client, including telnet. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TCPInterface==1 + +#ifndef __SIMPLE_TCP_SERVER +#define __SIMPLE_TCP_SERVER + +#include "RakMemoryOverride.hpp" +#include "DS_List.hpp" +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "RakThread.hpp" +#include "DS_Queue.hpp" +#include "SimpleMutex.hpp" +#include "RakNetDefines.hpp" +#include "SocketIncludes.hpp" +#include "DS_ByteQueue.hpp" +#include "DS_ThreadsafeAllocatingQueue.hpp" +#include "LocklessTypes.hpp" +#include "PluginInterface2.hpp" + +#if OPEN_SSL_CLIENT_SUPPORT==1 +#include +#include +#include +#include +#include +#endif + +namespace RakNet +{ +/// Forward declarations +struct RemoteClient; + +/// \internal +/// \brief As the name says, a simple multithreaded TCP server. Used by TelnetTransport +class RAK_DLL_EXPORT TCPInterface +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(TCPInterface) + + TCPInterface(); + virtual ~TCPInterface(); + + // TODO - add socketdescriptor + /// Starts the TCP server on the indicated port + /// \param[in] port Which port to listen on. + /// \param[in] maxIncomingConnections Max incoming connections we will accept + /// \param[in] maxConnections Max total connections, which should be >= maxIncomingConnections + /// \param[in] threadPriority Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application. + /// \param[in] socketFamily IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. + bool Start(unsigned short port, unsigned short maxIncomingConnections, unsigned short maxConnections=0, int _threadPriority=-99999, unsigned short socketFamily=AF_INET, const char *bindAddress=0); + + /// Stops the TCP server + void Stop(void); + + /// Connect to the specified host on the specified port + SystemAddress Connect(const char* host, unsigned short remotePort, bool block=true, unsigned short socketFamily=AF_INET, const char *bindAddress=0); + +#if OPEN_SSL_CLIENT_SUPPORT==1 + /// Start SSL on an existing connection, notified with HasCompletedConnectionAttempt + void StartSSLClient(SystemAddress systemAddress); + + /// Was SSL started on this socket? + bool IsSSLActive(SystemAddress systemAddress); +#endif + + /// Sends a byte stream + virtual void Send( const char *data, unsigned int length, const SystemAddress &systemAddress, bool broadcast ); + + // Sends a concatenated list of byte streams + virtual bool SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ); + + // Get how many bytes are waiting to be sent. If too many, you may want to skip sending + unsigned int GetOutgoingDataBufferSize(SystemAddress systemAddress) const; + + /// Returns if Receive() will return data + /// Do not use on PacketizedTCP + virtual bool ReceiveHasPackets( void ); + + /// Returns data received + virtual Packet* Receive( void ); + + /// Disconnects a player/address + void CloseConnection( SystemAddress systemAddress ); + + /// Deallocates a packet returned by Receive + void DeallocatePacket( Packet *packet ); + + /// Fills the array remoteSystems with the SystemAddress of all the systems we are connected to + /// \param[out] remoteSystems An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to + /// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array + void GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const; + + /// Returns just the number of connections we have + unsigned short GetConnectionCount(void) const; + + /// Has a previous call to connect succeeded? + /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. + SystemAddress HasCompletedConnectionAttempt(void); + + /// Has a previous call to connect failed? + /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. + SystemAddress HasFailedConnectionAttempt(void); + + /// Queued events of new incoming connections + SystemAddress HasNewIncomingConnection(void); + + /// Queued events of lost connections + SystemAddress HasLostConnection(void); + + /// Return an allocated but empty packet, for custom use + Packet* AllocatePacket(unsigned dataSize); + + // Push a packet back to the queue + virtual void PushBackPacket( Packet *packet, bool pushAtHead ); + + /// Returns if Start() was called successfully + bool WasStarted(void) const; + + void AttachPlugin( PluginInterface2 *plugin ); + void DetachPlugin( PluginInterface2 *plugin ); +protected: + + Packet* ReceiveInt( void ); + +#if defined(WINDOWS_STORE_RT) + bool CreateListenSocket_WinStore8(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *hostAddress); +#else + bool CreateListenSocket(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *hostAddress); +#endif + + // Plugins + DataStructures::List messageHandlerList; + + RakNet::LocklessUint32_t isStarted, threadRunning; + __TCPSOCKET__ listenSocket; + + DataStructures::Queue headPush, tailPush; + RemoteClient* remoteClients; + int remoteClientsLength; + + // Assuming remoteClients is only used by one thread! + // DataStructures::List remoteClients; + // Use this thread-safe queue to add to remoteClients + // DataStructures::Queue remoteClientsInsertionQueue; + // SimpleMutex remoteClientsInsertionQueueMutex; + + /* + struct OutgoingMessage + { + unsigned char* data; + SystemAddress systemAddress; + bool broadcast; + unsigned int length; + }; + */ +// DataStructures::SingleProducerConsumer outgoingMessages; +// DataStructures::SingleProducerConsumer incomingMessages; +// DataStructures::SingleProducerConsumer newIncomingConnections, lostConnections, requestedCloseConnections; +// DataStructures::SingleProducerConsumer newRemoteClients; +// DataStructures::ThreadsafeAllocatingQueue outgoingMessages; + DataStructures::ThreadsafeAllocatingQueue incomingMessages; + DataStructures::ThreadsafeAllocatingQueue newIncomingConnections, lostConnections, requestedCloseConnections; + DataStructures::ThreadsafeAllocatingQueue newRemoteClients; + SimpleMutex completedConnectionAttemptMutex, failedConnectionAttemptMutex; + DataStructures::Queue completedConnectionAttempts, failedConnectionAttempts; + + int threadPriority; + + DataStructures::List<__TCPSOCKET__> blockingSocketList; + SimpleMutex blockingSocketListMutex; + + + + + + friend RAK_THREAD_DECLARATION(UpdateTCPInterfaceLoop); + friend RAK_THREAD_DECLARATION(ConnectionAttemptLoop); + +// void DeleteRemoteClient(RemoteClient *remoteClient, fd_set *exceptionFD); +// void InsertRemoteClient(RemoteClient* remoteClient); + __TCPSOCKET__ SocketConnect(const char* host, unsigned short remotePort, unsigned short socketFamily, const char *bindAddress); + + struct ThisPtrPlusSysAddr + { + TCPInterface *tcpInterface; + SystemAddress systemAddress; + bool useSSL; + char bindAddress[64]; + unsigned short socketFamily; + }; + +#if OPEN_SSL_CLIENT_SUPPORT==1 + SSL_CTX* ctx; + SSL_METHOD *meth; + DataStructures::ThreadsafeAllocatingQueue startSSL; + DataStructures::List activeSSLConnections; + SimpleMutex sharedSslMutex; +#endif +}; + +/// Stores information about a remote client. +struct RemoteClient +{ + RemoteClient() { +#if OPEN_SSL_CLIENT_SUPPORT==1 + ssl=0; +#endif + isActive=false; +#if !defined(WINDOWS_STORE_RT) + socket=0; +#endif + } + __TCPSOCKET__ socket; + SystemAddress systemAddress; + DataStructures::ByteQueue outgoingData; + bool isActive; + SimpleMutex outgoingDataMutex; + SimpleMutex isActiveMutex; + +#if OPEN_SSL_CLIENT_SUPPORT==1 + SSL* ssl; + bool InitSSL(SSL_CTX* ctx, SSL_METHOD *meth); + void DisconnectSSL(void); + void FreeSSL(void); + int Send(const char *data, unsigned int length); + int Recv(char *data, const int dataSize); +#else + int Send(const char *data, unsigned int length); + int Recv(char *data, const int dataSize); +#endif + void Reset(void) + { + outgoingDataMutex.Lock(); + outgoingData.Clear(_FILE_AND_LINE_); + outgoingDataMutex.Unlock(); + } + void SetActive(bool a); + void SendOrBuffer(const char **data, const unsigned int *lengths, const int numParameters); +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* + diff --git a/include/raknet/TableSerializer.hpp b/include/raknet/TableSerializer.hpp new file mode 100644 index 0000000..ba2f67f --- /dev/null +++ b/include/raknet/TableSerializer.hpp @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __TABLE_SERIALIZER_H +#define __TABLE_SERIALIZER_H + +#include "RakMemoryOverride.hpp" +#include "DS_Table.hpp" +#include "Export.hpp" + +namespace RakNet +{ + class BitStream; +} + +namespace RakNet +{ + +class RAK_DLL_EXPORT TableSerializer +{ +public: + static void SerializeTable(DataStructures::Table *in, RakNet::BitStream *out); + static bool DeserializeTable(unsigned char *serializedTable, unsigned int dataLength, DataStructures::Table *out); + static bool DeserializeTable(RakNet::BitStream *in, DataStructures::Table *out); + static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out); + static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out, DataStructures::List &skipColumnIndices); + static bool DeserializeColumns(RakNet::BitStream *in, DataStructures::Table *out); + static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out); + static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out, DataStructures::List &skipColumnIndices); + static bool DeserializeRow(RakNet::BitStream *in, DataStructures::Table *out); + static void SerializeCell(RakNet::BitStream *out, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); + static bool DeserializeCell(RakNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); + static void SerializeFilterQuery(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query); + // Note that this allocates query->cell->c! + static bool DeserializeFilterQuery(RakNet::BitStream *out, DataStructures::Table::FilterQuery *query); + static void SerializeFilterQueryList(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query, unsigned int numQueries, unsigned int maxQueries); + // Note that this allocates queries, cells, and query->cell->c!. Use DeallocateQueryList to free. + static bool DeserializeFilterQueryList(RakNet::BitStream *out, DataStructures::Table::FilterQuery **query, unsigned int *numQueries, unsigned int maxQueries, int allocateExtraQueries=0); + static void DeallocateQueryList(DataStructures::Table::FilterQuery *query, unsigned int numQueries); +}; + +} // namespace RakNet + +#endif + +// Test code for the table +/* +#include "LightweightDatabaseServer.hpp" +#include "LightweightDatabaseClient.hpp" +#include "TableSerializer.hpp" +#include "BitStream.hpp" +#include "StringCompressor.hpp" +#include "DS_Table.hpp" +void main(void) +{ + DataStructures::Table table; + DataStructures::Table::Row *row; + unsigned int dummydata=12345; + + // Add columns Name (string), IP (binary), score (int), and players (int). + table.AddColumn("Name", DataStructures::Table::STRING); + table.AddColumn("IP", DataStructures::Table::BINARY); + table.AddColumn("Score", DataStructures::Table::NUMERIC); + table.AddColumn("Players", DataStructures::Table::NUMERIC); + table.AddColumn("Empty Test Column", DataStructures::Table::STRING); + RakAssert(table.GetColumnCount()==5); + row=table.AddRow(0); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,5); + row->UpdateCell(3,10); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(1); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,5); + row->UpdateCell(3,15); + + row=table.AddRow(2); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,5); + row->UpdateCell(3,20); + + row=table.AddRow(3); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,15); + row->UpdateCell(3,5); + row->UpdateCell(4,"col index 4"); + + row=table.AddRow(4); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + //row->UpdateCell(2,25); + row->UpdateCell(3,30); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(5); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + //row->UpdateCell(2,25); + row->UpdateCell(3,5); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(6); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,35); + //row->UpdateCell(3,40); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(7); + RakAssert(row); + row->UpdateCell(0,"Bob Jenkins"); + + row=table.AddRow(8); + RakAssert(row); + row->UpdateCell(0,"Zack Jenkins"); + + // Test multi-column sorting + DataStructures::Table::Row *rows[30]; + DataStructures::Table::SortQuery queries[4]; + queries[0].columnIndex=0; + queries[0].operation=DataStructures::Table::QS_INCREASING_ORDER; + queries[1].columnIndex=1; + queries[1].operation=DataStructures::Table::QS_INCREASING_ORDER; + queries[2].columnIndex=2; + queries[2].operation=DataStructures::Table::QS_INCREASING_ORDER; + queries[3].columnIndex=3; + queries[3].operation=DataStructures::Table::QS_DECREASING_ORDER; + table.SortTable(queries, 4, rows); + unsigned i; + char out[256]; + RAKNET_DEBUG_PRINTF("Sort: Ascending except for column index 3\n"); + for (i=0; i < table.GetRowCount(); i++) + { + table.PrintRow(out,256,',',true, rows[i]); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + // Test query: + // Don't return column 3, and swap columns 0 and 2 + unsigned columnsToReturn[4]; + columnsToReturn[0]=2; + columnsToReturn[1]=1; + columnsToReturn[2]=0; + columnsToReturn[3]=4; + DataStructures::Table resultsTable; + table.QueryTable(columnsToReturn,4,0,0,&resultsTable); + RAKNET_DEBUG_PRINTF("Query: Don't return column 3, and swap columns 0 and 2:\n"); + for (i=0; i < resultsTable.GetRowCount(); i++) + { + resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + // Test filter: + // Only return rows with column index 4 empty + DataStructures::Table::FilterQuery inclusionFilters[3]; + inclusionFilters[0].columnIndex=4; + inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; + // inclusionFilters[0].cellValue; // Unused for IS_EMPTY + table.QueryTable(0,0,inclusionFilters,1,&resultsTable); + RAKNET_DEBUG_PRINTF("Filter: Only return rows with column index 4 empty:\n"); + for (i=0; i < resultsTable.GetRowCount(); i++) + { + resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + // Column 5 empty and column 0 == Kevin Jenkins + inclusionFilters[0].columnIndex=4; + inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; + inclusionFilters[1].columnIndex=0; + inclusionFilters[1].operation=DataStructures::Table::QF_EQUAL; + inclusionFilters[1].cellValue.Set("Kevin Jenkins"); + table.QueryTable(0,0,inclusionFilters,2,&resultsTable); + RAKNET_DEBUG_PRINTF("Filter: Column 5 empty and column 0 == Kevin Jenkins:\n"); + for (i=0; i < resultsTable.GetRowCount(); i++) + { + resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + RakNet::BitStream bs; + RAKNET_DEBUG_PRINTF("PreSerialize:\n"); + for (i=0; i < table.GetRowCount(); i++) + { + table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + StringCompressor::AddReference(); + TableSerializer::Serialize(&table, &bs); + TableSerializer::Deserialize(&bs, &table); + StringCompressor::RemoveReference(); + RAKNET_DEBUG_PRINTF("PostDeserialize:\n"); + for (i=0; i < table.GetRowCount(); i++) + { + table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + int a=5; +} +*/ diff --git a/include/raknet/TeamBalancer.hpp b/include/raknet/TeamBalancer.hpp new file mode 100644 index 0000000..95a0b58 --- /dev/null +++ b/include/raknet/TeamBalancer.hpp @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file TeamBalancer.h +/// \brief Set and network team selection (supports peer to peer or client/server) +/// \details Automatically handles transmission and resolution of team selection, including team switching and balancing +/// \deprecated Use TeamManager intead +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TeamBalancer==1 + +#ifndef __TEAM_BALANCER_H +#define __TEAM_BALANCER_H + +#include "PluginInterface2.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" +#include "DS_List.hpp" +#include "RakString.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \defgroup TEAM_BALANCER_GROUP TeamBalancer +/// \brief Set and network team selection (supports peer to peer or client/server) +/// \details Automatically handles transmission and resolution of team selection, including team switching and balancing +/// \deprecated Use TeamManager intead +/// \ingroup PLUGINS_GROUP + +/// 0...254 for your team number identifiers. 255 is reserved as undefined. +/// \deprecated Use TeamManager intead +/// \ingroup TEAM_BALANCER_GROUP +typedef unsigned char TeamId; + +#define UNASSIGNED_TEAM_ID 255 + +/// \brief Set and network team selection (supports peer to peer or client/server) +/// \details Automatically handles transmission and resolution of team selection, including team switching and balancing.
    +/// Usage: TODO +/// \deprecated Use TeamManager intead +/// \ingroup TEAM_BALANCER_GROUP +class RAK_DLL_EXPORT TeamBalancer : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(TeamBalancer) + + TeamBalancer(); + virtual ~TeamBalancer(); + + /// \brief Set the limit to the number of players on the specified team + /// \details SetTeamSizeLimit() must be called on the host, so the host can enforce the maximum number of players on each team. + /// SetTeamSizeLimit() can be called on all systems if desired - for example, in a P2P environment you may wish to call it on all systems in advanced in case you become host. + /// \param[in] team Which team to set the limit for + /// \param[in] limit The maximum number of people on this team + void SetTeamSizeLimit(TeamId team, unsigned short limit); + + enum DefaultAssigmentAlgorithm + { + /// Among all the teams, join the team with the smallest number of players + SMALLEST_TEAM, + /// Join the team with the lowest index that has open slots. + FILL_IN_ORDER + }; + /// \brief Determine how players' teams will be set when they call RequestAnyTeam() + /// \details Based on the specified enumeration, a player will join a team automatically + /// Defaults to SMALLEST_TEAM + /// This function is only used by the host + /// \param[in] daa Enumeration describing the algorithm to use + void SetDefaultAssignmentAlgorithm(DefaultAssigmentAlgorithm daa); + + /// \brief By default, teams can be unbalanced up to the team size limit defined by SetTeamSizeLimits() + /// \details If SetForceEvenTeams(true) is called on the host, then teams cannot be unbalanced by more than 1 player + /// If teams are uneven at the time that SetForceEvenTeams(true) is called, players at randomly will be switched, and will be notified of ID_TEAM_BALANCER_TEAM_ASSIGNED + /// If players disconnect from the host such that teams would not be even, and teams are not locked, then a player from the largest team is randomly moved to even the teams. + /// Defaults to false + /// \note SetLockTeams(true) takes priority over SetForceEvenTeams(), so if teams are currently locked, this function will have no effect until teams become unlocked. + /// \param[in] force True to force even teams. False to allow teams to not be evenly matched + void SetForceEvenTeams(bool force); + + /// \brief If set, calls to RequestSpecificTeam() and RequestAnyTeam() will return the team you are currently on. + /// \details However, if those functions are called and you do not have a team, then you will be assigned to a default team according to SetDefaultAssignmentAlgorithm() and possibly SetForceEvenTeams(true) + /// If \a lock is false, and SetForceEvenTeams() was called with \a force as true, and teams are currently uneven, they will be made even, and those players randomly moved will get ID_TEAM_BALANCER_TEAM_ASSIGNED + /// Defaults to false + /// \param[in] lock True to lock teams, false to unlock + void SetLockTeams(bool lock); + + /// Set your requested team. UNASSIGNED_TEAM_ID means no team. + /// After enough time for network communication, ID_TEAM_BALANCER_SET_TEAM will be returned with your current team, or + /// If team switch is not possible, ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING or ID_TEAM_BALANCER_TEAMS_LOCKED will be returned. + /// In the case of ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING the request will stay in memory. ID_TEAM_BALANCER_SET_TEAM will be returned when someone on the desired team leaves or wants to switch to your team. + /// If SetLockTeams(true) is called while you have a request pending, you will get ID_TEAM_BALANCER_TEAMS_LOCKED + /// \pre Call SetTeamSizeLimits() on the host and call SetHostGuid() on this system. If the host is not running the TeamBalancer plugin or did not have SetTeamSizeLimits() called, then you will not get any response. + /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. + /// \param[in] desiredTeam An index representing your team number. The index should range from 0 to one less than the size of the list passed to SetTeamSizeLimits() on the host. You can also pass UNASSIGNED_TEAM_ID to not be on any team (such as if spectating) + void RequestSpecificTeam(NetworkID memberId, TeamId desiredTeam); + + /// If ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING is returned after a call to RequestSpecificTeam(), the request will stay in memory on the host and execute when available, or until the teams become locked. + /// You can cancel the request by calling CancelRequestSpecificTeam(), in which case you will stay on your existing team. + /// \note Due to latency, even after calling CancelRequestSpecificTeam() you may still get ID_TEAM_BALANCER_SET_TEAM if the packet was already in transmission. + /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. + void CancelRequestSpecificTeam(NetworkID memberId); + + /// Allow host to pick your team, based on whatever algorithm it uses for default team assignments. + /// This only has an effect if you are not currently on a team (GetMyTeam() returns UNASSIGNED_TEAM_ID) + /// \pre Call SetTeamSizeLimits() on the host and call SetHostGuid() on this system + /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. + void RequestAnyTeam(NetworkID memberId); + + /// Returns your team. + /// As your team changes, you are notified through the ID_TEAM_BALANCER_TEAM_ASSIGNED packet in byte 1. + /// Returns UNASSIGNED_TEAM_ID initially + /// \pre For this to return anything other than UNASSIGNED_TEAM_ID, connect to a properly initialized host and RequestSpecificTeam() or RequestAnyTeam() first + /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. + /// \return UNASSIGNED_TEAM_ID for no team. Otherwise, the index should range from 0 to one less than the size of the list passed to SetTeamSizeLimits() on the host + TeamId GetMyTeam(NetworkID memberId) const; + + /// If you called RequestSpecificTeam() or RequestAnyTeam() with a value for \a memberId that + /// Has since been deleted, call DeleteMember(). to notify this plugin of that event. + /// Not necessary with only one team member per system + /// \param[in] memberId If there is more than one player per computer, this number identifies that player. Use any consistent value, such as UNASSIGNED_NETWORK_ID if there is only one player. + void DeleteMember(NetworkID memberId); + + struct TeamMember + { + RakNetGUID memberGuid; + NetworkID memberId; + TeamId currentTeam; + TeamId requestedTeam; + }; + struct MyTeamMembers + { + NetworkID memberId; + TeamId currentTeam; + TeamId requestedTeam; + }; + +protected: + + /// \internal + virtual PluginReceiveResult OnReceive(Packet *packet); + /// \internal + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + /// \internal + void OnAttach(void); + + void OnStatusUpdateToNewHost(Packet *packet); + void OnCancelTeamRequest(Packet *packet); + void OnRequestAnyTeam(Packet *packet); + void OnRequestSpecificTeam(Packet *packet); + + RakNetGUID hostGuid; + DefaultAssigmentAlgorithm defaultAssigmentAlgorithm; + bool forceTeamsToBeEven; + bool lockTeams; + // So if we lose the connection while processing, we request the same info of the new host + DataStructures::List myTeamMembers; + + DataStructures::List teamLimits; + DataStructures::List teamMemberCounts; + DataStructures::List teamMembers; + unsigned int GetMemberIndex(NetworkID memberId, RakNetGUID guid) const; + unsigned int AddTeamMember(const TeamMember &tm); // Returns index of new member + void RemoveTeamMember(unsigned int index); + void EvenTeams(void); + unsigned int GetMemberIndexToSwitchTeams(const DataStructures::List &sourceTeamNumbers, TeamId targetTeamNumber); + void GetOverpopulatedTeams(DataStructures::List &overpopulatedTeams, int maxTeamSize); + void SwitchMemberTeam(unsigned int teamMemberIndex, TeamId destinationTeam); + void NotifyTeamAssigment(unsigned int teamMemberIndex); + bool WeAreHost(void) const; + PluginReceiveResult OnTeamAssigned(Packet *packet); + PluginReceiveResult OnRequestedTeamChangePending(Packet *packet); + PluginReceiveResult OnTeamsLocked(Packet *packet); + void GetMinMaxTeamMembers(int &minMembersOnASingleTeam, int &maxMembersOnASingleTeam); + TeamId GetNextDefaultTeam(void); // Accounting for team balancing and team limits, get the team a player should be placed on + bool TeamWouldBeOverpopulatedOnAddition(TeamId teamId, unsigned int teamMemberSize); // Accounting for team balancing and team limits, would this team be overpopulated if a member was added to it? + bool TeamWouldBeUnderpopulatedOnLeave(TeamId teamId, unsigned int teamMemberSize); + TeamId GetSmallestNonFullTeam(void) const; + TeamId GetFirstNonFullTeam(void) const; + void MoveMemberThatWantsToJoinTeam(TeamId teamId); + TeamId MoveMemberThatWantsToJoinTeamInternal(TeamId teamId); + void NotifyTeamsLocked(RakNetGUID target, TeamId requestedTeam); + void NotifyTeamSwitchPending(RakNetGUID target, TeamId requestedTeam, NetworkID memberId); + void NotifyNoTeam(NetworkID memberId, RakNetGUID target); + void SwapTeamMembersByRequest(unsigned int memberIndex1, unsigned int memberIndex2); + void RemoveByGuid(RakNetGUID rakNetGUID); + bool TeamsWouldBeEvenOnSwitch(TeamId t1, TeamId t2); + +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/TeamManager.hpp b/include/raknet/TeamManager.hpp new file mode 100644 index 0000000..45c8809 --- /dev/null +++ b/include/raknet/TeamManager.hpp @@ -0,0 +1,757 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +// TODO: optimize the list of teams and team members to be O(1). Store in hashes, use linked lists to get ordered traversal + +/// \file TeamManager.h +/// \brief Automates networking and list management for teams +/// \details TeamManager provides support for teams. A team is a list of team members. +/// Teams contain properties including the number of team members per team, whether or not tagged teams must have equal numbers of members, and if a team is locked or not to certain entry conditions +/// Team members contain properties including which teams they are on and which teams they want to join if a team is not immediately joinable +/// Advanced functionality includes the ability for a team member to be on multiple teams simultaneously, the ability to swap teams with other members, and the ability to resize the number of members supported per team +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TeamManager==1 + +#ifndef __TEAM_MANAGER_H +#define __TEAM_MANAGER_H + +#include "PluginInterface2.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" +#include "DS_List.hpp" +#include "RakNetTypes.hpp" +#include "DS_Hash.hpp" +#include "DS_OrderedList.hpp" + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \defgroup TEAM_MANAGER_GROUP TeamManager +/// \brief Automates networking and list management for teams +/// \details When used with ReplicaManager3 and FullyConnectedMesh2, provides a complete solution to managing a distributed list of teams and team member objects with support for host migration. +/// \ingroup PLUGINS_GROUP + +/// \ingroup TEAM_MANAGER_GROUP +/// \brief A subcategory of not being on a team. For example, 0 may mean no team for a player, while 1 may mean no team for a spectator. Defined by the user. +typedef unsigned char NoTeamId; + +/// \ingroup TEAM_MANAGER_GROUP +/// Used for multiple worlds. +typedef uint8_t WorldId; + +/// \ingroup TEAM_MANAGER_GROUP +/// Maximum number of members on one team. Use 65535 for unlimited. +typedef uint16_t TeamMemberLimit; + +/// Allow members to join this team when they specify TeamSelection::JOIN_ANY_AVAILABLE_TEAM +#define ALLOW_JOIN_ANY_AVAILABLE_TEAM (1<<0) +/// Allow members to join this team when they specify TeamSelection::JOIN_SPECIFIC_TEAM +#define ALLOW_JOIN_SPECIFIC_TEAM (1<<1) +/// Allow the host to put members on this team when rebalancing with TM_World::SetBalanceTeams() +#define ALLOW_JOIN_REBALANCING (1<<2) + +// Bitwise combination of ALLOW_JOIN_ANY_AVAILABLE_TEAM, ALLOW_JOIN_SPECIFIC_TEAM, ALLOW_JOIN_REBALANCING +typedef uint8_t JoinPermissions; + +// Forward declarations +class TM_Team; +class TM_TeamMember; +class TM_World; +class TeamManager; + +/// \ingroup TEAM_MANAGER_GROUP +enum JoinTeamType +{ + /// Attempt to join the first available team. + JOIN_ANY_AVAILABLE_TEAM, + /// Attempt to join a specific team, previously added with TM_World::ReferenceTeam() + JOIN_SPECIFIC_TEAM, + /// No team. Always succeeds. + JOIN_NO_TEAM +}; + +/// \ingroup TEAM_MANAGER_GROUP +enum TMTopology +{ + // Each system will send all messages to all participants + TM_PEER_TO_PEER, + + // The host will relay incoming messages to all participants + TM_CLIENT_SERVER, +}; + +/// \brief Parameter to TM_World::ReferenceTeamMember() +/// \details Use TeamSelection::AnyAvailable(), TeamSelection::SpecificTeam(), or TeamSelection::NoTeam() +/// \ingroup TEAM_MANAGER_GROUP +struct TeamSelection +{ + TeamSelection(); + TeamSelection(JoinTeamType itt); + TeamSelection(JoinTeamType itt, TM_Team *param); + TeamSelection(JoinTeamType itt, NoTeamId param); + JoinTeamType joinTeamType; + + union + { + TM_Team *specificTeamToJoin; + NoTeamId noTeamSubcategory; + } teamParameter; + + /// \brief Join any team that has available slots and is tagged with ALLOW_JOIN_ANY_AVAILABLE_TEAM + /// \details ID_TEAM_BALANCER_TEAM_ASSIGNED, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED will be returned to all systems. + static TeamSelection AnyAvailable(void); + /// \brief Join a specific team if it has available slots, and is tagged with JOIN_SPECIFIC_TEAMS + /// \details ID_TEAM_BALANCER_TEAM_ASSIGNED, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED will be returned to all systems. + /// \param[in] specificTeamToJoin Which team to attempt to join. + static TeamSelection SpecificTeam(TM_Team *specificTeamToJoin); + /// \brief Do not join a team, or leave all current teams. + /// \details This always succeeds. ID_TEAM_BALANCER_TEAM_ASSIGNED will be returned to all systems. + /// \param[in] noTeamSubcategory Even when not on a team, you can internally identify a subcategory of not being on a team, such as AI or spectator. + static TeamSelection NoTeam(NoTeamId noTeamSubcategory); +}; + +/// \brief A member of one or more teams. +/// \details Contains data and operations on data to manage which team your game's team members are on. +/// Best used as a composite member of your "User" or "Player" class(es). +/// When using with ReplicaManager3, call TM_TeamMember::ReferenceTeamMember() in Replica3::DeserializeConstruction() and TM_TeamMember::DeserializeConstruction() in Replica3::PostDeserializeConstruction() +/// There is otherwise no need to manually serialize the class, as operations are networked internally. +/// \ingroup TEAM_MANAGER_GROUP +class RAK_DLL_EXPORT TM_TeamMember +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(TM_TeamMember) + + TM_TeamMember(); + virtual ~TM_TeamMember(); + + /// \brief Request to join any team, a specific team, or to leave all teams + /// \details Function will return false on invalid operations, such as joining a team you are already on. + /// Will also fail with TeamSelection::JOIN_ANY_AVAILABLE_TEAM if you are currently on a team. + /// On success, every system will get ID_TEAM_BALANCER_TEAM_ASSIGNED. Use TeamManager::DecomposeTeamAssigned() to get details of which team member the message refers to. + /// On failure, all systems will get ID_TEAM_BALANCER_REQUESTED_TEAM_FULL or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED. Use TeamManager::DecomposeTeamFull() and TeamManager::DecomposeTeamLocked() to get details of which team member the message refers to. + /// \note Joining a specific team with this function may result in being on more than one team at once, even if you call the function while locally only on one team. If your game depends on only being on one team at a team, use RequestTeamSwitch() instead with the parameter teamToLeave set to 0 + /// \param[in] TeamSelection::AnyAvailable(), TeamSelection::SpecificTeam(), or TeamSelection::NoTeam() + /// \return false On invalid or unnecessary operation. Otherwise returns true + bool RequestTeam(TeamSelection teamSelection); + + /// \brief Similar to RequestTeam with TeamSelection::SpecificTeam(), but leave a team simultaneously when the desired team is joinable + /// \param[in] teamToJoin Which team to join + /// \param[in] teamToLeave If 0, means leave all current teams. Otherwise, leave the specified team. + /// \return false On invalid or unnecessary operation. Otherwise returns true + bool RequestTeamSwitch(TM_Team *teamToJoin, TM_Team *teamToLeave); + + /// \brief Returns the first requested team in the list of requested teams, if you have a requested team at all. + /// \return TeamSelection::SpecificTeam(), TeamSelection::NoTeam(), or TeamSelection::AnyAvailable() + TeamSelection GetRequestedTeam(void) const; + + /// \brief Returns pending calls to RequestTeam() when using TeamSelection::JOIN_SPECIFIC_TEAM + /// \param[out] All pending requested teams + void GetRequestedSpecificTeams(DataStructures::List &requestedTeams) const; + + /// \brief Returns if the specified team is in the list of pending requested teams + /// \param[in] The team we are checking + /// \return Did we request to join this specific team? + bool HasRequestedTeam(TM_Team *team) const; + + /// \brief Returns the index of \a team in the requested teams list + /// \param[in] The team we are checking + /// \return -1 if we did not requested to join this team. Otherwise the index. + unsigned int GetRequestedTeamIndex(TM_Team *team) const; + + /// \return The number of teams that would be returned by a call to GetRequestedSpecificTeams() + unsigned int GetRequestedTeamCount(void) const; + + /// \brief Cancels a request to join a specific team. + /// \details Useful if you got ID_TEAM_BALANCER_REQUESTED_TEAM_FULL or ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED and changed your mind about joining the team. + /// \note This is not guaranteed to work due to latency. To clarify, If the host switches your team at the same time you call CancelRequestTeam() you may still get ID_TEAM_BALANCER_TEAM_ASSIGNED for the team you tried to cancel. + /// \param[in] specificTeamToCancel Which team to no longer join. Use 0 for all. + /// \return false On invalid or unnecessary operation. Otherwise returns true + bool CancelTeamRequest(TM_Team *specificTeamToCancel); + + /// \brief Leave a team + /// \details Leaves a team that you are on. Always succeeds provided you are on that team + /// Generates ID_TEAM_BALANCER_TEAM_ASSIGNED on all systems on success. + /// If you leave the last team you are on, \a noTeamSubcategory is set as well. + /// \param[in] team Which team to leave + /// \param[in] _noTeamSubcategory If the team member has been removed from all teams, which subcategory of NoTeamId to set them to + /// \return false On invalid or unnecessary operation. Otherwise returns true + bool LeaveTeam(TM_Team* team, NoTeamId _noTeamSubcategory); + + /// \brief Leave all teams + /// \Details Leaves all teams you are on, and sets \a noTeamSubcategory + /// \note This is the same as and just calls RequestTeam(TeamSelection::NoTeam(noTeamSubcategory)); + /// \return false On invalid or unnecessary operation. Otherwise returns true + bool LeaveAllTeams(NoTeamId noTeamSubcategory); + + /// \return Get the first team we are on, or 0 if we are not on a team. + TM_Team* GetCurrentTeam(void) const; + + /// \return How many teams we are on + unsigned int GetCurrentTeamCount(void) const; + + /// \return Returns one of the teams in the current team list, up to GetCurrentTeamCount() + TM_Team* GetCurrentTeamByIndex(unsigned int index); + + /// \param[out] Get all teams we are on, as a list + void GetCurrentTeams(DataStructures::List &_teams) const; + + /// For each team member, when you get ID_TEAM_BALANCER_TEAM_ASSIGNED for that member, the team list is saved. + /// Use this function to get that list, for example to determine which teams we just left or joined + /// \param[out] _teams The previous list of teams we were on + void GetLastTeams(DataStructures::List &_teams) const; + + /// \param[in] The team we are checking + /// \return Are we on this team? + bool IsOnTeam(TM_Team *team) const; + + /// \return The teamMemberID parameter passed to TM_World::ReferenceTeamMember() + NetworkID GetNetworkID(void) const; + + /// \return The TM_World instance that was used when calling TM_World::ReferenceTeamMember() + TM_World* GetTM_World(void) const; + + /// \brief Serializes the current state of this object + /// \details To replicate a TM_TeamMember on another system, first instantiate the object using your own code, or a system such as ReplicaManager3. + /// Next, call SerializeConstruction() from whichever system owns the team member + /// Last, call DeserializeConstruction() on the newly created TM_TeamMember + /// \note You must instantiate and deserialize all TM_Team instances that the team member refers to before calling DesrializeConstruction(). ReplicaManager3::PostSerializeConstruction() and ReplicaManager3::PostDeserializeConstruction() will ensure this. + /// \param[out] constructionBitstream This object serialized to a BitStream + void SerializeConstruction(BitStream *constructionBitstream); + + /// \brief Deserializes the current state of this object + /// \details See SerializeConstruction for more details() + /// \note DeserializeConstruction also calls ReferenceTeamMember on the passed \a teamManager instance, there is no need to do so yourself + /// \param[in] teamManager TeamManager instance + /// \param[in] constructionBitstream This object serialized to a BitStream + bool DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream); + + /// \param[in] o Stores a void* for your own use. If using composition, this is useful to store a pointer to the containing object. + void SetOwner(void *o); + + /// \return Whatever was passed to SetOwner() + void *GetOwner(void) const; + + /// \return If not on a team, returns the current NoTeamId value + NoTeamId GetNoTeamId(void) const; + + /// Return world->GetTeamMemberIndex(this) + unsigned int GetWorldIndex(void) const; + + /// \internal + static unsigned long ToUint32( const NetworkID &g ); + + /// \internal + struct RequestedTeam + { + RakNet::Time whenRequested; + unsigned int requestIndex; + TM_Team *requested; + bool isTeamSwitch; + TM_Team *teamToLeave; + }; + +protected: + NetworkID networkId; + TM_World* world; + // Teams we are a member of. We can be on more than one team, but not on the same team more than once + DataStructures::List teams; + // If teams is empty, which subcategory of noTeam we are on + NoTeamId noTeamSubcategory; + // Teams we have requested to join. Mutually exclusive with teams we are already on. Cannot request the same team more than once. + DataStructures::List teamsRequested; + // If teamsRequested is not empty, we want to join a specific team + // If teamsRequested is empty, then joinTeamType is either JOIN_NO_TEAM or JOIN_ANY_AVAILABLE_TEAM + JoinTeamType joinTeamType; + // Set by StoreLastTeams() + DataStructures::List lastTeams; + RakNet::Time whenJoinAnyRequested; + unsigned int joinAnyRequestIndex; + void *owner; + + // Remove from all requested and current teams. + void UpdateListsToNoTeam(NoTeamId nti); + bool JoinAnyTeamCheck(void) const; + bool JoinSpecificTeamCheck(TM_Team *specificTeamToJoin, bool ignoreRequested) const; + bool SwitchSpecificTeamCheck(TM_Team *teamToJoin, TM_Team *teamToLeave, bool ignoreRequested) const; + bool LeaveTeamCheck(TM_Team *team) const; + void UpdateTeamsRequestedToAny(void); + void UpdateTeamsRequestedToNone(void); + void AddToRequestedTeams(TM_Team *teamToJoin); + void AddToRequestedTeams(TM_Team *teamToJoin, TM_Team *teamToLeave); + bool RemoveFromRequestedTeams(TM_Team *team); + void AddToTeamList(TM_Team *team); + void RemoveFromSpecificTeamInternal(TM_Team *team); + void RemoveFromAllTeamsInternal(void); + void StoreLastTeams(void); + + friend class TM_World; + friend class TM_Team; + friend class TeamManager; +}; + +/// \brief A team, containing a list of TM_TeamMember instances +/// \details Contains lists of TM_TeamMember instances +/// Best used as a composite member of your "Team" or "PlayerList" class(es). +/// When using with ReplicaManager3, call TM_Team::ReferenceTeam() in Replica3::DeserializeConstruction() and TM_Team::DeserializeConstruction() in Replica3::PostDeserializeConstruction() +/// There is otherwise no need to manually serialize the class, as operations are networked internally. +/// \ingroup TEAM_MANAGER_GROUP +class RAK_DLL_EXPORT TM_Team +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(TM_Team) + + TM_Team(); + virtual ~TM_Team(); + + /// \brief Set the maximum number of members that can join this team. + /// Defaults to 65535 + /// Setting the limit lower than the existing number of members kicks members out, and assigns noTeamSubcategory to them if they have no other team to go to + /// Setting the limit higher allows members to join in. If a member has a pending request to join this team, they join automatically and ID_TEAM_BALANCER_TEAM_ASSIGNED will be returned for those members. + /// \param[in] _teamMemberLimit The new limit + /// \param[in] noTeamSubcategory Which noTeamSubcategory to assign to members that now have no team. + /// \return false On invalid or unnecessary operation. Otherwise returns true + bool SetMemberLimit(TeamMemberLimit _teamMemberLimit, NoTeamId noTeamSubcategory); + + /// \return If team balancing is on, the most members that can be on this team that would not either unbalance it or exceed the value passed to SetMemberLimit(). If team balancing is off, the same as GetMemberLimitSetting() + TeamMemberLimit GetMemberLimit(void) const; + + /// \return What was passed to SetMemberLimit() or the default + TeamMemberLimit GetMemberLimitSetting(void) const; + + /// \brief Who can join this team under what conditions, while the team is not full + /// To not allow new joins, pass 0 + /// To allow all new joins under any circumstances, bitwise-OR all permission defines. + /// For an invite-only team, use ALLOW_JOIN_SPECIFIC_TEAM only and only allow the requester to call TM_TeamMember::RequestTeam() upon invitiation through your game code. + /// Defaults to allow all + /// \param[in] _joinPermissions Bitwise combination of ALLOW_JOIN_ANY_AVAILABLE_TEAM, ALLOW_JOIN_SPECIFIC_TEAM, ALLOW_JOIN_REBALANCING + /// \return false On invalid or unnecessary operation. Otherwise returns true + bool SetJoinPermissions(JoinPermissions _joinPermissions); + + /// \return Whatever was passed to SetJoinPermissions(), or the default. + JoinPermissions GetJoinPermissions(void) const; + + /// \brief Removes a member from a team he or she is on + /// \details Identical to teamMember->LeaveTeam(this, noTeamSubcategory); See TeamMember::LeaveTeam() for details. + /// \param[in] teamMember Which team member to remove + /// \param[in] noTeamSubcategory If the team member has been removed from all teams, which subcategory of NoTeamId to set them to + void LeaveTeam(TM_TeamMember* teamMember, NoTeamId noTeamSubcategory); + + /// \return What was passed as the \a applyBalancing parameter TM_World::ReferenceTeam() when this team was added. + bool GetBalancingApplies(void) const; + + /// \param[out] All team members of this team + void GetTeamMembers(DataStructures::List &_teamMembers) const; + + /// \return The number of team members on this team + unsigned int GetTeamMembersCount(void) const; + + /// \return A team member on this team. Members are stored in the order they are added + /// \param[in] index A value between 0 and GetTeamMembersCount() + TM_TeamMember *GetTeamMemberByIndex(unsigned int index) const; + + /// \return The teamID parameter passed to TM_World::ReferenceTeam() + NetworkID GetNetworkID(void) const; + + /// \return The TM_World instance that was used when calling TM_World::ReferenceTeamMember() + TM_World* GetTM_World(void) const; + + /// \brief Used by the host to serialize the initial state of this object to a new system + /// \details On the host, when sending existing objects to a new system, call SerializeConstruction() on each of those objects to serialize creation state. + /// Creating the actual Team and TeamMember objects should be handled by your game code, or a system such as ReplicaManager3 + void SerializeConstruction(BitStream *constructionBitstream); + + /// \brief Used by non-host systems to read the bitStream written by SerializeConstruction() + /// \details On non-host systems, after creating existing objects, call DeserializeConstruction() to read and setup that object + /// Creating the actual Team and TeamMember objects should be handled by your game code, or a system such as ReplicaManager3 + bool DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream); + + /// \param[in] o Stores a void* for your own use. If using composition, this is useful to store a pointer to the containing object. + void SetOwner(void *o); + + /// \return Whatever was passed to SetOwner() + void *GetOwner(void) const; + + /// Return world->GetTeamIndex(this) + unsigned int GetWorldIndex(void) const; + + /// \internal + static unsigned long ToUint32( const NetworkID &g ); + +protected: + NetworkID ID; + TM_World* world; + // Which members are on this team. The same member cannot be on the same team more than once + DataStructures::List teamMembers; + // Permissions on who can join this team + JoinPermissions joinPermissions; + // Whether or not to consider this team when balancing teams + bool balancingApplies; + TeamMemberLimit teamMemberLimit; + void *owner; + + // Remove input from list teamMembers + void RemoveFromTeamMemberList(TM_TeamMember *teamMember); + + // Find the member index that wants to join the indicated team, is only on one team, and wants to leave that team + unsigned int GetMemberWithRequestedSingleTeamSwitch(TM_Team *team); + + + friend class TM_World; + friend class TM_TeamMember; + friend class TeamManager; +}; + +/// \brief Stores a list of teams which may be enforcing a balanced number of members +/// \details Each TM_World instance is independent of other TM_World world instances. This enables you to host multiple games on a single computer. +/// Not currently supported to have the same TM_Team or TM_TeamMember in more than one world at a time, but easily added on request. +/// \ingroup TEAM_MANAGER_GROUP +class TM_World +{ +public: + TM_World(); + virtual ~TM_World(); + + /// \return Returns the plugin that created this TM_World instance + TeamManager *GetTeamManager(void) const; + + /// \brief Add a new system to send team and team member updates to. + /// \param[in] rakNetGUID GUID of the system you are adding. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress() + void AddParticipant(RakNetGUID rakNetGUID); + + /// \brief Remove a system that was previously added with AddParticipant() + /// \details Systems that disconnect are removed automatically + /// \param[in] rakNetGUID GUID of the system you are removing. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress() + void RemoveParticipant(RakNetGUID rakNetGUID); + + /// \brief If true, all new connections are added to this world using AddParticipant() + /// \details Defaults to true + /// \param[in] autoAdd Setting to set + void SetAutoManageConnections(bool autoAdd); + + /// Get the participants added with AddParticipant() + /// \param[out] participantList Participants added with AddParticipant(); + void GetParticipantList(DataStructures::List &participantList); + + /// \brief Register a TM_Team object with this system. + /// \details Your game should contain instances of TM_Team, for example by using composition with your game's Team or PlayerList class + /// Tell TeamManager about these instances using ReferenceTeam(). + /// \note The destrutor of TM_Team calls DereferenceTeam() automatically. + /// \param[in] team The instance you are registering + /// \param[in] networkId Identifies this instance. This value is independent of values used by NetworkIDManager. You can use the same value as the object that contains this instance. + /// \param[in] applyBalancing Whether or not to include this team for balancing when calling SetBalanceTeams(). + void ReferenceTeam(TM_Team *team, NetworkID networkId, bool applyBalancing); + + /// \brief Unregisters the associated TM_Team object with this system. + /// Call when a TM_Team instance is no longer needed + /// \param[in] team Which team instance to unregister + /// \param[in] noTeamSubcategory All players on this team are kicked off. If these players then have no team, they are set to this no team category. + void DereferenceTeam(TM_Team *team, NoTeamId noTeamSubcategory); + + /// \return Number of teams uniquely added with ReferenceTeam() + unsigned int GetTeamCount(void) const; + + /// \param[in] index A value between 0 and GetTeamCount() + /// \return Returns whatever was passed to \a team in the function ReferenceTeam() in the order it was called. + TM_Team *GetTeamByIndex(unsigned int index) const; + + /// \param[in] teamId Value passed to ReferenceTeam() + /// \return Returns whatever was passed to \a team in the function ReferenceTeam() with this NetworkID. + TM_Team *GetTeamByNetworkID(NetworkID teamId); + + /// \brief Inverse of GetTeamByIndex() + /// \param[in] team Which taem + /// \return The index of the specified team, or -1 if not found + unsigned int GetTeamIndex(const TM_Team *team) const; + + /// \brief Register a TM_TeamMember object with this system. + /// \details Your game should contain instances of TM_TeamMember, for example by using composition with your game's User or Player classes + /// Tell TeamManager about these instances using ReferenceTeamMember(). + /// \note The destrutor of TM_TeamMember calls DereferenceTeamMember() automatically. + /// \param[in] teamMember The instance you are registering + /// \param[in] networkId Identifies this instance. This value is independent of values used by NetworkIDManager. You can use the same value as the object that contains this instance + void ReferenceTeamMember(TM_TeamMember *teamMember, NetworkID networkId); + + /// \brief Unregisters the associated TM_TeamMember object with this system. + /// Call when a TM_TeamMember instance is no longer needed + /// \note This is called by the destructor of TM_TeamMember automatically, so you do not normally need to call this function + void DereferenceTeamMember(TM_TeamMember *teamMember); + + /// \return Number of team members uniquely added with ReferenceTeamMember() + unsigned int GetTeamMemberCount(void) const; + + /// \param[in] index A value between 0 and GetTeamMemberCount() + /// \return Returns whatever was passed to \a team in the function ReferenceTeamMember() in the order it was called. + TM_TeamMember *GetTeamMemberByIndex(unsigned int index) const; + + /// \param[in] index A value between 0 and GetTeamMemberCount() + /// \return Returns whatever was passed to \a teamMemberID in the function ReferenceTeamMember() in the order it was called. + NetworkID GetTeamMemberIDByIndex(unsigned int index) const; + + /// \param[in] teamId Value passed to ReferenceTeamMember() + /// \return Returns Returns whatever was passed to \a team in the function ReferenceTeamMember() with this NetworkID + TM_TeamMember *GetTeamMemberByNetworkID(NetworkID teamMemberId); + + /// \brief Inverse of GetTeamMemberByIndex() + /// \param[in] team Which team member + /// \return The index of the specified team member, or -1 if not found + unsigned int GetTeamMemberIndex(const TM_TeamMember *teamMember) const; + + /// \brief Force or stop forcing teams to be balanced. + /// \details For each team added with ReferenceTeam() and \a applyBalancing set to true, players on unbalanced teams will be redistributed + /// While active, players can only join balanced teams if doing so would not cause that team to become unbalanced. + /// If a player on the desired team also wants to switch, then both players will switch simultaneously. Otherwise, ID_TEAM_BALANCER_REQUESTED_TEAM_FULL will be returned to the requester and switching will occur when possible. + /// If balanceTeams is true and later set to false, players waiting on ID_TEAM_BALANCER_REQUESTED_TEAM_FULL will be able to join the desired team immediately provided it is not full. + /// \param[in] balanceTeams Whether to activate or deactivate team balancing. + /// \param[in] noTeamSubcategory If a player is kicked off a team and is no longer on any team, his or her noTeamSubcategory is set to this value + bool SetBalanceTeams(bool balanceTeams, NoTeamId noTeamSubcategory); + + /// \return \a balanceTeams parameter of SetBalanceTeams(), or the default + bool GetBalanceTeams(void) const; + + /// \brief Set the host that will perform balancing calculations and send notifications + /// \details Operations that can cause conflicts due to latency, such as joining teams, are operated on by the host. The result is sent to all systems added with AddParticipant() + /// For a client/server game, call SetHost() with the server's RakNetGUID value on all systems (including the server itself). If you call TeamManager::SetTopology(TM_CLIENT_SERVER), the server will also relay messages between participants. + /// For a peer to peer game, call SetHost() on the same peer when host migration occurs. Use TeamManager::SetTopology(TM_PEER_TO_PEER) in this case. + /// \note If using FullyConnectedMesh2, SetHost() is called automatically when ID_FCM2_NEW_HOST is returned. + /// \param[in] _hostGuid The host, which is the system that will serialize and resolve team disputes and calculate team balancing. + void SetHost(RakNetGUID _hostGuid); + + /// \return Returns the current host, or UNASSIGNED_RAKNET_GUID if unknown + RakNetGUID GetHost(void) const; + + /// \return The \a worldId passed to TeamManagr::AddWorld() + WorldId GetWorldId(void) const; + + /// \brief Clear all memory and reset everything. + /// \details It is up to the user to deallocate pointers passed to ReferenceTeamMember() or ReferenceTeam(), if so desired. + void Clear(void); + + /// \internal + struct JoinRequestHelper + { + RakNet::Time whenRequestMade; + unsigned int teamMemberIndex; + unsigned int indexIntoTeamsRequested; + unsigned int requestIndex; + }; + /// \internal + static int JoinRequestHelperComp(const TM_World::JoinRequestHelper &key, const TM_World::JoinRequestHelper &data); + +protected: + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + + // Teams with too many members have those members go to other teams. + void EnforceTeamBalance(NoTeamId noTeamSubcategory); + void KickExcessMembers(NoTeamId noTeamSubcategory); + void FillRequestedSlots(void); + unsigned int GetAvailableTeamIndexWithFewestMembers(TeamMemberLimit secondaryLimit, JoinPermissions joinPermissions); + + void GetSortedJoinRequests(DataStructures::OrderedList &joinRequests); + + + // Send a message to all participants + void BroadcastToParticipants(RakNet::BitStream *bsOut, RakNetGUID exclusionGuid); + void BroadcastToParticipants(unsigned char *data, const int length, RakNetGUID exclusionGuid); + + // 1. If can join a team: + // A. teamMember->UpdateTeamsRequestedToNone(); + // B. teamMember->AddToTeamList() + // C. Return new team + // 2. Else return 0 + TM_Team* JoinAnyTeam(TM_TeamMember *teamMember, int *resultCode); + + int JoinSpecificTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave, DataStructures::List &teamsWeAreLeaving); + + TeamMemberLimit GetBalancedTeamLimit(void) const; + + // For fast lookup. Shares pointers with list teams + DataStructures::Hash teamsHash; + // For fast lookup. Shares pointers with list teamMembers + DataStructures::Hash teamMembersHash; + + TeamManager *teamManager; + DataStructures::List participants; + DataStructures::List teams; + DataStructures::List teamMembers; + bool balanceTeamsIsActive; + RakNetGUID hostGuid; + WorldId worldId; + bool autoAddParticipants; + int teamRequestIndex; + + friend class TeamManager; + friend class TM_TeamMember; + friend class TM_Team; +}; + +/// \brief Automates networking and list management for teams +/// \details TeamManager provides support for teams. A team is a list of team members. +/// Teams contain properties including the number of team members per team, whether or not tagged teams must have equal numbers of members, and if a team is locked or not to certain entry conditions +/// Team members contain properties including which teams they are on and which teams they want to join if a team is not immediately joinable +/// Advanced functionality includes the ability for a team member to be on multiple teams simultaneously, the ability to swap teams with other members, and the ability to resize the number of members supported per team +/// The architecture is designed for easy integration with ReplicaManager3 +/// +/// Usage:
    +/// 1. Define your game classes to represent teams and team members. Your game classes should hold game-specific information such as team name and color.
    +/// 2. Have those game classes contain a corresponding TM_Team or TM_TeamMember instance. Operations on teams will be performed by those instances. Use SetOwner() to refer to the parent object when using composition.
    +/// 3. Call TeamManager::SetTopology() for client/server or peer to peer.
    +/// 4. Call AddWorld() to instantiate a TM_World object which will contain references to your TM_TeamMember and TM_Team instances.
    +/// 5. When you instantiate a TM_TeamMember or TM_Team object, call ReferenceTeam() and ReferenceTeamMember() for each corresponding object
    +/// 6. When sending world state to a new connection, for example in ReplicaManager3::SerializeConstruction(), call TM_SerializeConstruction() on the corresponding TM_TeamMember and TM_Team objects. TM_Team instances on the new connection must be created before TM_TeamMember instances.
    +/// 7. Call TM_DeserializeConstruction() on your new corresponding TM_TeamMember and TM_Team instances.
    +/// 8. Execute team operations. ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED, and ID_TEAM_BALANCER_TEAM_ASSIGNED are returned to all systems when the corresponding event occurs for a team member.
    +/// 9. As the peer to peer session host changes, call SetHost() (Not necessary if using FullyConnectedMesh2). If using client/server, you must set the host
    +/// \note This replaces TeamBalancer. You cannot use TeamBalancer and TeamManager at the same time. +/// \ingroup TEAM_MANAGER_GROUP +class RAK_DLL_EXPORT TeamManager : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(TeamManager) + + TeamManager(); + virtual ~TeamManager(); + + /// \brief Allocate a world to hold a list of teams and players for that team. + /// Use the returned TM_World object for actual team functionality. + /// \note The world is tracked by TeamManager and deallocated by calling Clear() + /// \param[in] worldId Arbitrary user-defined id of the world to create. Each world instance must have a unique id. + TM_World* AddWorld(WorldId worldId); + + /// \brief Deallocate a world created with AddWorld() + /// \param[in] worldId The world to deallocate + void RemoveWorld(WorldId worldId); + + /// \return Returns the number of worlds created with AddWorld() + unsigned int GetWorldCount(void) const; + + /// \param[in] index A value beteween 0 and GetWorldCount()-1 inclusive. + /// \return Returns a world created with AddWorld() + TM_World* GetWorldAtIndex(unsigned int index) const; + + /// \param[in] worldId \a worldId value passed to AddWorld() + /// \return Returns a world created with AddWorld(), or 0 if no such \a worldId + TM_World* GetWorldWithId(WorldId worldId) const; + + /// \brief When auto managing connections, call TM_World::AddParticipant() on all worlds for all new connections automatically + /// Defaults to true + /// \note You probably want this set to false if using multiple worlds + /// \param[in] autoAdd Automatically call TM_World::AddParticipant() all worlds each new connection. Defaults to true. + void SetAutoManageConnections(bool autoAdd); + + /// \brief If \a _topology is set to TM_CLIENT_SERVER, the host will relay messages to participants. + /// \details If topology is set to TM_PEER_TO_PEER, the host assumes the original message source was connected to all other participants and does not relay messages. + /// \note If TM_PEER_TO_PEER, this plugin will listen for ID_FCM2_NEW_HOST and call SetHost() on all worlds automatically + /// \note Defaults to TM_PEER_TO_PEER + /// \param[in] _topology Topology to use + void SetTopology(TMTopology _topology); + + /// \brief When you get ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, pass the packet to this function to read out parameters + /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_FULL + /// \return true on success, false on read error + void DecomposeTeamFull(Packet *packet, + TM_World **world, TM_TeamMember **teamMember, TM_Team **team, + uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions); + + /// \brief When you get ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, pass the packet to this function to read out parameters + /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED + /// \return true on success, false on read error + void DecomposeTeamLocked(Packet *packet, + TM_World **world, TM_TeamMember **teamMember, TM_Team **team, + uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions); + + /// \brief Clear all memory and reset everything. + /// \details Deallocates TM_World instances. It is up to the user to deallocate pointers passed to ReferenceTeamMember() or ReferenceTeam(), if so desired. + void Clear(void); + + /// \brief Reads out the world and teamMember from ID_TEAM_BALANCER_TEAM_ASSIGNED + /// \note You can get the current and prior team list from the teamMember itself + /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_ASSIGNED + /// \param[out] world Set to the world this \a teamMember is on. 0 on bad lookup. + /// \param[out] teamMember Set to the teamMember affected. 0 on bad lookup. + void DecodeTeamAssigned(Packet *packet, TM_World **world, TM_TeamMember **teamMember); + + // \brief Reads out the world and teamMember from ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED + /// \note You can get the requested team list from the teamMember itself + /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED + /// \param[out] world Set to the world this \a teamMember is on. 0 on bad lookup. + /// \param[out] teamMember Set to the teamMember affected. 0 on bad lookup. + /// \param[out] teamCancelled Set to the team that was cancelled. 0 for all teams. + void DecodeTeamCancelled(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **teamCancelled); + +protected: + + virtual void Update(void); + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming); + void Send( const RakNet::BitStream * bitStream, const AddressOrGUID systemIdentifier, bool broadcast ); + + void EncodeTeamFullOrLocked(RakNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team); + void DecomposeTeamFullOrLocked(RakNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, TM_Team **team, + uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions); + void ProcessTeamAssigned(RakNet::BitStream *bsIn); + + void EncodeTeamAssigned(RakNet::BitStream *bitStream, TM_TeamMember *teamMember); + void RemoveFromTeamsRequestedAndAddTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave); + + void PushTeamAssigned(TM_TeamMember *teamMember); + void PushBitStream(RakNet::BitStream *bitStream); + void OnUpdateListsToNoTeam(Packet *packet, TM_World *world); + void OnUpdateTeamsRequestedToAny(Packet *packet, TM_World *world); + void OnJoinAnyTeam(Packet *packet, TM_World *world); + void OnJoinRequestedTeam(Packet *packet, TM_World *world); + void OnUpdateTeamsRequestedToNoneAndAddTeam(Packet *packet, TM_World *world); + void OnRemoveFromTeamsRequestedAndAddTeam(Packet *packet, TM_World *world); + void OnAddToRequestedTeams(Packet *packet, TM_World *world); + bool OnRemoveFromRequestedTeams(Packet *packet, TM_World *world); + void OnLeaveTeam(Packet *packet, TM_World *world); + void OnSetMemberLimit(Packet *packet, TM_World *world); + void OnSetJoinPermissions(Packet *packet, TM_World *world); + void OnSetBalanceTeams(Packet *packet, TM_World *world); + void OnSetBalanceTeamsInitial(Packet *packet, TM_World *world); + + + void EncodeTeamFull(RakNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team); + void EncodeTeamLocked(RakNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team); + + /// \brief When you get ID_TEAM_BALANCER_TEAM_ASSIGNED, pass the packet to this function to read out parameters + /// \param[in] A packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_ASSIGNED + /// \return true on success, false on read error + void DecodeTeamAssigned(RakNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, NoTeamId &noTeamSubcategory, + JoinTeamType &joinTeamType, DataStructures::List &newTeam, + DataStructures::List &teamsLeft, DataStructures::List &teamsJoined); + + // O(1) lookup for a given world. If I need more worlds, change this to a hash or ordered list + TM_World *worldsArray[255]; + // All allocated worlds for linear traversal + DataStructures::List worldsList; + bool autoAddParticipants; + TMTopology topology; + + friend class TM_TeamMember; + friend class TM_World; + friend class TM_Team; +}; + +} // namespace RakNet + +#endif // __TEAM_MANAGER_H + +#endif // _RAKNET_SUPPORT_* + diff --git a/include/raknet/TelnetTransport.hpp b/include/raknet/TelnetTransport.hpp new file mode 100644 index 0000000..279e7ba --- /dev/null +++ b/include/raknet/TelnetTransport.hpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains TelnetTransport , used to supports the telnet transport protocol. Insecure +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TelnetTransport==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#ifndef __TELNET_TRANSPORT +#define __TELNET_TRANSPORT + +#include "TransportInterface.hpp" +#include "DS_List.hpp" +#include "Export.hpp" + +namespace RakNet +{ +/// Forward declarations +class TCPInterface; +struct TelnetClient; + +/// \brief Use TelnetTransport to easily allow windows telnet to connect to your ConsoleServer +/// \details To run Windows telnet, go to your start menu, click run, and in the edit box type "telnet " where is the ip address.
    +/// of your ConsoleServer (most likely the same IP as your game).
    +/// This implementation always echos commands. +class RAK_DLL_EXPORT TelnetTransport : public TransportInterface +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(TelnetTransport) + + TelnetTransport(); + virtual ~TelnetTransport(); + bool Start(unsigned short port, bool serverMode); + void Stop(void); + void Send( SystemAddress systemAddress, const char *data, ... ); + void CloseConnection( SystemAddress systemAddress ); + Packet* Receive( void ); + void DeallocatePacket( Packet *packet ); + SystemAddress HasNewIncomingConnection(void); + SystemAddress HasLostConnection(void); + CommandParserInterface* GetCommandParser(void); + void SetSendSuffix(const char *suffix); + void SetSendPrefix(const char *prefix); +protected: + + struct TelnetClient + { + SystemAddress systemAddress; + char textInput[REMOTE_MAX_TEXT_INPUT]; + char lastSentTextInput[REMOTE_MAX_TEXT_INPUT]; + unsigned cursorPosition; + }; + + TCPInterface *tcpInterface; + void AutoAllocate(void); + bool ReassembleLine(TelnetTransport::TelnetClient* telnetClient, unsigned char c); + + // Crap this sucks but because windows telnet won't send line at a time, I have to reconstruct the lines at the server per player + DataStructures::List remoteClients; + + char *sendSuffix, *sendPrefix; + +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/ThreadPool.hpp b/include/raknet/ThreadPool.hpp new file mode 100644 index 0000000..368c3a6 --- /dev/null +++ b/include/raknet/ThreadPool.hpp @@ -0,0 +1,633 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __THREAD_POOL_H +#define __THREAD_POOL_H + +#include "RakMemoryOverride.hpp" +#include "DS_Queue.hpp" +#include "SimpleMutex.hpp" +#include "Export.hpp" +#include "RakThread.hpp" +#include "SignaledEvent.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +class ThreadDataInterface +{ +public: + ThreadDataInterface() {} + virtual ~ThreadDataInterface() {} + + virtual void* PerThreadFactory(void *context)=0; + virtual void PerThreadDestructor(void* factoryResult, void *context)=0; +}; +/// A simple class to create worker threads that processes a queue of functions with data. +/// This class does not allocate or deallocate memory. It is up to the user to handle memory management. +/// InputType and OutputType are stored directly in a queue. For large structures, if you plan to delete from the middle of the queue, +/// you might wish to store pointers rather than the structures themselves so the array can shift efficiently. +template +struct RAK_DLL_EXPORT ThreadPool +{ + ThreadPool(); + ~ThreadPool(); + + /// Start the specified number of threads. + /// \param[in] numThreads The number of threads to start + /// \param[in] stackSize 0 for default (except on consoles). + /// \param[in] _perThreadInit User callback to return data stored per thread. Pass 0 if not needed. + /// \param[in] _perThreadDeinit User callback to destroy data stored per thread, created by _perThreadInit. Pass 0 if not needed. + /// \return True on success, false on failure. + bool StartThreads(int numThreads, int stackSize, void* (*_perThreadInit)()=0, void (*_perThreadDeinit)(void*)=0); + + // Alternate form of _perThreadDataFactory, _perThreadDataDestructor + void SetThreadDataInterface(ThreadDataInterface *tdi, void *context); + + /// Stops all threads + void StopThreads(void); + + /// Adds a function to a queue with data to pass to that function. This function will be called from the thread + /// Memory management is your responsibility! This class does not allocate or deallocate memory. + /// The best way to deallocate \a inputData is in userCallback. If you call EndThreads such that callbacks were not called, you + /// can iterate through the inputQueue and deallocate all pending input data there + /// The best way to deallocate output is as it is returned to you from GetOutput. Similarly, if you end the threads such that + /// not all output was returned, you can iterate through outputQueue and deallocate it there. + /// \param[in] workerThreadCallback The function to call from the thread + /// \param[in] inputData The parameter to pass to \a userCallback + void AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData); + + /// Adds to the output queue + /// Use it if you want to inject output into the same queue that the system uses. Normally you would not use this. Consider it a convenience function. + /// \param[in] outputData The output to inject + void AddOutput(OutputType outputData); + + /// Returns true if output from GetOutput is waiting. + /// \return true if output is waiting, false otherwise + bool HasOutput(void); + + /// Inaccurate but fast version of HasOutput. If this returns true, you should still check HasOutput for the real value. + /// \return true if output is probably waiting, false otherwise + bool HasOutputFast(void); + + /// Returns true if input from GetInput is waiting. + /// \return true if input is waiting, false otherwise + bool HasInput(void); + + /// Inaccurate but fast version of HasInput. If this returns true, you should still check HasInput for the real value. + /// \return true if input is probably waiting, false otherwise + bool HasInputFast(void); + + /// Gets the output of a call to \a userCallback + /// HasOutput must return true before you call this function. Otherwise it will assert. + /// \return The output of \a userCallback. If you have different output signatures, it is up to you to encode the data to indicate this + OutputType GetOutput(void); + + /// Clears internal buffers + void Clear(void); + + /// Lock the input buffer before calling the functions InputSize, InputAtIndex, and RemoveInputAtIndex + /// It is only necessary to lock the input or output while the threads are running + void LockInput(void); + + /// Unlock the input buffer after you are done with the functions InputSize, GetInputAtIndex, and RemoveInputAtIndex + void UnlockInput(void); + + /// Length of the input queue + unsigned InputSize(void); + + /// Get the input at a specified index + InputType GetInputAtIndex(unsigned index); + + /// Remove input from a specific index. This does NOT do memory deallocation - it only removes the item from the queue + void RemoveInputAtIndex(unsigned index); + + /// Lock the output buffer before calling the functions OutputSize, OutputAtIndex, and RemoveOutputAtIndex + /// It is only necessary to lock the input or output while the threads are running + void LockOutput(void); + + /// Unlock the output buffer after you are done with the functions OutputSize, GetOutputAtIndex, and RemoveOutputAtIndex + void UnlockOutput(void); + + /// Length of the output queue + unsigned OutputSize(void); + + /// Get the output at a specified index + OutputType GetOutputAtIndex(unsigned index); + + /// Remove output from a specific index. This does NOT do memory deallocation - it only removes the item from the queue + void RemoveOutputAtIndex(unsigned index); + + /// Removes all items from the input queue + void ClearInput(void); + + /// Removes all items from the output queue + void ClearOutput(void); + + /// Are any of the threads working, or is input or output available? + bool IsWorking(void); + + /// The number of currently active threads. + int NumThreadsWorking(void); + + /// Did we call Start? + bool WasStarted(void); + + // Block until all threads are stopped. + bool Pause(void); + + // Continue running + void Resume(void); + +protected: + // It is valid to cancel input before it is processed. To do so, lock the inputQueue with inputQueueMutex, + // Scan the list, and remove the item you don't want. + RakNet::SimpleMutex inputQueueMutex, outputQueueMutex, workingThreadCountMutex, runThreadsMutex; + + void* (*perThreadDataFactory)(); + void (*perThreadDataDestructor)(void*); + + // inputFunctionQueue & inputQueue are paired arrays so if you delete from one at a particular index you must delete from the other + // at the same index + DataStructures::Queue inputFunctionQueue; + DataStructures::Queue inputQueue; + DataStructures::Queue outputQueue; + + ThreadDataInterface *threadDataInterface; + void *tdiContext; + + + template + friend RAK_THREAD_DECLARATION(WorkerThread); + + /* +#ifdef _WIN32 + friend unsigned __stdcall WorkerThread( LPVOID arguments ); +#else + friend void* WorkerThread( void* arguments ); +#endif + */ + + /// \internal + bool runThreads; + /// \internal + int numThreadsRunning; + /// \internal + int numThreadsWorking; + /// \internal + RakNet::SimpleMutex numThreadsRunningMutex; + + RakNet::SignaledEvent quitAndIncomingDataEvents; + +// #if defined(SN_TARGET_PSP2) +// RakNet::RakThread::UltUlThreadRuntime *runtime; +// #endif +}; + +#include "ThreadPool.hpp" +#include "RakSleep.hpp" +#ifdef _WIN32 + +#else +#include +#endif + +#ifdef _MSC_VER +#pragma warning(disable:4127) +#pragma warning( disable : 4701 ) // potentially uninitialized local variable 'inputData' used +#endif + +template +RAK_THREAD_DECLARATION(WorkerThread) +/* +#ifdef _WIN32 +unsigned __stdcall WorkerThread( LPVOID arguments ) +#else +void* WorkerThread( void* arguments ) +#endif +*/ +{ + + + + ThreadPool *threadPool = (ThreadPool*) arguments; + + + bool returnOutput; + ThreadOutputType (*userCallback)(ThreadInputType, bool *, void*); + ThreadInputType inputData; + ThreadOutputType callbackOutput; + + userCallback=0; + + void *perThreadData; + if (threadPool->perThreadDataFactory) + perThreadData=threadPool->perThreadDataFactory(); + else if (threadPool->threadDataInterface) + perThreadData=threadPool->threadDataInterface->PerThreadFactory(threadPool->tdiContext); + else + perThreadData=0; + + // Increase numThreadsRunning + threadPool->numThreadsRunningMutex.Lock(); + ++threadPool->numThreadsRunning; + threadPool->numThreadsRunningMutex.Unlock(); + + while (1) + { +//#ifdef _WIN32 + if (userCallback==0) + { + threadPool->quitAndIncomingDataEvents.WaitOnEvent(1000); + } +// #else +// if (userCallback==0) +// RakSleep(30); +// #endif + + threadPool->runThreadsMutex.Lock(); + if (threadPool->runThreads==false) + { + threadPool->runThreadsMutex.Unlock(); + break; + } + threadPool->runThreadsMutex.Unlock(); + + threadPool->workingThreadCountMutex.Lock(); + ++threadPool->numThreadsWorking; + threadPool->workingThreadCountMutex.Unlock(); + + // Read input data + userCallback=0; + threadPool->inputQueueMutex.Lock(); + if (threadPool->inputFunctionQueue.Size()) + { + userCallback=threadPool->inputFunctionQueue.Pop(); + inputData=threadPool->inputQueue.Pop(); + } + threadPool->inputQueueMutex.Unlock(); + + if (userCallback) + { + callbackOutput=userCallback(inputData, &returnOutput,perThreadData); + if (returnOutput) + { + threadPool->outputQueueMutex.Lock(); + threadPool->outputQueue.Push(callbackOutput, _FILE_AND_LINE_ ); + threadPool->outputQueueMutex.Unlock(); + } + } + + threadPool->workingThreadCountMutex.Lock(); + --threadPool->numThreadsWorking; + threadPool->workingThreadCountMutex.Unlock(); + } + + // Decrease numThreadsRunning + threadPool->numThreadsRunningMutex.Lock(); + --threadPool->numThreadsRunning; + threadPool->numThreadsRunningMutex.Unlock(); + + if (threadPool->perThreadDataDestructor) + threadPool->perThreadDataDestructor(perThreadData); + else if (threadPool->threadDataInterface) + threadPool->threadDataInterface->PerThreadDestructor(perThreadData, threadPool->tdiContext); + + + + + return 0; + +} +template +ThreadPool::ThreadPool() +{ + runThreads=false; + numThreadsRunning=0; + threadDataInterface=0; + tdiContext=0; + numThreadsWorking=0; + +} +template +ThreadPool::~ThreadPool() +{ + StopThreads(); + Clear(); +} +template +bool ThreadPool::StartThreads(int numThreads, int stackSize, void* (*_perThreadDataFactory)(), void (*_perThreadDataDestructor)(void *)) +{ + (void) stackSize; + +// #if defined(SN_TARGET_PSP2) +// runtime = RakNet::RakThread::AllocRuntime(numThreads); +// #endif + + runThreadsMutex.Lock(); + if (runThreads==true) + { + // Already running + runThreadsMutex.Unlock(); + return false; + } + runThreadsMutex.Unlock(); + + quitAndIncomingDataEvents.InitEvent(); + + perThreadDataFactory=_perThreadDataFactory; + perThreadDataDestructor=_perThreadDataDestructor; + + runThreadsMutex.Lock(); + runThreads=true; + runThreadsMutex.Unlock(); + + numThreadsWorking=0; + unsigned threadId = 0; + (void) threadId; + int i; + for (i=0; i < numThreads; i++) + { + int errorCode; + + + + + errorCode = RakNet::RakThread::Create(WorkerThread, this); + + if (errorCode!=0) + { + StopThreads(); + return false; + } + } + // Wait for number of threads running to increase to numThreads + bool done=false; + while (done==false) + { + RakSleep(50); + numThreadsRunningMutex.Lock(); + if (numThreadsRunning==numThreads) + done=true; + numThreadsRunningMutex.Unlock(); + } + + return true; +} +template +void ThreadPool::SetThreadDataInterface(ThreadDataInterface *tdi, void *context) +{ + threadDataInterface=tdi; + tdiContext=context; +} +template +void ThreadPool::StopThreads(void) +{ + runThreadsMutex.Lock(); + if (runThreads==false) + { + runThreadsMutex.Unlock(); + return; + } + + runThreads=false; + runThreadsMutex.Unlock(); + + // Wait for number of threads running to decrease to 0 + bool done=false; + while (done==false) + { + quitAndIncomingDataEvents.SetEvent(); + + RakSleep(50); + numThreadsRunningMutex.Lock(); + if (numThreadsRunning==0) + done=true; + numThreadsRunningMutex.Unlock(); + } + + quitAndIncomingDataEvents.CloseEvent(); + +// #if defined(SN_TARGET_PSP2) +// RakNet::RakThread::DeallocRuntime(runtime); +// runtime=0; +// #endif + +} +template +void ThreadPool::AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData) +{ + inputQueueMutex.Lock(); + inputQueue.Push(inputData, _FILE_AND_LINE_ ); + inputFunctionQueue.Push(workerThreadCallback, _FILE_AND_LINE_ ); + inputQueueMutex.Unlock(); + + quitAndIncomingDataEvents.SetEvent(); +} +template +void ThreadPool::AddOutput(OutputType outputData) +{ + outputQueueMutex.Lock(); + outputQueue.Push(outputData, _FILE_AND_LINE_ ); + outputQueueMutex.Unlock(); +} +template +bool ThreadPool::HasOutputFast(void) +{ + return outputQueue.IsEmpty()==false; +} +template +bool ThreadPool::HasOutput(void) +{ + bool res; + outputQueueMutex.Lock(); + res=outputQueue.IsEmpty()==false; + outputQueueMutex.Unlock(); + return res; +} +template +bool ThreadPool::HasInputFast(void) +{ + return inputQueue.IsEmpty()==false; +} +template +bool ThreadPool::HasInput(void) +{ + bool res; + inputQueueMutex.Lock(); + res=inputQueue.IsEmpty()==false; + inputQueueMutex.Unlock(); + return res; +} +template +OutputType ThreadPool::GetOutput(void) +{ + // Real output check + OutputType output; + outputQueueMutex.Lock(); + output=outputQueue.Pop(); + outputQueueMutex.Unlock(); + return output; +} +template +void ThreadPool::Clear(void) +{ + runThreadsMutex.Lock(); + if (runThreads) + { + runThreadsMutex.Unlock(); + inputQueueMutex.Lock(); + inputFunctionQueue.Clear(_FILE_AND_LINE_); + inputQueue.Clear(_FILE_AND_LINE_); + inputQueueMutex.Unlock(); + + outputQueueMutex.Lock(); + outputQueue.Clear(_FILE_AND_LINE_); + outputQueueMutex.Unlock(); + } + else + { + inputFunctionQueue.Clear(_FILE_AND_LINE_); + inputQueue.Clear(_FILE_AND_LINE_); + outputQueue.Clear(_FILE_AND_LINE_); + } +} +template +void ThreadPool::LockInput(void) +{ + inputQueueMutex.Lock(); +} +template +void ThreadPool::UnlockInput(void) +{ + inputQueueMutex.Unlock(); +} +template +unsigned ThreadPool::InputSize(void) +{ + return inputQueue.Size(); +} +template +InputType ThreadPool::GetInputAtIndex(unsigned index) +{ + return inputQueue[index]; +} +template +void ThreadPool::RemoveInputAtIndex(unsigned index) +{ + inputQueue.RemoveAtIndex(index); + inputFunctionQueue.RemoveAtIndex(index); +} +template +void ThreadPool::LockOutput(void) +{ + outputQueueMutex.Lock(); +} +template +void ThreadPool::UnlockOutput(void) +{ + outputQueueMutex.Unlock(); +} +template +unsigned ThreadPool::OutputSize(void) +{ + return outputQueue.Size(); +} +template +OutputType ThreadPool::GetOutputAtIndex(unsigned index) +{ + return outputQueue[index]; +} +template +void ThreadPool::RemoveOutputAtIndex(unsigned index) +{ + outputQueue.RemoveAtIndex(index); +} +template +void ThreadPool::ClearInput(void) +{ + inputQueue.Clear(_FILE_AND_LINE_); + inputFunctionQueue.Clear(_FILE_AND_LINE_); +} + +template +void ThreadPool::ClearOutput(void) +{ + outputQueue.Clear(_FILE_AND_LINE_); +} +template +bool ThreadPool::IsWorking(void) +{ + bool isWorking; +// workingThreadCountMutex.Lock(); +// isWorking=numThreadsWorking!=0; +// workingThreadCountMutex.Unlock(); + +// if (isWorking) +// return true; + + // Bug fix: Originally the order of these two was reversed. + // It's possible with the thread timing that working could have been false, then it picks up the data in the other thread, then it checks + // here and sees there is no data. So it thinks the thread is not working when it was. + if (HasOutputFast() && HasOutput()) + return true; + + if (HasInputFast() && HasInput()) + return true; + + // Need to check is working again, in case the thread was between the first and second checks + workingThreadCountMutex.Lock(); + isWorking=numThreadsWorking!=0; + workingThreadCountMutex.Unlock(); + + return isWorking; +} + +template +int ThreadPool::NumThreadsWorking(void) +{ + return numThreadsWorking; +} + +template +bool ThreadPool::WasStarted(void) +{ + bool b; + runThreadsMutex.Lock(); + b = runThreads; + runThreadsMutex.Unlock(); + return b; +} +template +bool ThreadPool::Pause(void) +{ + if (WasStarted()==false) + return false; + + workingThreadCountMutex.Lock(); + while (numThreadsWorking>0) + { + RakSleep(30); + } + return true; +} +template +void ThreadPool::Resume(void) +{ + workingThreadCountMutex.Unlock(); +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif + diff --git a/include/raknet/ThreadsafePacketLogger.hpp b/include/raknet/ThreadsafePacketLogger.hpp new file mode 100644 index 0000000..cf3f511 --- /dev/null +++ b/include/raknet/ThreadsafePacketLogger.hpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Derivation of the packet logger to defer the call to WriteLog until the user thread. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 + +#ifndef __THREADSAFE_PACKET_LOGGER_H +#define __THREADSAFE_PACKET_LOGGER_H + +#include "PacketLogger.hpp" +#include "SingleProducerConsumer.hpp" + +namespace RakNet +{ + +/// \ingroup PACKETLOGGER_GROUP +/// \brief Same as PacketLogger, but writes output in the user thread. +class RAK_DLL_EXPORT ThreadsafePacketLogger : public PacketLogger +{ +public: + ThreadsafePacketLogger(); + virtual ~ThreadsafePacketLogger(); + + virtual void Update(void); + +protected: + virtual void AddToLog(const char *str); + + DataStructures::SingleProducerConsumer logMessages; +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/TransportInterface.hpp b/include/raknet/TransportInterface.hpp new file mode 100644 index 0000000..f1d1a53 --- /dev/null +++ b/include/raknet/TransportInterface.hpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Contains TransportInterface from which you can derive custom transport providers for ConsoleServer. +/// + + + +#ifndef __TRANSPORT_INTERFACE_H +#define __TRANSPORT_INTERFACE_H + +#include "RakNetTypes.hpp" +#include "Export.hpp" +#include "RakMemoryOverride.hpp" + +#define REMOTE_MAX_TEXT_INPUT 2048 + +namespace RakNet +{ + +class CommandParserInterface; + + +/// \brief Defines an interface that is used to send and receive null-terminated strings. +/// \details In practice this is only used by the CommandParser system for for servers. +class RAK_DLL_EXPORT TransportInterface +{ +public: + TransportInterface() {} + virtual ~TransportInterface() {} + + /// Start the transport provider on the indicated port. + /// \param[in] port The port to start the transport provider on + /// \param[in] serverMode If true, you should allow incoming connections (I don't actually use this anywhere) + /// \return Return true on success, false on failure. + virtual bool Start(unsigned short port, bool serverMode)=0; + + /// Stop the transport provider. You can clear memory and shutdown threads here. + virtual void Stop(void)=0; + + /// Send a null-terminated string to \a systemAddress + /// If your transport method requires particular formatting of the outgoing data (e.g. you don't just send strings) you can do it here + /// and parse it out in Receive(). + /// \param[in] systemAddress The player to send the string to + /// \param[in] data format specifier - same as RAKNET_DEBUG_PRINTF + /// \param[in] ... format specification arguments - same as RAKNET_DEBUG_PRINTF + virtual void Send( SystemAddress systemAddress, const char *data, ... )=0; + + /// Disconnect \a systemAddress . The binary address and port defines the SystemAddress structure. + /// \param[in] systemAddress The player/address to disconnect + virtual void CloseConnection( SystemAddress systemAddress )=0; + + /// Return a string. The string should be allocated and written to Packet::data . + /// The byte length should be written to Packet::length . The player/address should be written to Packet::systemAddress + /// If your transport protocol adds special formatting to the data stream you should parse it out before returning it in the packet + /// and thus only return a string in Packet::data + /// \return The packet structure containing the result of Receive, or 0 if no data is available + virtual Packet* Receive( void )=0; + + /// Deallocate the Packet structure returned by Receive + /// \param[in] The packet to deallocate + virtual void DeallocatePacket( Packet *packet )=0; + + /// If a new system connects to you, you should queue that event and return the systemAddress/address of that player in this function. + /// \return The SystemAddress/address of the system + virtual SystemAddress HasNewIncomingConnection(void)=0; + + /// If a system loses the connection, you should queue that event and return the systemAddress/address of that player in this function. + /// \return The SystemAddress/address of the system + virtual SystemAddress HasLostConnection(void)=0; + + /// Your transport provider can itself have command parsers if the transport layer has user-modifiable features + /// For example, your transport layer may have a password which you want remote users to be able to set or you may want + /// to allow remote users to turn on or off command echo + /// \return 0 if you do not need a command parser - otherwise the desired derivation of CommandParserInterface + virtual CommandParserInterface* GetCommandParser(void)=0; +protected: +}; + +} // namespace RakNet + +#endif + diff --git a/include/raknet/TwoWayAuthentication.hpp b/include/raknet/TwoWayAuthentication.hpp new file mode 100644 index 0000000..7a5401d --- /dev/null +++ b/include/raknet/TwoWayAuthentication.hpp @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file TwoWayAuthentication.h +/// \brief Implements two way authentication +/// \details Given two systems, each of whom known a common password, verify the password without transmitting it +/// This can be used to determine what permissions are should be allowed to the other system +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TwoWayAuthentication==1 + +#ifndef __TWO_WAY_AUTHENTICATION_H +#define __TWO_WAY_AUTHENTICATION_H + +// How often to change the nonce. +#define NONCE_TIMEOUT_MS 10000 +// How often to check for ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, and the minimum timeout time. Maximum is double this value. +#define CHALLENGE_MINIMUM_TIMEOUT 3000 + +#if LIBCAT_SECURITY==1 +// From CPP FILE: +// static const int HASH_BITS = 256; +// static const int HASH_BYTES = HASH_BITS / 8; +// static const int STRENGTHENING_FACTOR = 1000; +#define TWO_WAY_AUTHENTICATION_NONCE_LENGTH 32 +#define HASHED_NONCE_AND_PW_LENGTH 32 +#else +#include "DR_SHA1.hpp" +#define TWO_WAY_AUTHENTICATION_NONCE_LENGTH 20 +#define HASHED_NONCE_AND_PW_LENGTH SHA1_LENGTH +#endif + +#include "PluginInterface2.hpp" +#include "RakMemoryOverride.hpp" +#include "NativeTypes.hpp" +#include "RakString.hpp" +#include "DS_Hash.hpp" +#include "DS_Queue.hpp" + +typedef int64_t FCM2Guid; + +namespace RakNet +{ +/// Forward declarations +class RakPeerInterface; + +/// \brief Implements two way authentication +/// \details Given two systems, each of whom known a common password / identifier pair, verify the password without transmitting it +/// This can be used to determine what permissions are should be allowed to the other system +/// If the other system should not send any data until authentication passes, you can use the MessageFilter plugin for this. Call MessageFilter::SetAllowMessageID() including ID_TWO_WAY_AUTHENTICATION_NEGOTIATION when doing so. Also attach MessageFilter first in the list of plugins +/// \note If other systems challenges us, and fails, you will get ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILED. +/// \ingroup PLUGINS_GROUP +class RAK_DLL_EXPORT TwoWayAuthentication : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(TwoWayAuthentication) + + TwoWayAuthentication(); + virtual ~TwoWayAuthentication(); + + /// \brief Adds a password to the list of passwords the system will accept + /// \details Each password, which is secret and not transmitted, is identified by \a identifier. + /// \a identifier is transmitted in plaintext with the request. It is only needed because the system supports multiple password. + /// It is used to only hash against once password on the remote system, rather than having to hash against every known password. + /// \param[in] identifier A unique identifier representing this password. This is transmitted in plaintext and should be considered insecure + /// \param[in] password The password to add + /// \return True on success, false on identifier==password, either identifier or password is blank, or identifier is already in use + bool AddPassword(RakNet::RakString identifier, RakNet::RakString password); + + /// \brief Challenge another system for the specified identifier + /// \details After calling Challenge, you will get back ID_TWO_WAY_AUTHENTICATION_SUCCESS, ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, or ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILED + /// ID_TWO_WAY_AUTHENTICATION_SUCCESS will be returned if and only if the other system has called AddPassword() with the same identifier\password pair as this system. + /// \param[in] identifier A unique identifier representing this password. This is transmitted in plaintext and should be considered insecure + /// \return True on success, false on remote system not connected, or identifier not previously added with AddPassword() + bool Challenge(RakNet::RakString identifier, AddressOrGUID remoteSystem); + + /// \brief Free all memory + void Clear(void); + + /// \internal + virtual void Update(void); + /// \internal + virtual PluginReceiveResult OnReceive(Packet *packet); + /// \internal + virtual void OnRakPeerShutdown(void); + /// \internal + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + + /// \internal + struct PendingChallenge + { + RakNet::RakString identifier; + AddressOrGUID remoteSystem; + RakNet::Time time; + bool sentHash; + }; + + DataStructures::Queue outgoingChallenges; + + /// \internal + struct NonceAndRemoteSystemRequest + { + char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; + RakNet::AddressOrGUID remoteSystem; + unsigned short requestId; + RakNet::Time whenGenerated; + }; + /// \internal + struct RAK_DLL_EXPORT NonceGenerator + { + NonceGenerator(); + ~NonceGenerator(); + void GetNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short *requestId, RakNet::AddressOrGUID remoteSystem); + void GenerateNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]); + bool GetNonceById(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short requestId, RakNet::AddressOrGUID remoteSystem, bool popIfFound); + void Clear(void); + void ClearByAddress(RakNet::AddressOrGUID remoteSystem); + void Update(RakNet::Time curTime); + + DataStructures::List generatedNonces; + unsigned short nextRequestId; + }; + +protected: + void PushToUser(MessageID messageId, RakNet::RakString password, RakNet::AddressOrGUID remoteSystem); + // Key is identifier, data is password + DataStructures::Hash passwords; + + RakNet::Time whenLastTimeoutCheck; + + NonceGenerator nonceGenerator; + + void OnNonceRequest(Packet *packet); + void OnNonceReply(Packet *packet); + PluginReceiveResult OnHashedNonceAndPassword(Packet *packet); + void OnPasswordResult(Packet *packet); + void Hash(char thierNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], RakNet::RakString password, char out[HASHED_NONCE_AND_PW_LENGTH]); +}; + +} // namespace RakNet + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/UDPForwarder.hpp b/include/raknet/UDPForwarder.hpp new file mode 100644 index 0000000..27ba1cc --- /dev/null +++ b/include/raknet/UDPForwarder.hpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Forwards UDP datagrams. Independent of RakNet's protocol. +/// + + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_UDPForwarder==1 + +#ifndef __UDP_FORWARDER_H +#define __UDP_FORWARDER_H + +#include "Export.hpp" +#include "RakNetTypes.hpp" +#include "SocketIncludes.hpp" +#include "UDPProxyCommon.hpp" +#include "SimpleMutex.hpp" +#include "RakString.hpp" +#include "RakThread.hpp" +#include "DS_Queue.hpp" +#include "DS_OrderedList.hpp" +#include "LocklessTypes.hpp" +#include "DS_ThreadsafeAllocatingQueue.hpp" + +namespace RakNet +{ + +enum UDPForwarderResult +{ + UDPFORWARDER_FORWARDING_ALREADY_EXISTS, + UDPFORWARDER_NO_SOCKETS, + UDPFORWARDER_BIND_FAILED, + UDPFORWARDER_INVALID_PARAMETERS, + UDPFORWARDER_NOT_RUNNING, + UDPFORWARDER_SUCCESS, + UDPFORWARDER_RESULT_COUNT +}; + +/// \brief Forwards UDP datagrams. Independent of RakNet's protocol. +/// \ingroup NAT_PUNCHTHROUGH_GROUP +class RAK_DLL_EXPORT UDPForwarder +{ +public: + UDPForwarder(); + virtual ~UDPForwarder(); + + /// Starts the system. + /// Required to call before StartForwarding + void Startup(void); + + /// Stops the system, and frees all sockets + void Shutdown(void); + + /// Sets the maximum number of forwarding entries allowed + /// Set according to your available bandwidth and the estimated average bandwidth per forwarded address. + /// \param[in] maxEntries The maximum number of simultaneous forwarding entries. Defaults to 64 (32 connections) + void SetMaxForwardEntries(unsigned short maxEntries); + + /// \return The \a maxEntries parameter passed to SetMaxForwardEntries(), or the default if it was never called + int GetMaxForwardEntries(void) const; + + /// \return How many entries have been used + int GetUsedForwardEntries(void) const; + + /// Forwards datagrams from source to destination, and vice-versa + /// Does nothing if this forward entry already exists via a previous call + /// \pre Call Startup() + /// \note RakNet's protocol will ensure a message is sent at least every 15 seconds, so if routing RakNet messages, it is a reasonable value for timeoutOnNoDataMS, plus an some extra seconds for latency + /// \param[in] source The source IP and port + /// \param[in] destination Where to forward to (and vice-versa) + /// \param[in] timeoutOnNoDataMS If no messages are forwarded for this many MS, then automatically remove this entry. + /// \param[in] forceHostAddress Force binding on a particular address. 0 to use any. + /// \param[in] socketFamily IP version: For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. + /// \param[out] forwardingPort New opened port for forwarding + /// \param[out] forwardingSocket New opened socket for forwarding + /// \return UDPForwarderResult + UDPForwarderResult StartForwarding( + SystemAddress source, SystemAddress destination, RakNet::TimeMS timeoutOnNoDataMS, + const char *forceHostAddress, unsigned short socketFamily, + unsigned short *forwardingPort, __UDPSOCKET__ *forwardingSocket); + + /// No longer forward datagrams from source to destination + /// \param[in] source The source IP and port + /// \param[in] destination Where to forward to + void StopForwarding(SystemAddress source, SystemAddress destination); + + + struct ForwardEntry + { + ForwardEntry(); + ~ForwardEntry(); + SystemAddress addr1Unconfirmed, addr2Unconfirmed, addr1Confirmed, addr2Confirmed; + RakNet::TimeMS timeLastDatagramForwarded; + __UDPSOCKET__ socket; + RakNet::TimeMS timeoutOnNoDataMS; + short socketFamily; + }; + + +protected: + friend RAK_THREAD_DECLARATION(UpdateUDPForwarderGlobal); + + void UpdateUDPForwarder(void); + void RecvFrom(RakNet::TimeMS curTime, ForwardEntry *forwardEntry); + + struct StartForwardingInputStruct + { + SystemAddress source; + SystemAddress destination; + RakNet::TimeMS timeoutOnNoDataMS; + RakString forceHostAddress; + unsigned short socketFamily; + unsigned int inputId; + }; + + DataStructures::ThreadsafeAllocatingQueue startForwardingInput; + + struct StartForwardingOutputStruct + { + unsigned short forwardingPort; + __UDPSOCKET__ forwardingSocket; + UDPForwarderResult result; + unsigned int inputId; + }; + DataStructures::Queue startForwardingOutput; + SimpleMutex startForwardingOutputMutex; + + struct StopForwardingStruct + { + SystemAddress source; + SystemAddress destination; + }; + DataStructures::ThreadsafeAllocatingQueue stopForwardingCommands; + unsigned int nextInputId; + + // New entries are added to forwardListNotUpdated + DataStructures::List forwardListNotUpdated; +// SimpleMutex forwardListNotUpdatedMutex; + + unsigned short maxForwardEntries; + RakNet::LocklessUint32_t isRunning, threadRunning; + +}; + +} // End namespace + +#endif + +#endif // #if _RAKNET_SUPPORT_UDPForwarder==1 diff --git a/include/raknet/UDPProxyClient.hpp b/include/raknet/UDPProxyClient.hpp new file mode 100644 index 0000000..0be30e2 --- /dev/null +++ b/include/raknet/UDPProxyClient.hpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief A RakNet plugin performing networking to communicate with UDPProxyCoordinator. Ultimately used to tell UDPProxyServer to forward UDP packets. + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_UDPProxyClient==1 + +#ifndef __UDP_PROXY_CLIENT_H +#define __UDP_PROXY_CLIENT_H + +#include "Export.hpp" +#include "RakNetTypes.hpp" +#include "PluginInterface2.hpp" +#include "DS_List.hpp" + +/// \defgroup UDP_PROXY_GROUP UDPProxy +/// \brief Forwards UDP datagrams from one system to another. Protocol independent +/// \details Used when NatPunchthroughClient fails +/// \ingroup PLUGINS_GROUP + +namespace RakNet +{ +class UDPProxyClient; + +/// Callback to handle results of calling UDPProxyClient::RequestForwarding() +/// \ingroup UDP_PROXY_GROUP +struct UDPProxyClientResultHandler +{ + UDPProxyClientResultHandler() {} + virtual ~UDPProxyClientResultHandler() {} + + /// Called when our forwarding request was completed. We can now connect to \a targetAddress by using \a proxyAddress instead + /// \param[out] proxyIPAddress IP Address of the proxy server, which will forward messages to targetAddress + /// \param[out] proxyPort Remote port to use on the proxy server, which will forward messages to targetAddress + /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. + /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] proxyClient The plugin that is calling this callback + virtual void OnForwardingSuccess(const char *proxyIPAddress, unsigned short proxyPort, + SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin)=0; + + /// Called when another system has setup forwarding, with our system as the target address. + /// Plugin automatically sends a datagram to proxyIPAddress before this callback, to open our router if necessary. + /// \param[out] proxyIPAddress IP Address of the proxy server, which will forward messages to targetAddress + /// \param[out] proxyPort Remote port to use on the proxy server, which will forward messages to targetAddress + /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. This is originating source IP address of the remote system that will be sending to us. + /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding. This is our external IP address. + /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] proxyClient The plugin that is calling this callback + virtual void OnForwardingNotification(const char *proxyIPAddress, unsigned short proxyPort, + SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin)=0; + + /// Called when our forwarding request failed, because no UDPProxyServers are connected to UDPProxyCoordinator + /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. + /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] proxyClient The plugin that is calling this callback + virtual void OnNoServersOnline(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin)=0; + + /// Called when our forwarding request failed, because no UDPProxyServers are connected to UDPProxyCoordinator + /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. + /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] proxyClient The plugin that is calling this callback + virtual void OnRecipientNotConnected(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin)=0; + + /// Called when our forwarding request failed, because all UDPProxyServers that are connected to UDPProxyCoordinator are at their capacity + /// Either add more servers, or increase capacity via UDPForwarder::SetMaxForwardEntries() + /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. + /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] proxyClient The plugin that is calling this callback + virtual void OnAllServersBusy(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin)=0; + + /// Called when our forwarding request is already in progress on the \a proxyCoordinator. + /// This can be ignored, but indicates an unneeded second request + /// \param[out] proxyIPAddress IP Address of the proxy server, which is forwarding messages to targetAddress + /// \param[out] proxyPort Remote port to use on the proxy server, which is forwarding messages to targetAddress + /// \param[out] proxyCoordinator \a proxyCoordinator parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] sourceAddress \a sourceAddress parameter passed to UDPProxyClient::RequestForwarding. If it was UNASSIGNED_SYSTEM_ADDRESS, it is now our external IP address. + /// \param[out] targetAddress \a targetAddress parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] targetGuid \a targetGuid parameter originally passed to UDPProxyClient::RequestForwarding + /// \param[out] proxyClient The plugin that is calling this callback + virtual void OnForwardingInProgress(const char *proxyIPAddress, unsigned short proxyPort, SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddress, RakNetGUID targetGuid, RakNet::UDPProxyClient *proxyClientPlugin)=0; +}; + + +/// \brief Communicates with UDPProxyCoordinator, in order to find a UDPProxyServer to forward our datagrams. +/// \details When NAT Punchthrough fails, it is possible to use a non-NAT system to forward messages from us to the recipient, and vice-versa.
    +/// The class to forward messages is UDPForwarder, and it is triggered over the network via the UDPProxyServer plugin.
    +/// The UDPProxyClient connects to UDPProxyCoordinator to get a list of servers running UDPProxyServer, and the coordinator will relay our forwarding request +/// \sa NatPunchthroughServer +/// \sa NatPunchthroughClient +/// \ingroup UDP_PROXY_GROUP +class RAK_DLL_EXPORT UDPProxyClient : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(UDPProxyClient) + + UDPProxyClient(); + ~UDPProxyClient(); + + /// Receives the results of calling RequestForwarding() + /// Set before calling RequestForwarding or you won't know what happened + /// \param[in] resultHandler + void SetResultHandler(UDPProxyClientResultHandler *rh); + + /// Sends a request to proxyCoordinator to find a server and have that server setup UDPForwarder::StartForwarding() on our address to \a targetAddressAsSeenFromCoordinator + /// The forwarded datagrams can be from any UDP source, not just RakNet + /// \pre Must be connected to \a proxyCoordinator + /// \pre Systems running UDPProxyServer must be connected to \a proxyCoordinator and logged in via UDPProxyCoordinator::LoginServer() or UDPProxyServer::LoginToCoordinator() + /// \note May still fail, if all proxy servers have no open connections. + /// \note RakNet's protocol will ensure a message is sent at least every 5 seconds, so if routing RakNet messages, it is a reasonable value for timeoutOnNoDataMS, plus an extra few seconds for latency. + /// \param[in] proxyCoordinator System we are connected to that is running the UDPProxyCoordinator plugin + /// \param[in] sourceAddress External IP address of the system we want to forward messages from. This does not have to be our own system. To specify our own system, you can pass UNASSIGNED_SYSTEM_ADDRESS which the coordinator will treat as our external IP address. + /// \param[in] targetAddressAsSeenFromCoordinator External IP address of the system we want to forward messages to. If this system is connected to UDPProxyCoordinator at this address using RakNet, that system will ping the server and thus open the router for incoming communication. In any other case, you are responsible for doing your own network communication to have that system ping the server. See also targetGuid in the other version of RequestForwarding(), to avoid the need to know the IP address to the coordinator of the destination. + /// \param[in] timeoutOnNoData If no data is sent by the forwarded systems, how long before removing the forward entry from UDPForwarder? UDP_FORWARDER_MAXIMUM_TIMEOUT is the maximum value. Recommended 10 seconds. + /// \param[in] serverSelectionBitstream If you want to send data to UDPProxyCoordinator::GetBestServer(), write it here + /// \return true if the request was sent, false if we are not connected to proxyCoordinator + bool RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddressAsSeenFromCoordinator, RakNet::TimeMS timeoutOnNoDataMS, RakNet::BitStream *serverSelectionBitstream=0); + + /// Same as above, but specify the target with a GUID, in case you don't know what its address is to the coordinator + /// If requesting forwarding to a RakNet enabled system, then it is easier to use targetGuid instead of targetAddressAsSeenFromCoordinator + bool RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, RakNetGUID targetGuid, RakNet::TimeMS timeoutOnNoDataMS, RakNet::BitStream *serverSelectionBitstream=0); + + /// \internal + virtual void Update(void); + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnRakPeerShutdown(void); + + struct ServerWithPing + { + unsigned short ping; + SystemAddress serverAddress; + }; + struct SenderAndTargetAddress + { + SystemAddress senderClientAddress; + SystemAddress targetClientAddress; + }; + struct PingServerGroup + { + SenderAndTargetAddress sata; + RakNet::TimeMS startPingTime; + SystemAddress coordinatorAddressForPings; + //DataStructures::Multilist serversToPing; + DataStructures::List serversToPing; + bool AreAllServersPinged(void) const; + void SendPingedServersToCoordinator(RakPeerInterface *rakPeerInterface); + }; + //DataStructures::Multilist pingServerGroups; + DataStructures::List pingServerGroups; +protected: + + void OnPingServers(Packet *packet); + void Clear(void); + UDPProxyClientResultHandler *resultHandler; + +}; + +} // End namespace + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/UDPProxyCommon.hpp b/include/raknet/UDPProxyCommon.hpp new file mode 100644 index 0000000..c9a0b49 --- /dev/null +++ b/include/raknet/UDPProxyCommon.hpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __UDP_PROXY_COMMON_H +#define __UDP_PROXY_COMMON_H + +// System flow: +/* +UDPProxyClient: End user +UDPProxyServer: open server, to route messages from end users that can't connect to each other using UDPForwarder class. +UDPProxyCoordinator: Server somewhere, connected to by RakNet, to maintain a list of UDPProxyServer + +UDPProxyServer + On startup, log into UDPProxyCoordinator and register self + +UDPProxyClient + Wish to open route to X + Send message to UDPProxyCoordinator containing X, desired timeout + Wait for success or failure + +UDPProxyCoordinator: +* Get openRouteRequest + If no servers registered, return failure + Add entry to memory + chooseBestUDPProxyServer() (overridable, chooses at random by default) + Query this server to StartForwarding(). Return success or failure + If failure, choose another server from the remaining list. If none remaining, return failure. Else return success. +* Disconnect: + If disconnected system is pending client on openRouteRequest, delete that request + If disconnected system is UDPProxyServer, remove from list. For each pending client for this server, choose from remaining servers. +* Login: + Add to UDPProxyServer list, validating password if set +*/ + +// Stored in the second byte after ID_UDP_PROXY_GENERAL +// Otherwise MessageIdentifiers.h is too cluttered and will hit the limit on enumerations in a single byte +enum UDPProxyMessages +{ + ID_UDP_PROXY_FORWARDING_SUCCEEDED, + ID_UDP_PROXY_FORWARDING_NOTIFICATION, + ID_UDP_PROXY_NO_SERVERS_ONLINE, + ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR, + ID_UDP_PROXY_ALL_SERVERS_BUSY, + ID_UDP_PROXY_IN_PROGRESS, + ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR, + ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT, + ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR, + ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR, + ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR, + ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER +}; + + +#define UDP_FORWARDER_MAXIMUM_TIMEOUT (60000 * 10) + +#endif diff --git a/include/raknet/UDPProxyCoordinator.hpp b/include/raknet/UDPProxyCoordinator.hpp new file mode 100644 index 0000000..d0f2cde --- /dev/null +++ b/include/raknet/UDPProxyCoordinator.hpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief Essentially maintains a list of servers running UDPProxyServer, and some state management for UDPProxyClient to find a free server to forward datagrams +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_UDPProxyCoordinator==1 && _RAKNET_SUPPORT_UDPForwarder==1 + +#ifndef __UDP_PROXY_COORDINATOR_H +#define __UDP_PROXY_COORDINATOR_H + +#include "Export.hpp" +#include "RakNetTypes.hpp" +#include "PluginInterface2.hpp" +#include "RakString.hpp" +#include "BitStream.hpp" +#include "DS_Queue.hpp" +#include "DS_OrderedList.hpp" + +namespace RakNet +{ + /// When NAT Punchthrough fails, it is possible to use a non-NAT system to forward messages from us to the recipient, and vice-versa + /// The class to forward messages is UDPForwarder, and it is triggered over the network via the UDPProxyServer plugin. + /// The UDPProxyClient connects to UDPProxyCoordinator to get a list of servers running UDPProxyServer, and the coordinator will relay our forwarding request + /// \brief Middleman between UDPProxyServer and UDPProxyClient, maintaining a list of UDPProxyServer, and managing state for clients to find an available forwarding server. + /// \ingroup NAT_PUNCHTHROUGH_GROUP + class RAK_DLL_EXPORT UDPProxyCoordinator : public PluginInterface2 + { + public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(UDPProxyCoordinator) + + UDPProxyCoordinator(); + virtual ~UDPProxyCoordinator(); + + /// For UDPProxyServers logging in remotely, they must pass a password to UDPProxyServer::LoginToCoordinator(). It must match the password set here. + /// If no password is set, they cannot login remotely. + /// By default, no password is set + void SetRemoteLoginPassword(RakNet::RakString password); + + /// \internal + virtual void Update(void); + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + + struct SenderAndTargetAddress + { + SystemAddress senderClientAddress; + RakNetGUID senderClientGuid; + SystemAddress targetClientAddress; + RakNetGUID targetClientGuid; + }; + + struct ServerWithPing + { + unsigned short ping; + SystemAddress serverAddress; + }; + + struct ForwardingRequest + { + RakNet::TimeMS timeoutOnNoDataMS; + RakNet::TimeMS timeoutAfterSuccess; + SenderAndTargetAddress sata; + SystemAddress requestingAddress; // Which system originally sent the network message to start forwarding + SystemAddress currentlyAttemptedServerAddress; + DataStructures::Queue remainingServersToTry; + RakNet::BitStream serverSelectionBitstream; + + DataStructures::List sourceServerPings, targetServerPings; + RakNet::TimeMS timeRequestedPings; + // Order based on sourceServerPings and targetServerPings + void OrderRemainingServersToTry(void); + + }; + protected: + + static int ServerWithPingComp( const unsigned short &key, const UDPProxyCoordinator::ServerWithPing &data ); + static int ForwardingRequestComp( const SenderAndTargetAddress &key, ForwardingRequest* const &data); + + void OnForwardingRequestFromClientToCoordinator(Packet *packet); + void OnLoginRequestFromServerToCoordinator(Packet *packet); + void OnForwardingReplyFromServerToCoordinator(Packet *packet); + void OnPingServersReplyFromClientToCoordinator(Packet *packet); + void TryNextServer(SenderAndTargetAddress sata, ForwardingRequest *fw); + void SendAllBusy(SystemAddress senderClientAddress, SystemAddress targetClientAddress, RakNetGUID targetClientGuid, SystemAddress requestingAddress); + void Clear(void); + + void SendForwardingRequest(SystemAddress sourceAddress, SystemAddress targetAddress, SystemAddress serverAddress, RakNet::TimeMS timeoutOnNoDataMS); + + // Logged in servers + //DataStructures::Multilist serverList; + DataStructures::List serverList; + + // Forwarding requests in progress + //DataStructures::Multilist forwardingRequestList; + DataStructures::OrderedList forwardingRequestList; + + RakNet::RakString remoteLoginPassword; + + }; + +} // End namespace + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/UDPProxyServer.hpp b/include/raknet/UDPProxyServer.hpp new file mode 100644 index 0000000..f68fb0c --- /dev/null +++ b/include/raknet/UDPProxyServer.hpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief A RakNet plugin performing networking to communicate with UDPProxyServer. It allows UDPProxyServer to control our instance of UDPForwarder. +/// + + +#include "NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_UDPProxyServer==1 && _RAKNET_SUPPORT_UDPForwarder==1 + +#ifndef __UDP_PROXY_SERVER_H +#define __UDP_PROXY_SERVER_H + +#include "Export.hpp" +#include "RakNetTypes.hpp" +#include "PluginInterface2.hpp" +#include "UDPForwarder.hpp" +#include "RakString.hpp" + +namespace RakNet +{ +class UDPProxyServer; + +/// Callback to handle results of calling UDPProxyServer::LoginToCoordinator() +/// \ingroup UDP_PROXY_GROUP +struct UDPProxyServerResultHandler +{ + UDPProxyServerResultHandler() {} + virtual ~UDPProxyServerResultHandler() {} + + /// Called when our login succeeds + /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() + /// \param[out] proxyServer The plugin calling this callback + virtual void OnLoginSuccess(RakNet::RakString usedPassword, RakNet::UDPProxyServer *proxyServerPlugin)=0; + + /// We are already logged in. + /// This login failed, but the system is operational as if it succeeded + /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() + /// \param[out] proxyServer The plugin calling this callback + virtual void OnAlreadyLoggedIn(RakNet::RakString usedPassword, RakNet::UDPProxyServer *proxyServerPlugin)=0; + + /// The coordinator operator forgot to call UDPProxyCoordinator::SetRemoteLoginPassword() + /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() + /// \param[out] proxyServer The plugin calling this callback + virtual void OnNoPasswordSet(RakNet::RakString usedPassword, RakNet::UDPProxyServer *proxyServerPlugin)=0; + + /// The coordinator operator set a different password in UDPProxyCoordinator::SetRemoteLoginPassword() than what we passed + /// \param[out] usedPassword The password we passed to UDPProxyServer::LoginToCoordinator() + /// \param[out] proxyServer The plugin calling this callback + virtual void OnWrongPassword(RakNet::RakString usedPassword, RakNet::UDPProxyServer *proxyServerPlugin)=0; +}; + +/// \brief UDPProxyServer to control our instance of UDPForwarder +/// \details When NAT Punchthrough fails, it is possible to use a non-NAT system to forward messages from us to the recipient, and vice-versa.
    +/// The class to forward messages is UDPForwarder, and it is triggered over the network via the UDPProxyServer plugin.
    +/// The UDPProxyServer connects to UDPProxyServer to get a list of servers running UDPProxyServer, and the coordinator will relay our forwarding request. +/// \ingroup UDP_PROXY_GROUP +class RAK_DLL_EXPORT UDPProxyServer : public PluginInterface2 +{ +public: + // GetInstance() and DestroyInstance(instance*) + STATIC_FACTORY_DECLARATIONS(UDPProxyServer) + + UDPProxyServer(); + ~UDPProxyServer(); + + /// Sets the socket family to use, either IPV4 or IPV6 + /// \param[in] socketFamily For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC. + void SetSocketFamily(unsigned short _socketFamily); + + /// Receives the results of calling LoginToCoordinator() + /// Set before calling LoginToCoordinator or you won't know what happened + /// \param[in] resultHandler + void SetResultHandler(UDPProxyServerResultHandler *rh); + + /// Before the coordinator will register the UDPProxyServer, you must login + /// \pre Must be connected to the coordinator + /// \pre Coordinator must have set a password with UDPProxyCoordinator::SetRemoteLoginPassword() + /// \returns false if already logged in, or logging in. Returns true otherwise + bool LoginToCoordinator(RakNet::RakString password, SystemAddress coordinatorAddress); + + /// \brief The server IP reported to the client is the IP address from the server to the coordinator. + /// If the server and coordinator are on the same LAN, you need to call SetServerPublicIP() to tell the client what address to connect to + /// \param[in] ip IP address to report in UDPProxyClientResultHandler::OnForwardingSuccess() and UDPProxyClientResultHandler::OnForwardingNotification() as proxyIPAddress + void SetServerPublicIP(RakString ip); + + /// Operative class that performs the forwarding + /// Exposed so you can call UDPForwarder::SetMaxForwardEntries() if you want to change away from the default + /// UDPForwarder::Startup(), UDPForwarder::Shutdown(), and UDPForwarder::Update() are called automatically by the plugin + UDPForwarder udpForwarder; + + virtual void OnAttach(void); + virtual void OnDetach(void); + + /// \internal + virtual void Update(void); + virtual PluginReceiveResult OnReceive(Packet *packet); + virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ); + virtual void OnRakPeerStartup(void); + virtual void OnRakPeerShutdown(void); + +protected: + void OnForwardingRequestFromCoordinatorToServer(Packet *packet); + + DataStructures::OrderedList loggingInCoordinators; + DataStructures::OrderedList loggedInCoordinators; + + UDPProxyServerResultHandler *resultHandler; + unsigned short socketFamily; + RakString serverPublicIp; + +}; + +} // End namespace + +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/include/raknet/VariableDeltaSerializer.hpp b/include/raknet/VariableDeltaSerializer.hpp new file mode 100644 index 0000000..d448d6b --- /dev/null +++ b/include/raknet/VariableDeltaSerializer.hpp @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __VARIABLE_DELTA_SERIALIZER_H +#define __VARIABLE_DELTA_SERIALIZER_H + +#include "VariableListDeltaTracker.hpp" +#include "DS_MemoryPool.hpp" +#include "NativeTypes.hpp" +#include "BitStream.hpp" +#include "PacketPriority.hpp" +#include "DS_OrderedList.hpp" + +namespace RakNet +{ + +/// \brief Class to compare memory values of variables in a current state to a prior state +/// Results of the comparisons will be written to a bitStream, such that only changed variables get written
    +/// Can be used with ReplicaManager3 to Serialize a Replica3 per-variable, rather than comparing the entire object against itself
    +/// Usage:
    +///
    +/// 1. Call BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(). In the case of Replica3, this would be in the Serialize() call
    +/// 2. For each variable of the type in step 1, call Serialize(). The same variables must be serialized every tick()
    +/// 3. Call EndSerialize()
    +/// 4. Repeat step 1 for each of the other categories of how to send varaibles
    +///
    +/// On the receiver:
    +///
    +/// 1. Call BeginDeserialize(). In the case of Replica3, this would be in the Deserialize() call
    +/// 2. Call DeserializeVariable() for each variable, in the same order as was Serialized()
    +/// 3. Call EndSerialize()
    +/// \sa The ReplicaManager3 sample +class RAK_DLL_EXPORT VariableDeltaSerializer +{ +protected: + struct RemoteSystemVariableHistory; + struct ChangedVariablesList; + +public: + VariableDeltaSerializer(); + ~VariableDeltaSerializer(); + + struct SerializationContext + { + SerializationContext(); + ~SerializationContext(); + + RakNetGUID guid; + BitStream *bitStream; + uint32_t rakPeerSendReceipt; + RemoteSystemVariableHistory *variableHistory; + RemoteSystemVariableHistory *variableHistoryIdentical; + RemoteSystemVariableHistory *variableHistoryUnique; + ChangedVariablesList *changedVariables; + uint32_t sendReceipt; + PacketReliability serializationMode; + bool anyVariablesWritten; + bool newSystemSend; // Force send all, do not record + }; + + struct DeserializationContext + { + BitStream *bitStream; + }; + + /// \brief Call before doing one or more SerializeVariable calls when the data will be sent UNRELIABLE_WITH_ACK_RECEIPT + /// The last value of each variable will be saved per remote system. Additionally, a history of \a _sendReceipts is stored to determine what to resend on packetloss. + /// When variables are lost, they will be flagged dirty and always resent to the system that lost it + /// Disadvantages: Every variable for every remote system is copied internally, in addition to a history list of what variables changed for which \a _sendReceipt. Very memory and CPU intensive for multiple connections. + /// Advantages: When data needs to be resent by RakNet, RakNet can only resend the value it currently has. This allows the application to control the resend, sending the most recent value of the variable. The end result is that bandwidth is used more efficiently because old data is never sent. + /// \pre Upon getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED call OnMessageReceipt() + /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections + /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. + /// \param[in] _guid Which system we are sending to + /// \param[in] _bitSteam Which bitStream to write to + /// \param[in] _sendReceipt Returned from RakPeer::IncrementNextSendReceipt() and passed to the Send() or SendLists() function. Identifies this update for ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED + void BeginUnreliableAckedSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream, uint32_t _sendReceipt); + + /// \brief Call before doing one or more SerializeVariable calls for data that may be sent differently to every remote system (such as an invisibility flag that only teammates can see) + /// The last value of each variable will be saved per remote system. + /// Unlike BeginUnreliableAckedSerialize(), send receipts are not necessary + /// Disadvantages: Every variable for every remote system is copied internally. Very memory and CPU intensive for multiple connections. + /// Advantages: When data is sent differently depending on the recipient, this system can make things easier to use and is as efficient as it can be. + /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections + /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. + /// \param[in] _guid Which system we are sending to + /// \param[in] _bitSteam Which bitStream to write to + void BeginUniqueSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream); + + /// \brief Call before doing one or more SerializeVariable calls for data that is sent with the same value to every remote system (such as health, position, etc.) + /// This is the most common type of serialization, and also the most efficient + /// Disadvantages: A copy of every variable still needs to be held, although only once + /// Advantages: After the first serialization, the last serialized bitStream will be used for subsequent sends + /// \pre Call OnPreSerializeTick() before doing any calls to BeginIdenticalSerialize() for each of your objects, once per game tick + /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. + /// \param[in] _isFirstSerializeToThisSystem Pass true if this is the first time ever serializing to this system (the initial download). This way all variables will be written, rather than checking against prior sent values. + /// \param[in] _bitSteam Which bitStream to write to + void BeginIdenticalSerialize(SerializationContext *context, bool _isFirstSerializeToThisSystem, BitStream *_bitStream); + + /// \brief Call after BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(), then after calling SerializeVariable() one or more times + /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() + void EndSerialize(SerializationContext *context); + + /// \brief Call when you receive the BitStream written by SerializeVariable(), before calling DeserializeVariable() + /// \param[in] context Holds the context of this group of deserialize calls. This can be a stack object just passed to the function. + /// \param[in] _bitStream Pass the bitStream originally passed to and written to by serialize calls + void BeginDeserialize(DeserializationContext *context, BitStream *_bitStream); + + /// \param[in] context Same context pointer passed to BeginDeserialize() + void EndDeserialize(DeserializationContext *context); + + /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped + /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events + /// \param[in] _guid Which system we are sending to + void AddRemoteSystemVariableHistory(RakNetGUID guid); + + /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped + /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events + /// \param[in] _guid Which system we are sending to + void RemoveRemoteSystemVariableHistory(RakNetGUID guid); + + /// BeginIdenticalSerialize() requires knowledge of when serialization has started for an object across multiple systems + /// This way it can setup the flag to do new comparisons against the last sent values, rather than just resending the last sent bitStream + /// For Replica3, overload and call this from Replica3::OnUserReplicaPreSerializeTick() + void OnPreSerializeTick(void); + + /// Call when getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED for a particular system + /// Example: + /// + /// uint32_t msgNumber; + /// memcpy(&msgNumber, packet->data+1, 4); + /// DataStructures::List replicaListOut; + /// replicaManager.GetReplicasCreatedByMe(replicaListOut); + /// unsigned int idx; + /// for (idx=0; idx < replicaListOut.GetSize(); idx++) + /// { + /// ((SampleReplica*)replicaListOut[idx])->NotifyReplicaOfMessageDeliveryStatus(packet->guid,msgNumber, packet->data[0]==ID_SND_RECEIPT_ACKED); + /// } + /// + /// \param[in] guid Which system we are sending to + /// \param[in] receiptId Encoded in bytes 1-4 inclusive of ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED + /// \param[in] messageArrived True for ID_SND_RECEIPT_ACKED, false otherwise + void OnMessageReceipt(RakNetGUID guid, uint32_t receiptId, bool messageArrived); + + /// Call to Serialize a variable + /// Will write to the bitSteam passed to \a context true, variableValue if the variable has changed or has never been written. Otherwise will write false. + /// \pre You have called BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() + /// \pre Will also require calling OnPreSerializeTick() if using BeginIdenticalSerialize() + /// \note Be sure to call EndSerialize() after finishing all serializations + /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() + /// \param[in] variable A variable to write to the bitStream passed to \a context + template + void SerializeVariable(SerializationContext *context, const VarType &variable) + { + if (context->newSystemSend) + { + if (context->variableHistory->variableListDeltaTracker.IsPastEndOfList()==false) + { + // previously sent data to another system + context->bitStream->Write(true); + context->bitStream->Write(variable); + context->anyVariablesWritten=true; + } + else + { + // never sent data to another system + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); + context->anyVariablesWritten=true; + } + } + else if (context->serializationMode==UNRELIABLE_WITH_ACK_RECEIPT) + { + context->anyVariablesWritten|= + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream, context->changedVariables->bitField, context->changedVariables->bitWriteIndex++); + } + else + { + if (context->variableHistoryIdentical) + { + // Identical serialization to a number of systems + if (didComparisonThisTick==false) + context->anyVariablesWritten|= + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); + // Else bitstream is written to at the end + } + else + { + // Per-system serialization + context->anyVariablesWritten|= + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); + } + } + } + + /// Call to deserialize into a variable + /// \pre You have called BeginDeserialize() + /// \note Be sure to call EndDeserialize() after finishing all deserializations + /// \param[in] context Same context pointer passed to BeginDeserialize() + /// \param[in] variable A variable to write to the bitStream passed to \a context + template + bool DeserializeVariable(DeserializationContext *context, VarType &variable) + { + return VariableListDeltaTracker::ReadVarFromBitstream(variable, context->bitStream); + } + + + +protected: + + // For a given send receipt from RakPeer::Send() track which variables we updated + // That way if that send does not arrive (ID_SND_RECEIPT_LOSS) we can mark those variables as dirty to resend them with current values + struct ChangedVariablesList + { + uint32_t sendReceipt; + unsigned short bitWriteIndex; + unsigned char bitField[56]; + }; + + // static int Replica2ObjectComp( const uint32_t &key, ChangedVariablesList* const &data ); + + static int UpdatedVariablesListPtrComp( const uint32_t &key, ChangedVariablesList* const &data ); + + // For each remote system, track the last values of variables we sent to them, and the history of what values changed per call to Send() + // Every serialize if a variable changes from its last value, send it out again + // Also if a send does not arrive (ID_SND_RECEIPT_LOSS) we use updatedVariablesHistory to mark those variables as dirty, to resend them unreliably with the current values + struct RemoteSystemVariableHistory + { + RakNetGUID guid; + VariableListDeltaTracker variableListDeltaTracker; + DataStructures::OrderedList updatedVariablesHistory; + }; + /// A list of RemoteSystemVariableHistory indexed by guid, one per connection that we serialize to + /// List is added to when SerializeConstruction is called, and removed from when SerializeDestruction is called, or when a given connection is dropped + DataStructures::List remoteSystemVariableHistoryList; + + // Because the ChangedVariablesList is created every serialize and destroyed every receipt I use a pool to avoid fragmentation + DataStructures::MemoryPool updatedVariablesMemoryPool; + + bool didComparisonThisTick; + RakNet::BitStream identicalSerializationBs; + + void FreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); + void DirtyAndFreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); + unsigned int GetVarsWrittenPerRemoteSystemListIndex(RakNetGUID guid); + void RemoveRemoteSystemVariableHistory(void); + + RemoteSystemVariableHistory* GetRemoteSystemVariableHistory(RakNetGUID guid); + + ChangedVariablesList *AllocChangedVariablesList(void); + void FreeChangedVariablesList(ChangedVariablesList *changedVariables); + void StoreChangedVariablesList(RemoteSystemVariableHistory *variableHistory, ChangedVariablesList *changedVariables, uint32_t sendReceipt); + + RemoteSystemVariableHistory *StartVariableHistoryWrite(RakNetGUID guid); + unsigned int GetRemoteSystemHistoryListIndex(RakNetGUID guid); + +}; + +} + +#endif diff --git a/include/raknet/VariableListDeltaTracker.hpp b/include/raknet/VariableListDeltaTracker.hpp new file mode 100644 index 0000000..7074c73 --- /dev/null +++ b/include/raknet/VariableListDeltaTracker.hpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "NativeTypes.hpp" +#include "DS_List.hpp" +#include "RakMemoryOverride.hpp" +#include "BitStream.hpp" + +#ifndef __VARIABLE_LIST_DELTA_TRACKER +#define __VARIABLE_LIST_DELTA_TRACKER + +namespace RakNet +{ +/// Class to write a series of variables, copy the contents to memory, and return if the newly written value is different than what was last written +/// Can also encode the reads, writes, and results directly to/from a bitstream +class VariableListDeltaTracker +{ +public: + VariableListDeltaTracker(); + ~VariableListDeltaTracker(); + + // Call before using a series of WriteVar + void StartWrite(void); + + bool IsPastEndOfList(void) const {return nextWriteIndex>=variableList.Size();} + + /// Records the passed value of the variable to memory, and returns true if the value is different from the write before that (or if it is the first write) + /// \pre Call StartWrite() before doing the first of a series of calls to WriteVar or other functions that call WriteVar + /// \note Variables must be of the same type, written in the same order, each time + template + bool WriteVar(const VarType &varData) + { + RakNet::BitStream temp; + temp.Write(varData); + if (nextWriteIndex>=variableList.Size()) + { + variableList.Push(VariableLastValueNode(temp.GetData(),temp.GetNumberOfBytesUsed()),_FILE_AND_LINE_); + nextWriteIndex++; + return true; // Different because it's new + } + + if (temp.GetNumberOfBytesUsed()!=variableList[nextWriteIndex].byteLength) + { + variableList[nextWriteIndex].lastData=(char*) rakRealloc_Ex(variableList[nextWriteIndex].lastData, temp.GetNumberOfBytesUsed(),_FILE_AND_LINE_); + variableList[nextWriteIndex].byteLength=temp.GetNumberOfBytesUsed(); + memcpy(variableList[nextWriteIndex].lastData,temp.GetData(),temp.GetNumberOfBytesUsed()); + nextWriteIndex++; + variableList[nextWriteIndex].isDirty=false; + return true; // Different because the serialized size is different + } + if (variableList[nextWriteIndex].isDirty==false && memcmp(temp.GetData(),variableList[nextWriteIndex].lastData, variableList[nextWriteIndex].byteLength)==0) + { + nextWriteIndex++; + return false; // Same because not dirty and memcmp is the same + } + + variableList[nextWriteIndex].isDirty=false; + memcpy(variableList[nextWriteIndex].lastData,temp.GetData(),temp.GetNumberOfBytesUsed()); + nextWriteIndex++; + return true; // Different because dirty or memcmp was different + } + /// Calls WriteVar. If the variable has changed, writes true, and writes the variable. Otherwise writes false. + template + bool WriteVarToBitstream(const VarType &varData, RakNet::BitStream *bitStream) + { + bool wasDifferent = WriteVar(varData); + bitStream->Write(wasDifferent); + if (wasDifferent) + { + bitStream->Write(varData); + return true; + } + return false; + } + /// Calls WriteVarToBitstream(). Additionally, adds the boolean result of WriteVar() to boolean bit array + template + bool WriteVarToBitstream(const VarType &varData, RakNet::BitStream *bitStream, unsigned char *bArray, unsigned short writeOffset) + { + if (WriteVarToBitstream(varData,bitStream)==true) + { + BitSize_t numberOfBitsMod8 = writeOffset & 7; + + if ( numberOfBitsMod8 == 0 ) + bArray[ writeOffset >> 3 ] = 0x80; + else + bArray[ writeOffset >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1 + + return true; + } + else + { + if ( ( writeOffset & 7 ) == 0 ) + bArray[ writeOffset >> 3 ] = 0; + + return false; + } + } + + /// Paired with a call to WriteVarToBitstream(), will read a variable if it had changed. Otherwise the values remains the same. + template + static bool ReadVarFromBitstream(VarType &varData, RakNet::BitStream *bitStream) + { + bool wasWritten; + if (bitStream->Read(wasWritten)==false) + return false; + if (wasWritten) + { + if (bitStream->Read(varData)==false) + return false; + } + return wasWritten; + } + + /// Variables flagged dirty will cause WriteVar() to return true, even if the variable had not otherwise changed + /// This updates all the variables in the list, where in each index \a varsWritten is true, so will the variable at the corresponding index be flagged dirty + void FlagDirtyFromBitArray(unsigned char *bArray); + + /// \internal + struct VariableLastValueNode + { + VariableLastValueNode(); + VariableLastValueNode(const unsigned char *data, int _byteLength); + ~VariableLastValueNode(); + char *lastData; + unsigned int byteLength; + bool isDirty; + }; + +protected: + /// \internal + DataStructures::List variableList; + /// \internal + unsigned int nextWriteIndex; +}; + + +} + +#endif diff --git a/include/raknet/VariadicSQLParser.hpp b/include/raknet/VariadicSQLParser.hpp new file mode 100644 index 0000000..6900d0d --- /dev/null +++ b/include/raknet/VariadicSQLParser.hpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __VARIADIC_SQL_PARSER_H +#define __VARIADIC_SQL_PARSER_H + +#include "DS_List.hpp" + +#include + +namespace VariadicSQLParser +{ + struct IndexAndType + { + unsigned int strIndex; + unsigned int typeMappingIndex; + }; + const char* GetTypeMappingAtIndex(int i); + void GetTypeMappingIndices( const char *format, DataStructures::List &indices ); + // Given an SQL string with variadic arguments, allocate argumentBinary and argumentLengths, and hold the parameters in binary format + // Last 2 parameters are out parameters + void ExtractArguments( va_list argptr, const DataStructures::List &indices, char ***argumentBinary, int **argumentLengths ); + void FreeArguments(const DataStructures::List &indices, char **argumentBinary, int *argumentLengths); +} + + +#endif diff --git a/include/raknet/VitaIncludes.hpp b/include/raknet/VitaIncludes.hpp new file mode 100644 index 0000000..f6993a1 --- /dev/null +++ b/include/raknet/VitaIncludes.hpp @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/include/raknet/WSAStartupSingleton.hpp b/include/raknet/WSAStartupSingleton.hpp new file mode 100644 index 0000000..168d463 --- /dev/null +++ b/include/raknet/WSAStartupSingleton.hpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __WSA_STARTUP_SINGLETON_H +#define __WSA_STARTUP_SINGLETON_H + +class WSAStartupSingleton +{ +public: + WSAStartupSingleton(); + ~WSAStartupSingleton(); + static void AddRef(void); + static void Deref(void); + +protected: + static int refCount; +}; + +#endif diff --git a/include/raknet/WindowsIncludes.hpp b/include/raknet/WindowsIncludes.hpp new file mode 100644 index 0000000..6363335 --- /dev/null +++ b/include/raknet/WindowsIncludes.hpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#if defined (WINDOWS_STORE_RT) +#include +#include +#elif defined (_WIN32) +#include +#include +#include + +// Must always include Winsock2.h before windows.h +// or else: +// winsock2.h(99) : error C2011: 'fd_set' : 'struct' type redefinition +// winsock2.h(134) : warning C4005: 'FD_SET' : macro redefinition +// winsock.h(83) : see previous definition of 'FD_SET' +// winsock2.h(143) : error C2011: 'timeval' : 'struct' type redefinition +// winsock2.h(199) : error C2011: 'hostent' : 'struct' type redefinition +// winsock2.h(212) : error C2011: 'netent' : 'struct' type redefinition +// winsock2.h(219) : error C2011: 'servent' : 'struct' type redefinition + +#endif diff --git a/include/raknet/XBox360Includes.hpp b/include/raknet/XBox360Includes.hpp new file mode 100644 index 0000000..bd70cd1 --- /dev/null +++ b/include/raknet/XBox360Includes.hpp @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/include/raknet/_FindFirst.hpp b/include/raknet/_FindFirst.hpp new file mode 100644 index 0000000..b29fa13 --- /dev/null +++ b/include/raknet/_FindFirst.hpp @@ -0,0 +1,56 @@ +/// +/// Original file by the_viking, fixed by Rmulo Fernandes +/// Should emulate windows finddata structure +/// + +#ifndef GCC_FINDFIRST_H +#define GCC_FINDFIRST_H + +#if (defined(__GNUC__) || defined(__ARMCC_VERSION) || defined(__GCCXML__) || defined(__S3E__) ) && !defined(__WIN32) + +#include + +#include "RakString.hpp" + +#define _A_NORMAL 0x00 // Normal file +#define _A_RDONLY 0x01 // Read-only file +#define _A_HIDDEN 0x02 // Hidden file +#define _A_SYSTEM 0x04 // System file +#define _A_VOLID 0x08 // Volume ID +#define _A_SUBDIR 0x10 // Subdirectory +#define _A_ARCH 0x20 // File changed since last archive +#define FA_NORMAL 0x00 // Synonym of _A_NORMAL +#define FA_RDONLY 0x01 // Synonym of _A_RDONLY +#define FA_HIDDEN 0x02 // Synonym of _A_HIDDEN +#define FA_SYSTEM 0x04 // Synonym of _A_SYSTEM +#define FA_LABEL 0x08 // Synonym of _A_VOLID +#define FA_DIREC 0x10 // Synonym of _A_SUBDIR +#define FA_ARCH 0x20 // Synonym of _A_ARCH + + +const unsigned STRING_BUFFER_SIZE = 512; + +typedef struct _finddata_t +{ + char name[STRING_BUFFER_SIZE]; + int attrib; + unsigned long size; +} _finddata; + +/** + * Hold information about the current search + */ +typedef struct _findinfo_t +{ + DIR* openedDir; + RakNet::RakString filter; + RakNet::RakString dirName; +} _findinfo; + +long _findfirst(const char *name, _finddata_t *f); +int _findnext(long h, _finddata_t *f); +int _findclose(long h); + +#endif +#endif + diff --git a/include/raknet/gettimeofday.hpp b/include/raknet/gettimeofday.hpp new file mode 100644 index 0000000..29ddc5a --- /dev/null +++ b/include/raknet/gettimeofday.hpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#ifndef __GET_TIME_OF_DAY_H +#define __GET_TIME_OF_DAY_H + +#if defined(_WIN32) && !defined(__GNUC__) &&!defined(__GCCXML__) +#include < time.h > +struct timezone +{ + int tz_minuteswest; /* minutes W of Greenwich */ + int tz_dsttime; /* type of dst correction */ +}; + +#if defined(WINDOWS_STORE_RT) +struct timeval { + long tv_sec; + long tv_usec; +}; +#endif + +int gettimeofday(struct timeval *tv, struct timezone *tz); + + +#else + + + + +#include + +#include + +// Uncomment this if you need to +/* +// http://www.halcode.com/archives/2008/08/26/retrieving-system-time-gettimeofday/ +struct timezone +{ + int tz_minuteswest; + int tz_dsttime; +}; + +#ifdef __cplusplus + +void GetSystemTimeAsFileTime(FILETIME*); + +inline int gettimeofday(struct timeval* p, void* tz ) +{ + union { + long long ns100; // time since 1 Jan 1601 in 100ns units + FILETIME ft; + } now; + + GetSystemTimeAsFileTime( &(now.ft) ); + p->tv_usec=(long)((now.ns100 / 10LL) % 1000000LL ); + p->tv_sec= (long)((now.ns100-(116444736000000000LL))/10000000LL); + return 0; +} + +#else + int gettimeofday(struct timeval* p, void* tz ); +#endif +*/ + +#endif + +#endif diff --git a/include/utils/BitReader.hpp b/include/utils/BitReader.hpp new file mode 100644 index 0000000..5743f40 --- /dev/null +++ b/include/utils/BitReader.hpp @@ -0,0 +1,48 @@ +#ifndef BYTEREADER_HPP +#define BYTEREADER_HPP + +class BitReader{ + + public: + + BitReader(const char* dataArray, unsigned int arrayLength); + + ~BitReader(); + + unsigned char getBitsFromArray(unsigned int count); + + char* getFixedDepthBitsFromArray(unsigned int bitDepth, unsigned count); + + unsigned long long int getBitIndex(); + + unsigned int getBitIndexOfCurrentByte(); + + unsigned int getByteIndex(); + + void setBitIndex(unsigned long long int index); + + void setBitIndexOfCurrentByte(unsigned int index); + + void setByteIndex(unsigned int); + + unsigned int isEOA(); + + static unsigned char getBitsFromByte(unsigned char byte, unsigned int count); + + static unsigned char getBitsFromByte(unsigned char byte, unsigned int index, unsigned int count); + + private: + + unsigned int page; + + unsigned int currentBitCursor; + + unsigned int arrlen=0; + + char* array; + + BitReader(void); + +}; + +#endif // BYTEREADER_HPP diff --git a/include/utils/CRC.hpp b/include/utils/CRC.hpp new file mode 100644 index 0000000..38f1ba6 --- /dev/null +++ b/include/utils/CRC.hpp @@ -0,0 +1,30 @@ +#ifndef CRC_HPP +#define CRC_HPP + +class CRC{ + + private: + + static const unsigned int CRC32_POLYNOMIAL; + + static const unsigned int CRC32_POLYNOMIAL_DRF; + + unsigned int* crc32_table=0; + + public: + + static const unsigned int CRC_MODE_DEFAULT; + + static const unsigned int CRC_MODE_DRF; + + unsigned int update_crc32(const unsigned char* data, unsigned int dataLength, unsigned int old_crc32); + + unsigned int getCRC32(const unsigned char* data, unsigned int dataLength); + + CRC(unsigned int mode=CRC::CRC_MODE_DEFAULT); + + ~CRC(); + +}; + +#endif diff --git a/include/utils/EndianUtils.hpp b/include/utils/EndianUtils.hpp new file mode 100644 index 0000000..d70e7be --- /dev/null +++ b/include/utils/EndianUtils.hpp @@ -0,0 +1,30 @@ +#ifndef ENDIANUTILS_HPP +#define ENDIANUTILS_HPP + +class EndianUtils{ + + private: + + EndianUtils(); + + public: + + static unsigned int isLittleEndian(); + + static unsigned long long reverseBytes(unsigned long long arg, unsigned int dataSize); + + static unsigned long long reverseBytes(unsigned long long arg); + + static unsigned int reverseBytes(unsigned int arg); + + static unsigned short reverseBytes(unsigned short arg); + + static unsigned long long toNativeEndian(unsigned long long arg); + + static unsigned int toNativeEndian(unsigned int arg); + + static unsigned short toNativeEndian(unsigned short arg); + +}; + +#endif diff --git a/include/utils/FileReader.hpp b/include/utils/FileReader.hpp new file mode 100644 index 0000000..2b9fa06 --- /dev/null +++ b/include/utils/FileReader.hpp @@ -0,0 +1,33 @@ +#ifndef FILEREADER_HPP +#define FILEREADER_HPP + +#include + +class FileReader{ + + private: + + FILE* fd; + unsigned int length; + + public: + + FileReader(const char* path); + + void readFully(char* buffer, unsigned int length); + + unsigned int read(char* buffer, unsigned int count); + + unsigned int isEOF(); + + void reset(); + + void seekTo(unsigned int index); + + unsigned int getFileLength(); + + ~FileReader(); + +}; + +#endif // FILEREADER_H diff --git a/include/utils/FileWriter.hpp b/include/utils/FileWriter.hpp new file mode 100644 index 0000000..6402df8 --- /dev/null +++ b/include/utils/FileWriter.hpp @@ -0,0 +1,28 @@ +#ifndef FILEWRITER_HPP +#define FILEWRITER_HPP + +#include + +class FileWriter{ + + private: + + FILE* fd; + + public: + + FileWriter(const char* path); + + void write(const char* data, unsigned int length); + + void reset(); + + void seekTo(unsigned int length); + + unsigned int getCurrentFileSize(); + + ~FileWriter(); + +}; + +#endif // FILEWRITER_H diff --git a/include/utils/GzipUtils.hpp b/include/utils/GzipUtils.hpp new file mode 100644 index 0000000..d9cf512 --- /dev/null +++ b/include/utils/GzipUtils.hpp @@ -0,0 +1,17 @@ +#ifndef GZIPUTILS_HPP +#define GZIPUTILS_HPP + +class GzipUtils{ + + public: + + static unsigned char* compressData(const unsigned char* data, unsigned long dataLength, unsigned long* resultLength); + + static unsigned char* decompressData(const unsigned char* data, unsigned long dataLength, unsigned long* resultLength); + + static int decompressData(const unsigned char* data, unsigned long dataLength, unsigned char* resultBuffer, unsigned long resultBufferSize, unsigned long* resultLength); + + +}; + +#endif // GZIPUTILS_HPP diff --git a/include/utils/HeaderChecker.hpp b/include/utils/HeaderChecker.hpp new file mode 100644 index 0000000..8d003cf --- /dev/null +++ b/include/utils/HeaderChecker.hpp @@ -0,0 +1,25 @@ +#ifndef HEADERCHECKER_HPP +#define HEADERCHECKER_HPP + +class HeaderChecker{ + + private: + + HeaderChecker(); + + public: + + static const unsigned int HEADER_DRF_LENGTH=4; + + static const unsigned char HEADER_DRF[HEADER_DRF_LENGTH]; + + static const unsigned int HEADER_PNG_LENGTH=8; + + static const unsigned char HEADER_PNG[HEADER_PNG_LENGTH]; + + static unsigned char checkHeader(const unsigned char* srcHeader, unsigned int srcHeaderLength, const unsigned char* dstHeader); + +}; + + +#endif // HEADERCHECKER_HPP diff --git a/include/utils/Integer.hpp b/include/utils/Integer.hpp new file mode 100644 index 0000000..2e80a74 --- /dev/null +++ b/include/utils/Integer.hpp @@ -0,0 +1,35 @@ +#ifndef INTEGER_HPP +#define INTEGER_HPP + +#define INTEGER_MAX_LENGTH 20 +#define HEX_MAX_LENGTH 18 + +class Integer{ + + private: + + Integer(); + + public: + + static const char hexChars[17]; + + static int getIntegerLength(const long long int arg); + + static long long int parseInteger(const char* str); + + static long long int parseHex(const char* str); + + static char* toString(const long long int arg); + + static int toString(const long long int arg, char* buffer, const unsigned int buffer_size); + + static char* toHexString(const unsigned long long arg); + + static char* toHexString(const unsigned long long int arg, unsigned int format); + + static int toHexString(const unsigned long long int arg, const unsigned int format, char* buffer, const unsigned int bufferSize); + +}; + +#endif // INTEGER_HPP diff --git a/include/utils/LineReader.hpp b/include/utils/LineReader.hpp new file mode 100644 index 0000000..bcab8b3 --- /dev/null +++ b/include/utils/LineReader.hpp @@ -0,0 +1,28 @@ +#ifndef LINEREADER_HPP +#define LINEREADER_HPP + +#include + +class LineReader{ + + private: + + FILE* fileHandle; + + public: + + LineReader(const char* filePath); + + static char* getLine(const char* data, const unsigned int data_length, const unsigned int lineNum, unsigned int withLineBreak); + + static char* getLine(const char* data, const unsigned int data_length, const unsigned int lineNum); + + unsigned char* getLine(unsigned int lineNum, unsigned int withLineBreak); + + unsigned char* getLine(unsigned int lineNum); + + ~LineReader(); + +}; + +#endif diff --git a/include/utils/Obfuscator.hpp b/include/utils/Obfuscator.hpp new file mode 100644 index 0000000..d3a0497 --- /dev/null +++ b/include/utils/Obfuscator.hpp @@ -0,0 +1,19 @@ +#ifndef OBFUSCATOR_HPP +#define OBFUSCATOR_HPP + +class Obfuscator{ + + public: + + static unsigned char* encode(unsigned char* data, unsigned int dataLength, unsigned int* resultLength); + + static unsigned char* decode(unsigned char* data, unsigned int dataLength, unsigned int* resultLength); + + private: + + Obfuscator(); + + +}; + +#endif diff --git a/include/utils/ZLibUtils.hpp b/include/utils/ZLibUtils.hpp new file mode 100644 index 0000000..a711a5c --- /dev/null +++ b/include/utils/ZLibUtils.hpp @@ -0,0 +1,20 @@ +#ifndef ZLIBUTILS_HPP +#define ZLIBUTILS_HPP + +class ZLibUtils{ + + private: + + ZLibUtils(); + + public: + + static unsigned char* compressData(const unsigned char* data, unsigned long dataLength, unsigned long* resultLength); + + static unsigned char* decompressData(const unsigned char* data, unsigned long dataLength, unsigned long* resultLength); + + static int decompressData(const unsigned char* data, unsigned long dataLength, unsigned char* resultBuffer, unsigned long resultBufferSize, unsigned long* resultLength); + +}; + +#endif // ZLIBUTILS_H diff --git a/include/zlib/crc32.h b/include/zlib/crc32.h new file mode 100644 index 0000000..9e0c778 --- /dev/null +++ b/include/zlib/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const z_crc_t FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/include/zlib/deflate.h b/include/zlib/deflate.h new file mode 100644 index 0000000..122ba6a --- /dev/null +++ b/include/zlib/deflate.h @@ -0,0 +1,349 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2016 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "include/zlib/zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + +#define INIT_STATE 42 /* zlib header -> BUSY_STATE */ +#ifdef GZIP +# define GZIP_STATE 57 /* gzip header -> BUSY_STATE | EXTRA_STATE */ +#endif +#define EXTRA_STATE 69 /* gzip extra block -> NAME_STATE */ +#define NAME_STATE 73 /* gzip file name -> COMMENT_STATE */ +#define COMMENT_STATE 91 /* gzip comment -> HCRC_STATE */ +#define HCRC_STATE 103 /* gzip header CRC -> BUSY_STATE */ +#define BUSY_STATE 113 /* deflate -> FINISH_STATE */ +#define FINISH_STATE 666 /* stream complete */ +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + const static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + ulg pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + ulg gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to suppress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + uInt insert; /* bytes at end of window left to insert */ + +#ifdef ZLIB_DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef ZLIB_DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (uch)(length); \ + ush dist = (ush)(distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/include/zlib/gzguts.h b/include/zlib/gzguts.h new file mode 100644 index 0000000..e701306 --- /dev/null +++ b/include/zlib/gzguts.h @@ -0,0 +1,218 @@ +/* gzguts.h -- zlib internal header definitions for gz* operations + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#ifdef _LARGEFILE64_SOURCE +# ifndef _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 +# endif +# ifdef _FILE_OFFSET_BITS +# undef _FILE_OFFSET_BITS +# endif +#endif + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include +#include "include/zlib/zlib.h" +#ifdef STDC +# include +# include +# include +#endif + +#ifndef _POSIX_SOURCE +# define _POSIX_SOURCE +#endif +#include + +#ifdef _WIN32 +# include +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) +# define WIDECHAR +#endif + +#ifdef WINAPI_FAMILY +# define open _open +# define read _read +# define write _write +# define close _close +#endif + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif +#endif + +/* unlike snprintf (which is required in C99), _snprintf does not guarantee + null termination of the result -- however this is only used in gzlib.c where + the result is assured to fit in the space provided */ +#if defined(_MSC_VER) && _MSC_VER < 1900 +# define snprintf _snprintf +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +/* gz* functions always use library allocation functions */ +#ifndef STDC + extern voidp malloc OF((uInt size)); + extern void free OF((voidpf ptr)); +#endif + +/* get errno and strerror definition */ +#if defined UNDER_CE +# include +# define zstrerror() gz_strwinerror((DWORD)GetLastError()) +#else +# ifndef NO_STRERROR +# include +# define zstrerror() strerror(errno) +# else +# define zstrerror() "stdio error (consult errno)" +# endif +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +#endif + +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif + +/* default i/o buffer size -- double this for output when reading (this and + twice this must be able to fit in an unsigned type) */ +#define GZBUFSIZE 8192 + +/* gzip modes, also provide a little integrity check on the passed structure */ +#define GZ_NONE 0 +#define GZ_READ 7247 +#define GZ_WRITE 31153 +#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ + +/* values for gz_state how */ +#define LOOK 0 /* look for a gzip header */ +#define COPY 1 /* copy input directly */ +#define GZIP 2 /* decompress a gzip stream */ + +/* internal gzip file state data structure */ +typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ + /* used for both reading and writing */ + int mode; /* see gzip modes above */ + int fd; /* file descriptor */ + char *path; /* path or fd for error messages */ + unsigned size; /* buffer size, zero if not allocated yet */ + unsigned want; /* requested buffer size, default is GZBUFSIZE */ + unsigned char *in; /* input buffer (double-sized when writing) */ + unsigned char *out; /* output buffer (double-sized when reading) */ + int direct; /* 0 if processing gzip, 1 if transparent */ + /* just for reading */ + int how; /* 0: get header, 1: copy, 2: decompress */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ + /* just for writing */ + int level; /* compression level */ + int strategy; /* compression strategy */ + /* seek request */ + z_off64_t skip; /* amount to skip (already rewound if backwards) */ + int seek; /* true if seek request pending */ + /* error information */ + int err; /* error code */ + char *msg; /* error message */ + /* zlib inflate or deflate stream */ + z_stream strm; /* stream structure in-place (not a pointer) */ +} gz_state; +typedef gz_state FAR *gz_statep; + +/* shared functions */ +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); +#endif + +/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +#ifdef INT_MAX +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +#else +unsigned ZLIB_INTERNAL gz_intmax OF((void)); +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +#endif diff --git a/include/zlib/inffast.h b/include/zlib/inffast.h new file mode 100644 index 0000000..e5c1aa4 --- /dev/null +++ b/include/zlib/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/include/zlib/inffixed.h b/include/zlib/inffixed.h new file mode 100644 index 0000000..d628327 --- /dev/null +++ b/include/zlib/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/include/zlib/inflate.h b/include/zlib/inflate.h new file mode 100644 index 0000000..a46cce6 --- /dev/null +++ b/include/zlib/inflate.h @@ -0,0 +1,125 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD = 16180, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* State maintained between inflate() calls -- approximately 7K bytes, not + including the allocated sliding window, which is up to 32K bytes. */ +struct inflate_state { + z_streamp strm; /* pointer back to this zlib stream */ + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip, + bit 2 true to validate check value */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/include/zlib/inftrees.h b/include/zlib/inftrees.h new file mode 100644 index 0000000..baa53a0 --- /dev/null +++ b/include/zlib/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/include/zlib/trees.h b/include/zlib/trees.h new file mode 100644 index 0000000..d35639d --- /dev/null +++ b/include/zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/include/zlib/zconf.h b/include/zlib/zconf.h new file mode 100644 index 0000000..5e1d68a --- /dev/null +++ b/include/zlib/zconf.h @@ -0,0 +1,534 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/include/zlib/zlib.h b/include/zlib/zlib.h new file mode 100644 index 0000000..f09cdaf --- /dev/null +++ b/include/zlib/zlib.h @@ -0,0 +1,1912 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.11" +#define ZLIB_VERNUM 0x12b0 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 11 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more ouput + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if any input has been consumed in a previous + deflate() call, then the input available so far is compressed with the old + level and strategy using deflate(strm, Z_BLOCK). There are three approaches + for the compression levels 0, 1..3, and 4..9 respectively. The new level + and strategy will take effect at the next call of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will not automatically decode concatenated gzip streams. + inflate() will return Z_STREAM_END at the end of the gzip stream. The state + would need to be reset to continue decoding a subsequent gzip stream. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen)); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Three times that size in buffer space is allocated. A larger buffer + size of, for example, 64K or 128K bytes will noticeably increase the speed + of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. Previously provided + data is flushed before the parameter change. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + gzFile file)); +/* + Read up to nitems items of size size from file to buf, otherwise operating + as gzread() does. This duplicates the interface of stdio's fread(), with + size_t request and return types. If the library defines size_t, then + z_size_t is identical to size_t. If not, then z_size_t is an unsigned + integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevetheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written + file, reseting and retrying on end-of-file, when size is not 1. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + z_size_t nitems, gzFile file)); +/* + gzfwrite() writes nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. + This can be determined using zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as adler32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as crc32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/include/zlib/zutil.h b/include/zlib/zutil.h new file mode 100644 index 0000000..b079ea6 --- /dev/null +++ b/include/zlib/zutil.h @@ -0,0 +1,271 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* since "static" is used to mean two completely different things in C, we + define "local" for the non-static meaning of "static", for readability + (compile with -Dlocal if your debugger can't find static symbols) */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 1 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 2 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#ifdef __370__ +# if __TARGET_LIB__ < 0x20000000 +# define OS_CODE 4 +# elif __TARGET_LIB__ < 0x40000000 +# define OS_CODE 11 +# else +# define OS_CODE 8 +# endif +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 5 +#endif + +#ifdef OS2 +# define OS_CODE 6 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 7 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef __acorn +# define OS_CODE 13 +#endif + +#if defined(WIN32) && !defined(__CYGWIN__) +# define OS_CODE 10 +#endif + +#ifdef _BEOS_ +# define OS_CODE 16 +#endif + +#ifdef __TOS_OS400__ +# define OS_CODE 18 +#endif + +#ifdef __APPLE__ +# define OS_CODE 19 +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 3 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef ZLIB_DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */ diff --git a/libs/libcrypto64.a b/libs/libcrypto64.a new file mode 100644 index 0000000..a997e64 Binary files /dev/null and b/libs/libcrypto64.a differ diff --git a/libs/libssl64.a b/libs/libssl64.a new file mode 100644 index 0000000..0192945 Binary files /dev/null and b/libs/libssl64.a differ diff --git a/native-utilities-dll.pro b/native-utilities-dll.pro new file mode 100644 index 0000000..8ee1301 --- /dev/null +++ b/native-utilities-dll.pro @@ -0,0 +1,576 @@ +QT -= gui + +TEMPLATE = lib +DEFINES += NATIVEUTILITIESDLL_LIBRARY + +CONFIG += c++11 + +CONFIG += dll + +QMAKE_CXXFLAGS_RELEASE += -O2 + +QMAKE_LFLAGS_RELEASE += -static -static-libgcc + +LIBS += -lws2_32 -L$$PWD/libs -lssl64 -lcrypto64 + +# The following define makes your compiler emit warnings if you use +# any Qt feature that has been marked deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +# Default rules for deployment. +unix { + target.path = /usr/lib +} +!isEmpty(target.path): INSTALLS += target + +HEADERS += \ + include/array/GrowableArray.hpp \ + include/array/GrowableBooleanArray.hpp \ + include/array/GrowableByteArray.hpp \ + include/array/GrowableDoubleArray.hpp \ + include/array/GrowableFloatArray.hpp \ + include/array/GrowableIntegerArray.hpp \ + include/array/GrowableLongArray.hpp \ + include/array/GrowableObjectArray.hpp \ + include/array/GrowableShortArray.hpp \ + include/colorspace/SampleUtils.hpp \ + include/drfstream/drfstream.hpp \ + include/encoding/CharTableGBK.hpp \ + include/encoding/CharTableUTF8.hpp \ + include/encoding/EncodingUtils.hpp \ + include/memory/Memory.hpp \ + include/openssl/__DECC_INCLUDE_EPILOGUE.H \ + include/openssl/__DECC_INCLUDE_PROLOGUE.H \ + include/openssl/aes.h \ + include/openssl/asn1.h \ + include/openssl/asn1_mac.h \ + include/openssl/asn1err.h \ + include/openssl/asn1t.h \ + include/openssl/async.h \ + include/openssl/asyncerr.h \ + include/openssl/bio.h \ + include/openssl/bioerr.h \ + include/openssl/blowfish.h \ + include/openssl/bn.h \ + include/openssl/bnerr.h \ + include/openssl/buffer.h \ + include/openssl/buffererr.h \ + include/openssl/camellia.h \ + include/openssl/cast.h \ + include/openssl/cmac.h \ + include/openssl/cms.h \ + include/openssl/cmserr.h \ + include/openssl/comp.h \ + include/openssl/comperr.h \ + include/openssl/conf.h \ + include/openssl/conf_api.h \ + include/openssl/conferr.h \ + include/openssl/crypto.h \ + include/openssl/crypto/arm_arch.h \ + include/openssl/crypto/buildinf.h \ + include/openssl/crypto/internal/__DECC_INCLUDE_EPILOGUE.H \ + include/openssl/crypto/internal/__DECC_INCLUDE_PROLOGUE.H \ + include/openssl/crypto/internal/aria.h \ + include/openssl/crypto/internal/asn1_int.h \ + include/openssl/crypto/internal/async.h \ + include/openssl/crypto/internal/bn_conf.h \ + include/openssl/crypto/internal/bn_dh.h \ + include/openssl/crypto/internal/bn_int.h \ + include/openssl/crypto/internal/bn_srp.h \ + include/openssl/crypto/internal/chacha.h \ + include/openssl/crypto/internal/cryptlib_int.h \ + include/openssl/crypto/internal/ctype.h \ + include/openssl/crypto/internal/dso_conf.h \ + include/openssl/crypto/internal/ec_int.h \ + include/openssl/crypto/internal/engine.h \ + include/openssl/crypto/internal/err_int.h \ + include/openssl/crypto/internal/evp_int.h \ + include/openssl/crypto/internal/lhash.h \ + include/openssl/crypto/internal/md32_common.h \ + include/openssl/crypto/internal/objects.h \ + include/openssl/crypto/internal/poly1305.h \ + include/openssl/crypto/internal/rand_int.h \ + include/openssl/crypto/internal/sha.h \ + include/openssl/crypto/internal/siphash.h \ + include/openssl/crypto/internal/sm2.h \ + include/openssl/crypto/internal/sm2err.h \ + include/openssl/crypto/internal/sm3.h \ + include/openssl/crypto/internal/sm4.h \ + include/openssl/crypto/internal/store.h \ + include/openssl/crypto/internal/store_int.h \ + include/openssl/crypto/internal/x509_int.h \ + include/openssl/crypto/mips_arch.h \ + include/openssl/crypto/ppc_arch.h \ + include/openssl/crypto/s390x_arch.h \ + include/openssl/crypto/sparc_arch.h \ + include/openssl/crypto/vms_rms.h \ + include/openssl/cryptoerr.h \ + include/openssl/ct.h \ + include/openssl/cterr.h \ + include/openssl/des.h \ + include/openssl/dh.h \ + include/openssl/dherr.h \ + include/openssl/dsa.h \ + include/openssl/dsaerr.h \ + include/openssl/dtls1.h \ + include/openssl/e_os2.h \ + include/openssl/ebcdic.h \ + include/openssl/ec.h \ + include/openssl/ecdh.h \ + include/openssl/ecdsa.h \ + include/openssl/ecerr.h \ + include/openssl/engine.h \ + include/openssl/engineerr.h \ + include/openssl/err.h \ + include/openssl/evp.h \ + include/openssl/evperr.h \ + include/openssl/hmac.h \ + include/openssl/idea.h \ + include/openssl/internal/__DECC_INCLUDE_EPILOGUE.H \ + include/openssl/internal/__DECC_INCLUDE_PROLOGUE.H \ + include/openssl/internal/bio.h \ + include/openssl/internal/comp.h \ + include/openssl/internal/conf.h \ + include/openssl/internal/constant_time_locl.h \ + include/openssl/internal/cryptlib.h \ + include/openssl/internal/dane.h \ + include/openssl/internal/dso.h \ + include/openssl/internal/dsoerr.h \ + include/openssl/internal/err.h \ + include/openssl/internal/nelem.h \ + include/openssl/internal/numbers.h \ + include/openssl/internal/o_dir.h \ + include/openssl/internal/o_str.h \ + include/openssl/internal/refcount.h \ + include/openssl/internal/sockets.h \ + include/openssl/internal/sslconf.h \ + include/openssl/internal/thread_once.h \ + include/openssl/internal/tsan_assist.h \ + include/openssl/kdf.h \ + include/openssl/kdferr.h \ + include/openssl/lhash.h \ + include/openssl/md2.h \ + include/openssl/md4.h \ + include/openssl/md5.h \ + include/openssl/mdc2.h \ + include/openssl/modes.h \ + include/openssl/obj_mac.h \ + include/openssl/objects.h \ + include/openssl/objectserr.h \ + include/openssl/ocsp.h \ + include/openssl/ocsperr.h \ + include/openssl/opensslconf.h \ + include/openssl/opensslv.h \ + include/openssl/ossl_typ.h \ + include/openssl/pem.h \ + include/openssl/pem2.h \ + include/openssl/pemerr.h \ + include/openssl/pkcs12.h \ + include/openssl/pkcs12err.h \ + include/openssl/pkcs7.h \ + include/openssl/pkcs7err.h \ + include/openssl/rand.h \ + include/openssl/rand_drbg.h \ + include/openssl/randerr.h \ + include/openssl/rc2.h \ + include/openssl/rc4.h \ + include/openssl/rc5.h \ + include/openssl/ripemd.h \ + include/openssl/rsa.h \ + include/openssl/rsaerr.h \ + include/openssl/safestack.h \ + include/openssl/seed.h \ + include/openssl/sha.h \ + include/openssl/srp.h \ + include/openssl/srtp.h \ + include/openssl/ssl.h \ + include/openssl/ssl2.h \ + include/openssl/ssl3.h \ + include/openssl/sslerr.h \ + include/openssl/stack.h \ + include/openssl/store.h \ + include/openssl/storeerr.h \ + include/openssl/symhacks.h \ + include/openssl/tls1.h \ + include/openssl/ts.h \ + include/openssl/tserr.h \ + include/openssl/txt_db.h \ + include/openssl/ui.h \ + include/openssl/uierr.h \ + include/openssl/whrlpool.h \ + include/openssl/x509.h \ + include/openssl/x509_vfy.h \ + include/openssl/x509err.h \ + include/openssl/x509v3.h \ + include/openssl/x509v3err.h \ + include/png/IDATDecoder.hpp \ + include/png/PNGChunk.hpp \ + include/png/PNGChunkIDAT.hpp \ + include/png/PNGChunkIHDR.hpp \ + include/png/PNGChunkITXT.hpp \ + include/png/PNGChunkPHYS.hpp \ + include/png/PNGChunkPLTE.hpp \ + include/png/PNGChunkTEXT.hpp \ + include/png/PNGChunkTIME.hpp \ + include/png/PNGChunkTRNS.hpp \ + include/png/PNGChunkZTXT.hpp \ + include/png/UnfilterAverage.hpp \ + include/png/UnfilterNone.hpp \ + include/png/UnfilterPaeth.hpp \ + include/png/UnfilterSub.hpp \ + include/png/UnfilterUp.hpp \ + include/raknet/AutopatcherPatchContext.hpp \ + include/raknet/AutopatcherRepositoryInterface.hpp \ + include/raknet/Base64Encoder.hpp \ + include/raknet/BitStream.hpp \ + include/raknet/CCRakNetSlidingWindow.hpp \ + include/raknet/CCRakNetUDT.hpp \ + include/raknet/CheckSum.hpp \ + include/raknet/CloudClient.hpp \ + include/raknet/CloudCommon.hpp \ + include/raknet/CloudServer.hpp \ + include/raknet/CommandParserInterface.hpp \ + include/raknet/ConnectionGraph2.hpp \ + include/raknet/ConsoleServer.hpp \ + include/raknet/DR_SHA1.hpp \ + include/raknet/DS_BPlusTree.hpp \ + include/raknet/DS_BinarySearchTree.hpp \ + include/raknet/DS_BytePool.hpp \ + include/raknet/DS_ByteQueue.hpp \ + include/raknet/DS_Hash.hpp \ + include/raknet/DS_Heap.hpp \ + include/raknet/DS_HuffmanEncodingTree.hpp \ + include/raknet/DS_HuffmanEncodingTreeFactory.hpp \ + include/raknet/DS_HuffmanEncodingTreeNode.hpp \ + include/raknet/DS_LinkedList.hpp \ + include/raknet/DS_List.hpp \ + include/raknet/DS_Map.hpp \ + include/raknet/DS_MemoryPool.hpp \ + include/raknet/DS_Multilist.hpp \ + include/raknet/DS_OrderedChannelHeap.hpp \ + include/raknet/DS_OrderedList.hpp \ + include/raknet/DS_Queue.hpp \ + include/raknet/DS_QueueLinkedList.hpp \ + include/raknet/DS_RangeList.hpp \ + include/raknet/DS_Table.hpp \ + include/raknet/DS_ThreadsafeAllocatingQueue.hpp \ + include/raknet/DS_Tree.hpp \ + include/raknet/DS_WeightedGraph.hpp \ + include/raknet/DataCompressor.hpp \ + include/raknet/DirectoryDeltaTransfer.hpp \ + include/raknet/DynDNS.hpp \ + include/raknet/EmailSender.hpp \ + include/raknet/EmptyHeader.hpp \ + include/raknet/EpochTimeToString.hpp \ + include/raknet/Export.hpp \ + include/raknet/FileList.hpp \ + include/raknet/FileListNodeContext.hpp \ + include/raknet/FileListTransfer.hpp \ + include/raknet/FileListTransferCBInterface.hpp \ + include/raknet/FileOperations.hpp \ + include/raknet/FormatString.hpp \ + include/raknet/FullyConnectedMesh2.hpp \ + include/raknet/GetTime.hpp \ + include/raknet/Getche.hpp \ + include/raknet/Gets.hpp \ + include/raknet/GridSectorizer.hpp \ + include/raknet/HTTPConnection.hpp \ + include/raknet/HTTPConnection2.hpp \ + include/raknet/IncrementalReadInterface.hpp \ + include/raknet/InternalPacket.hpp \ + include/raknet/Itoa.hpp \ + include/raknet/Kbhit.hpp \ + include/raknet/LinuxStrings.hpp \ + include/raknet/LocklessTypes.hpp \ + include/raknet/LogCommandParser.hpp \ + include/raknet/MTUSize.hpp \ + include/raknet/MessageFilter.hpp \ + include/raknet/MessageIdentifiers.hpp \ + include/raknet/NatPunchthroughClient.hpp \ + include/raknet/NatPunchthroughServer.hpp \ + include/raknet/NatTypeDetectionClient.hpp \ + include/raknet/NatTypeDetectionCommon.hpp \ + include/raknet/NatTypeDetectionServer.hpp \ + include/raknet/NativeFeatureIncludes.hpp \ + include/raknet/NativeFeatureIncludesOverrides.hpp \ + include/raknet/NativeTypes.hpp \ + include/raknet/NetworkIDManager.hpp \ + include/raknet/NetworkIDObject.hpp \ + include/raknet/PS3Includes.hpp \ + include/raknet/PS4Includes.hpp \ + include/raknet/PacketConsoleLogger.hpp \ + include/raknet/PacketFileLogger.hpp \ + include/raknet/PacketLogger.hpp \ + include/raknet/PacketOutputWindowLogger.hpp \ + include/raknet/PacketPool.hpp \ + include/raknet/PacketPriority.hpp \ + include/raknet/PacketizedTCP.hpp \ + include/raknet/PluginInterface2.hpp \ + include/raknet/RPC4Plugin.hpp \ + include/raknet/Rackspace.hpp \ + include/raknet/RakAlloca.hpp \ + include/raknet/RakAssert.hpp \ + include/raknet/RakMemoryOverride.hpp \ + include/raknet/RakNetCommandParser.hpp \ + include/raknet/RakNetDefines.hpp \ + include/raknet/RakNetDefinesOverrides.hpp \ + include/raknet/RakNetSmartPtr.hpp \ + include/raknet/RakNetSocket.hpp \ + include/raknet/RakNetSocket2.hpp \ + include/raknet/RakNetStatistics.hpp \ + include/raknet/RakNetTime.hpp \ + include/raknet/RakNetTransport2.hpp \ + include/raknet/RakNetTypes.hpp \ + include/raknet/RakNetVersion.hpp \ + include/raknet/RakPeer.hpp \ + include/raknet/RakPeerInterface.hpp \ + include/raknet/RakSleep.hpp \ + include/raknet/RakString.hpp \ + include/raknet/RakThread.hpp \ + include/raknet/RakWString.hpp \ + include/raknet/Rand.hpp \ + include/raknet/RandSync.hpp \ + include/raknet/ReadyEvent.hpp \ + include/raknet/RefCountedObj.hpp \ + include/raknet/RelayPlugin.hpp \ + include/raknet/ReliabilityLayer.hpp \ + include/raknet/ReplicaEnums.hpp \ + include/raknet/ReplicaManager3.hpp \ + include/raknet/Router2.hpp \ + include/raknet/SecureHandshake.hpp \ + include/raknet/SendToThread.hpp \ + include/raknet/SignaledEvent.hpp \ + include/raknet/SimpleMutex.hpp \ + include/raknet/SimpleTCPServer.hpp \ + include/raknet/SingleProducerConsumer.hpp \ + include/raknet/SocketDefines.hpp \ + include/raknet/SocketIncludes.hpp \ + include/raknet/SocketLayer.hpp \ + include/raknet/StatisticsHistory.hpp \ + include/raknet/StringCompressor.hpp \ + include/raknet/StringTable.hpp \ + include/raknet/SuperFastHash.hpp \ + include/raknet/TCPInterface.hpp \ + include/raknet/TableSerializer.hpp \ + include/raknet/TeamBalancer.hpp \ + include/raknet/TeamManager.hpp \ + include/raknet/TelnetTransport.hpp \ + include/raknet/ThreadPool.hpp \ + include/raknet/ThreadsafePacketLogger.hpp \ + include/raknet/TransportInterface.hpp \ + include/raknet/TwoWayAuthentication.hpp \ + include/raknet/UDPForwarder.hpp \ + include/raknet/UDPProxyClient.hpp \ + include/raknet/UDPProxyCommon.hpp \ + include/raknet/UDPProxyCoordinator.hpp \ + include/raknet/UDPProxyServer.hpp \ + include/raknet/VariableDeltaSerializer.hpp \ + include/raknet/VariableListDeltaTracker.hpp \ + include/raknet/VariadicSQLParser.hpp \ + include/raknet/VitaIncludes.hpp \ + include/raknet/WSAStartupSingleton.hpp \ + include/raknet/WindowsIncludes.hpp \ + include/raknet/XBox360Includes.hpp \ + include/raknet/_FindFirst.hpp \ + include/raknet/gettimeofday.hpp \ + include/utils/BitReader.hpp \ + include/utils/CRC.hpp \ + include/utils/EndianUtils.hpp \ + include/utils/FileReader.hpp \ + include/utils/FileWriter.hpp \ + include/utils/GzipUtils.hpp \ + include/utils/HeaderChecker.hpp \ + include/utils/Integer.hpp \ + include/utils/LineReader.hpp \ + include/utils/Obfuscator.hpp \ + include/utils/ZLibUtils.hpp \ + include/zlib/crc32.h \ + include/zlib/deflate.h \ + include/zlib/gzguts.h \ + include/zlib/inffast.h \ + include/zlib/inffixed.h \ + include/zlib/inflate.h \ + include/zlib/inftrees.h \ + include/zlib/trees.h \ + include/zlib/zconf.h \ + include/zlib/zlib.h \ + include/zlib/zutil.h + +SOURCES += \ + src/array/GrowableArray.cpp \ + src/array/GrowableBooleanArray.cpp \ + src/array/GrowableByteArray.cpp \ + src/array/GrowableDoubleArray.cpp \ + src/array/GrowableFloatArray.cpp \ + src/array/GrowableIntegerArray.cpp \ + src/array/GrowableLongArray.cpp \ + src/array/GrowableObjectArray.cpp \ + src/array/GrowableShortArray.cpp \ + src/colorspace/SampleUtils.cpp \ + src/drfstream/drfstream.cpp \ + src/encoding/CharTableGBK.cpp \ + src/encoding/CharTableUTF8.cpp \ + src/encoding/EncodingUtils.cpp \ + src/main.cpp \ + src/memory/Memory.cpp \ + src/png/IDATDecoder.cpp \ + src/png/PNGChunk.cpp \ + src/png/PNGChunkIDAT.cpp \ + src/png/PNGChunkIHDR.cpp \ + src/png/PNGChunkITXT.cpp \ + src/png/PNGChunkPHYS.cpp \ + src/png/PNGChunkPLTE.cpp \ + src/png/PNGChunkTEXT.cpp \ + src/png/PNGChunkTIME.cpp \ + src/png/PNGChunkTRNS.cpp \ + src/png/PNGChunkZTXT.cpp \ + src/png/UnfilterAverage.cpp \ + src/png/UnfilterNone.cpp \ + src/png/UnfilterPaeth.cpp \ + src/png/UnfilterSub.cpp \ + src/png/UnfilterUp.cpp \ + src/raknet/Base64Encoder.cpp \ + src/raknet/BitStream.cpp \ + src/raknet/CCRakNetSlidingWindow.cpp \ + src/raknet/CCRakNetUDT.cpp \ + src/raknet/CheckSum.cpp \ + src/raknet/CloudClient.cpp \ + src/raknet/CloudCommon.cpp \ + src/raknet/CloudServer.cpp \ + src/raknet/CommandParserInterface.cpp \ + src/raknet/ConnectionGraph2.cpp \ + src/raknet/ConsoleServer.cpp \ + src/raknet/DR_SHA1.cpp \ + src/raknet/DS_BytePool.cpp \ + src/raknet/DS_ByteQueue.cpp \ + src/raknet/DS_HuffmanEncodingTree.cpp \ + src/raknet/DS_Table.cpp \ + src/raknet/DataCompressor.cpp \ + src/raknet/DirectoryDeltaTransfer.cpp \ + src/raknet/DynDNS.cpp \ + src/raknet/EmailSender.cpp \ + src/raknet/EpochTimeToString.cpp \ + src/raknet/FileList.cpp \ + src/raknet/FileListTransfer.cpp \ + src/raknet/FileOperations.cpp \ + src/raknet/FormatString.cpp \ + src/raknet/FullyConnectedMesh2.cpp \ + src/raknet/GetTime.cpp \ + src/raknet/Getche.cpp \ + src/raknet/Gets.cpp \ + src/raknet/GridSectorizer.cpp \ + src/raknet/HTTPConnection.cpp \ + src/raknet/HTTPConnection2.cpp \ + src/raknet/IncrementalReadInterface.cpp \ + src/raknet/Itoa.cpp \ + src/raknet/LinuxStrings.cpp \ + src/raknet/LocklessTypes.cpp \ + src/raknet/LogCommandParser.cpp \ + src/raknet/MessageFilter.cpp \ + src/raknet/NatPunchthroughClient.cpp \ + src/raknet/NatPunchthroughServer.cpp \ + src/raknet/NatTypeDetectionClient.cpp \ + src/raknet/NatTypeDetectionCommon.cpp \ + src/raknet/NatTypeDetectionServer.cpp \ + src/raknet/NetworkIDManager.cpp \ + src/raknet/NetworkIDObject.cpp \ + src/raknet/PS4Includes.cpp \ + src/raknet/PacketConsoleLogger.cpp \ + src/raknet/PacketFileLogger.cpp \ + src/raknet/PacketLogger.cpp \ + src/raknet/PacketOutputWindowLogger.cpp \ + src/raknet/PacketizedTCP.cpp \ + src/raknet/PluginInterface2.cpp \ + src/raknet/RPC4Plugin.cpp \ + src/raknet/Rackspace.cpp \ + src/raknet/RakMemoryOverride.cpp \ + src/raknet/RakNetCommandParser.cpp \ + src/raknet/RakNetSocket.cpp \ + src/raknet/RakNetSocket2.cpp \ + src/raknet/RakNetSocket2_360_720.cpp \ + src/raknet/RakNetSocket2_Berkley.cpp \ + src/raknet/RakNetSocket2_Berkley_NativeClient.cpp \ + src/raknet/RakNetSocket2_NativeClient.cpp \ + src/raknet/RakNetSocket2_PS3_PS4.cpp \ + src/raknet/RakNetSocket2_PS4.cpp \ + src/raknet/RakNetSocket2_Vita.cpp \ + src/raknet/RakNetSocket2_WindowsStore8.cpp \ + src/raknet/RakNetSocket2_Windows_Linux.cpp \ + src/raknet/RakNetSocket2_Windows_Linux_360.cpp \ + src/raknet/RakNetStatistics.cpp \ + src/raknet/RakNetTransport2.cpp \ + src/raknet/RakNetTypes.cpp \ + src/raknet/RakPeer.cpp \ + src/raknet/RakSleep.cpp \ + src/raknet/RakString.cpp \ + src/raknet/RakThread.cpp \ + src/raknet/RakWString.cpp \ + src/raknet/Rand.cpp \ + src/raknet/RandSync.cpp \ + src/raknet/ReadyEvent.cpp \ + src/raknet/RelayPlugin.cpp \ + src/raknet/ReliabilityLayer.cpp \ + src/raknet/ReplicaManager3.cpp \ + src/raknet/Router2.cpp \ + src/raknet/SecureHandshake.cpp \ + src/raknet/SendToThread.cpp \ + src/raknet/SignaledEvent.cpp \ + src/raknet/SimpleMutex.cpp \ + src/raknet/SocketLayer.cpp \ + src/raknet/StatisticsHistory.cpp \ + src/raknet/StringCompressor.cpp \ + src/raknet/StringTable.cpp \ + src/raknet/SuperFastHash.cpp \ + src/raknet/TCPInterface.cpp \ + src/raknet/TableSerializer.cpp \ + src/raknet/TeamBalancer.cpp \ + src/raknet/TeamManager.cpp \ + src/raknet/TelnetTransport.cpp \ + src/raknet/ThreadsafePacketLogger.cpp \ + src/raknet/TwoWayAuthentication.cpp \ + src/raknet/UDPForwarder.cpp \ + src/raknet/UDPProxyClient.cpp \ + src/raknet/UDPProxyCoordinator.cpp \ + src/raknet/UDPProxyServer.cpp \ + src/raknet/VariableDeltaSerializer.cpp \ + src/raknet/VariableListDeltaTracker.cpp \ + src/raknet/VariadicSQLParser.cpp \ + src/raknet/VitaIncludes.cpp \ + src/raknet/WSAStartupSingleton.cpp \ + src/raknet/_FindFirst.cpp \ + src/raknet/gettimeofday.cpp \ + src/utils/BitReader.cpp \ + src/utils/CRC.cpp \ + src/utils/EndianUtils.cpp \ + src/utils/FileReader.cpp \ + src/utils/FileWriter.cpp \ + src/utils/GzipUtils.cpp \ + src/utils/HeaderChecker.cpp \ + src/utils/Integer.cpp \ + src/utils/LineReader.cpp \ + src/utils/Obfuscator.cpp \ + src/utils/ZLibUtils.cpp \ + src/zlib/adler32.c \ + src/zlib/compress.c \ + src/zlib/crc32.c \ + src/zlib/deflate.c \ + src/zlib/gzclose.c \ + src/zlib/gzlib.c \ + src/zlib/gzread.c \ + src/zlib/gzwrite.c \ + src/zlib/inffast.c \ + src/zlib/inflate.c \ + src/zlib/inftrees.c \ + src/zlib/trees.c \ + src/zlib/uncompr.c \ + src/zlib/zutil.c + + + diff --git a/native-utilities-dll.pro.user b/native-utilities-dll.pro.user new file mode 100644 index 0000000..db3e7e5 --- /dev/null +++ b/native-utilities-dll.pro.user @@ -0,0 +1,1102 @@ + + + + + + EnvironmentId + {87fc2a75-2572-46ac-b6f5-60fddbf1d68a} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + true + 0 + 8 + true + 2 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + -fno-delayed-template-parsing + + true + Builtin.Questionable + + true + Builtin.DefaultTidyAndClazy + 2 + + + + true + + + + + ProjectExplorer.Project.Target.0 + + Desktop Qt 5.12.8 MinGW 64bit static + Desktop Qt 5.12.8 MinGW 64bit static + {d8b4bfd4-e397-448a-8107-d84b25a5e8f4} + 1 + 0 + 0 + + true + 0 + D:\UserData\Codes\QTProjects\native-utilities-dll\build-native-utilities-dll-Debug + D:\UserData\Codes\QTProjects\native-utilities-dll\build-native-utilities-dll-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:\UserData\Codes\QTProjects\native-utilities-dll\build-native-utilities-dll-Release + D:\UserData\Codes\QTProjects\native-utilities-dll\build-native-utilities-dll-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + + ProjectExplorer.CustomExecutableRunConfiguration + + + false + + false + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.Target.1 + + Desktop Qt 5.12.8 MinGW 32bit dynamic + Desktop Qt 5.12.8 MinGW 32bit dynamic + {5e2222b5-489c-4fa6-bc9b-4d12c1479aee} + 0 + 0 + 0 + + true + 0 + D:\UserData\Codes\QTProjects\native-utilities-dll\build-native-utilities-dll-Debug + D:\UserData\Codes\QTProjects\native-utilities-dll\build-native-utilities-dll-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Release + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + + ProjectExplorer.CustomExecutableRunConfiguration + + + false + + false + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.Target.2 + + Desktop Qt 5.12.8 MinGW 32bit static + Desktop Qt 5.12.8 MinGW 32bit static + {cb57d89d-c4c6-49ad-8777-a5c31c4a2542} + 0 + 0 + 0 + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Debug + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Release + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + + ProjectExplorer.CustomExecutableRunConfiguration + + + false + + false + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.Target.3 + + Desktop Qt 5.12.8 MinGW 64bit dynamic + Desktop Qt 5.12.8 MinGW 64bit dynamic + {26d0e756-05d8-46b6-8725-6e919c2417bb} + 0 + 0 + 0 + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Debug + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Release + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + D:/UserData/Codes/QTProjects/native-utilities-dll/build-native-utilities-dll-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + + ProjectExplorer.CustomExecutableRunConfiguration + + + false + + false + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.TargetCount + 4 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/native-utilities.pro.user b/native-utilities.pro.user new file mode 100644 index 0000000..1140913 --- /dev/null +++ b/native-utilities.pro.user @@ -0,0 +1,1102 @@ + + + + + + EnvironmentId + {87fc2a75-2572-46ac-b6f5-60fddbf1d68a} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + true + 0 + 8 + true + 2 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + -fno-delayed-template-parsing + + true + Builtin.Questionable + + true + Builtin.DefaultTidyAndClazy + 2 + + + + true + + + + + ProjectExplorer.Project.Target.0 + + Desktop Qt 5.12.8 MinGW 64bit static + Desktop Qt 5.12.8 MinGW 64bit static + {d8b4bfd4-e397-448a-8107-d84b25a5e8f4} + 0 + 0 + 0 + + true + 0 + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Debug + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Release + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:D:/UserData/Codes/QTProjects/native-utilities/native-utilities.pro + D:/UserData/Codes/QTProjects/native-utilities/native-utilities.pro + + false + + false + true + true + false + false + true + + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Debug + + 1 + + + + ProjectExplorer.Project.Target.1 + + Desktop Qt 5.12.8 MinGW 32bit dynamic + Desktop Qt 5.12.8 MinGW 32bit dynamic + {5e2222b5-489c-4fa6-bc9b-4d12c1479aee} + 0 + 0 + 0 + + true + 0 + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Debug + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Release + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:D:/UserData/Codes/QTProjects/native-utilities/native-utilities.pro + D:/UserData/Codes/QTProjects/native-utilities/native-utilities.pro + + false + + false + true + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.Target.2 + + Desktop Qt 5.12.8 MinGW 32bit static + Desktop Qt 5.12.8 MinGW 32bit static + {cb57d89d-c4c6-49ad-8777-a5c31c4a2542} + 0 + 0 + 0 + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Debug + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Release + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + + ProjectExplorer.CustomExecutableRunConfiguration + + + false + + false + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.Target.3 + + Desktop Qt 5.12.8 MinGW 64bit dynamic + Desktop Qt 5.12.8 MinGW 64bit dynamic + {26d0e756-05d8-46b6-8725-6e919c2417bb} + 0 + 0 + 0 + + true + 0 + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Debug + D:\UserData\Codes\QTProjects\native-utilities\build-native-utilities-Debug + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + 2 + 2 + + + true + 2 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Release + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Release + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 2 + + + true + 0 + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + D:/UserData/Codes/QTProjects/native-utilities/build-native-utilities-Profile + + + true + QtProjectManager.QMakeBuildStep + + false + + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + 0 + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:D:/UserData/Codes/QTProjects/native-utilities/native-utilities.pro + D:/UserData/Codes/QTProjects/native-utilities/native-utilities.pro + + false + + false + true + true + false + false + true + + + + 1 + + + + ProjectExplorer.Project.TargetCount + 4 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..510b73b --- /dev/null +++ b/readme.md @@ -0,0 +1,7 @@ +## å½±æ²çºªå¿µé¡¹ç›® + +#### JNI工具库 + +

    一些jni的工具库,包括`png解æž`,`raknet安å“`,`加解密库` 等等

    + +

    安å“项目

    \ No newline at end of file diff --git a/src/array/GrowableArray.cpp b/src/array/GrowableArray.cpp new file mode 100644 index 0000000..c568306 --- /dev/null +++ b/src/array/GrowableArray.cpp @@ -0,0 +1,281 @@ +#include "include/array/GrowableArray.hpp" +#include "include/utils/Integer.hpp" +#include +#include +#include +#include + +const unsigned int GrowableArray::TYPE_BYTE=0x7fffe310; +const unsigned int GrowableArray::TYPE_SHORT=0x7fffe332; +const unsigned int GrowableArray::TYPE_INT=0x7fffe340; +const unsigned int GrowableArray::TYPE_LONG=0x7fffe348; + +const unsigned int GrowableArray::TYPE_VOIDPTR=0x7fffe372; + +const unsigned int GrowableArray::TYPE_BOOLEAN=0x7fffaab0; +const unsigned int GrowableArray::TYPE_FLOAT=0x7fffaab4; +const unsigned int GrowableArray::TYPE_DOUBLE=0x7fffaab8; + +GrowableArray::GrowableArray(unsigned int type, unsigned int initSize){ + + switch(type){ + + case GrowableArray::TYPE_BYTE: + + this->elementSize=sizeof(unsigned char); + + break; + + case GrowableArray::TYPE_SHORT: + + this->elementSize=sizeof(unsigned short); + + break; + + case GrowableArray::TYPE_INT: + + this->elementSize=sizeof(unsigned int); + + break; + + case GrowableArray::TYPE_LONG: + + this->elementSize=sizeof(unsigned long long int); + + break; + + case GrowableArray::TYPE_VOIDPTR: + + this->elementSize=sizeof(void*); + + break; + + case GrowableArray::TYPE_BOOLEAN: + + this->elementSize=sizeof(unsigned int); + + break; + + case GrowableArray::TYPE_FLOAT: + + this->elementSize=sizeof(float); + + break; + + case GrowableArray::TYPE_DOUBLE: + + this->elementSize=sizeof(double); + + break; + + } + + this->arrlen=0; + + this->init_cap=initSize; + + this->arrayCapacity=this->init_cap; + + this->array=new char[this->arrayCapacity*this->elementSize]; + +} + +void GrowableArray::set(unsigned int index, const void* e){ + + this->checkIndex(index); + + memcpy((((unsigned char*)this->array)+(this->elementSize*index)),e,this->elementSize); + +} + +void GrowableArray::copyFrom(const void* data, unsigned int count){ + + return GrowableArray::copyFrom(data,0,count); + +} + +void GrowableArray::copyFrom(const void* data, unsigned int index, unsigned int count){ + + return GrowableArray::copyFrom(data,index,0,count); + +} + +void GrowableArray::copyFrom(const void* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + if(index!=this->arrlen){ + + this->checkIndex(index); + + } + + if(count>(this->arrayCapacity-index)){ + + this->grow(count-(this->arrayCapacity-index)); + + } + + if(count>(this->arrlen-index)){ + + this->arrlen=this->arrlen+(count-(this->arrlen-index)); + + } + + memcpy(((unsigned char*)this->array+(index*this->elementSize)),((unsigned char*)data+(bufferOffset*this->elementSize)),count*this->elementSize); + +} + +void GrowableArray::put(const void* e){ + + if(this->arrlen==this->arrayCapacity){ + + float grow_size=this->arrayCapacity*0.25; + + if(((int)grow_size)==0){ + grow_size++; + } + + this->grow(grow_size); + + } + + memcpy(((unsigned char*)this->array+(this->elementSize*(this->arrlen))),e,this->elementSize); + + this->arrlen++; + +} + +void* GrowableArray::get(unsigned int index){ + + this->checkIndex(index); + + return ((unsigned char*)(this->array))+(index*this->elementSize); + +} + +void GrowableArray::remove(unsigned int index){ + + this->checkIndex(index); + + if(index!=(this->arrlen-1)){ + + memcpy((unsigned char*)this->array+(index*this->elementSize), (unsigned char*)this->array+((index*this->elementSize)+this->elementSize), (this->arrlen*this->elementSize)-this->elementSize); + + } + + this->arrlen--; + + if(this->arrlen<=(this->init_cap)&&this->arrayCapacity>(this->init_cap)){ + + this->decrease(this->arrayCapacity-(this->init_cap)); + + } + +} + +void GrowableArray::gc(){ + + if(this->arrayCapacity==this->arrlen||this->arrlen<=this->init_cap){ + + return; + + } + + int needToFree=this->arrlen>=((this->arrayCapacity)-(this->arrlen)); + + this->decrease(needToFree); + +} + +void* GrowableArray::getArrayData(){ + + return this->array; + +} + +unsigned int GrowableArray::capacity(){ + + return this->arrayCapacity; + +} + +void GrowableArray::grow(unsigned int count){ + + if(count==0){ + + return; + + } + + void* ptr=realloc(this->array, (this->arrayCapacity*this->elementSize)+(count*this->elementSize)); + + if(ptr!=nullptr){ + + this->array=ptr; + + this->arrayCapacity=arrayCapacity+count; + + }else{ + + std::runtime_error error("OutOfMemoryError: No enough memory!"); + + throw error; + + } + +} + +void GrowableArray::decrease(unsigned int count){ + + if((this->arrayCapacity-count)init_cap||count>(this->arrayCapacity-this->arrlen)||count==0){ + + return; + + } + + this->array=realloc(this->array,(this->arrayCapacity*this->elementSize)-(count*this->elementSize)); + + this->arrayCapacity=this->arrayCapacity-count; + +} + +void GrowableArray::checkIndex(unsigned int index){ + + if(index>=this->arrlen){ + + const char* errmsg="ArrayIndexOutOfBoundsException: Index: %s, Size: %s"; + + char* indexStr=Integer::toString(index); + char* arrlenStr=Integer::toString(this->arrlen); + + const int bufferLen=strlen(errmsg)+strlen(indexStr)+strlen(arrlenStr); + + char* errmsg_buffer=new char[bufferLen]; + + memset(errmsg_buffer,0,bufferLen); + + sprintf(errmsg_buffer,errmsg,indexStr,arrlenStr); + + std::runtime_error error(errmsg_buffer); + + free(errmsg_buffer); + + throw error; + + } + +} + +void GrowableArray::clear(){ + + this->arrlen=0; + this->decrease(this->arrayCapacity-(this->init_cap)); + + +} + +GrowableArray::~GrowableArray(){ + + free(this->array); + +} + diff --git a/src/array/GrowableBooleanArray.cpp b/src/array/GrowableBooleanArray.cpp new file mode 100644 index 0000000..5a50910 --- /dev/null +++ b/src/array/GrowableBooleanArray.cpp @@ -0,0 +1,102 @@ +#include "include/array/GrowableBooleanArray.hpp" + +const unsigned int GrowableBooleanArray::minmum_capacity=16; + +GrowableBooleanArray::GrowableBooleanArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_INT, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + + +} + +int* GrowableBooleanArray::getArrayData(){ + + return (int*)this->array->getArrayData(); + +} + +unsigned int GrowableBooleanArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableBooleanArray::put(const int e){ + + unsigned int flag=e?1:0; + + this->array->put(&flag); + + this->arrlen=this->array->length; + +} + +void GrowableBooleanArray::set(unsigned index, const int e){ + + unsigned int flag=e?1:0; + + this->array->set(index,&flag); + +} + +void GrowableBooleanArray::copyFrom(const int* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableBooleanArray::copyFrom(const int* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableBooleanArray::copyFrom(const int* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +int GrowableBooleanArray::get(unsigned int index){ + + return *(int*)(this->array->get(index)); + +} + +void GrowableBooleanArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableBooleanArray::gc(){ + + this->array->gc(); + +} + +void GrowableBooleanArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +GrowableBooleanArray::~GrowableBooleanArray(){ + + delete this->array; + +} diff --git a/src/array/GrowableByteArray.cpp b/src/array/GrowableByteArray.cpp new file mode 100644 index 0000000..80355e9 --- /dev/null +++ b/src/array/GrowableByteArray.cpp @@ -0,0 +1,98 @@ +#include "include/array/GrowableByteArray.hpp" +#include + +const unsigned int GrowableByteArray::minmum_capacity=128; + +GrowableByteArray::GrowableByteArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_BYTE, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + +} + +unsigned char* GrowableByteArray::getArrayData(){ + + return (unsigned char*)this->array->getArrayData(); + +} + +unsigned int GrowableByteArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableByteArray::put(const unsigned char e){ + + this->array->put(&e); + + this->arrlen=this->array->length; + +} + +void GrowableByteArray::set(unsigned index, const unsigned char e){ + + this->array->set(index,&e); + +} + +void GrowableByteArray::copyFrom(const unsigned char* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableByteArray::copyFrom(const unsigned char* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableByteArray::copyFrom(const unsigned char* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +unsigned char GrowableByteArray::get(unsigned int index){ + + return *(unsigned char*)(this->array->get(index)); + +} + +void GrowableByteArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableByteArray::gc(){ + + this->array->gc(); + +} + +void GrowableByteArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +GrowableByteArray::~GrowableByteArray(){ + + delete this->array; + +} diff --git a/src/array/GrowableDoubleArray.cpp b/src/array/GrowableDoubleArray.cpp new file mode 100644 index 0000000..c390962 --- /dev/null +++ b/src/array/GrowableDoubleArray.cpp @@ -0,0 +1,97 @@ +#include "include/array/GrowableDoubleArray.hpp" + +const unsigned int GrowableDoubleArray::minmum_capacity=16; + +GrowableDoubleArray::GrowableDoubleArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_DOUBLE, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + +} + +double* GrowableDoubleArray::getArrayData(){ + + return (double*)this->array->getArrayData(); + +} + +unsigned int GrowableDoubleArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableDoubleArray::put(const double e){ + + this->array->put(&e); + + this->arrlen=this->array->length; + +} + +void GrowableDoubleArray::set(unsigned index, const double e){ + + this->array->set(index,&e); + +} + +void GrowableDoubleArray::copyFrom(const double* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableDoubleArray::copyFrom(const double* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableDoubleArray::copyFrom(const double* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +double GrowableDoubleArray::get(unsigned int index){ + + return *(double*)(this->array->get(index)); + +} + +void GrowableDoubleArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableDoubleArray::gc(){ + + this->array->gc(); + +} + +void GrowableDoubleArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +GrowableDoubleArray::~GrowableDoubleArray(){ + + delete this->array; + +} diff --git a/src/array/GrowableFloatArray.cpp b/src/array/GrowableFloatArray.cpp new file mode 100644 index 0000000..b110996 --- /dev/null +++ b/src/array/GrowableFloatArray.cpp @@ -0,0 +1,97 @@ +#include "include/array/GrowableFloatArray.hpp" + +const unsigned int GrowableFloatArray::minmum_capacity=16; + +GrowableFloatArray::GrowableFloatArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_FLOAT, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + +} + +float* GrowableFloatArray::getArrayData(){ + + return (float*)this->array->getArrayData(); + +} + +unsigned int GrowableFloatArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableFloatArray::put(const float e){ + + this->array->put(&e); + + this->arrlen=this->array->length; + +} + +void GrowableFloatArray::set(unsigned index, const float e){ + + this->array->set(index,&e); + +} + +void GrowableFloatArray::copyFrom(const float* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableFloatArray::copyFrom(const float* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableFloatArray::copyFrom(const float* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +float GrowableFloatArray::get(unsigned int index){ + + return *(float*)(this->array->get(index)); + +} + +void GrowableFloatArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableFloatArray::gc(){ + + this->array->gc(); + +} + +void GrowableFloatArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +GrowableFloatArray::~GrowableFloatArray(){ + + delete this->array; + +} diff --git a/src/array/GrowableIntegerArray.cpp b/src/array/GrowableIntegerArray.cpp new file mode 100644 index 0000000..c383458 --- /dev/null +++ b/src/array/GrowableIntegerArray.cpp @@ -0,0 +1,97 @@ +#include "include/array/GrowableIntegerArray.hpp" + +const unsigned int GrowableIntegerArray::minmum_capacity=16; + +GrowableIntegerArray::GrowableIntegerArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_INT, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + +} + +int* GrowableIntegerArray::getArrayData(){ + + return (int*)this->array->getArrayData(); + +} + +unsigned int GrowableIntegerArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableIntegerArray::put(const int e){ + + this->array->put(&e); + + this->arrlen=this->array->length; + +} + +void GrowableIntegerArray::set(unsigned index, const int e){ + + this->array->set(index,&e); + +} + +void GrowableIntegerArray::copyFrom(const int* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableIntegerArray::copyFrom(const int* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableIntegerArray::copyFrom(const int* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +int GrowableIntegerArray::get(unsigned int index){ + + return *(int*)(this->array->get(index)); + +} + +void GrowableIntegerArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableIntegerArray::gc(){ + + this->array->gc(); + +} + +void GrowableIntegerArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +GrowableIntegerArray::~GrowableIntegerArray(){ + + delete this->array; + +} diff --git a/src/array/GrowableLongArray.cpp b/src/array/GrowableLongArray.cpp new file mode 100644 index 0000000..93562b0 --- /dev/null +++ b/src/array/GrowableLongArray.cpp @@ -0,0 +1,97 @@ +#include "include/array/GrowableLongArray.hpp" + +const unsigned int GrowableLongArray::minmum_capacity=16; + +GrowableLongArray::GrowableLongArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_LONG, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + +} + +long long* GrowableLongArray::getArrayData(){ + + return (long long*)this->array->getArrayData(); + +} + +unsigned int GrowableLongArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableLongArray::put(const long long e){ + + this->array->put(&e); + + this->arrlen=this->array->length; + +} + +void GrowableLongArray::set(unsigned index, const long long e){ + + this->array->set(index,&e); + +} + +void GrowableLongArray::copyFrom(const long long* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableLongArray::copyFrom(const long long* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableLongArray::copyFrom(const long long* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +long long GrowableLongArray::get(unsigned int index){ + + return *(long long*)(this->array->get(index)); + +} + +void GrowableLongArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableLongArray::gc(){ + + this->array->gc(); + +} + +void GrowableLongArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +GrowableLongArray::~GrowableLongArray(){ + + delete this->array; + +} diff --git a/src/array/GrowableObjectArray.cpp b/src/array/GrowableObjectArray.cpp new file mode 100644 index 0000000..de8bdbc --- /dev/null +++ b/src/array/GrowableObjectArray.cpp @@ -0,0 +1,118 @@ +#include "include/array/GrowableObjectArray.hpp" +#include + +const unsigned int GrowableObjectArray::minmum_capacity=16; + +GrowableObjectArray::GrowableObjectArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_VOIDPTR, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + +} + +void* GrowableObjectArray::getArrayData(){ + + return (void*)this->array->getArrayData(); + +} + +unsigned int GrowableObjectArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableObjectArray::put(const void* e){ + + this->array->put(&e); + + this->arrlen=this->array->length; + +} + +void GrowableObjectArray::set(unsigned index, const void* e){ + + this->array->set(index,&e); + +} + +void GrowableObjectArray::copyFrom(const void* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableObjectArray::copyFrom(const void* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableObjectArray::copyFrom(const void* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +void* GrowableObjectArray::get(unsigned int index){ + + void* ptr=nullptr; + + memcpy(&ptr,this->array->get(index),this->array->element_size); + + return ptr; + +} + +void GrowableObjectArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableObjectArray::gc(){ + + this->array->gc(); + +} + +void GrowableObjectArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +void GrowableObjectArray::destroyAllObjectOnDelete(unsigned int flag){ + + this->destroyFlag=flag; + +} + +GrowableObjectArray::~GrowableObjectArray(){ + + if(this->destroyFlag){ + + for(unsigned int i=0;i<(this->array->length);i++){ + + delete (unsigned char*)this->array->get(i); + + } + + } + + delete this->array; + +} diff --git a/src/array/GrowableShortArray.cpp b/src/array/GrowableShortArray.cpp new file mode 100644 index 0000000..b9cc8ee --- /dev/null +++ b/src/array/GrowableShortArray.cpp @@ -0,0 +1,97 @@ +#include "include/array/GrowableShortArray.hpp" + +const unsigned int GrowableShortArray::minmum_capacity=16; + +GrowableShortArray::GrowableShortArray(unsigned int initSize){ + + this->array=new GrowableArray(GrowableArray::TYPE_SHORT, initSize); + + this->elementSize=this->array->element_size; + + this->arrlen=this->array->length; + +} + +short* GrowableShortArray::getArrayData(){ + + return (short*)this->array->getArrayData(); + +} + +unsigned int GrowableShortArray::capacity(){ + + return this->array->capacity(); + +} + +void GrowableShortArray::put(const short e){ + + this->array->put(&e); + + this->arrlen=this->array->length; + +} + +void GrowableShortArray::set(unsigned index, const short e){ + + this->array->set(index,&e); + +} + +void GrowableShortArray::copyFrom(const short* data, unsigned int count){ + + this->array->copyFrom(data,0,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableShortArray::copyFrom(const short* data, unsigned int index, unsigned int count){ + + this->array->copyFrom(data,index,0,count); + + this->arrlen=this->array->length; + +} + +void GrowableShortArray::copyFrom(const short* data, unsigned int index, unsigned int bufferOffset, unsigned int count){ + + this->array->copyFrom(data,index,bufferOffset,count); + + this->arrlen=this->array->length; + +} + +short GrowableShortArray::get(unsigned int index){ + + return *(short*)(this->array->get(index)); + +} + +void GrowableShortArray::remove(unsigned int index){ + + this->array->remove(index); + + this->arrlen=this->array->length; + +} + +void GrowableShortArray::gc(){ + + this->array->gc(); + +} + +void GrowableShortArray::clear(){ + + this->array->clear(); + + this->arrlen=this->array->length; + +} + +GrowableShortArray::~GrowableShortArray(){ + + delete this->array; + +} diff --git a/src/colorspace/SampleUtils.cpp b/src/colorspace/SampleUtils.cpp new file mode 100644 index 0000000..2a0ad2d --- /dev/null +++ b/src/colorspace/SampleUtils.cpp @@ -0,0 +1,39 @@ +#include "include/colorspace/SampleUtils.hpp" +#include "include/utils/EndianUtils.hpp" +#include + +unsigned char SampleUtils::convert1BitTo8Bit(unsigned char color){ + + return color*255; + +} + +unsigned char SampleUtils::convert2BitTo8Bit(unsigned char color){ + + return color*85; + +} + +unsigned char SampleUtils::convert4BitTo8Bit(unsigned char color){ + + return color*17; + +} + +unsigned char SampleUtils::convert16BitTo8Bit(unsigned short color){ + + return (unsigned char)(floor(color/257.0f)+0.5f); + +} + +unsigned int SampleUtils::convertRGBtoBrightness(unsigned int color){ + + if(EndianUtils::isLittleEndian()){ + + color=EndianUtils::reverseBytes((unsigned int)color); + + } + + return (((unsigned char*)(&color))[1]*0.2126)+(((unsigned char*)(&color))[2]*0.7152)+(((unsigned char*)(&color))[3]*0.0722); + +} diff --git a/src/drfstream/drfstream.cpp b/src/drfstream/drfstream.cpp new file mode 100644 index 0000000..84f22b3 --- /dev/null +++ b/src/drfstream/drfstream.cpp @@ -0,0 +1,209 @@ +#include "include/utils/HeaderChecker.hpp" +#include "include/utils/EndianUtils.hpp" +#include "include/utils/ZLibUtils.hpp" +#include "include/utils/Obfuscator.hpp" +#include +#include +#include +#include "include/drfstream/drfstream.hpp" + +#define DRF_VERSION_1 0x7fff0109 +#define DRF_VERSION_LENGTH 4 +#define ZLIB_CMF 0x78 +#define ZLIB_FLG 0xDA +#define MAX_BUFFER_SIZE 65536 + +#define OBFUSCATE_KEY_LENGTH 8 +#define CRC32_LENGTH 4 + +char* encode(const char* data, const unsigned int data_length, unsigned int* resultLength){ + + if(data==nullptr||data_length==0){ + + return nullptr; + + } + + unsigned int result_buf_offset=0; + + unsigned char* result_buf=0; + result_buf=(unsigned char*)realloc(result_buf,HeaderChecker::HEADER_DRF_LENGTH+DRF_VERSION_LENGTH); + + memcpy(result_buf+result_buf_offset,HeaderChecker::HEADER_DRF,HeaderChecker::HEADER_DRF_LENGTH); + + result_buf_offset=result_buf_offset+HeaderChecker::HEADER_DRF_LENGTH; + + const static int DRF_V1=EndianUtils::isLittleEndian()?EndianUtils::reverseBytes((unsigned int)DRF_VERSION_1):DRF_VERSION_1; + + memcpy(result_buf+result_buf_offset,&DRF_V1,DRF_VERSION_LENGTH); + + result_buf_offset=result_buf_offset+DRF_VERSION_LENGTH; + + unsigned int loopCount=(data_length%MAX_BUFFER_SIZE)==0?(data_length/MAX_BUFFER_SIZE):(data_length/MAX_BUFFER_SIZE)+1; + + unsigned int data_cursor=0; + + for(unsigned int i=0;iDRF_VERSION_1){ + + delete unobfuscated_data; + return NULL; + + } + + data_cursor=data_cursor+DRF_VERSION_LENGTH; + + unsigned char* result_buf=NULL; + unsigned int result_buf_offset=0; + + for(;data_cursor +#include + +char* EncodingUtils::convertUTF8toGBK(const char* input){ + + if(input==nullptr||input[0]==0){ + return 0; + } + + unsigned int inputLength=strlen(input); + + GrowableByteArray* result=new GrowableByteArray(); + + for(unsigned int i=0;iput(input[i]); + + i++; + + continue; + + } + + unsigned int targetChar=0; + + memcpy(((char*)(&targetChar))+(sizeof(unsigned int)-byteCount),input+i,byteCount); + + targetChar=EndianUtils::toNativeEndian(targetChar); + + unsigned short GBKChar=0; + + for(unsigned int i3=0;i3put(' '); + + } + + }else{ + + result->copyFrom(((const unsigned char*)&GBKChar),result->length,2); + + } + + i=i+byteCount; + + } + + result->put(0); + + char* resultBuf=new char[result->length]; + + memcpy(resultBuf,result->getArrayData(), result->length); + + delete result; + + return resultBuf; + +} + +char* EncodingUtils::convertGBKtoUTF8(const char* input){ + + //TODO: implement this method + + if(input==nullptr||input[0]==0){ + return 0; + } + + unsigned int inputLength=strlen(input); + + GrowableByteArray* result=new GrowableByteArray(); + + for(unsigned int i=0;iput(input[i]); + + i++; + + continue; + + } + + unsigned short GBKChar=*((unsigned short*)(&input[i])); + + GBKChar=EndianUtils::toNativeEndian(GBKChar); + + unsigned int UTF8Char=0; + + for(unsigned int i=0;icopyFrom((const unsigned char*)" ",result->length,2); + + }else{ + + unsigned int uStartIndex=0; + + for(;((char*)&UTF8Char)[uStartIndex]==0;uStartIndex++); + + unsigned int chr_len=EncodingUtils::getUTF8CharLength(((char*)&UTF8Char)[uStartIndex]); + + result->copyFrom(((const unsigned char*)(&UTF8Char))+uStartIndex,result->length,chr_len); + + } + + i=i+2; + + } + + result->put(0); + + char* resultBuf=new char[result->length]; + + memcpy(resultBuf,result->getArrayData(), result->length); + + delete result; + + return resultBuf; + +} + +unsigned int EncodingUtils::getUTF8TableSize(){ + + return CharTableUTF8::UTF8Table_size; + +} + +char* EncodingUtils::getUTF8TableElement(unsigned int index){ + + if(index>=CharTableUTF8::UTF8Table_size){ + return 0; + } + + char* result=new char[sizeof(unsigned int)+1]; + + result[sizeof(unsigned int)]=0; + + unsigned int targetChar=CharTableUTF8::UTF8Table[index]; + + if(EndianUtils::isLittleEndian()){ + + targetChar=EndianUtils::reverseBytes(targetChar); + + } + + unsigned int uStartIndex=0; + + for(;((char*)&targetChar)[uStartIndex]==0;uStartIndex++); + + memcpy(result,(char*)(&targetChar)+uStartIndex,EncodingUtils::getUTF8CharLength(((char*)(&targetChar)+uStartIndex)[0])); + + return result; + +} + +unsigned int EncodingUtils::getGBKTableSize(){ + + return CharTableGBK::GBKTable_size; + +} + +char* EncodingUtils::getGBKTableElement(unsigned int index){ + + if(index>=CharTableGBK::GBKTable_size){ + return 0; + } + + char* result=new char[sizeof(unsigned short)+1]; + + result[sizeof(unsigned short)]=0; + + unsigned short targetChar=CharTableGBK::GBKTable[index]; + + if(EndianUtils::isLittleEndian()){ + + targetChar=EndianUtils::reverseBytes((unsigned short)targetChar); + + } + + memcpy(result,(char*)(&targetChar),sizeof(unsigned short)); + + return result; +} + +unsigned int EncodingUtils::getUTF8CharLength(char hdr){ + + if(hdr==0){ + + return 0; + + } + + unsigned char utfHeader=((unsigned char)(hdr)); + + if(utfHeader>=0xF0){ + return 4; + }else if(utfHeader>=0xE0){ + return 3; + }else if(utfHeader>=0xC0){ + return 2; + }else if(0==(utfHeader&0x80)){ + return 1; + } + + return 0; + +} + +unsigned int EncodingUtils::getGBKCharLength(char header){ + + if(header==0){ + + return 0; + + } + + unsigned char gbkHeader=(unsigned char)header; + + if(gbkHeader<=0x7E){ + + return sizeof(unsigned char); + + }else{ + + return sizeof(unsigned char)*2; + + } + +} + diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..5081b41 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,20 @@ +#include "include/encoding/EncodingUtils.hpp" +#include "include/utils/BitReader.hpp" +#include "include/array/GrowableObjectArray.hpp" +#include "include/array/GrowableByteArray.hpp" +#include "include/utils/Integer.hpp" +#include "include/drfstream/drfstream.hpp" +#include "include/utils/FileReader.hpp" +#include "include/utils/FileWriter.hpp" +#include "include/utils/GzipUtils.hpp" +#include +#include +#include + +int main(){ + + EncodingUtils::convertUTF8toGBK("测试"); + + return 0; + +} diff --git a/src/memory/Memory.cpp b/src/memory/Memory.cpp new file mode 100644 index 0000000..1292406 --- /dev/null +++ b/src/memory/Memory.cpp @@ -0,0 +1,123 @@ +#include "include/memory/Memory.hpp" + +#ifdef __linux__ + +#include + +void* Memory::allocateMemory(unsigned long size){ + + if(size==0){ + + return nullptr; + + } + + return mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + +} + +void* Memory::allocateExecutableMemory(unsigned long size){ + + if(size==0){ + + return nullptr; + + } + + return mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + +} + +void* Memory::allocateHugePage(unsigned long size){ + + if(size==0){ + + return nullptr; + + } + + return mmap(nullptr, info.size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0); + +} + +int Memory::setPremission(void* page,unsigned long size, unsigned int permission){ + + return mprotect(page, size, permission); + +} + +int Memory::releaseMemory(void* mem, unsigned long size){ + + return munmap(mem, size); + +} + + +#endif + +#ifdef __WIN32__ + +#include + +void* Memory::allocateMemory(unsigned long size){ + + if(size==0){ + + return nullptr; + + } + + return VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + +} + +void* Memory::allocateExecutableMemory(unsigned long size){ + + if(size==0){ + + return nullptr; + + } + + return VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + +} + +void* Memory::allocateHugePage(unsigned long size){ + + if(size==0){ + + return nullptr; + + } + + return VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE); + +} + +int Memory::setPremission(void* page,unsigned long size, unsigned int permission){ + + unsigned long oldProtect=0; + + int failed=VirtualProtect(page, size, permission, &oldProtect); + + if(oldProtect!=0){ + + return oldProtect; + + }else{ + + return failed; + + } + +} + +int Memory::releaseMemory(void* mem, unsigned long size){ + + return VirtualFree(mem, size, MEM_RELEASE); + +} + + +#endif diff --git a/src/png/IDATDecoder.cpp b/src/png/IDATDecoder.cpp new file mode 100644 index 0000000..c960dc0 --- /dev/null +++ b/src/png/IDATDecoder.cpp @@ -0,0 +1,143 @@ +#include "include/png/IDATDecoder.hpp" +#include "include/utils/ZLibUtils.hpp" +#include "include/png/UnfilterNone.hpp" +#include "include/png/UnfilterSub.hpp" +#include "include/png/UnfilterUp.hpp" +#include "include/png/UnfilterAverage.hpp" +#include "include/png/UnfilterPaeth.hpp" +#include +#include + +unsigned char* IDATDecoder::decompressIDATChunks(GrowableObjectArray* chunks, unsigned long* dataSize){ + + if(chunks==nullptr||chunks->length==0||dataSize==0){ + return nullptr; + } + + if(chunks->length==1){ + PNGChunkIDAT* chunk=(PNGChunkIDAT*)chunks->get(0); + return ZLibUtils::decompressData(chunk->getChunkData(),chunk->getChunkLength(),dataSize); + } + + unsigned char* data=nullptr; + unsigned int offset=0; + + for(unsigned int i=0; i<(chunks->length); i++){ + + PNGChunkIDAT* currentChunk=(PNGChunkIDAT*)chunks->get(i); + + data=(unsigned char*)realloc(data,offset+currentChunk->getChunkLength()); + + memcpy(data+offset,currentChunk->getChunkData(),currentChunk->getChunkLength()); + + offset=offset+currentChunk->getChunkLength(); + + } + + unsigned char* result=ZLibUtils::decompressData(data,offset,dataSize); + delete data; + return result; + +} + +unsigned char** IDATDecoder::decodeIDATChunks(GrowableObjectArray* chunks, unsigned long* dataSize, PNGChunkIHDR* info){ + + unsigned long idatSize=0; + + unsigned char* idat=decompressIDATChunks(chunks,&idatSize); + + if(idat==nullptr){ + return nullptr; + } + + unsigned int bitsPerLine=info->getBitsPerPixel()*info->getImageWidth(); + + unsigned int rowSize=(bitsPerLine+7)/8; + + unsigned char** result=new unsigned char*[info->getImageHeight()]; + + unsigned char* dataCursor=idat; + + UnfilterNone* filter0=new UnfilterNone(); + UnfilterSub* filter1=new UnfilterSub(info->getBitsPerPixel()); + UnfilterUp* filter2=new UnfilterUp(); + UnfilterAverage* filter3=new UnfilterAverage(info->getBitsPerPixel()); + UnfilterPaeth* filter4=new UnfilterPaeth(info->getBitsPerPixel()); + + + for(unsigned int i=0;i<(info->getImageHeight());i++){ + + switch(*dataCursor){ + + //None + case 0: + + //printf("%s","Filter Type 0\n"); + //printf("line: %u\n",i); + dataCursor++; + result[i]=filter0->unfilter(dataCursor,rowSize); + dataCursor=dataCursor+rowSize; + + break; + + //Sub + case 1: + + //printf("%s","Filter Type 1\n"); + //printf("line: %u\n",i); + dataCursor++; + result[i]=filter1->unfilter(dataCursor,rowSize); + dataCursor=dataCursor+rowSize; + + break; + + //Up + case 2: + + //printf("%s","Filter Type 2\n"); + //printf("line: %u\n",i); + dataCursor++; + result[i]=filter2->unfilter(i==0?0:result[i-1],dataCursor,rowSize); + dataCursor=dataCursor+rowSize; + + break; + + //Average + case 3: + + //printf("%s","Filter Type 3\n"); + //printf("line: %u\n",i); + dataCursor++; + result[i]=filter3->unfilter(i==0?0:result[i-1],dataCursor,rowSize); + dataCursor=dataCursor+rowSize; + + break; + + //Paeth + case 4: + + //printf("%s","Filter Type 4\n"); + //printf("line: %u\n",i); + dataCursor++; + result[i]=filter4->unfilter(i==0?0:result[i-1],dataCursor,rowSize); + dataCursor=dataCursor+rowSize; + + break; + + } + + } + + delete idat; + + delete filter0; + delete filter1; + delete filter2; + delete filter3; + delete filter4; + + *dataSize=idatSize-(info->getImageHeight()); + + return result; + +} diff --git a/src/png/PNGChunk.cpp b/src/png/PNGChunk.cpp new file mode 100644 index 0000000..a6382d4 --- /dev/null +++ b/src/png/PNGChunk.cpp @@ -0,0 +1,183 @@ +#include "include/png/PNGChunk.hpp" +#include "include/utils/EndianUtils.hpp" +#include "include/utils/CRC.hpp" +#include "include/png/PNGChunkIHDR.hpp" +#include "include/png/PNGChunkPHYS.hpp" +#include "include/png/PNGChunkPLTE.hpp" +#include "include/png/PNGChunkTRNS.hpp" +#include "include/png/PNGChunkTEXT.hpp" +#include "include/png/PNGChunkITXT.hpp" +#include "include/png/PNGChunkZTXT.hpp" +#include "include/png/PNGChunkIDAT.hpp" +#include "include/png/PNGChunkTIME.hpp" + +#include +#include + +const char* PNGChunk::CHUNKTYPE_IHDR="IHDR"; +const char* PNGChunk::CHUNKTYPE_PHYS="pHYs"; +const char* PNGChunk::CHUNKTYPE_TEXT="tEXt"; +const char* PNGChunk::CHUNKTYPE_ZTXT="zTXt"; +const char* PNGChunk::CHUNKTYPE_TRNS="tRNS"; +const char* PNGChunk::CHUNKTYPE_IDAT="IDAT"; +const char* PNGChunk::CHUNKTYPE_PLTE="PLTE"; +const char* PNGChunk::CHUNKTYPE_ITXT="iTXt"; +const char* PNGChunk::CHUNKTYPE_TIME="tIME"; +const char* PNGChunk::CHUNKTYPE_IEND="IEND"; + +unsigned int PNGChunk::chunkTypeToInt(const char* chunkType){ + unsigned int chunkTypeInt=0; + memcpy(&chunkTypeInt,chunkType,4); + return chunkTypeInt; + +} + +GrowableObjectArray* PNGChunk::readChunks(const unsigned char* data, const char* chunkType){ + + unsigned int cursor=0; + + GrowableObjectArray* result=new GrowableObjectArray(); + + while(1){ + + unsigned int chunkLength=0; + memcpy(&chunkLength,data+cursor,4); + cursor=cursor+4; + + chunkLength=EndianUtils::toNativeEndian(chunkLength); + unsigned int tempChunkType=0; + memcpy(&tempChunkType,data+cursor,4); + cursor=cursor+4; + + const unsigned char* chunkData=data+cursor; + cursor=cursor+chunkLength; + + unsigned int crc32=0; + memcpy(&crc32,data+cursor,4); + crc32=EndianUtils::toNativeEndian(crc32); + cursor=cursor+4; + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_IEND)){ + break; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(chunkType)){ + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_IHDR)){ + result->put(new PNGChunkIHDR(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_PHYS)){ + result->put(new PNGChunkPHYS(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_PLTE)){ + result->put(new PNGChunkPLTE(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_TRNS)){ + result->put(new PNGChunkTRNS(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_TEXT)){ + result->put(new PNGChunkTEXT(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_ZTXT)){ + result->put(new PNGChunkZTXT(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_ITXT)){ + result->put(new PNGChunkITXT(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_IDAT)){ + result->put(new PNGChunkIDAT(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + if(tempChunkType==PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_TIME)){ + result->put(new PNGChunkTIME(chunkLength,tempChunkType,chunkData,crc32)); + continue; + } + + //other chunks + result->put(new PNGChunk(chunkLength,tempChunkType,chunkData,crc32)); + continue; + + } + } + + if(result->length==0){ + + delete result; + result=nullptr; + + } + + return result; + +} + +PNGChunk::PNGChunk(unsigned int chunkLength,unsigned chunkTypeInt,const unsigned char* chunkData,unsigned int crc32){ + + this->chunkLength=chunkLength; + this->chunkTypeInt=chunkTypeInt; + + unsigned char* tempChunkData=new unsigned char[this->chunkLength]; + + memcpy(tempChunkData,chunkData,this->chunkLength); + + this->chunkData=tempChunkData; + this->crc32=crc32; + +} + +unsigned int PNGChunk::getChunkLength(){ + + return this->chunkLength; + +} + +const unsigned char* PNGChunk::getChunkData(){ + + return this->chunkData; + +} + +unsigned int PNGChunk::getCRC32(){ + + return this->crc32; + +} + +unsigned int PNGChunk::isCRC32Matched(){ + + CRC* crcUtil=new CRC(); + + unsigned char* temp=new unsigned char[this->chunkLength+4]; + + memcpy(temp,&this->chunkTypeInt,4); + memcpy(temp+4,this->chunkData,this->chunkLength); + + unsigned int crc32=crcUtil->getCRC32(temp,this->chunkLength+4); + + delete crcUtil; + delete temp; + + return crc32==this->crc32; + +} + +PNGChunk::~PNGChunk(){ + + delete this->chunkData; + +} diff --git a/src/png/PNGChunkIDAT.cpp b/src/png/PNGChunkIDAT.cpp new file mode 100644 index 0000000..1fbb04e --- /dev/null +++ b/src/png/PNGChunkIDAT.cpp @@ -0,0 +1,12 @@ +#include "include/png/PNGChunkIDAT.hpp" +#include + +PNGChunkIDAT::PNGChunkIDAT(unsigned int chunkLength,unsigned chunkTypeInt,const unsigned char* chunkData,unsigned int crc32):PNGChunk(chunkLength,chunkTypeInt,chunkData,crc32){ + + //Do not decompress data at here! + //All data must be merged before decompression can be performed. + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_IDAT)){ + std::runtime_error error("PNGChunkTypeMismatchException: Not a IDAT chunk!"); + throw error; + } +} diff --git a/src/png/PNGChunkIHDR.cpp b/src/png/PNGChunkIHDR.cpp new file mode 100644 index 0000000..9f8ca6f --- /dev/null +++ b/src/png/PNGChunkIHDR.cpp @@ -0,0 +1,122 @@ +#include "include/png/PNGChunkIHDR.hpp" +#include "include/utils/EndianUtils.hpp" +#include +#include + +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_GRAYSCALE=0; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_GRAYSCALE_CHANNEL=1; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_TRUECOLOR=2; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_TRUECOLOR_CHANNEL=3; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_INDEXEDCOLOR=3; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_INDEXEDCOLOR_CHANNEL=1; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_ALPHA_GRAYSCALE=4; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_ALPHA_GRAYSCALE_CHANNEL=2; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_ALPHA_TRUECOLOR=6; +const unsigned char PNGChunkIHDR::IMG_COLORTYPE_ALPHA_TRUECOLOR_CHANNEL=4; +const unsigned char PNGChunkIHDR::IMG_COMPRESS_METHOD_DEFAULT=0; +const unsigned char PNGChunkIHDR::IMG_SCAN_METHOD_SCANLINE=0; +const unsigned char PNGChunkIHDR::IMG_SCAN_METHOD_ADAM7=1; + +PNGChunkIHDR::PNGChunkIHDR(unsigned int chunkLength,unsigned int chunkType,const unsigned char* chunkData,unsigned int crc):PNGChunk(chunkLength,chunkType,chunkData,crc){ + + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_IHDR)){ + std::runtime_error error("PNGChunkTypeMismatchException: Not a IHDR chunk!"); + throw error; + } + + unsigned int cursor=0; + + unsigned tempImgWidth=0; + memcpy(&tempImgWidth,this->chunkData,4); + this->imgWidth=EndianUtils::toNativeEndian(tempImgWidth); + cursor=cursor+4; + unsigned tempImgHeight=0; + memcpy(&tempImgHeight,this->chunkData+cursor,4); + this->imgHeight=EndianUtils::toNativeEndian(tempImgHeight); + cursor=cursor+4; + this->imgBitDepth=this->chunkData[cursor]; + cursor++; + this->imgColorType=this->chunkData[cursor]; + cursor++; + this->imgCompressMethod=this->chunkData[cursor]; + cursor++; + this->imgFilterMethod=this->chunkData[cursor]; + cursor++; + this->imgInterlaceMethod=this->chunkData[cursor]; + cursor++; + +} + +unsigned int PNGChunkIHDR::getImageWidth(){ + + return this->imgWidth; + +} + +unsigned int PNGChunkIHDR::getImageHeight(){ + + return this->imgHeight; + +} + +unsigned int PNGChunkIHDR::getImageBitBepth(){ + + return this->imgBitDepth; + +} + +unsigned int PNGChunkIHDR::getImageColorType(){ + + return this->imgColorType; + +} + +unsigned int PNGChunkIHDR::getImageCompressMethod(){ + + return this->imgCompressMethod; + +} + +unsigned int PNGChunkIHDR::getImageFilterMethod(){ + + return this->imgFilterMethod; + +} + +unsigned int PNGChunkIHDR::getImageInterlaceMethod(){ + + return this->imgInterlaceMethod; + +} + +unsigned int PNGChunkIHDR::getCRC32(){ + + return this->crc32; + +} + +unsigned int PNGChunkIHDR::getColorChannelCount(){ + + if(this->imgColorType==IMG_COLORTYPE_GRAYSCALE){ + return IMG_COLORTYPE_GRAYSCALE_CHANNEL; + } + if(this->imgColorType==IMG_COLORTYPE_ALPHA_GRAYSCALE){ + return IMG_COLORTYPE_ALPHA_GRAYSCALE_CHANNEL; + } + if(this->imgColorType==IMG_COLORTYPE_INDEXEDCOLOR){ + return IMG_COLORTYPE_INDEXEDCOLOR_CHANNEL; + } + if(this->imgColorType==IMG_COLORTYPE_TRUECOLOR){ + return IMG_COLORTYPE_TRUECOLOR_CHANNEL; + } + if(this->imgColorType==IMG_COLORTYPE_ALPHA_TRUECOLOR){ + return IMG_COLORTYPE_ALPHA_TRUECOLOR_CHANNEL; + } + return -1; +} + +unsigned int PNGChunkIHDR::getBitsPerPixel(){ + + return this->getColorChannelCount()*this->imgBitDepth; + +} diff --git a/src/png/PNGChunkITXT.cpp b/src/png/PNGChunkITXT.cpp new file mode 100644 index 0000000..bfd1806 --- /dev/null +++ b/src/png/PNGChunkITXT.cpp @@ -0,0 +1,140 @@ +#include "include/png/PNGChunkITXT.hpp" +#include "include/utils/ZLibUtils.hpp" +#include +#include +#include + +PNGChunkITXT::PNGChunkITXT(unsigned int chunkLength,unsigned int chunkType,const unsigned char* chunkData,unsigned int crc32):PNGChunk(chunkLength,chunkType,chunkData,crc32){ + + if(PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_ITXT)!=chunkType){ + + this->keyword=nullptr; + this->label=nullptr; + this->translatedKeyword=nullptr; + this->content=nullptr; + + std::runtime_error error("PNGChunkTypeMismatchException: Not a iTXt chunk!"); + throw error; + + } + + unsigned int cursor=0; + + unsigned int keyWordLength=strlen((const char*)this->chunkData); + + unsigned char* tempKeyword=new unsigned char[keyWordLength+1]; + + memcpy(tempKeyword,this->chunkData,keyWordLength+1); + + cursor=cursor+keyWordLength+1; + + this->keyword=tempKeyword; + + this->compressFlag=this->chunkData[cursor]; + cursor++; + this->compressMethod=this->chunkData[cursor]; + cursor++; + + unsigned int labelLength=strlen((const char*)this->chunkData+cursor); + + unsigned char* tempLabel=new unsigned char[labelLength+1]; + + memcpy(tempLabel,this->chunkData+cursor,labelLength+1); + cursor=cursor+labelLength+1; + + this->label=tempLabel; + + unsigned int translatedKeywordLength=strlen((const char*)(this->chunkData+cursor)); + + unsigned char* tempTranslatedKeyword=new unsigned char[translatedKeywordLength+1]; + + memcpy(tempTranslatedKeyword,this->chunkData+cursor,translatedKeywordLength+1); + + cursor=cursor+translatedKeywordLength+1; + + unsigned int contentDataLength=chunkLength-cursor; + + unsigned char* tempContent=this->compressFlag?new unsigned char[contentDataLength]:new unsigned char[contentDataLength+1]; + + if(this->compressFlag==0){ + + tempContent[contentDataLength]=0; + + } + + memcpy(tempContent,this->chunkData+cursor,contentDataLength); + + if(this->compressFlag){ + + unsigned long resultLength=0; + + unsigned char* tempResult=ZLibUtils::decompressData(tempContent,contentDataLength,&resultLength); + + delete tempContent; + + if(tempResult==nullptr){ + + this->content=nullptr; + + std::runtime_error error("PNGChunkDataException: Unknown stream format!(iTXt)\n"); + throw error; + + } + + tempResult=(unsigned char*)(realloc(tempResult,resultLength+1)); + + tempResult[resultLength]=0; + + this->content=tempResult; + + }else{ + + this->content=tempContent; + + } +} + +unsigned char PNGChunkITXT::isCompressed(){ + + return this->compressFlag; + +} + +unsigned char PNGChunkITXT::getCompressMethod(){ + + return this->compressMethod; + +} + +const unsigned char* PNGChunkITXT::getKeyword(){ + + return this->keyword; + +} + +const unsigned char* PNGChunkITXT::getLabel(){ + + return this->label; + +} + +const unsigned char* PNGChunkITXT::getTranslatedKeyword(){ + + return this->translatedKeyword; + +} + +const unsigned char* PNGChunkITXT::getText(){ + + return this->content; + +} + +PNGChunkITXT::~PNGChunkITXT(){ + + delete keyword; + delete label; + delete translatedKeyword; + delete content; + +} diff --git a/src/png/PNGChunkPHYS.cpp b/src/png/PNGChunkPHYS.cpp new file mode 100644 index 0000000..9f73fbb --- /dev/null +++ b/src/png/PNGChunkPHYS.cpp @@ -0,0 +1,46 @@ +#include "include/png/PNGChunkPHYS.hpp" +#include "include/utils/EndianUtils.hpp" +#include +#include + + +PNGChunkPHYS::PNGChunkPHYS(unsigned int chunkLength,unsigned int chunkType,const unsigned char* chunkData,unsigned int crc):PNGChunk(chunkLength,chunkType,chunkData,crc){ + + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_PHYS)){ + std::runtime_error error("PNGChunkTypeMismatchException: Not a pHYs chunk!"); + throw error; + } + + unsigned int cursor=0; + unsigned int tempPixelsPerUnitX=0; + memcpy(&tempPixelsPerUnitX,this->chunkData+cursor,4); + tempPixelsPerUnitX=EndianUtils::toNativeEndian(tempPixelsPerUnitX); + this->pixelsPerUnitX=tempPixelsPerUnitX; + cursor=cursor+4; + unsigned int tempPixelsPerUnitY=0; + memcpy(&tempPixelsPerUnitY,this->chunkData+cursor,4); + tempPixelsPerUnitY=EndianUtils::toNativeEndian(tempPixelsPerUnitY); + this->pixelsPerUnitY=tempPixelsPerUnitY; + cursor=cursor+4; + this->unitToken=this->chunkData[cursor]; + cursor++; + +} + +unsigned int PNGChunkPHYS::getPixelsPerUnitX(){ + + return this->pixelsPerUnitX; + +} + +unsigned int PNGChunkPHYS::getPixelsPerUnitY(){ + + return this->pixelsPerUnitY; + +} + +unsigned int PNGChunkPHYS::getUnit(){ + + return this->unitToken; + +} diff --git a/src/png/PNGChunkPLTE.cpp b/src/png/PNGChunkPLTE.cpp new file mode 100644 index 0000000..8ebdc8e --- /dev/null +++ b/src/png/PNGChunkPLTE.cpp @@ -0,0 +1,14 @@ +#include "include/png/PNGChunkPLTE.hpp" +#include "include/png/PNGChunk.hpp" +#include + +PNGChunkPLTE::PNGChunkPLTE(unsigned int chunkLength,unsigned chunkTypeInt,const unsigned char* chunkData,unsigned int crc32):PNGChunk(chunkLength,chunkTypeInt,chunkData,crc32){ + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_PLTE)){ + std::runtime_error error("PNGChunkTypeMismatchException: Not a PLTE chunk!"); + throw error; + } + if(this->chunkLength%3!=0){ + std::runtime_error error("PLTE: Bad data length."); + throw error; + } +} diff --git a/src/png/PNGChunkTEXT.cpp b/src/png/PNGChunkTEXT.cpp new file mode 100644 index 0000000..efb2a0e --- /dev/null +++ b/src/png/PNGChunkTEXT.cpp @@ -0,0 +1,61 @@ +#include "include/png/PNGChunkTEXT.hpp" +#include +#include + + +PNGChunkTEXT::PNGChunkTEXT(unsigned int chunkLength,unsigned int chunkType,const unsigned char* chunkData,unsigned int crc):PNGChunk(chunkLength,chunkType,chunkData,crc){ + + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_TEXT)){ + + this->keyword=nullptr; + this->text=nullptr; + + std::runtime_error error("PNGChunkTypeMismatchException: Not a tEXt chunk!"); + throw error; + + } + + unsigned int cursor=0; + + unsigned int keywordLength=strlen((const char*)this->chunkData); + + unsigned char* tempKeyword=new unsigned char[keywordLength+1]; + + memcpy(tempKeyword,this->chunkData,keywordLength+1); + + cursor=cursor+keywordLength+1; + cursor++; + + unsigned int textLength=chunkLength-keywordLength; + + unsigned char* tempText=new unsigned char[textLength+1]; + + memcpy(tempText,this->chunkData+cursor,textLength); + + tempText[textLength]=0; + + cursor=cursor+textLength; + + this->keyword=tempKeyword; + this->text=tempText; + +} + +const unsigned char* PNGChunkTEXT::getKeyword(){ + + return this->keyword; + +} + +const unsigned char* PNGChunkTEXT::getText(){ + + return this->text; + +} + +PNGChunkTEXT::~PNGChunkTEXT(){ + + delete this->keyword; + delete this->text; + +} diff --git a/src/png/PNGChunkTIME.cpp b/src/png/PNGChunkTIME.cpp new file mode 100644 index 0000000..e875dd8 --- /dev/null +++ b/src/png/PNGChunkTIME.cpp @@ -0,0 +1,144 @@ +#include "include/png/PNGChunkTIME.hpp" +#include "include/utils/EndianUtils.hpp" +#include "include/array/GrowableByteArray.hpp" +#include "include/utils/Integer.hpp" +#include +#include +#include + +PNGChunkTIME::PNGChunkTIME(unsigned int chunkLength,unsigned chunkTypeInt,const unsigned char* chunkData,unsigned int crc32) : PNGChunk(chunkLength,chunkTypeInt,chunkData,crc32){ + + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_TIME)){ + + this->timeString=nullptr; + + std::runtime_error error("PNGChunkTypeMismatchException: Not a tIME chunk!"); + throw error; + + } + + unsigned int cursor=0; + unsigned short tempYear=0; + + memcpy(&tempYear,this->chunkData,2); + + this->year=EndianUtils::toNativeEndian(tempYear); + + cursor=cursor+1; + + this->month=this->chunkData[cursor]; + cursor++; + + this->day=this->chunkData[cursor]; + cursor++; + + this->hour=this->chunkData[cursor]; + cursor++; + + this->minute=this->chunkData[cursor]; + cursor++; + + this->seconds=this->chunkData[cursor]; + cursor++; + + GrowableByteArray* array=new GrowableByteArray(); + + char* num_str=Integer::toString(this->year); + + array->copyFrom((unsigned char*)num_str, array->length, strlen(num_str)); + + delete num_str; + + num_str=Integer::toString(this->month); + + array->put('-'); + array->copyFrom((unsigned char*)num_str, array->length, strlen(num_str)); + + delete num_str; + + num_str=Integer::toString(this->day); + + array->put('-'); + array->copyFrom((unsigned char*)num_str, array->length, strlen(num_str)); + + delete num_str; + + array->put(' '); + + num_str=Integer::toString(this->hour); + + array->copyFrom((unsigned char*)num_str, array->length, strlen(num_str)); + + delete num_str; + + num_str=Integer::toString(this->minute); + + array->put(':'); + array->copyFrom((unsigned char*)num_str, array->length, strlen(num_str)); + + delete num_str; + + num_str=Integer::toString(this->seconds); + + array->put(':'); + array->copyFrom((unsigned char*)num_str, array->length, strlen(num_str)); + + delete num_str; + + array->put(0); + + unsigned char* timeStrBuf=new unsigned char[array->length]; + + memcpy(timeStrBuf, array->getArrayData(), array->length); + + this->timeString=timeStrBuf; + + delete array; + +} + +unsigned short PNGChunkTIME::getYear(){ + + return this->year; +} + +unsigned char PNGChunkTIME::getMonth(){ + + return this->month; + +} + +unsigned char PNGChunkTIME::getDay(){ + + return this->day; + +} + +unsigned char PNGChunkTIME::getHour(){ + + return this->hour; + +} + +unsigned char PNGChunkTIME::getMinute(){ + + return this->minute; + +} + +unsigned char PNGChunkTIME::getSecond(){ + + return this->seconds; + +} + +const unsigned char* PNGChunkTIME::getTimeString(){ + + return this->timeString; +} + +PNGChunkTIME::~PNGChunkTIME(){ + + delete timeString; + +} diff --git a/src/png/PNGChunkTRNS.cpp b/src/png/PNGChunkTRNS.cpp new file mode 100644 index 0000000..04002cf --- /dev/null +++ b/src/png/PNGChunkTRNS.cpp @@ -0,0 +1,10 @@ +#include "include/png/PNGChunkTRNS.hpp" +#include "include/png/PNGChunk.hpp" +#include + +PNGChunkTRNS::PNGChunkTRNS(unsigned int chunkLength,unsigned chunkTypeInt,const unsigned char* chunkData,unsigned int crc32):PNGChunk(chunkLength,chunkTypeInt,chunkData,crc32){ + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_TRNS)){ + std::runtime_error error("PNGChunkTypeMismatchException: Not a tRNS chunk!"); + throw error; + } +} diff --git a/src/png/PNGChunkZTXT.cpp b/src/png/PNGChunkZTXT.cpp new file mode 100644 index 0000000..249246a --- /dev/null +++ b/src/png/PNGChunkZTXT.cpp @@ -0,0 +1,84 @@ +#include "include/png/PNGChunkZTXT.hpp" +#include "include/utils/ZLibUtils.hpp" +#include +#include +#include + +PNGChunkZTXT::PNGChunkZTXT(unsigned int chunkLength,unsigned int chunkType,const unsigned char* chunkData,unsigned int crc32) : PNGChunk(chunkLength,chunkType,chunkData,crc32){ + + if(this->chunkTypeInt!=PNGChunk::chunkTypeToInt(PNGChunk::CHUNKTYPE_ZTXT)){ + + this->keyword=nullptr; + this->content=nullptr; + + std::runtime_error error("PNGChunkTypeMismatchException: Not a zTXt chunk!"); + throw error; + + } + + unsigned int cursor=0; + + unsigned int keywordLength=strlen((const char*)this->chunkData); + + unsigned char* tempKeyword=new unsigned char[strlen((const char*)this->chunkData)+1]; + + memcpy(tempKeyword,this->chunkData,keywordLength+1); + cursor=cursor+keywordLength+1; + + this->keyword=tempKeyword; + + unsigned char tempCompressMethodFlag=this->chunkData[cursor]; + + if(tempCompressMethodFlag!=0){ + + this->content=nullptr; + + std::runtime_error error("PNGChunkDataException: Unknown stream format!(zTXt: Bad compression method)"); + throw error; + + } + + cursor++; + + unsigned char* tempContent=new unsigned char[chunkLength-cursor]; + + memcpy(tempContent,this->chunkData+cursor,chunkLength-cursor); + + unsigned long resultlength=0; + + unsigned char* tempResult=ZLibUtils::decompressData(tempContent,chunkLength-cursor,&resultlength); + + delete tempContent; + + if(tempResult==0){ + + this->content=nullptr; + + std::runtime_error error("PNGChunkDataException: Unknown stream format!(zTXt: zTxt_Content)"); + throw error; + + } + + tempResult=(unsigned char*)(realloc(tempResult,resultlength+1)); + + tempResult[resultlength]=0; + + this->content=tempResult; + +} + +const unsigned char* PNGChunkZTXT::getKeyword(){ + return this->keyword; +} + +const unsigned char* PNGChunkZTXT::getText(){ + return this->content; +} + + +PNGChunkZTXT::~PNGChunkZTXT(){ + + delete this->keyword; + delete this->content; + +} diff --git a/src/png/UnfilterAverage.cpp b/src/png/UnfilterAverage.cpp new file mode 100644 index 0000000..411c1ad --- /dev/null +++ b/src/png/UnfilterAverage.cpp @@ -0,0 +1,38 @@ +#include "include/png/UnfilterAverage.hpp" +#include +#include + +UnfilterAverage::UnfilterAverage(unsigned int bitsPerPixel){ + + this->bytesPerPixel=(bitsPerPixel+7)/8; + +} + +unsigned char* UnfilterAverage::unfilter(unsigned char* upperLine,unsigned char* currentLine,unsigned int dataLength){ + + if(currentLine==nullptr||dataLength==0||this->bytesPerPixel==0){ + return nullptr; + } + + unsigned char* result=new unsigned char[dataLength]; + + for(unsigned int i=0;ibytesPerPixel); + + if(flag>=0){ + raw = result[flag]; + } + if(upperLine != nullptr){ + prior = upperLine[i]; + } + + unsigned int average = floor((raw+prior) / 2.0f); + result[i] = currentLine[i] + average; + + } + return result; +} diff --git a/src/png/UnfilterNone.cpp b/src/png/UnfilterNone.cpp new file mode 100644 index 0000000..25c8bf9 --- /dev/null +++ b/src/png/UnfilterNone.cpp @@ -0,0 +1,17 @@ +#include "include/png/UnfilterNone.hpp" +#include + + +unsigned char* UnfilterNone::unfilter(unsigned char* currentLine, unsigned int dataLength){ + + if(currentLine==0||dataLength==0){ + return 0; + } + + unsigned char* result=new unsigned char[dataLength]; + + memcpy(result,currentLine,dataLength); + + return result; + +} diff --git a/src/png/UnfilterPaeth.cpp b/src/png/UnfilterPaeth.cpp new file mode 100644 index 0000000..59d6967 --- /dev/null +++ b/src/png/UnfilterPaeth.cpp @@ -0,0 +1,63 @@ +#include "include/png/UnfilterPaeth.hpp" +#include +#include + +UnfilterPaeth::UnfilterPaeth(unsigned int bitsPerPixel){ + + this->bytesPerPixel=(bitsPerPixel+7)/8; + +} + +unsigned int paethPredictor(int a, int b, int c){ + + int p = a + b - c; + int pa = abs(p - a); + int pb = abs(p - b); + int pc = abs(p - c); + + if ((pa <= pb) && (pa <= pc)) { + return a; + } else if (pb <= pc) { + return b; + } else { + return c; + } + + +} + +unsigned char* UnfilterPaeth::unfilter(unsigned char* upperLine, unsigned char* currentLine, unsigned int dataLength){ + + if(currentLine==0||dataLength==0||this->bytesPerPixel==0){ + return 0; + } + + unsigned char* result=new unsigned char[dataLength]; + + for(unsigned int i=0;ibytesPerPixel); + + if(flag>=0){ + left=result[flag]; + } + if(upperLine!=0){ + above=upperLine[i]; + } + if(upperLine!=0 && flag>=0){ + upperLeft=upperLine[flag]; + } + + unsigned int paethPredictor_val = paethPredictor(left,above,upperLeft); + + result[i]=currentLine[i]+paethPredictor_val; + + } + + return result; + +} diff --git a/src/png/UnfilterSub.cpp b/src/png/UnfilterSub.cpp new file mode 100644 index 0000000..ad73156 --- /dev/null +++ b/src/png/UnfilterSub.cpp @@ -0,0 +1,27 @@ +#include "include/png/UnfilterSub.hpp" +#include + +UnfilterSub::UnfilterSub(unsigned int bitsPerPixel){ + + this->bytesPerPixel=(bitsPerPixel+7)/8; + +} + +unsigned char* UnfilterSub::unfilter(const unsigned char* currentLine,unsigned int dataLength){ + + if(currentLine==0||dataLength==0||this->bytesPerPixel==0){ + return 0; + } + + unsigned char* result=new unsigned char[dataLength]; + + for(unsigned int i=0;ibytesPerPixel); + if(flag>=0){ + result[i]=(currentLine[i]+result[flag]); + }else{ + result[i]=currentLine[i]; + } + } + return result; +} diff --git a/src/png/UnfilterUp.cpp b/src/png/UnfilterUp.cpp new file mode 100644 index 0000000..50a3edc --- /dev/null +++ b/src/png/UnfilterUp.cpp @@ -0,0 +1,23 @@ +#include "include/png/UnfilterUp.hpp" +#include + +unsigned char* UnfilterUp::unfilter(unsigned char* upperLine,unsigned char* currentLine,unsigned int dataLength){ + + if(currentLine==0||dataLength==0){ + return 0; + } + + unsigned char* result=new unsigned char[dataLength]; + + if(upperLine==0){ + memcpy(result,currentLine,dataLength); + return result; + } + + for(unsigned int i=0;i> 2]; + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // Remaining 2 bits from first byte, placed in position, and 4 high bits from the second byte, masked to ignore bits 7,8 + outputData[outputOffset++]=base64Map[((inputData[j*3+0] << 4) | (inputData[j*3+1] >> 4)) & 63]; + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // 4 low bits from the second byte and the two high bits from the third byte, masked to ignore bits 7,8 + outputData[outputOffset++]=base64Map[((inputData[j*3+1] << 2) | (inputData[j*3+2] >> 6)) & 63]; // Third 6 bits + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // Last 6 bits from the third byte, masked to ignore bits 7,8 + outputData[outputOffset++]=base64Map[inputData[j*3+2] & 63]; + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + } + + if (dataLength % 3==1) + { + // One input byte remaining + outputData[outputOffset++]=base64Map[inputData[j*3+0] >> 2]; + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // Remaining 2 bits from first byte, placed in position, and 4 high bits from the second byte, masked to ignore bits 7,8 + outputData[outputOffset++]=base64Map[((inputData[j*3+0] << 4) | (inputData[j*3+1] >> 4)) & 63]; + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // Pad with two equals + outputData[outputOffset++]='='; + outputData[outputOffset++]='='; + } + else if (dataLength % 3==2) + { + // Two input bytes remaining + + // 6 leftmost bits from first byte, shifted to bits 7,8 are 0 + outputData[outputOffset++]=base64Map[inputData[j*3+0] >> 2]; + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // Remaining 2 bits from first byte, placed in position, and 4 high bits from the second byte, masked to ignore bits 7,8 + outputData[outputOffset++]=base64Map[((inputData[j*3+0] << 4) | (inputData[j*3+1] >> 4)) & 63]; + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // 4 low bits from the second byte, followed by 00 + outputData[outputOffset++]=base64Map[(inputData[j*3+1] << 2) & 63]; // Third 6 bits + if ((++charCount % 76)==0) {outputData[outputOffset++]='\r'; outputData[outputOffset++]='\n'; charCount=0;} + + // Pad with one equal + outputData[outputOffset++]='='; + //outputData[outputOffset++]='='; + } + + // Append \r\n + outputData[outputOffset++]='\r'; + outputData[outputOffset++]='\n'; + outputData[outputOffset]=0; + + return outputOffset; +} + +int Base64Encoding(const unsigned char *inputData, int dataLength, char **outputData) +{ + *outputData = (char*) rakMalloc_Ex(dataLength * 2 + 6, _FILE_AND_LINE_); + return Base64Encoding(inputData, dataLength, *outputData); +} diff --git a/src/raknet/BitStream.cpp b/src/raknet/BitStream.cpp new file mode 100644 index 0000000..071e54c --- /dev/null +++ b/src/raknet/BitStream.cpp @@ -0,0 +1,1182 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + + +#if defined(_MSC_VER) && _MSC_VER < 1299 // VC6 doesn't support template specialization +#include "include/raknet/BitStream_NoTemplate.cpp" +#else + +#include "include/raknet/BitStream.hpp" +#include +#include +#include + +#include "include/raknet/SocketIncludes.hpp" +#include "include/raknet/RakNetDefines.hpp" + + + +#if defined(_WIN32) +#include "include/raknet/WindowsIncludes.hpp" +#include +#include +#include + + + + +#else +#include +#include +#if defined(ANDROID) +#include +#else +#include +#endif +#include +#endif + +// MSWin uses _copysign, others use copysign... +#ifndef _WIN32 +#define _copysign copysign +#endif + +using namespace RakNet; + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +STATIC_FACTORY_DEFINITIONS(BitStream,BitStream) + +BitStream::BitStream() +{ + numberOfBitsUsed = 0; + //numberOfBitsAllocated = 32 * 8; + numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE * 8; + readOffset = 0; + //data = ( unsigned char* ) rakMalloc_Ex( 32, _FILE_AND_LINE_ ); + data = ( unsigned char* ) stackData; + +#ifdef _DEBUG + // RakAssert( data ); +#endif + //memset(data, 0, 32); + copyData = true; +} + +BitStream::BitStream( const unsigned int initialBytesToAllocate ) +{ + numberOfBitsUsed = 0; + readOffset = 0; + if (initialBytesToAllocate <= BITSTREAM_STACK_ALLOCATION_SIZE) + { + data = ( unsigned char* ) stackData; + numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE * 8; + } + else + { + data = ( unsigned char* ) rakMalloc_Ex( (size_t) initialBytesToAllocate, _FILE_AND_LINE_ ); + numberOfBitsAllocated = initialBytesToAllocate << 3; + } +#ifdef _DEBUG + RakAssert( data ); +#endif + // memset(data, 0, initialBytesToAllocate); + copyData = true; +} + +BitStream::BitStream( unsigned char* _data, const unsigned int lengthInBytes, bool _copyData ) +{ + numberOfBitsUsed = lengthInBytes << 3; + readOffset = 0; + copyData = _copyData; + numberOfBitsAllocated = lengthInBytes << 3; + + if ( copyData ) + { + if ( lengthInBytes > 0 ) + { + if (lengthInBytes < BITSTREAM_STACK_ALLOCATION_SIZE) + { + data = ( unsigned char* ) stackData; + numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE << 3; + } + else + { + data = ( unsigned char* ) rakMalloc_Ex( (size_t) lengthInBytes, _FILE_AND_LINE_ ); + } +#ifdef _DEBUG + RakAssert( data ); +#endif + memcpy( data, _data, (size_t) lengthInBytes ); + } + else + data = 0; + } + else + data = ( unsigned char* ) _data; +} + +// Use this if you pass a pointer copy to the constructor (_copyData==false) and want to overallocate to prevent reallocation +void BitStream::SetNumberOfBitsAllocated( const BitSize_t lengthInBits ) +{ +#ifdef _DEBUG + RakAssert( lengthInBits >= ( BitSize_t ) numberOfBitsAllocated ); +#endif + numberOfBitsAllocated = lengthInBits; +} + +BitStream::~BitStream() +{ + if ( copyData && numberOfBitsAllocated > (BITSTREAM_STACK_ALLOCATION_SIZE << 3)) + rakFree_Ex( data , _FILE_AND_LINE_ ); // Use realloc and free so we are more efficient than delete and new for resizing +} + +void BitStream::Reset( void ) +{ + // Note: Do NOT reallocate memory because BitStream is used + // in places to serialize/deserialize a buffer. Reallocation + // is a dangerous operation (may result in leaks). + + if ( numberOfBitsUsed > 0 ) + { + // memset(data, 0, BITS_TO_BYTES(numberOfBitsUsed)); + } + + // Don't free memory here for speed efficiency + //free(data); // Use realloc and free so we are more efficient than delete and new for resizing + numberOfBitsUsed = 0; + + //numberOfBitsAllocated=8; + readOffset = 0; + + //data=(unsigned char*)rakMalloc_Ex(1, _FILE_AND_LINE_); + // if (numberOfBitsAllocated>0) + // memset(data, 0, BITS_TO_BYTES(numberOfBitsAllocated)); +} + +// Write an array or casted stream +void BitStream::Write( const char* inputByteArray, const unsigned int numberOfBytes ) +{ + if (numberOfBytes==0) + return; + + // Optimization: + if ((numberOfBitsUsed & 7) == 0) + { + AddBitsAndReallocate( BYTES_TO_BITS(numberOfBytes) ); + memcpy(data+BITS_TO_BYTES(numberOfBitsUsed), inputByteArray, (size_t) numberOfBytes); + numberOfBitsUsed+=BYTES_TO_BITS(numberOfBytes); + } + else + { + WriteBits( ( unsigned char* ) inputByteArray, numberOfBytes * 8, true ); + } + +} +void BitStream::Write( BitStream *bitStream) +{ + Write(bitStream, bitStream->GetNumberOfBitsUsed()-bitStream->GetReadOffset()); +} +void BitStream::Write( BitStream *bitStream, BitSize_t numberOfBits ) +{ + AddBitsAndReallocate( numberOfBits ); + BitSize_t numberOfBitsMod8; + + if ((bitStream->GetReadOffset()&7)==0 && (numberOfBitsUsed&7)==0) + { + int readOffsetBytes=bitStream->GetReadOffset()/8; + int numBytes=numberOfBits/8; + memcpy(data + (numberOfBitsUsed >> 3), bitStream->GetData()+readOffsetBytes, numBytes); + numberOfBits-=BYTES_TO_BITS(numBytes); + bitStream->SetReadOffset(BYTES_TO_BITS(numBytes+readOffsetBytes)); + numberOfBitsUsed+=BYTES_TO_BITS(numBytes); + } + + while (numberOfBits-->0 && bitStream->readOffset + 1 <= bitStream->numberOfBitsUsed) + { + numberOfBitsMod8 = numberOfBitsUsed & 7; + if ( numberOfBitsMod8 == 0 ) + { + // New byte + if (bitStream->data[ bitStream->readOffset >> 3 ] & ( 0x80 >> ( bitStream->readOffset & 7 ) ) ) + { + // Write 1 + data[ numberOfBitsUsed >> 3 ] = 0x80; + } + else + { + // Write 0 + data[ numberOfBitsUsed >> 3 ] = 0; + } + + } + else + { + // Existing byte + if (bitStream->data[ bitStream->readOffset >> 3 ] & ( 0x80 >> ( bitStream->readOffset & 7 ) ) ) + data[ numberOfBitsUsed >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1 + // else 0, do nothing + } + + bitStream->readOffset++; + numberOfBitsUsed++; + } +} +void BitStream::Write( BitStream &bitStream, BitSize_t numberOfBits ) +{ + Write(&bitStream, numberOfBits); +} +void BitStream::Write( BitStream &bitStream ) +{ + Write(&bitStream); +} +bool BitStream::Read( BitStream *bitStream, BitSize_t numberOfBits ) +{ + if (GetNumberOfUnreadBits() < numberOfBits) + return false; + bitStream->Write(this, numberOfBits); + return true; +} +bool BitStream::Read( BitStream *bitStream ) +{ + bitStream->Write(this); + return true; +} +bool BitStream::Read( BitStream &bitStream, BitSize_t numberOfBits ) +{ + if (GetNumberOfUnreadBits() < numberOfBits) + return false; + bitStream.Write(this, numberOfBits); + return true; +} +bool BitStream::Read( BitStream &bitStream ) +{ + bitStream.Write(this); + return true; +} + +// Read an array or casted stream +bool BitStream::Read( char* outByteArray, const unsigned int numberOfBytes ) +{ + // Optimization: + if ((readOffset & 7) == 0) + { + if ( readOffset + ( numberOfBytes << 3 ) > numberOfBitsUsed ) + return false; + + // Write the data + memcpy( outByteArray, data + ( readOffset >> 3 ), (size_t) numberOfBytes ); + + readOffset += numberOfBytes << 3; + return true; + } + else + { + return ReadBits( ( unsigned char* ) outByteArray, numberOfBytes * 8 ); + } +} + +// Sets the read pointer back to the beginning of your data. +void BitStream::ResetReadPointer( void ) +{ + readOffset = 0; +} + +// Sets the write pointer back to the beginning of your data. +void BitStream::ResetWritePointer( void ) +{ + numberOfBitsUsed = 0; +} + +// Write a 0 +void BitStream::Write0( void ) +{ + AddBitsAndReallocate( 1 ); + + // New bytes need to be zeroed + if ( ( numberOfBitsUsed & 7 ) == 0 ) + data[ numberOfBitsUsed >> 3 ] = 0; + + numberOfBitsUsed++; +} + +// Write a 1 +void BitStream::Write1( void ) +{ + AddBitsAndReallocate( 1 ); + + BitSize_t numberOfBitsMod8 = numberOfBitsUsed & 7; + + if ( numberOfBitsMod8 == 0 ) + data[ numberOfBitsUsed >> 3 ] = 0x80; + else + data[ numberOfBitsUsed >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1 + + numberOfBitsUsed++; +} + +// Returns true if the next data read is a 1, false if it is a 0 +bool BitStream::ReadBit( void ) +{ + bool result = ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) !=0; + readOffset++; + return result; +} + +// Align the bitstream to the byte boundary and then write the specified number of bits. +// This is faster than WriteBits but wastes the bits to do the alignment and requires you to call +// SetReadToByteAlignment at the corresponding read position +void BitStream::WriteAlignedBytes( const unsigned char* inByteArray, const unsigned int numberOfBytesToWrite ) +{ + AlignWriteToByteBoundary(); + Write((const char*) inByteArray, numberOfBytesToWrite); +} +void BitStream::EndianSwapBytes( int byteOffset, int length ) +{ + if (DoEndianSwap()) + { + ReverseBytesInPlace(data+byteOffset, length); + } +} +/// Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite +void BitStream::WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite ) +{ + if (inByteArray==0 || inputLength==0) + { + WriteCompressed((unsigned int)0); + return; + } + WriteCompressed(inputLength); + WriteAlignedBytes((const unsigned char*) inByteArray, inputLength < maxBytesToWrite ? inputLength : maxBytesToWrite); +} + +// Read bits, starting at the next aligned bits. Note that the modulus 8 starting offset of the +// sequence must be the same as was used with WriteBits. This will be a problem with packet coalescence +// unless you byte align the coalesced packets. +bool BitStream::ReadAlignedBytes( unsigned char* inOutByteArray, const unsigned int numberOfBytesToRead ) +{ +#ifdef _DEBUG + RakAssert( numberOfBytesToRead > 0 ); +#endif + + if ( numberOfBytesToRead <= 0 ) + return false; + + // Byte align + AlignReadToByteBoundary(); + + if ( readOffset + ( numberOfBytesToRead << 3 ) > numberOfBitsUsed ) + return false; + + // Write the data + memcpy( inOutByteArray, data + ( readOffset >> 3 ), (size_t) numberOfBytesToRead ); + + readOffset += numberOfBytesToRead << 3; + + return true; +} +bool BitStream::ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead ) +{ + return ReadAlignedBytesSafe(inOutByteArray,(unsigned int&) inputLength,(unsigned int)maxBytesToRead); +} +bool BitStream::ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ) +{ + if (ReadCompressed(inputLength)==false) + return false; + if (inputLength > maxBytesToRead) + inputLength=maxBytesToRead; + if (inputLength==0) + return true; + return ReadAlignedBytes((unsigned char*) inOutByteArray, inputLength); +} +bool BitStream::ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead ) +{ + return ReadAlignedBytesSafeAlloc(outByteArray,(unsigned int&) inputLength, maxBytesToRead); +} +bool BitStream::ReadAlignedBytesSafeAlloc( char ** outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead ) +{ + rakFree_Ex(*outByteArray, _FILE_AND_LINE_ ); + *outByteArray=0; + if (ReadCompressed(inputLength)==false) + return false; + if (inputLength > maxBytesToRead) + inputLength=maxBytesToRead; + if (inputLength==0) + return true; + *outByteArray = (char*) rakMalloc_Ex( (size_t) inputLength, _FILE_AND_LINE_ ); + return ReadAlignedBytes((unsigned char*) *outByteArray, inputLength); +} + +// Write numberToWrite bits from the input source +void BitStream::WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits ) +{ +// if (numberOfBitsToWrite<=0) +// return; + + AddBitsAndReallocate( numberOfBitsToWrite ); + + const BitSize_t numberOfBitsUsedMod8 = numberOfBitsUsed & 7; + + // If currently aligned and numberOfBits is a multiple of 8, just memcpy for speed + if (numberOfBitsUsedMod8==0 && (numberOfBitsToWrite&7)==0) + { + memcpy( data + ( numberOfBitsUsed >> 3 ), inByteArray, numberOfBitsToWrite>>3); + numberOfBitsUsed+=numberOfBitsToWrite; + return; + } + + unsigned char dataByte; + const unsigned char* inputPtr=inByteArray; + + // Faster to put the while at the top surprisingly enough + while ( numberOfBitsToWrite > 0 ) + //do + { + dataByte = *( inputPtr++ ); + + if ( numberOfBitsToWrite < 8 && rightAlignedBits ) // rightAlignedBits means in the case of a partial byte, the bits are aligned from the right (bit 0) rather than the left (as in the normal internal representation) + dataByte <<= 8 - numberOfBitsToWrite; // shift left to get the bits on the left, as in our internal representation + + // Writing to a new byte each time + if ( numberOfBitsUsedMod8 == 0 ) + * ( data + ( numberOfBitsUsed >> 3 ) ) = dataByte; + else + { + // Copy over the new data. + *( data + ( numberOfBitsUsed >> 3 ) ) |= dataByte >> ( numberOfBitsUsedMod8 ); // First half + + if ( 8 - ( numberOfBitsUsedMod8 ) < 8 && 8 - ( numberOfBitsUsedMod8 ) < numberOfBitsToWrite ) // If we didn't write it all out in the first half (8 - (numberOfBitsUsed%8) is the number we wrote in the first half) + { + *( data + ( numberOfBitsUsed >> 3 ) + 1 ) = (unsigned char) ( dataByte << ( 8 - ( numberOfBitsUsedMod8 ) ) ); // Second half (overlaps byte boundary) + } + } + + if ( numberOfBitsToWrite >= 8 ) + { + numberOfBitsUsed += 8; + numberOfBitsToWrite -= 8; + } + else + { + numberOfBitsUsed += numberOfBitsToWrite; + numberOfBitsToWrite=0; + } + } + // } while(numberOfBitsToWrite>0); +} + +// Set the stream to some initial data. For internal use +void BitStream::SetData( unsigned char *inByteArray ) +{ + data=inByteArray; + copyData=false; +} + +// Assume the input source points to a native type, compress and write it +void BitStream::WriteCompressed( const unsigned char* inByteArray, + const unsigned int size, const bool unsignedData ) +{ + BitSize_t currentByte = ( size >> 3 ) - 1; // PCs + + unsigned char byteMatch; + + if ( unsignedData ) + { + byteMatch = 0; + } + + else + { + byteMatch = 0xFF; + } + + // Write upper bytes with a single 1 + // From high byte to low byte, if high byte is a byteMatch then write a 1 bit. Otherwise write a 0 bit and then write the remaining bytes + while ( currentByte > 0 ) + { + if ( inByteArray[ currentByte ] == byteMatch ) // If high byte is byteMatch (0 of 0xff) then it would have the same value shifted + { + bool b = true; + Write( b ); + } + else + { + // Write the remainder of the data after writing 0 + bool b = false; + Write( b ); + + WriteBits( inByteArray, ( currentByte + 1 ) << 3, true ); + // currentByte--; + + + return ; + } + + currentByte--; + } + + // If the upper half of the last byte is a 0 (positive) or 16 (negative) then write a 1 and the remaining 4 bits. Otherwise write a 0 and the 8 bites. + if ( ( unsignedData && ( ( *( inByteArray + currentByte ) ) & 0xF0 ) == 0x00 ) || + ( unsignedData == false && ( ( *( inByteArray + currentByte ) ) & 0xF0 ) == 0xF0 ) ) + { + bool b = true; + Write( b ); + WriteBits( inByteArray + currentByte, 4, true ); + } + + else + { + bool b = false; + Write( b ); + WriteBits( inByteArray + currentByte, 8, true ); + } +} + +// Read numberOfBitsToRead bits to the output source +// alignBitsToRight should be set to true to convert internal bitstream data to userdata +// It should be false if you used WriteBits with rightAlignedBits false +bool BitStream::ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight ) +{ +#ifdef _DEBUG + // RakAssert( numberOfBitsToRead > 0 ); +#endif + if (numberOfBitsToRead<=0) + return false; + + if ( readOffset + numberOfBitsToRead > numberOfBitsUsed ) + return false; + + + const BitSize_t readOffsetMod8 = readOffset & 7; + + // If currently aligned and numberOfBits is a multiple of 8, just memcpy for speed + if (readOffsetMod8==0 && (numberOfBitsToRead&7)==0) + { + memcpy( inOutByteArray, data + ( readOffset >> 3 ), numberOfBitsToRead>>3); + readOffset+=numberOfBitsToRead; + return true; + } + + + + BitSize_t offset = 0; + + memset( inOutByteArray, 0, (size_t) BITS_TO_BYTES( numberOfBitsToRead ) ); + + while ( numberOfBitsToRead > 0 ) + { + *( inOutByteArray + offset ) |= *( data + ( readOffset >> 3 ) ) << ( readOffsetMod8 ); // First half + + if ( readOffsetMod8 > 0 && numberOfBitsToRead > 8 - ( readOffsetMod8 ) ) // If we have a second half, we didn't read enough bytes in the first half + *( inOutByteArray + offset ) |= *( data + ( readOffset >> 3 ) + 1 ) >> ( 8 - ( readOffsetMod8 ) ); // Second half (overlaps byte boundary) + + if (numberOfBitsToRead>=8) + { + numberOfBitsToRead -= 8; + readOffset += 8; + offset++; + } + else + { + int neg = (int) numberOfBitsToRead - 8; + + if ( neg < 0 ) // Reading a partial byte for the last byte, shift right so the data is aligned on the right + { + + if ( alignBitsToRight ) + * ( inOutByteArray + offset ) >>= -neg; + + readOffset += 8 + neg; + } + else + readOffset += 8; + + offset++; + + numberOfBitsToRead=0; + } + } + + return true; +} + +// Assume the input source points to a compressed native type. Decompress and read it +bool BitStream::ReadCompressed( unsigned char* inOutByteArray, + const unsigned int size, const bool unsignedData ) +{ + unsigned int currentByte = ( size >> 3 ) - 1; + + + unsigned char byteMatch, halfByteMatch; + + if ( unsignedData ) + { + byteMatch = 0; + halfByteMatch = 0; + } + + else + { + byteMatch = 0xFF; + halfByteMatch = 0xF0; + } + + // Upper bytes are specified with a single 1 if they match byteMatch + // From high byte to low byte, if high byte is a byteMatch then write a 1 bit. Otherwise write a 0 bit and then write the remaining bytes + while ( currentByte > 0 ) + { + // If we read a 1 then the data is byteMatch. + + bool b; + + if ( Read( b ) == false ) + return false; + + if ( b ) // Check that bit + { + inOutByteArray[ currentByte ] = byteMatch; + currentByte--; + } + else + { + // Read the rest of the bytes + + if ( ReadBits( inOutByteArray, ( currentByte + 1 ) << 3 ) == false ) + return false; + + return true; + } + } + + // All but the first bytes are byteMatch. If the upper half of the last byte is a 0 (positive) or 16 (negative) then what we read will be a 1 and the remaining 4 bits. + // Otherwise we read a 0 and the 8 bytes + //RakAssert(readOffset+1 <=numberOfBitsUsed); // If this assert is hit the stream wasn't long enough to read from + if ( readOffset + 1 > numberOfBitsUsed ) + return false; + + bool b=false; + + if ( Read( b ) == false ) + return false; + + if ( b ) // Check that bit + { + + if ( ReadBits( inOutByteArray + currentByte, 4 ) == false ) + return false; + + inOutByteArray[ currentByte ] |= halfByteMatch; // We have to set the high 4 bits since these are set to 0 by ReadBits + } + else + { + if ( ReadBits( inOutByteArray + currentByte, 8 ) == false ) + return false; + } + + return true; +} + +// Reallocates (if necessary) in preparation of writing numberOfBitsToWrite +void BitStream::AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite ) +{ + BitSize_t newNumberOfBitsAllocated = numberOfBitsToWrite + numberOfBitsUsed; + + if ( numberOfBitsToWrite + numberOfBitsUsed > 0 && ( ( numberOfBitsAllocated - 1 ) >> 3 ) < ( ( newNumberOfBitsAllocated - 1 ) >> 3 ) ) // If we need to allocate 1 or more new bytes + { +#ifdef _DEBUG + // If this assert hits then we need to specify true for the third parameter in the constructor + // It needs to reallocate to hold all the data and can't do it unless we allocated to begin with + // Often hits if you call Write or Serialize on a read-only bitstream + RakAssert( copyData == true ); +#endif + + // Less memory efficient but saves on news and deletes + /// Cap to 1 meg buffer to save on huge allocations + newNumberOfBitsAllocated = ( numberOfBitsToWrite + numberOfBitsUsed ) * 2; + if (newNumberOfBitsAllocated - ( numberOfBitsToWrite + numberOfBitsUsed ) > 1048576 ) + newNumberOfBitsAllocated = numberOfBitsToWrite + numberOfBitsUsed + 1048576; + + // BitSize_t newByteOffset = BITS_TO_BYTES( numberOfBitsAllocated ); + // Use realloc and free so we are more efficient than delete and new for resizing + BitSize_t amountToAllocate = BITS_TO_BYTES( newNumberOfBitsAllocated ); + if (data==(unsigned char*)stackData) + { + if (amountToAllocate > BITSTREAM_STACK_ALLOCATION_SIZE) + { + data = ( unsigned char* ) rakMalloc_Ex( (size_t) amountToAllocate, _FILE_AND_LINE_ ); + RakAssert(data); + + // need to copy the stack data over to our new memory area too + memcpy ((void *)data, (void *)stackData, (size_t) BITS_TO_BYTES( numberOfBitsAllocated )); + } + } + else + { + data = ( unsigned char* ) rakRealloc_Ex( data, (size_t) amountToAllocate, _FILE_AND_LINE_ ); + } + +#ifdef _DEBUG + RakAssert( data ); // Make sure realloc succeeded +#endif + // memset(data+newByteOffset, 0, ((newNumberOfBitsAllocated-1)>>3) - ((numberOfBitsAllocated-1)>>3)); // Set the new data block to 0 + } + + if ( newNumberOfBitsAllocated > numberOfBitsAllocated ) + numberOfBitsAllocated = newNumberOfBitsAllocated; +} +BitSize_t BitStream::GetNumberOfBitsAllocated(void) const +{ + return numberOfBitsAllocated; +} +void BitStream::PadWithZeroToByteLength( unsigned int bytes ) +{ + if (GetNumberOfBytesUsed() < bytes) + { + AlignWriteToByteBoundary(); + unsigned int numToWrite = bytes - GetNumberOfBytesUsed(); + AddBitsAndReallocate( BYTES_TO_BITS(numToWrite) ); + memset(data+BITS_TO_BYTES(numberOfBitsUsed), 0, (size_t) numToWrite); + numberOfBitsUsed+=BYTES_TO_BITS(numToWrite); + } +} + +/* +// Julius Goryavsky's version of Harley's algorithm. +// 17 elementary ops plus an indexed load, if the machine +// has "and not." + +int nlz10b(unsigned x) { + + static char table[64] = + {32,20,19, u, u,18, u, 7, 10,17, u, u,14, u, 6, u, + u, 9, u,16, u, u, 1,26, u,13, u, u,24, 5, u, u, + u,21, u, 8,11, u,15, u, u, u, u, 2,27, 0,25, u, + 22, u,12, u, u, 3,28, u, 23, u, 4,29, u, u,30,31}; + + x = x | (x >> 1); // Propagate leftmost + x = x | (x >> 2); // 1-bit to the right. + x = x | (x >> 4); + x = x | (x >> 8); + x = x & ~(x >> 16); + x = x*0xFD7049FF; // Activate this line or the following 3. +// x = (x << 9) - x; // Multiply by 511. +// x = (x << 11) - x; // Multiply by 2047. +// x = (x << 14) - x; // Multiply by 16383. + return table[x >> 26]; +} +*/ +int BitStream::NumberOfLeadingZeroes( int8_t x ) {return NumberOfLeadingZeroes((uint8_t)x);} +int BitStream::NumberOfLeadingZeroes( uint8_t x ) +{ + uint8_t y; + int n; + + n = 8; + y = x >> 4; if (y != 0) {n = n - 4; x = y;} + y = x >> 2; if (y != 0) {n = n - 2; x = y;} + y = x >> 1; if (y != 0) return n - 2; + return (int)(n - x); +} +int BitStream::NumberOfLeadingZeroes( int16_t x ) {return NumberOfLeadingZeroes((uint16_t)x);} +int BitStream::NumberOfLeadingZeroes( uint16_t x ) +{ + uint16_t y; + int n; + + n = 16; + y = x >> 8; if (y != 0) {n = n - 8; x = y;} + y = x >> 4; if (y != 0) {n = n - 4; x = y;} + y = x >> 2; if (y != 0) {n = n - 2; x = y;} + y = x >> 1; if (y != 0) return n - 2; + return (int)(n - x); +} +int BitStream::NumberOfLeadingZeroes( int32_t x ) {return NumberOfLeadingZeroes((uint32_t)x);} +int BitStream::NumberOfLeadingZeroes( uint32_t x ) +{ + uint32_t y; + int n; + + n = 32; + y = x >>16; if (y != 0) {n = n -16; x = y;} + y = x >> 8; if (y != 0) {n = n - 8; x = y;} + y = x >> 4; if (y != 0) {n = n - 4; x = y;} + y = x >> 2; if (y != 0) {n = n - 2; x = y;} + y = x >> 1; if (y != 0) return n - 2; + return (int)(n - x); +} +int BitStream::NumberOfLeadingZeroes( int64_t x ) {return NumberOfLeadingZeroes((uint64_t)x);} +int BitStream::NumberOfLeadingZeroes( uint64_t x ) +{ + uint64_t y; + int n; + + n = 64; + y = x >>32; if (y != 0) {n = n -32; x = y;} + y = x >>16; if (y != 0) {n = n -16; x = y;} + y = x >> 8; if (y != 0) {n = n - 8; x = y;} + y = x >> 4; if (y != 0) {n = n - 4; x = y;} + y = x >> 2; if (y != 0) {n = n - 2; x = y;} + y = x >> 1; if (y != 0) return n - 2; + return (int)(n - x); +} + +// Should hit if reads didn't match writes +void BitStream::AssertStreamEmpty( void ) +{ + RakAssert( readOffset == numberOfBitsUsed ); +} +void BitStream::PrintBits( char *out ) const +{ + if ( numberOfBitsUsed <= 0 ) + { + strcpy(out, "No bits\n" ); + return; + } + + unsigned int strIndex=0; + for ( BitSize_t counter = 0; counter < BITS_TO_BYTES( numberOfBitsUsed ) && strIndex < 2000 ; counter++ ) + { + BitSize_t stop; + + if ( counter == ( numberOfBitsUsed - 1 ) >> 3 ) + stop = 8 - ( ( ( numberOfBitsUsed - 1 ) & 7 ) + 1 ); + else + stop = 0; + + for ( BitSize_t counter2 = 7; counter2 >= stop; counter2-- ) + { + if ( ( data[ counter ] >> counter2 ) & 1 ) + out[strIndex++]='1'; + else + out[strIndex++]='0'; + + if (counter2==0) + break; + } + + out[strIndex++]=' '; + } + + out[strIndex++]='\n'; + + out[strIndex++]=0; +} +void BitStream::PrintBits( void ) const +{ + char out[2048]; + PrintBits(out); + RAKNET_DEBUG_PRINTF("%s", out); +} +void BitStream::PrintHex( char *out ) const +{ + BitSize_t i; + for ( i=0; i < GetNumberOfBytesUsed(); i++) + { + sprintf(out+i*3, "%02x ", data[i]); + } +} +void BitStream::PrintHex( void ) const +{ + char out[2048]; + PrintHex(out); + RAKNET_DEBUG_PRINTF("%s", out); +} + +// Exposes the data for you to look at, like PrintBits does. +// Data will point to the stream. Returns the length in bits of the stream. +BitSize_t BitStream::CopyData( unsigned char** _data ) const +{ +#ifdef _DEBUG + RakAssert( numberOfBitsUsed > 0 ); +#endif + + *_data = (unsigned char*) rakMalloc_Ex( (size_t) BITS_TO_BYTES( numberOfBitsUsed ), _FILE_AND_LINE_ ); + memcpy( *_data, data, sizeof(unsigned char) * (size_t) ( BITS_TO_BYTES( numberOfBitsUsed ) ) ); + return numberOfBitsUsed; +} + +// Ignore data we don't intend to read +void BitStream::IgnoreBits( const BitSize_t numberOfBits ) +{ + readOffset += numberOfBits; +} + +void BitStream::IgnoreBytes( const unsigned int numberOfBytes ) +{ + IgnoreBits(BYTES_TO_BITS(numberOfBytes)); +} + +// Move the write pointer to a position on the array. Dangerous if you don't know what you are doing! +// Doesn't work with non-aligned data! +void BitStream::SetWriteOffset( const BitSize_t offset ) +{ + numberOfBitsUsed = offset; +} + +/* +BitSize_t BitStream::GetWriteOffset( void ) const +{ +return numberOfBitsUsed; +} + +// Returns the length in bits of the stream +BitSize_t BitStream::GetNumberOfBitsUsed( void ) const +{ +return GetWriteOffset(); +} + +// Returns the length in bytes of the stream +BitSize_t BitStream::GetNumberOfBytesUsed( void ) const +{ +return BITS_TO_BYTES( numberOfBitsUsed ); +} + +// Returns the number of bits into the stream that we have read +BitSize_t BitStream::GetReadOffset( void ) const +{ +return readOffset; +} + + +// Sets the read bit index +void BitStream::SetReadOffset( const BitSize_t newReadOffset ) +{ +readOffset=newReadOffset; +} + +// Returns the number of bits left in the stream that haven't been read +BitSize_t BitStream::GetNumberOfUnreadBits( void ) const +{ +return numberOfBitsUsed - readOffset; +} +// Exposes the internal data +unsigned char* BitStream::GetData( void ) const +{ +return data; +} + +*/ +// If we used the constructor version with copy data off, this makes sure it is set to on and the data pointed to is copied. +void BitStream::AssertCopyData( void ) +{ + if ( copyData == false ) + { + copyData = true; + + if ( numberOfBitsAllocated > 0 ) + { + unsigned char * newdata = ( unsigned char* ) rakMalloc_Ex( (size_t) BITS_TO_BYTES( numberOfBitsAllocated ), _FILE_AND_LINE_ ); +#ifdef _DEBUG + + RakAssert( data ); +#endif + + memcpy( newdata, data, (size_t) BITS_TO_BYTES( numberOfBitsAllocated ) ); + data = newdata; + } + + else + data = 0; + } +} +bool BitStream::IsNetworkOrderInternal(void) +{ + + + + + + static unsigned long htonlValue = htonl(12345); + return htonlValue == 12345; + +} +void BitStream::ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length) +{ + for (BitSize_t i=0; i < length; i++) + inOutByteArray[i]=inByteArray[length-i-1]; +} +void BitStream::ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length) +{ + unsigned char temp; + BitSize_t i; + for (i=0; i < (length>>1); i++) + { + temp = inOutData[i]; + inOutData[i]=inOutData[length-i-1]; + inOutData[length-i-1]=temp; + } +} + +bool BitStream::Read(char *varString) +{ + return RakString::Deserialize(varString,this); +} +bool BitStream::Read(unsigned char *varString) +{ + return RakString::Deserialize((char*) varString,this); +} +void BitStream::WriteAlignedVar8(const char *inByteArray) +{ + RakAssert((numberOfBitsUsed&7)==0); + AddBitsAndReallocate(1*8); + data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0]; + numberOfBitsUsed+=1*8; +} +bool BitStream::ReadAlignedVar8(char *inOutByteArray) +{ + RakAssert((readOffset&7)==0); + if ( readOffset + 1*8 > numberOfBitsUsed ) + return false; + + inOutByteArray[0] = data[( readOffset >> 3 ) + 0]; + readOffset+=1*8; + return true; +} +void BitStream::WriteAlignedVar16(const char *inByteArray) +{ + RakAssert((numberOfBitsUsed&7)==0); + AddBitsAndReallocate(2*8); +#ifndef __BITSTREAM_NATIVE_END + if (DoEndianSwap()) + { + data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[1]; + data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[0]; + } + else +#endif + { + data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0]; + data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[1]; + } + + numberOfBitsUsed+=2*8; +} +bool BitStream::ReadAlignedVar16(char *inOutByteArray) +{ + RakAssert((readOffset&7)==0); + if ( readOffset + 2*8 > numberOfBitsUsed ) + return false; +#ifndef __BITSTREAM_NATIVE_END + if (DoEndianSwap()) + { + inOutByteArray[0] = data[( readOffset >> 3 ) + 1]; + inOutByteArray[1] = data[( readOffset >> 3 ) + 0]; + } + else +#endif + { + inOutByteArray[0] = data[( readOffset >> 3 ) + 0]; + inOutByteArray[1] = data[( readOffset >> 3 ) + 1]; + } + + readOffset+=2*8; + return true; +} +void BitStream::WriteAlignedVar32(const char *inByteArray) +{ + RakAssert((numberOfBitsUsed&7)==0); + AddBitsAndReallocate(4*8); +#ifndef __BITSTREAM_NATIVE_END + if (DoEndianSwap()) + { + data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[3]; + data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[2]; + data[( numberOfBitsUsed >> 3 ) + 2] = inByteArray[1]; + data[( numberOfBitsUsed >> 3 ) + 3] = inByteArray[0]; + } + else +#endif + { + data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0]; + data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[1]; + data[( numberOfBitsUsed >> 3 ) + 2] = inByteArray[2]; + data[( numberOfBitsUsed >> 3 ) + 3] = inByteArray[3]; + } + + numberOfBitsUsed+=4*8; +} +bool BitStream::ReadAlignedVar32(char *inOutByteArray) +{ + RakAssert((readOffset&7)==0); + if ( readOffset + 4*8 > numberOfBitsUsed ) + return false; +#ifndef __BITSTREAM_NATIVE_END + if (DoEndianSwap()) + { + inOutByteArray[0] = data[( readOffset >> 3 ) + 3]; + inOutByteArray[1] = data[( readOffset >> 3 ) + 2]; + inOutByteArray[2] = data[( readOffset >> 3 ) + 1]; + inOutByteArray[3] = data[( readOffset >> 3 ) + 0]; + } + else +#endif + { + inOutByteArray[0] = data[( readOffset >> 3 ) + 0]; + inOutByteArray[1] = data[( readOffset >> 3 ) + 1]; + inOutByteArray[2] = data[( readOffset >> 3 ) + 2]; + inOutByteArray[3] = data[( readOffset >> 3 ) + 3]; + } + + readOffset+=4*8; + return true; +} +bool BitStream::ReadFloat16( float &outFloat, float floatMin, float floatMax ) +{ + unsigned short percentile; + if (Read(percentile)) + { + RakAssert(floatMax>floatMin); + outFloat = floatMin + ((float) percentile / 65535.0f) * (floatMax-floatMin); + if (outFloatfloatMax) + outFloat=floatMax; + return true; + } + return false; +} +bool BitStream::SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax) +{ + if (writeToBitstream) + WriteFloat16(inOutFloat, floatMin, floatMax); + else + return ReadFloat16(inOutFloat, floatMin, floatMax); + return true; +} +void BitStream::WriteFloat16( float inOutFloat, float floatMin, float floatMax ) +{ + RakAssert(floatMax>floatMin); + if (inOutFloat>floatMax+.001) + { + RakAssert(inOutFloat<=floatMax+.001); + } + if (inOutFloat=floatMin-.001); + } + float percentile=65535.0f * (inOutFloat-floatMin)/(floatMax-floatMin); + if (percentile<0.0) + percentile=0.0; + if (percentile>65535.0f) + percentile=65535.0f; + Write((unsigned short)percentile); +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // #if _MSC_VER < 1299 diff --git a/src/raknet/CCRakNetSlidingWindow.cpp b/src/raknet/CCRakNetSlidingWindow.cpp new file mode 100644 index 0000000..00e2810 --- /dev/null +++ b/src/raknet/CCRakNetSlidingWindow.cpp @@ -0,0 +1,372 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/CCRakNetSlidingWindow.hpp" + +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1 + +static const double UNSET_TIME_US=-1; + +#if CC_TIME_TYPE_BYTES==4 +static const CCTimeType SYN=10; +#else +static const CCTimeType SYN=10000; +#endif + +#include "include/raknet/MTUSize.hpp" +#include +#include +#include +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakAlloca.hpp" + +using namespace RakNet; + +// ****************************************************** PUBLIC METHODS ****************************************************** + +CCRakNetSlidingWindow::CCRakNetSlidingWindow() +{ +} +// ---------------------------------------------------------------------------------------------------------------------------- +CCRakNetSlidingWindow::~CCRakNetSlidingWindow() +{ + +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::Init(CCTimeType curTime, uint32_t maxDatagramPayload) +{ + (void) curTime; + + lastRtt=estimatedRTT=deviationRtt=UNSET_TIME_US; + RakAssert(maxDatagramPayload <= MAXIMUM_MTU_SIZE); + MAXIMUM_MTU_INCLUDING_UDP_HEADER=maxDatagramPayload; + cwnd=maxDatagramPayload; + ssThresh=0.0; + oldestUnsentAck=0; + nextDatagramSequenceNumber=0; + nextCongestionControlBlock=0; + backoffThisBlock=speedUpThisBlock=false; + expectedNextSequenceNumber=0; + _isContinuousSend=false; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::Update(CCTimeType curTime, bool hasDataToSendOrResend) +{ + (void) curTime; + (void) hasDataToSendOrResend; +} +// ---------------------------------------------------------------------------------------------------------------------------- +int CCRakNetSlidingWindow::GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) +{ + (void) curTime; + (void) isContinuousSend; + (void) timeSinceLastTick; + + return unacknowledgedBytes; +} +// ---------------------------------------------------------------------------------------------------------------------------- +int CCRakNetSlidingWindow::GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) +{ + (void) curTime; + (void) timeSinceLastTick; + + _isContinuousSend=isContinuousSend; + + if (unacknowledgedBytes<=cwnd) + return (int) (cwnd-unacknowledgedBytes); + else + return 0; +} +// ---------------------------------------------------------------------------------------------------------------------------- +bool CCRakNetSlidingWindow::ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick) +{ + CCTimeType rto = GetSenderRTOForACK(); + (void) estimatedTimeToNextTick; + + // iphone crashes on comparison between double and int64 http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 + if (rto==(CCTimeType) UNSET_TIME_US) + { + // Unknown how long until the remote system will retransmit, so better send right away + return true; + } + + return curTime >= oldestUnsentAck + SYN; +} +// ---------------------------------------------------------------------------------------------------------------------------- +DatagramSequenceNumberType CCRakNetSlidingWindow::GetNextDatagramSequenceNumber(void) +{ + return nextDatagramSequenceNumber; +} +// ---------------------------------------------------------------------------------------------------------------------------- +DatagramSequenceNumberType CCRakNetSlidingWindow::GetAndIncrementNextDatagramSequenceNumber(void) +{ + DatagramSequenceNumberType dsnt=nextDatagramSequenceNumber; + nextDatagramSequenceNumber++; + return dsnt; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::OnSendBytes(CCTimeType curTime, uint32_t numBytes) +{ + (void) curTime; + (void) numBytes; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime) +{ + (void) curTime; + (void) sizeInBytes; + (void) datagramSequenceNumber; +} +// ---------------------------------------------------------------------------------------------------------------------------- +bool CCRakNetSlidingWindow::OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount) +{ + (void) curTime; + (void) sizeInBytes; + (void) isContinuousSend; + + if (oldestUnsentAck==0) + oldestUnsentAck=curTime; + + if (datagramSequenceNumber==expectedNextSequenceNumber) + { + *skippedMessageCount=0; + expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; + } + else if (GreaterThan(datagramSequenceNumber, expectedNextSequenceNumber)) + { + *skippedMessageCount=datagramSequenceNumber-expectedNextSequenceNumber; + // Sanity check, just use timeout resend if this was really valid + if (*skippedMessageCount>1000) + { + // During testing, the nat punchthrough server got 51200 on the first packet. I have no idea where this comes from, but has happened twice + if (*skippedMessageCount>(uint32_t)50000) + return false; + *skippedMessageCount=1000; + } + expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; + } + else + { + *skippedMessageCount=0; + } + + return true; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::OnResend(CCTimeType curTime, RakNet::TimeUS nextActionTime) +{ + (void) curTime; + (void) nextActionTime; + + if (_isContinuousSend && backoffThisBlock==false && cwnd>MAXIMUM_MTU_INCLUDING_UDP_HEADER*2) + { + // Spec says 1/2 cwnd, but it never recovers because cwnd increases too slowly + //ssThresh=cwnd-8.0 * (MAXIMUM_MTU_INCLUDING_UDP_HEADER*MAXIMUM_MTU_INCLUDING_UDP_HEADER/cwnd); + ssThresh=cwnd/2; + if (ssThresh ssThresh && ssThresh!=0) + cwnd = ssThresh + MAXIMUM_MTU_INCLUDING_UDP_HEADER*MAXIMUM_MTU_INCLUDING_UDP_HEADER/cwnd; + + // CC PRINTF + // printf("++ %.0f Slow start increase.\n", cwnd); + + } + else if (isNewCongestionControlPeriod) + { + cwnd+=MAXIMUM_MTU_INCLUDING_UDP_HEADER*MAXIMUM_MTU_INCLUDING_UDP_HEADER/cwnd; + + // CC PRINTF + // printf("+ %.0f Congestion avoidance increase.\n", cwnd); + } +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::OnDuplicateAck( CCTimeType curTime, DatagramSequenceNumberType sequenceNumber ) +{ + (void) curTime; + (void) sequenceNumber; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS) +{ + (void) curTime; + (void) _B; + (void) _AS; + + *hasBAndAS=false; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::OnSendAck(CCTimeType curTime, uint32_t numBytes) +{ + (void) curTime; + (void) numBytes; + + oldestUnsentAck=0; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::OnSendNACK(CCTimeType curTime, uint32_t numBytes) +{ + (void) curTime; + (void) numBytes; + +} +// ---------------------------------------------------------------------------------------------------------------------------- +CCTimeType CCRakNetSlidingWindow::GetRTOForRetransmission(unsigned char timesSent) const +{ + (void) timesSent; + +#if CC_TIME_TYPE_BYTES==4 + const CCTimeType maxThreshold=2000; + //const CCTimeType minThreshold=100; + const CCTimeType additionalVariance=30; +#else + const CCTimeType maxThreshold=2000000; + //const CCTimeType minThreshold=100000; + const CCTimeType additionalVariance=30000; +#endif + + + if (estimatedRTT==UNSET_TIME_US) + return maxThreshold; + + //double u=1.0f; + double u=2.0f; + double q=4.0f; + + CCTimeType threshhold = (CCTimeType) (u * estimatedRTT + q * deviationRtt) + additionalVariance; + if (threshhold > maxThreshold) + return maxThreshold; + return threshhold; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetSlidingWindow::SetMTU(uint32_t bytes) +{ + RakAssert(bytes < MAXIMUM_MTU_SIZE); + MAXIMUM_MTU_INCLUDING_UDP_HEADER=bytes; +} +// ---------------------------------------------------------------------------------------------------------------------------- +uint32_t CCRakNetSlidingWindow::GetMTU(void) const +{ + return MAXIMUM_MTU_INCLUDING_UDP_HEADER; +} +// ---------------------------------------------------------------------------------------------------------------------------- +BytesPerMicrosecond CCRakNetSlidingWindow::GetLocalReceiveRate(CCTimeType currentTime) const +{ + (void) currentTime; + + return 0; // TODO +} +// ---------------------------------------------------------------------------------------------------------------------------- +double CCRakNetSlidingWindow::GetRTT(void) const +{ + if (lastRtt==UNSET_TIME_US) + return 0.0; + return lastRtt; +} +// ---------------------------------------------------------------------------------------------------------------------------- +bool CCRakNetSlidingWindow::GreaterThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b) +{ + // a > b? + const DatagramSequenceNumberType halfSpan =(DatagramSequenceNumberType)(((DatagramSequenceNumberType)(uint32_t)-1)/(DatagramSequenceNumberType)2); + return b!=a && b-a>halfSpan; +} +// ---------------------------------------------------------------------------------------------------------------------------- +bool CCRakNetSlidingWindow::LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b) +{ + // a < b? + const DatagramSequenceNumberType halfSpan =(DatagramSequenceNumberType)(((DatagramSequenceNumberType)(uint32_t)-1)/(DatagramSequenceNumberType)2); + return b!=a && b-a +#include +#include +//#include +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakAlloca.hpp" + +using namespace RakNet; + +static const double UNSET_TIME_US=-1; +static const double CWND_MIN_THRESHOLD=2.0; +static const double UNDEFINED_TRANSFER_RATE=0.0; +/// Interval at which to update aspects of the system +/// 1. send acks +/// 2. update time interval between outgoing packets +/// 3, Yodate retransmit timeout +#if CC_TIME_TYPE_BYTES==4 +static const CCTimeType SYN=10; +#else +static const CCTimeType SYN=10000; +#endif + +#if CC_TIME_TYPE_BYTES==4 +#define MAX_RTT 1000 +#define RTT_TOLERANCE 30 +#else +#define MAX_RTT 1000000 +#define RTT_TOLERANCE 30000 +#endif + + +double RTTVarMultiple=4.0; + + +// ****************************************************** PUBLIC METHODS ****************************************************** + +CCRakNetUDT::CCRakNetUDT() +{ +} + +// ---------------------------------------------------------------------------------------------------------------------------- + +CCRakNetUDT::~CCRakNetUDT() +{ +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::Init(CCTimeType curTime, uint32_t maxDatagramPayload) +{ + (void) curTime; + + nextSYNUpdate=0; + packetPairRecieptHistoryWriteIndex=0; + packetArrivalHistoryWriteIndex=0; + packetArrivalHistoryWriteCount=0; + RTT=UNSET_TIME_US; + // RTTVar=UNSET_TIME_US; + isInSlowStart=true; + NAKCount=1000; + AvgNAKNum=1; + DecInterval=1; + DecCount=0; + nextDatagramSequenceNumber=0; + lastPacketPairPacketArrivalTime=0; + lastPacketPairSequenceNumber=(DatagramSequenceNumberType)(const uint32_t)-1; + lastPacketArrivalTime=0; + CWND=CWND_MIN_THRESHOLD; + lastUpdateWindowSizeAndAck=0; + lastTransmitOfBAndAS=0; + ExpCount=1.0; + totalUserDataBytesSent=0; + oldestUnsentAck=0; + MAXIMUM_MTU_INCLUDING_UDP_HEADER=maxDatagramPayload; + CWND_MAX_THRESHOLD=RESEND_BUFFER_ARRAY_LENGTH; +#if CC_TIME_TYPE_BYTES==4 + const BytesPerMicrosecond DEFAULT_TRANSFER_RATE=(BytesPerMicrosecond) 3.6; +#else + const BytesPerMicrosecond DEFAULT_TRANSFER_RATE=(BytesPerMicrosecond) .0036; +#endif + +#if CC_TIME_TYPE_BYTES==4 + lastRttOnIncreaseSendRate=1000; +#else + lastRttOnIncreaseSendRate=1000000; +#endif + nextCongestionControlBlock=0; + lastRtt=0; + + // B=DEFAULT_TRANSFER_RATE; + AS=UNDEFINED_TRANSFER_RATE; + const MicrosecondsPerByte DEFAULT_BYTE_INTERVAL=(MicrosecondsPerByte) (1.0/DEFAULT_TRANSFER_RATE); + SND=DEFAULT_BYTE_INTERVAL; + expectedNextSequenceNumber=0; + sendBAndASCount=0; + packetArrivalHistoryContinuousGapsIndex=0; + //packetPairRecipetHistoryGapsIndex=0; + hasWrittenToPacketPairReceiptHistory=false; + InitPacketArrivalHistory(); + + estimatedLinkCapacityBytesPerSecond=0; + bytesCanSendThisTick=0; + hadPacketlossThisBlock=false; + pingsLastInterval.Clear(__FILE__,__LINE__); +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::SetMTU(uint32_t bytes) +{ + MAXIMUM_MTU_INCLUDING_UDP_HEADER=bytes; +} +// ---------------------------------------------------------------------------------------------------------------------------- +uint32_t CCRakNetUDT::GetMTU(void) const +{ + return MAXIMUM_MTU_INCLUDING_UDP_HEADER; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::Update(CCTimeType curTime, bool hasDataToSendOrResend) +{ + (void) hasDataToSendOrResend; + (void) curTime; + + return; + + // I suspect this is causing major lag + + /* + if (hasDataToSendOrResend==false) + halveSNDOnNoDataTime=0; + else if (halveSNDOnNoDataTime==0) + { + UpdateHalveSNDOnNoDataTime(curTime); + ExpCount=1.0; + } + + // If you send, and get no data at all from that time to RTO, then halve send rate7 + if (HasHalveSNDOnNoDataTimeElapsed(curTime)) + { + /// 2000 bytes per second + /// 0.0005 seconds per byte + /// 0.5 milliseconds per byte + /// 500 microseconds per byte + // printf("No incoming data, halving send rate\n"); + SND*=2.0; + CapMinSnd(_FILE_AND_LINE_); + ExpCount+=1.0; + if (ExpCount>8.0) + ExpCount=8.0; + + UpdateHalveSNDOnNoDataTime(curTime); + } + */ +} +// ---------------------------------------------------------------------------------------------------------------------------- +int CCRakNetUDT::GetRetransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) +{ + (void) curTime; + + if (isInSlowStart) + { + uint32_t CWNDLimit = (uint32_t) (CWND*MAXIMUM_MTU_INCLUDING_UDP_HEADER); + return CWNDLimit; + } + return GetTransmissionBandwidth(curTime,timeSinceLastTick,unacknowledgedBytes,isContinuousSend); +} +// ---------------------------------------------------------------------------------------------------------------------------- +int CCRakNetUDT::GetTransmissionBandwidth(CCTimeType curTime, CCTimeType timeSinceLastTick, uint32_t unacknowledgedBytes, bool isContinuousSend) +{ + (void) curTime; + + if (isInSlowStart) + { + uint32_t CWNDLimit = (uint32_t) (CWND*MAXIMUM_MTU_INCLUDING_UDP_HEADER-unacknowledgedBytes); + return CWNDLimit; + } + if (bytesCanSendThisTick>0) + bytesCanSendThisTick=0; + +#if CC_TIME_TYPE_BYTES==4 + if (isContinuousSend==false && timeSinceLastTick>100) + timeSinceLastTick=100; +#else + if (isContinuousSend==false && timeSinceLastTick>100000) + timeSinceLastTick=100000; +#endif + + bytesCanSendThisTick=(int)((double)timeSinceLastTick*((double)1.0/SND)+(double)bytesCanSendThisTick); + if (bytesCanSendThisTick>0) + return bytesCanSendThisTick; + return 0; +} +uint64_t CCRakNetUDT::GetBytesPerSecondLimitByCongestionControl(void) const +{ + if (isInSlowStart) + return 0; +#if CC_TIME_TYPE_BYTES==4 + return (uint64_t) ((double)1.0/(SND*1000.0)); +#else + return (uint64_t) ((double)1.0/(SND*1000000.0)); +#endif +} +// ---------------------------------------------------------------------------------------------------------------------------- +bool CCRakNetUDT::ShouldSendACKs(CCTimeType curTime, CCTimeType estimatedTimeToNextTick) +{ + CCTimeType rto = GetSenderRTOForACK(); + + // iphone crashes on comparison between double and int64 http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 + if (rto==(CCTimeType) UNSET_TIME_US) + { + // Unknown how long until the remote system will retransmit, so better send right away + return true; + } + + + // CCTimeType remoteRetransmitTime=oldestUnsentAck+rto-RTT*.5; + // CCTimeType ackArrivalTimeIfWeDelay=RTT*.5+estimatedTimeToNextTick+curTime; + // return ackArrivalTimeIfWeDelay= oldestUnsentAck + SYN || + estimatedTimeToNextTick+curTime < oldestUnsentAck+rto-RTT; +} +// ---------------------------------------------------------------------------------------------------------------------------- +DatagramSequenceNumberType CCRakNetUDT::GetNextDatagramSequenceNumber(void) +{ + return nextDatagramSequenceNumber; +} +// ---------------------------------------------------------------------------------------------------------------------------- +DatagramSequenceNumberType CCRakNetUDT::GetAndIncrementNextDatagramSequenceNumber(void) +{ + DatagramSequenceNumberType dsnt=nextDatagramSequenceNumber; + nextDatagramSequenceNumber++; + return dsnt; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnSendBytes(CCTimeType curTime, uint32_t numBytes) +{ + (void) curTime; + + totalUserDataBytesSent+=numBytes; + if (isInSlowStart==false) + bytesCanSendThisTick-=numBytes; +} + +// ****************************************************** PROTECTED METHODS ****************************************************** + +void CCRakNetUDT::SetNextSYNUpdate(CCTimeType currentTime) +{ + nextSYNUpdate+=SYN; + if (nextSYNUpdate < currentTime) + nextSYNUpdate=currentTime+SYN; +} +// ---------------------------------------------------------------------------------------------------------------------------- +BytesPerMicrosecond CCRakNetUDT::ReceiverCalculateDataArrivalRate(CCTimeType curTime) const +{ + (void) curTime; + // Not an instantaneous measurement + /* + if (continuousBytesReceivedStartTime!=0 && curTime>continuousBytesReceivedStartTime) + { + #if CC_TIME_TYPE_BYTES==4 + const CCTimeType threshold=100; + #else + const CCTimeType threshold=100000; + #endif + if (curTime-continuousBytesReceivedStartTime>threshold) + return (BytesPerMicrosecond) continuousBytesReceived/(BytesPerMicrosecond) (curTime-continuousBytesReceivedStartTime); + } + + return UNDEFINED_TRANSFER_RATE; + */ + + + if (packetArrivalHistoryWriteCount=oneEighthMedian && + packetArrivalHistory[i] b? + const DatagramSequenceNumberType halfSpan =(DatagramSequenceNumberType) (((DatagramSequenceNumberType)(const uint32_t)-1)/(DatagramSequenceNumberType)2); + return b!=a && b-a>halfSpan; +} +// ---------------------------------------------------------------------------------------------------------------------------- +bool CCRakNetUDT::LessThan(DatagramSequenceNumberType a, DatagramSequenceNumberType b) +{ + // a < b? + const DatagramSequenceNumberType halfSpan = ((DatagramSequenceNumberType)(const uint32_t)-1)/(DatagramSequenceNumberType)2; + return b!=a && b-amaxThreshold) + return maxThreshold; + return ret; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnResend(CCTimeType curTime, RakNet::TimeUS nextActionTime) +{ + (void) curTime; + + if (isInSlowStart) + { + if (AS!=UNDEFINED_TRANSFER_RATE) + EndSlowStart(); + return; + } + + if (hadPacketlossThisBlock==false) + { + // Logging + // printf("Sending SLOWER due to Resend, Rate=%f MBPS. Rtt=%i\n", GetLocalSendRate(), lastRtt ); + + IncreaseTimeBetweenSends(); + hadPacketlossThisBlock=true; + } +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnNAK(CCTimeType curTime, DatagramSequenceNumberType nakSequenceNumber) +{ + (void) nakSequenceNumber; + (void) curTime; + + if (isInSlowStart) + { + if (AS!=UNDEFINED_TRANSFER_RATE) + EndSlowStart(); + return; + } + + if (hadPacketlossThisBlock==false) + { + // Logging + //printf("Sending SLOWER due to NAK, Rate=%f MBPS. Rtt=%i\n", GetLocalSendRate(), lastRtt ); + if (pingsLastInterval.Size()>10) + { + for (int i=0; i < 10; i++) + printf("%i, ", pingsLastInterval[pingsLastInterval.Size()-1-i]/1000); + } + printf("\n"); + IncreaseTimeBetweenSends(); + + hadPacketlossThisBlock=true; + } +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::EndSlowStart(void) +{ + RakAssert(isInSlowStart==true); + RakAssert(AS!=UNDEFINED_TRANSFER_RATE); + + // This overestimates + estimatedLinkCapacityBytesPerSecond=AS * 1000000.0; + + isInSlowStart=false; + SND=1.0/AS; + CapMinSnd(_FILE_AND_LINE_); + + // printf("ENDING SLOW START\n"); +#if CC_TIME_TYPE_BYTES==4 + // printf("Initial SND=%f Kilobytes per second\n", 1.0/SND); +#else + // printf("Initial SND=%f Megabytes per second\n", 1.0/SND); +#endif + if (SND > .1) + PrintLowBandwidthWarning(); +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnGotPacketPair(DatagramSequenceNumberType datagramSequenceNumber, uint32_t sizeInBytes, CCTimeType curTime) +{ + (void) datagramSequenceNumber; + (void) sizeInBytes; + (void) curTime; + +} +// ---------------------------------------------------------------------------------------------------------------------------- +bool CCRakNetUDT::OnGotPacket(DatagramSequenceNumberType datagramSequenceNumber, bool isContinuousSend, CCTimeType curTime, uint32_t sizeInBytes, uint32_t *skippedMessageCount) +{ + CC_DEBUG_PRINTF_2("R%i ",datagramSequenceNumber.val); + + if (datagramSequenceNumber==expectedNextSequenceNumber) + { + *skippedMessageCount=0; + expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; + } + else if (GreaterThan(datagramSequenceNumber, expectedNextSequenceNumber)) + { + *skippedMessageCount=datagramSequenceNumber-expectedNextSequenceNumber; + // Sanity check, just use timeout resend if this was really valid + if (*skippedMessageCount>1000) + { + // During testing, the nat punchthrough server got 51200 on the first packet. I have no idea where this comes from, but has happened twice + if (*skippedMessageCount>(uint32_t)50000) + return false; + *skippedMessageCount=1000; + } + expectedNextSequenceNumber=datagramSequenceNumber+(DatagramSequenceNumberType)1; + } + else + { + *skippedMessageCount=0; + } + + if (curTime>lastPacketArrivalTime) + { + CCTimeType interval = curTime-lastPacketArrivalTime; + + // printf("Packet arrival gap is %I64u\n", (interval)); + + if (isContinuousSend) + { + continuousBytesReceived+=sizeInBytes; + if (continuousBytesReceivedStartTime==0) + continuousBytesReceivedStartTime=lastPacketArrivalTime; + + + mostRecentPacketArrivalHistory=(BytesPerMicrosecond)sizeInBytes/(BytesPerMicrosecond)interval; + + // if (mostRecentPacketArrivalHistory < (BytesPerMicrosecond)0.0035) + // { + // printf("%s:%i LIKELY BUG: Calculated packetArrivalHistory is below 28.8 Kbps modem\nReport to rakkar@jenkinssoftware.com with file and line number\n", _FILE_AND_LINE_); + // } + + packetArrivalHistoryContinuousGaps[packetArrivalHistoryContinuousGapsIndex++]=(int) interval; + packetArrivalHistoryContinuousGapsIndex&=(CC_RAKNET_UDT_PACKET_HISTORY_LENGTH-1); + + packetArrivalHistoryWriteCount++; + packetArrivalHistory[packetArrivalHistoryWriteIndex++]=mostRecentPacketArrivalHistory; + // Wrap to 0 at the end of the range + // Assumes power of 2 for CC_RAKNET_UDT_PACKET_HISTORY_LENGTH + packetArrivalHistoryWriteIndex&=(CC_RAKNET_UDT_PACKET_HISTORY_LENGTH-1); + } + else + { + continuousBytesReceivedStartTime=0; + continuousBytesReceived=0; + } + + lastPacketArrivalTime=curTime; + } + return true; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnAck(CCTimeType curTime, CCTimeType rtt, bool hasBAndAS, BytesPerMicrosecond _B, BytesPerMicrosecond _AS, double totalUserDataBytesAcked, bool isContinuousSend, DatagramSequenceNumberType sequenceNumber ) +{ +#if CC_TIME_TYPE_BYTES==4 + RakAssert(rtt < 10000); +#else + RakAssert(rtt < 10000000); +#endif + (void) _B; + + if (hasBAndAS) + { + /// RakAssert(_B!=UNDEFINED_TRANSFER_RATE && _AS!=UNDEFINED_TRANSFER_RATE); + // B=B * .875 + _B * .125; + // AS is packet arrival rate + RakAssert(_AS!=UNDEFINED_TRANSFER_RATE); + AS=_AS; + CC_DEBUG_PRINTF_4("ArrivalRate=%f linkCap=%f incomingLinkCap=%f\n", _AS,B,_B); + } + + if (oldestUnsentAck==0) + oldestUnsentAck=curTime; + + if (isInSlowStart==true) + { + nextCongestionControlBlock=nextDatagramSequenceNumber; + lastRttOnIncreaseSendRate=rtt; + UpdateWindowSizeAndAckOnAckPreSlowStart(totalUserDataBytesAcked); + } + else + { + UpdateWindowSizeAndAckOnAckPerSyn(curTime, rtt, isContinuousSend, sequenceNumber); + } + + lastUpdateWindowSizeAndAck=curTime; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnSendAckGetBAndAS(CCTimeType curTime, bool *hasBAndAS, BytesPerMicrosecond *_B, BytesPerMicrosecond *_AS) +{ + if (curTime>lastTransmitOfBAndAS+SYN) + { + *_B=0; + *_AS=ReceiverCalculateDataArrivalRate(curTime); + + if (*_AS==UNDEFINED_TRANSFER_RATE) + { + *hasBAndAS=false; + } + else + { + *hasBAndAS=true; + } + } + else + { + *hasBAndAS=false; + } +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnSendAck(CCTimeType curTime, uint32_t numBytes) +{ + (void) numBytes; + (void) curTime; + + // This is not accounted for on the remote system, and thus causes bandwidth to be underutilized + //UpdateNextAllowedSend(curTime, numBytes+UDP_HEADER_SIZE); + + oldestUnsentAck=0; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::OnSendNACK(CCTimeType curTime, uint32_t numBytes) +{ + (void) numBytes; + (void) curTime; + + // This is not accounted for on the remote system, and thus causes bandwidth to be underutilized + // UpdateNextAllowedSend(curTime, numBytes+UDP_HEADER_SIZE); +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::UpdateWindowSizeAndAckOnAckPreSlowStart(double totalUserDataBytesAcked) +{ + // During slow start, max window size is the number of full packets that have been sent out + // CWND=(double) ((double)totalUserDataBytesSent/(double)MAXIMUM_MTU_INCLUDING_UDP_HEADER); + CC_DEBUG_PRINTF_3("CWND increasing from %f to %f\n", CWND, (double) ((double)totalUserDataBytesAcked/(double)MAXIMUM_MTU_INCLUDING_UDP_HEADER)); + CWND=(double) ((double)totalUserDataBytesAcked/(double)MAXIMUM_MTU_INCLUDING_UDP_HEADER); + if (CWND>=CWND_MAX_THRESHOLD) + { + CWND=CWND_MAX_THRESHOLD; + + if (AS!=UNDEFINED_TRANSFER_RATE) + EndSlowStart(); + } + if (CWNDintervalSize) + pingsLastInterval.Pop(); + if (GreaterThan(sequenceNumber, nextCongestionControlBlock) && + sequenceNumber-nextCongestionControlBlock>=intervalSize && + pingsLastInterval.Size()==intervalSize) + { + double slopeSum=0.0; + double average=(double) pingsLastInterval[0]; + int sampleSize=pingsLastInterval.Size(); + for (int i=1; i < sampleSize; i++) + { + slopeSum+=(double)pingsLastInterval[i]-(double)pingsLastInterval[i-1]; + average+=pingsLastInterval[i]; + } + average/=sampleSize; + + if (hadPacketlossThisBlock==true) + { + } + else if (slopeSum < -.10*average) + { + // Logging + //printf("Ping dropping. slope=%f%%. Rate=%f MBPS. Rtt=%i\n", 100.0*slopeSum/average, GetLocalSendRate(), rtt ); + } + else if (slopeSum > .10*average) + { + // Logging + //printf("Ping rising. slope=%f%%. Rate=%f MBPS. Rtt=%i\n", 100.0*slopeSum/average, GetLocalSendRate(), rtt ); + IncreaseTimeBetweenSends(); + } + else + { + // Logging + //printf("Ping stable. slope=%f%%. Rate=%f MBPS. Rtt=%i\n", 100.0*slopeSum/average, GetLocalSendRate(), rtt ); + + // No packetloss over time threshhold, and rtt decreased, so send faster + lastRttOnIncreaseSendRate=rtt; + DecreaseTimeBetweenSends(); + } + + pingsLastInterval.Clear(__FILE__,__LINE__); + hadPacketlossThisBlock=false; + nextCongestionControlBlock=nextDatagramSequenceNumber; + } + + lastRtt=rtt; +} + +// ---------------------------------------------------------------------------------------------------------------------------- +double CCRakNetUDT::BytesPerMicrosecondToPacketsPerMillisecond(BytesPerMicrosecond in) +{ +#if CC_TIME_TYPE_BYTES==4 + const BytesPerMicrosecond factor = 1.0 / (BytesPerMicrosecond) MAXIMUM_MTU_INCLUDING_UDP_HEADER; +#else + const BytesPerMicrosecond factor = 1000.0 / (BytesPerMicrosecond) MAXIMUM_MTU_INCLUDING_UDP_HEADER; +#endif + return in * factor; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::InitPacketArrivalHistory(void) +{ + unsigned int i; + for (i=0; i < CC_RAKNET_UDT_PACKET_HISTORY_LENGTH; i++) + { + packetArrivalHistory[i]=UNDEFINED_TRANSFER_RATE; + packetArrivalHistoryContinuousGaps[i]=0; + } + + packetArrivalHistoryWriteCount=0; + continuousBytesReceived=0; + continuousBytesReceivedStartTime=0; +} +// ---------------------------------------------------------------------------------------------------------------------------- +void CCRakNetUDT::PrintLowBandwidthWarning(void) +{ + + /* + printf("\n-------LOW BANDWIDTH -----\n"); + if (isInSlowStart==false) + printf("SND=%f Megabytes per second\n", 1.0/SND); + printf("Window size=%f\n", CWND); + printf("Pipe from packet pair = %f megabytes per second\n", B); + printf("RTT=%f milliseconds\n", RTT/1000.0); + printf("RTT Variance=%f milliseconds\n", RTTVar/1000.0); + printf("Retransmission=%i milliseconds\n", GetRTOForRetransmission(1)/1000); + printf("Packet arrival rate on the remote system=%f megabytes per second\n", AS); + printf("Packet arrival rate on our system=%f megabytes per second\n", ReceiverCalculateDataArrivalRate()); + printf("isInSlowStart=%i\n", isInSlowStart); + printf("---------------\n"); + */ +} +BytesPerMicrosecond CCRakNetUDT::GetLocalReceiveRate(CCTimeType currentTime) const +{ + return ReceiverCalculateDataArrivalRate(currentTime); +} +double CCRakNetUDT::GetRTT(void) const +{ + if (RTT==UNSET_TIME_US) + return 0.0; + return RTT; +} +void CCRakNetUDT::CapMinSnd(const char *file, int line) +{ + (void) file; + (void) line; + + if (SND > 500) + { + SND=500; + CC_DEBUG_PRINTF_3("%s:%i LIKELY BUG: SND has gotten above 500 microseconds between messages (28.8 modem)\nReport to rakkar@jenkinssoftware.com with file and line number\n", file, line); + } +} +void CCRakNetUDT::IncreaseTimeBetweenSends(void) +{ + // In order to converge, bigger numbers have to increase slower and decrease faster + // SND==500 then increment is .02 + // SND==0 then increment is near 0 + // (SND+1.0) brings it to the range of 1 to 501 + // Square the number, which is the range of 1 to 251001 + // Divide by 251001, which is the range of 1/251001 to 1 + + double increment; + increment = .02 * ((SND+1.0) * (SND+1.0)) / (501.0*501.0) ; + // SND=500 then increment=.02 + // SND=0 then increment=near 0 + SND*=(1.02 - increment); + + // SND=0 then fast increase, slow decrease + // SND=500 then slow increase, fast decrease + CapMinSnd(__FILE__,__LINE__); +} +void CCRakNetUDT::DecreaseTimeBetweenSends(void) +{ + double increment; + increment = .01 * ((SND+1.0) * (SND+1.0)) / (501.0*501.0) ; + // SND=500 then increment=.01 + // SND=0 then increment=near 0 + SND*=(.99 - increment); +} +/* +void CCRakNetUDT::SetTimeBetweenSendsLimit(unsigned int bitsPerSecond) +{ +// bitsPerSecond / 1000000 = bitsPerMicrosecond +// bitsPerMicrosecond / 8 = BytesPerMicrosecond +// 1 / BytesPerMicrosecond = MicrosecondsPerByte +// 1 / ( (bitsPerSecond / 1000000) / 8 ) = +// 1 / (bitsPerSecond / 8000000) = +// 8000000 / bitsPerSecond + +#if CC_TIME_TYPE_BYTES==4 + MicrosecondsPerByte limit = (MicrosecondsPerByte) 8000 / (MicrosecondsPerByte)bitsPerSecond; +#else + MicrosecondsPerByte limit = (MicrosecondsPerByte) 8000000 / (MicrosecondsPerByte)bitsPerSecond; +#endif + if (limit > SND) + SND=limit; +} +*/ + +#endif diff --git a/src/raknet/CheckSum.cpp b/src/raknet/CheckSum.cpp new file mode 100644 index 0000000..939e476 --- /dev/null +++ b/src/raknet/CheckSum.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/** +* @file +* @brief CheckSum implementation from http://www.flounder.com/checksum.htm +* +*/ +#include "include/raknet/CheckSum.hpp" + +/**************************************************************************** +* CheckSum::add +* Inputs: +* unsigned int d: word to add +* Result: void +* +* Effect: +* Adds the bytes of the unsigned int to the CheckSum +****************************************************************************/ + +void CheckSum::Add ( unsigned int value ) +{ + union + { + unsigned int value; + unsigned char bytes[ 4 ]; + } + + data; + data.value = value; + + for ( unsigned int i = 0; i < sizeof( data.bytes ); i++ ) + Add ( data.bytes[ i ] ) + + ; +} // CheckSum::add(unsigned int) + +/**************************************************************************** +* CheckSum::add +* Inputs: +* unsigned short value: +* Result: void +* +* Effect: +* Adds the bytes of the unsigned short value to the CheckSum +****************************************************************************/ + +void CheckSum::Add ( unsigned short value ) +{ + union + { + unsigned short value; + unsigned char bytes[ 2 ]; + } + + data; + data.value = value; + + for ( unsigned int i = 0; i < sizeof( data.bytes ); i++ ) + Add ( data.bytes[ i ] ) + + ; +} // CheckSum::add(unsigned short) + +/**************************************************************************** +* CheckSum::add +* Inputs: +* unsigned char value: +* Result: void +* +* Effect: +* Adds the byte to the CheckSum +****************************************************************************/ + +void CheckSum::Add ( unsigned char value ) +{ + unsigned char cipher = (unsigned char)( value ^ ( r >> 8 ) ); + r = ( cipher + r ) * c1 + c2; + sum += cipher; +} // CheckSum::add(unsigned char) + + +/**************************************************************************** +* CheckSum::add +* Inputs: +* LPunsigned char b: pointer to byte array +* unsigned int length: count +* Result: void +* +* Effect: +* Adds the bytes to the CheckSum +****************************************************************************/ + +void CheckSum::Add ( unsigned char *b, unsigned int length ) +{ + for ( unsigned int i = 0; i < length; i++ ) + Add ( b[ i ] ) + + ; +} // CheckSum::add(LPunsigned char, unsigned int) diff --git a/src/raknet/CloudClient.cpp b/src/raknet/CloudClient.cpp new file mode 100644 index 0000000..0932992 --- /dev/null +++ b/src/raknet/CloudClient.cpp @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_CloudClient==1 + +#include "include/raknet/CloudClient.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/RakPeerInterface.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(CloudClient,CloudClient); + +CloudClient::CloudClient() +{ + callback=0; + allocator=&unsetDefaultAllocator; +} +CloudClient::~CloudClient() +{ +} +void CloudClient::SetDefaultCallbacks(CloudAllocator *_allocator, CloudClientCallback *_callback) +{ + callback=_callback; + allocator=_allocator; +} +void CloudClient::Post(CloudKey *cloudKey, const unsigned char *data, uint32_t dataLengthBytes, RakNetGUID systemIdentifier) +{ + RakAssert(cloudKey); + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_POST_REQUEST); + cloudKey->Serialize(true,&bsOut); + if (data==0) + dataLengthBytes=0; + bsOut.Write(dataLengthBytes); + if (dataLengthBytes>0) + bsOut.WriteAlignedBytes((const unsigned char*) data, dataLengthBytes); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); +} +void CloudClient::Release(DataStructures::List &keys, RakNetGUID systemIdentifier) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_RELEASE_REQUEST); + RakAssert(keys.Size() < (uint16_t)-1 ); + bsOut.WriteCasted(keys.Size()); + for (uint16_t i=0; i < keys.Size(); i++) + { + keys[i].Serialize(true,&bsOut); + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); +} +bool CloudClient::Get(CloudQuery *keyQuery, RakNetGUID systemIdentifier) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_GET_REQUEST); + keyQuery->Serialize(true, &bsOut); + bsOut.WriteCasted(0); // Specific systems + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); + return true; +} +bool CloudClient::Get(CloudQuery *keyQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_GET_REQUEST); + keyQuery->Serialize(true, &bsOut); + bsOut.WriteCasted(specificSystems.Size()); + RakAssert(specificSystems.Size() < (uint16_t)-1 ); + for (uint16_t i=0; i < specificSystems.Size(); i++) + { + bsOut.Write(specificSystems[i]); + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); + return true; +} +bool CloudClient::Get(CloudQuery *keyQuery, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_GET_REQUEST); + keyQuery->Serialize(true, &bsOut); + bsOut.WriteCasted(specificSystems.Size()); + RakAssert(specificSystems.Size() < (uint16_t)-1 ); + for (uint16_t i=0; i < specificSystems.Size(); i++) + { + if (specificSystems[i]->clientGUID!=UNASSIGNED_RAKNET_GUID) + { + bsOut.Write(true); + bsOut.Write(specificSystems[i]->clientGUID); + } + else + { + bsOut.Write(false); + bsOut.Write(specificSystems[i]->clientSystemAddress); + } + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); + return true; +} +void CloudClient::Unsubscribe(DataStructures::List &keys, RakNetGUID systemIdentifier) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_UNSUBSCRIBE_REQUEST); + RakAssert(keys.Size() < (uint16_t)-1 ); + bsOut.WriteCasted(keys.Size()); + for (uint16_t i=0; i < keys.Size(); i++) + { + keys[i].Serialize(true,&bsOut); + } + bsOut.WriteCasted(0); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); +} +void CloudClient::Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_UNSUBSCRIBE_REQUEST); + RakAssert(keys.Size() < (uint16_t)-1 ); + bsOut.WriteCasted(keys.Size()); + for (uint16_t i=0; i < keys.Size(); i++) + { + keys[i].Serialize(true,&bsOut); + } + bsOut.WriteCasted(specificSystems.Size()); + RakAssert(specificSystems.Size() < (uint16_t)-1 ); + for (uint16_t i=0; i < specificSystems.Size(); i++) + { + bsOut.Write(specificSystems[i]); + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); +} +void CloudClient::Unsubscribe(DataStructures::List &keys, DataStructures::List &specificSystems, RakNetGUID systemIdentifier) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_UNSUBSCRIBE_REQUEST); + RakAssert(keys.Size() < (uint16_t)-1 ); + bsOut.WriteCasted(keys.Size()); + for (uint16_t i=0; i < keys.Size(); i++) + { + keys[i].Serialize(true,&bsOut); + } + bsOut.WriteCasted(specificSystems.Size()); + RakAssert(specificSystems.Size() < (uint16_t)-1 ); + for (uint16_t i=0; i < specificSystems.Size(); i++) + { + if (specificSystems[i]->clientGUID!=UNASSIGNED_RAKNET_GUID) + { + bsOut.Write(true); + bsOut.Write(specificSystems[i]->clientGUID); + } + else + { + bsOut.Write(false); + bsOut.Write(specificSystems[i]->clientSystemAddress); + } + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, false); +} +PluginReceiveResult CloudClient::OnReceive(Packet *packet) +{ + (void) packet; + + return RR_CONTINUE_PROCESSING; +} +void CloudClient::OnGetReponse(Packet *packet, CloudClientCallback *_callback, CloudAllocator *_allocator) +{ + if (_callback==0) + _callback=callback; + if (_allocator==0) + _allocator=allocator; + + CloudQueryResult cloudQueryResult; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + cloudQueryResult.Serialize(false,&bsIn,_allocator); + bool deallocateRowsAfterReturn=true; + _callback->OnGet(&cloudQueryResult, &deallocateRowsAfterReturn); + if (deallocateRowsAfterReturn) + { + unsigned int i; + for (i=0; i < cloudQueryResult.rowsReturned.Size(); i++) + { + _allocator->DeallocateRowData(cloudQueryResult.rowsReturned[i]->data); + _allocator->DeallocateCloudQueryRow(cloudQueryResult.rowsReturned[i]); + } + } +} +void CloudClient::OnGetReponse(CloudQueryResult *cloudQueryResult, Packet *packet, CloudAllocator *_allocator) +{ + if (_allocator==0) + _allocator=allocator; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + cloudQueryResult->Serialize(false,&bsIn,_allocator); +} +void CloudClient::OnSubscriptionNotification(Packet *packet, CloudClientCallback *_callback, CloudAllocator *_allocator) +{ + if (_callback==0) + _callback=callback; + if (_allocator==0) + _allocator=allocator; + + bool wasUpdated=false; + CloudQueryRow row; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + bsIn.Read(wasUpdated); + row.Serialize(false,&bsIn,_allocator); + bool deallocateRowAfterReturn=true; + _callback->OnSubscriptionNotification(&row, wasUpdated, &deallocateRowAfterReturn); + if (deallocateRowAfterReturn) + { + _allocator->DeallocateRowData(row.data); + } +} +void CloudClient::OnSubscriptionNotification(bool *wasUpdated, CloudQueryRow *row, Packet *packet, CloudAllocator *_allocator) +{ + if (_allocator==0) + _allocator=allocator; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + bool b=false; + bsIn.Read(b); + *wasUpdated=b; + row->Serialize(false,&bsIn,_allocator); +} +void CloudClient::DeallocateWithDefaultAllocator(CloudQueryResult *cloudQueryResult) +{ + unsigned int i; + for (i=0; i < cloudQueryResult->rowsReturned.Size(); i++) + { + allocator->DeallocateRowData(cloudQueryResult->rowsReturned[i]->data); + allocator->DeallocateCloudQueryRow(cloudQueryResult->rowsReturned[i]); + } + + cloudQueryResult->rowsReturned.Clear(false, _FILE_AND_LINE_); + cloudQueryResult->resultKeyIndices.Clear(false, _FILE_AND_LINE_); + cloudQueryResult->cloudQuery.keys.Clear(false, _FILE_AND_LINE_); +} +void CloudClient::DeallocateWithDefaultAllocator(CloudQueryRow *row) +{ + allocator->DeallocateRowData(row->data); +} +#endif diff --git a/src/raknet/CloudCommon.cpp b/src/raknet/CloudCommon.cpp new file mode 100644 index 0000000..4550f46 --- /dev/null +++ b/src/raknet/CloudCommon.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_CloudClient==1 || _RAKNET_SUPPORT_CloudServer==1 + +#include "include/raknet/CloudCommon.hpp" +#include "include/raknet/BitStream.hpp" + +using namespace RakNet; + +int RakNet::CloudKeyComp(const CloudKey &key, const CloudKey &data) +{ + if (key.primaryKey < data.primaryKey) + return -1; + if (key.primaryKey > data.primaryKey) + return 1; + if (key.secondaryKey < data.secondaryKey) + return -1; + if (key.secondaryKey > data.secondaryKey) + return 1; + return 0; +} + +CloudQueryRow* CloudAllocator::AllocateCloudQueryRow(void) +{ + return RakNet::OP_NEW(_FILE_AND_LINE_); +} +void CloudAllocator::DeallocateCloudQueryRow(CloudQueryRow *row) +{ + RakNet::OP_DELETE(row,_FILE_AND_LINE_); +} +unsigned char *CloudAllocator::AllocateRowData(uint32_t bytesNeededForData) +{ + return (unsigned char*) rakMalloc_Ex(bytesNeededForData,_FILE_AND_LINE_); +} +void CloudAllocator::DeallocateRowData(void *data) +{ + rakFree_Ex(data, _FILE_AND_LINE_); +} +void CloudKey::Serialize(bool writeToBitstream, BitStream *bitStream) +{ + bitStream->Serialize(writeToBitstream, primaryKey); + bitStream->Serialize(writeToBitstream, secondaryKey); +} +void CloudQuery::Serialize(bool writeToBitstream, BitStream *bitStream) +{ + bool startingRowIndexIsZero=0; + bool maxRowsToReturnIsZero=0; + startingRowIndexIsZero=startingRowIndex==0; + maxRowsToReturnIsZero=maxRowsToReturn==0; + bitStream->Serialize(writeToBitstream,startingRowIndexIsZero); + bitStream->Serialize(writeToBitstream,maxRowsToReturnIsZero); + bitStream->Serialize(writeToBitstream,subscribeToResults); + if (startingRowIndexIsZero==false) + bitStream->Serialize(writeToBitstream,startingRowIndex); + if (maxRowsToReturnIsZero==false) + bitStream->Serialize(writeToBitstream,maxRowsToReturn); + RakAssert(keys.Size()<(uint16_t)-1); + uint16_t numKeys = (uint16_t) keys.Size(); + bitStream->Serialize(writeToBitstream,numKeys); + if (writeToBitstream) + { + for (uint16_t i=0; i < numKeys; i++) + { + keys[i].Serialize(true,bitStream); + } + } + else + { + CloudKey cmdk; + for (uint16_t i=0; i < numKeys; i++) + { + cmdk.Serialize(false,bitStream); + keys.Push(cmdk, _FILE_AND_LINE_); + } + } +} +void CloudQueryRow::Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator) +{ + key.Serialize(writeToBitstream,bitStream); + bitStream->Serialize(writeToBitstream,serverSystemAddress); + bitStream->Serialize(writeToBitstream,clientSystemAddress); + bitStream->Serialize(writeToBitstream,serverGUID); + bitStream->Serialize(writeToBitstream,clientGUID); + bitStream->Serialize(writeToBitstream,length); + if (writeToBitstream) + { + bitStream->WriteAlignedBytes((const unsigned char*) data,length); + } + else + { + if (length>0) + { + data = allocator->AllocateRowData(length); + if (data) + { + bitStream->ReadAlignedBytes((unsigned char *) data,length); + } + else + { + notifyOutOfMemory(_FILE_AND_LINE_); + } + } + else + data=0; + } +} +void CloudQueryResult::SerializeHeader(bool writeToBitstream, BitStream *bitStream) +{ + cloudQuery.Serialize(writeToBitstream,bitStream); + bitStream->Serialize(writeToBitstream,subscribeToResults); +} +void CloudQueryResult::SerializeNumRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream) +{ + bitStream->Serialize(writeToBitstream,numRows); +} +void CloudQueryResult::SerializeCloudQueryRows(bool writeToBitstream, uint32_t &numRows, BitStream *bitStream, CloudAllocator *allocator) +{ + if (writeToBitstream) + { + for (uint16_t i=0; i < numRows; i++) + { + rowsReturned[i]->Serialize(true,bitStream, allocator); + } + } + else + { + CloudQueryRow* cmdr; + for (uint16_t i=0; i < numRows; i++) + { + cmdr = allocator->AllocateCloudQueryRow(); + if (cmdr) + { + cmdr->Serialize(false,bitStream,allocator); + if (cmdr->data==0 && cmdr->length>0) + { + allocator->DeallocateCloudQueryRow(cmdr); + notifyOutOfMemory(_FILE_AND_LINE_); + numRows=i; + return; + } + rowsReturned.Push(cmdr, _FILE_AND_LINE_); + } + else + { + notifyOutOfMemory(_FILE_AND_LINE_); + numRows=i; + return; + } + } + } +} +void CloudQueryResult::Serialize(bool writeToBitstream, BitStream *bitStream, CloudAllocator *allocator) +{ + SerializeHeader(writeToBitstream, bitStream); + uint32_t numRows = (uint32_t) rowsReturned.Size(); + SerializeNumRows(writeToBitstream, numRows, bitStream); + SerializeCloudQueryRows(writeToBitstream, numRows, bitStream, allocator); +} + +#endif // #if _RAKNET_SUPPORT_CloudMemoryClient==1 || _RAKNET_SUPPORT_CloudMemoryServer==1 diff --git a/src/raknet/CloudServer.cpp b/src/raknet/CloudServer.cpp new file mode 100644 index 0000000..b7cf4a0 --- /dev/null +++ b/src/raknet/CloudServer.cpp @@ -0,0 +1,1685 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_CloudServer==1 + +#include "include/raknet/CloudServer.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/RakPeerInterface.hpp" + +enum ServerToServerCommands +{ + STSC_PROCESS_GET_REQUEST, + STSC_PROCESS_GET_RESPONSE, + STSC_ADD_UPLOADED_AND_SUBSCRIBED_KEYS, + STSC_ADD_UPLOADED_KEY, + STSC_ADD_SUBSCRIBED_KEY, + STSC_REMOVE_UPLOADED_KEY, + STSC_REMOVE_SUBSCRIBED_KEY, + STSC_DATA_CHANGED, +}; + +using namespace RakNet; + +int CloudServer::RemoteServerComp(const RakNetGUID &key, RemoteServer* const &data ) +{ + if (key < data->serverAddress) + return -1; + if (key > data->serverAddress) + return 1; + return 0; +} +int CloudServer::KeySubscriberIDComp(const CloudKey &key, KeySubscriberID * const &data ) +{ + if (key.primaryKey < data->key.primaryKey) + return -1; + if (key.primaryKey > data->key.primaryKey) + return 1; + if (key.secondaryKey < data->key.secondaryKey) + return -1; + if (key.secondaryKey > data->key.secondaryKey) + return 1; + return 0; +} +int CloudServer::KeyDataPtrComp( const RakNetGUID &key, CloudData* const &data ) +{ + if (key < data->clientGUID) + return -1; + if (key > data->clientGUID) + return 1; + return 0; +} +int CloudServer::KeyDataListComp( const CloudKey &key, CloudDataList * const &data ) +{ + if (key.primaryKey < data->key.primaryKey) + return -1; + if (key.primaryKey > data->key.primaryKey) + return 1; + if (key.secondaryKey < data->key.secondaryKey) + return -1; + if (key.secondaryKey > data->key.secondaryKey) + return 1; + return 0; +} +int CloudServer::BufferedGetResponseFromServerComp(const RakNetGUID &key, CloudServer::BufferedGetResponseFromServer* const &data ) +{ + if (key < data->serverAddress) + return -1; + if (key > data->serverAddress) + return 1; + return 0; +} +int CloudServer::GetRequestComp(const uint32_t &key, CloudServer::GetRequest* const &data ) +{ + if (key < data->requestId) + return -1; + if (key > data->requestId) + return -1; + return 0; +} +void CloudServer::CloudQueryWithAddresses::Serialize(bool writeToBitstream, BitStream *bitStream) +{ + cloudQuery.Serialize(writeToBitstream, bitStream); + + if (writeToBitstream) + { + bitStream->WriteCasted(specificSystems.Size()); + RakAssert(specificSystems.Size() < (uint16_t)-1 ); + for (uint16_t i=0; i < specificSystems.Size(); i++) + { + bitStream->Write(specificSystems[i]); + } + } + else + { + uint16_t specificSystemsCount; + RakNetGUID addressOrGuid; + bitStream->Read(specificSystemsCount); + for (uint16_t i=0; i < specificSystemsCount; i++) + { + bitStream->Read(addressOrGuid); + specificSystems.Push(addressOrGuid, _FILE_AND_LINE_); + } + } +} +bool CloudServer::GetRequest::AllRemoteServersHaveResponded(void) const +{ + unsigned int i; + for (i=0; i < remoteServerResponses.Size(); i++) + if (remoteServerResponses[i]->gotResult==false) + return false; + return true; +} +void CloudServer::GetRequest::Clear(CloudAllocator *allocator) +{ + unsigned int i; + for (i=0; i < remoteServerResponses.Size(); i++) + { + remoteServerResponses[i]->Clear(allocator); + RakNet::OP_DELETE(remoteServerResponses[i], _FILE_AND_LINE_); + } + remoteServerResponses.Clear(false, _FILE_AND_LINE_); +} +void CloudServer::BufferedGetResponseFromServer::Clear(CloudAllocator *allocator) +{ + unsigned int i; + for (i=0; i < queryResult.rowsReturned.Size(); i++) + { + allocator->DeallocateRowData(queryResult.rowsReturned[i]->data); + allocator->DeallocateCloudQueryRow(queryResult.rowsReturned[i]); + } + queryResult.rowsReturned.Clear(false, _FILE_AND_LINE_); +} +CloudServer::CloudServer() +{ + maxUploadBytesPerClient=0; + maxBytesPerDowload=0; + nextGetRequestId=0; + nextGetRequestsCheck=0; +} +CloudServer::~CloudServer() +{ + Clear(); +} +void CloudServer::SetMaxUploadBytesPerClient(uint64_t bytes) +{ + maxUploadBytesPerClient=bytes; +} +void CloudServer::SetMaxBytesPerDownload(uint64_t bytes) +{ + maxBytesPerDowload=bytes; +} +void CloudServer::Update(void) +{ + // Timeout getRequests + RakNet::Time time = RakNet::Time(); + if (time > nextGetRequestsCheck) + { + nextGetRequestsCheck=time+1000; + + unsigned int i=0; + while (i < getRequests.Size()) + { + if (time - getRequests[i]->requestStartTime > 3000) + { + // Remote server is not responding, just send back data with whoever did respond + ProcessAndTransmitGetRequest(getRequests[i]); + getRequests[i]->Clear(this); + RakNet::OP_DELETE(getRequests[i],_FILE_AND_LINE_); + getRequests.RemoveAtIndex(i); + } + else + { + i++; + } + } + } +} +PluginReceiveResult CloudServer::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_CLOUD_POST_REQUEST: + OnPostRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_CLOUD_RELEASE_REQUEST: + OnReleaseRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_CLOUD_GET_REQUEST: + OnGetRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_CLOUD_UNSUBSCRIBE_REQUEST: + OnUnsubscribeRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_CLOUD_SERVER_TO_SERVER_COMMAND: + if (packet->length>1) + { + switch (packet->data[1]) + { + case STSC_PROCESS_GET_REQUEST: + OnServerToServerGetRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case STSC_PROCESS_GET_RESPONSE: + OnServerToServerGetResponse(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case STSC_ADD_UPLOADED_AND_SUBSCRIBED_KEYS: + OnSendUploadedAndSubscribedKeysToServer(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case STSC_ADD_UPLOADED_KEY: + OnSendUploadedKeyToServers(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case STSC_ADD_SUBSCRIBED_KEY: + OnSendSubscribedKeyToServers(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case STSC_REMOVE_UPLOADED_KEY: + OnRemoveUploadedKeyFromServers(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case STSC_REMOVE_SUBSCRIBED_KEY: + OnRemoveSubscribedKeyFromServers(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case STSC_DATA_CHANGED: + OnServerDataChanged(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + return RR_CONTINUE_PROCESSING; +} +void CloudServer::OnPostRequest(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + CloudKey key; + key.Serialize(false,&bsIn); + uint32_t dataLengthBytes; + bsIn.Read(dataLengthBytes); + if (maxUploadBytesPerClient>0 && dataLengthBytes>maxUploadBytesPerClient) + return; // Exceeded max upload bytes + + bsIn.AlignReadToByteBoundary(); + for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) + { + if (queryFilters[filterIndex]->OnPostRequest(packet->guid, packet->systemAddress, key, dataLengthBytes, (const char*) bsIn.GetData()+BITS_TO_BYTES(bsIn.GetReadOffset()))==false) + return; + } + + unsigned char *data; + if (dataLengthBytes>CLOUD_SERVER_DATA_STACK_SIZE) + { + data = (unsigned char *) rakMalloc_Ex(dataLengthBytes,_FILE_AND_LINE_); + if (data==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + return; + } + bsIn.ReadAlignedBytes(data,dataLengthBytes); + } + else + data=0; + + // Add this system to remoteSystems if they aren't there already + DataStructures::HashIndex remoteSystemsHashIndex = remoteSystems.GetIndexOf(packet->guid); + RemoteCloudClient *remoteCloudClient; + if (remoteSystemsHashIndex.IsInvalid()) + { + remoteCloudClient = RakNet::OP_NEW(_FILE_AND_LINE_); + remoteCloudClient->uploadedKeys.Insert(key,key,true,_FILE_AND_LINE_); + remoteCloudClient->uploadedBytes=0; + remoteSystems.Push(packet->guid, remoteCloudClient, _FILE_AND_LINE_); + } + else + { + remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemsHashIndex); + bool objectExists; + // Add to RemoteCloudClient::uploadedKeys if it isn't there already + unsigned int uploadedKeysIndex = remoteCloudClient->uploadedKeys.GetIndexFromKey(key,&objectExists); + if (objectExists==false) + { + remoteCloudClient->uploadedKeys.InsertAtIndex(key, uploadedKeysIndex, _FILE_AND_LINE_); + } + } + + bool cloudDataAlreadyUploaded; + unsigned int dataRepositoryIndex; + bool dataRepositoryExists; + CloudDataList* cloudDataList = GetOrAllocateCloudDataList(key, &dataRepositoryExists, dataRepositoryIndex); + if (dataRepositoryExists==false) + { + cloudDataList->uploaderCount=1; + cloudDataAlreadyUploaded=false; + } + else + { + cloudDataAlreadyUploaded=cloudDataList->uploaderCount>0; + cloudDataList->uploaderCount++; + } + + CloudData *cloudData; + bool keyDataListExists; + unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(packet->guid, &keyDataListExists); + if (keyDataListExists==false) + { + if (maxUploadBytesPerClient>0 && remoteCloudClient->uploadedBytes+dataLengthBytes>maxUploadBytesPerClient) + { + // Undo prior insertion of cloudDataList into cloudData if needed + if (keyDataListExists==false) + { + RakNet::OP_DELETE(cloudDataList,_FILE_AND_LINE_); + dataRepository.RemoveAtIndex(dataRepositoryIndex); + } + + if (remoteCloudClient->IsUnused()) + { + RakNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); + remoteSystems.Remove(packet->guid, _FILE_AND_LINE_); + } + + if (dataLengthBytes>CLOUD_SERVER_DATA_STACK_SIZE) + rakFree_Ex(data, _FILE_AND_LINE_); + + return; + } + + cloudData = RakNet::OP_NEW(_FILE_AND_LINE_); + cloudData->dataLengthBytes=dataLengthBytes; + cloudData->isUploaded=true; + if (forceAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + cloudData->serverSystemAddress=forceAddress; + cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetExternalID(packet->systemAddress).GetPort()); + } + else + { + cloudData->serverSystemAddress=rakPeerInterface->GetExternalID(packet->systemAddress); + if (cloudData->serverSystemAddress.IsLoopback()) + cloudData->serverSystemAddress.FromString(rakPeerInterface->GetLocalIP(0)); + } + if (cloudData->serverSystemAddress.GetPort()==0) + { + // Fix localhost port + cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetSocket(UNASSIGNED_SYSTEM_ADDRESS)->GetBoundAddress().GetPort()); + } + cloudData->clientSystemAddress=packet->systemAddress; + cloudData->serverGUID=rakPeerInterface->GetMyGUID(); + cloudData->clientGUID=packet->guid; + cloudDataList->keyData.Insert(packet->guid,cloudData,true,_FILE_AND_LINE_); + } + else + { + cloudData = cloudDataList->keyData[keyDataListIndex]; + + if (cloudDataAlreadyUploaded==false) + { + if (forceAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + cloudData->serverSystemAddress=forceAddress; + cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetExternalID(packet->systemAddress).GetPort()); + } + else + { + cloudData->serverSystemAddress=rakPeerInterface->GetExternalID(packet->systemAddress); + } + if (cloudData->serverSystemAddress.GetPort()==0) + { + // Fix localhost port + cloudData->serverSystemAddress.SetPortHostOrder(rakPeerInterface->GetSocket(UNASSIGNED_SYSTEM_ADDRESS)->GetBoundAddress().GetPort()); + } + + cloudData->clientSystemAddress=packet->systemAddress; + } + + if (maxUploadBytesPerClient>0 && remoteCloudClient->uploadedBytes-cloudData->dataLengthBytes+dataLengthBytes>maxUploadBytesPerClient) + { + // Undo prior insertion of cloudDataList into cloudData if needed + if (dataRepositoryExists==false) + { + RakNet::OP_DELETE(cloudDataList,_FILE_AND_LINE_); + dataRepository.RemoveAtIndex(dataRepositoryIndex); + } + return; + } + else + { + // Subtract already used bytes we are overwriting + remoteCloudClient->uploadedBytes-=cloudData->dataLengthBytes; + } + + if (cloudData->allocatedData!=0) + rakFree_Ex(cloudData->allocatedData,_FILE_AND_LINE_); + } + + if (dataLengthBytes>CLOUD_SERVER_DATA_STACK_SIZE) + { + // Data already allocated + cloudData->allocatedData=data; + cloudData->dataPtr=data; + } + else + { + // Read to stack + if (dataLengthBytes>0) + bsIn.ReadAlignedBytes(cloudData->stackData,dataLengthBytes); + cloudData->allocatedData=0; + cloudData->dataPtr=cloudData->stackData; + } + // Update how many bytes were written for this data + cloudData->dataLengthBytes=dataLengthBytes; + remoteCloudClient->uploadedBytes+=dataLengthBytes; + + if (cloudDataAlreadyUploaded==false) + { + // New data field + SendUploadedKeyToServers(cloudDataList->key); + } + + // Existing data field changed + NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudData->specificSubscribers, true ); + NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudDataList->nonSpecificSubscribers, true ); + + // Send update to all remote servers that subscribed to this key + NotifyServerSubscribersOfDataChange(cloudData, cloudDataList->key, true); + + // I could have also subscribed to a key not yet updated locally + // This means I have to go through every RemoteClient that wants this key + // Seems like cloudData->specificSubscribers is unnecessary in that case +} +void CloudServer::OnReleaseRequest(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + + uint16_t keyCount; + bsIn.Read(keyCount); + + if (keyCount==0) + return; + + DataStructures::HashIndex remoteSystemIndex = remoteSystems.GetIndexOf(packet->guid); + if (remoteSystemIndex.IsInvalid()==true) + return; + + RemoteCloudClient* remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemIndex); + + CloudKey key; + + // Read all in a list first so I can run filter on it + DataStructures::List cloudKeys; + for (uint16_t keyCountIndex=0; keyCountIndex < keyCount; keyCountIndex++) + { + key.Serialize(false, &bsIn); + cloudKeys.Push(key, _FILE_AND_LINE_); + } + + for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) + { + if (queryFilters[filterIndex]->OnReleaseRequest(packet->guid, packet->systemAddress, cloudKeys)==false) + return; + } + + for (uint16_t keyCountIndex=0; keyCountIndex < keyCount; keyCountIndex++) + { + // Serialize in list above so I can run the filter on it + // key.Serialize(false, &bsIn); + key=cloudKeys[keyCountIndex]; + + // Remove remote systems uploaded keys + bool objectExists; + unsigned int uploadedKeysIndex = remoteCloudClient->uploadedKeys.GetIndexFromKey(key,&objectExists); + if (objectExists) + { + bool dataRepositoryExists; + unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(key, &dataRepositoryExists); + CloudDataList* cloudDataList = dataRepository[dataRepositoryIndex]; + RakAssert(cloudDataList); + + CloudData *cloudData; + bool keyDataListExists; + unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(packet->guid, &keyDataListExists); + cloudData = cloudDataList->keyData[keyDataListIndex]; + + remoteCloudClient->uploadedKeys.RemoveAtIndex(uploadedKeysIndex); + remoteCloudClient->uploadedBytes-=cloudData->dataLengthBytes; + cloudDataList->uploaderCount--; + + // Broadcast destruction of this key to subscribers + NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudData->specificSubscribers, false ); + NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudDataList->nonSpecificSubscribers, false ); + NotifyServerSubscribersOfDataChange(cloudData, cloudDataList->key, false ); + + cloudData->Clear(); + + if (cloudData->IsUnused()) + { + RakNet::OP_DELETE(cloudData, _FILE_AND_LINE_); + cloudDataList->keyData.RemoveAtIndex(keyDataListIndex); + if (cloudDataList->IsNotUploaded()) + { + // Tell other servers that this key is no longer uploaded, so they do not request it from us + RemoveUploadedKeyFromServers(cloudDataList->key); + } + + if (cloudDataList->IsUnused()) + { + RakNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); + dataRepository.RemoveAtIndex(dataRepositoryIndex); + } + } + + if (remoteCloudClient->IsUnused()) + { + RakNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); + remoteSystems.RemoveAtIndex(remoteSystemIndex, _FILE_AND_LINE_); + break; + } + } + } +} +void CloudServer::OnGetRequest(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + uint16_t specificSystemsCount; + CloudKey cloudKey; + + // Create a new GetRequest + GetRequest *getRequest; + getRequest = RakNet::OP_NEW(_FILE_AND_LINE_); + getRequest->cloudQueryWithAddresses.cloudQuery.Serialize(false, &bsIn); + getRequest->requestingClient=packet->guid; + + RakNetGUID addressOrGuid; + bsIn.Read(specificSystemsCount); + for (uint16_t i=0; i < specificSystemsCount; i++) + { + bsIn.Read(addressOrGuid); + getRequest->cloudQueryWithAddresses.specificSystems.Push(addressOrGuid, _FILE_AND_LINE_); + } + + if (getRequest->cloudQueryWithAddresses.cloudQuery.keys.Size()==0) + { + RakNet::OP_DELETE(getRequest, _FILE_AND_LINE_); + return; + } + + for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) + { + if (queryFilters[filterIndex]->OnGetRequest(packet->guid, packet->systemAddress, getRequest->cloudQueryWithAddresses.cloudQuery, getRequest->cloudQueryWithAddresses.specificSystems )==false) + return; + } + + getRequest->requestStartTime=RakNet::GetTime(); + getRequest->requestId=nextGetRequestId++; + + // Send request to servers that have this data + DataStructures::List remoteServersWithData; + GetServersWithUploadedKeys(getRequest->cloudQueryWithAddresses.cloudQuery.keys, remoteServersWithData); + + if (remoteServersWithData.Size()==0) + { + ProcessAndTransmitGetRequest(getRequest); + } + else + { + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_PROCESS_GET_REQUEST); + getRequest->cloudQueryWithAddresses.Serialize(true, &bsOut); + bsOut.Write(getRequest->requestId); + + for (unsigned int remoteServerIndex=0; remoteServerIndex < remoteServersWithData.Size(); remoteServerIndex++) + { + BufferedGetResponseFromServer* bufferedGetResponseFromServer = RakNet::OP_NEW(_FILE_AND_LINE_); + bufferedGetResponseFromServer->serverAddress=remoteServersWithData[remoteServerIndex]->serverAddress; + bufferedGetResponseFromServer->gotResult=false; + getRequest->remoteServerResponses.Insert(remoteServersWithData[remoteServerIndex]->serverAddress, bufferedGetResponseFromServer, true, _FILE_AND_LINE_); + + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, remoteServersWithData[remoteServerIndex]->serverAddress, false); + } + + // Record that this system made this request + getRequests.Insert(getRequest->requestId, getRequest, true, _FILE_AND_LINE_); + } + + if (getRequest->cloudQueryWithAddresses.cloudQuery.subscribeToResults) + { + // Add to key subscription list for the client, which contains a keyId / specificUploaderList pair + DataStructures::HashIndex remoteSystemsHashIndex = remoteSystems.GetIndexOf(packet->guid); + RemoteCloudClient *remoteCloudClient; + if (remoteSystemsHashIndex.IsInvalid()) + { + remoteCloudClient = RakNet::OP_NEW(_FILE_AND_LINE_); + remoteCloudClient->uploadedBytes=0; + remoteSystems.Push(packet->guid, remoteCloudClient, _FILE_AND_LINE_); + } + else + { + remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemsHashIndex); + } + + unsigned int keyIndex; + for (keyIndex=0; keyIndex < getRequest->cloudQueryWithAddresses.cloudQuery.keys.Size(); keyIndex++) + { + cloudKey = getRequest->cloudQueryWithAddresses.cloudQuery.keys[keyIndex]; + + unsigned int keySubscriberIndex; + bool hasKeySubscriber; + keySubscriberIndex = remoteCloudClient->subscribedKeys.GetIndexFromKey(cloudKey, &hasKeySubscriber); + KeySubscriberID* keySubscriberId; + if (hasKeySubscriber) + { + DataStructures::List specificSystems; + UnsubscribeFromKey(remoteCloudClient, packet->guid, keySubscriberIndex, cloudKey, specificSystems); + } + + keySubscriberId = RakNet::OP_NEW(_FILE_AND_LINE_); + keySubscriberId->key=cloudKey; + + unsigned int specificSystemIndex; + for (specificSystemIndex=0; specificSystemIndex < getRequest->cloudQueryWithAddresses.specificSystems.Size(); specificSystemIndex++) + { + keySubscriberId->specificSystemsSubscribedTo.Insert(getRequest->cloudQueryWithAddresses.specificSystems[specificSystemIndex], getRequest->cloudQueryWithAddresses.specificSystems[specificSystemIndex], true, _FILE_AND_LINE_); + } + + remoteCloudClient->subscribedKeys.InsertAtIndex(keySubscriberId, keySubscriberIndex, _FILE_AND_LINE_); + + // Add CloudData in a similar way + unsigned int dataRepositoryIndex; + bool dataRepositoryExists; + CloudDataList* cloudDataList = GetOrAllocateCloudDataList(cloudKey, &dataRepositoryExists, dataRepositoryIndex); + + // If this is the first local client to subscribe to this key, call SendSubscribedKeyToServers + if (cloudDataList->subscriberCount==0) + SendSubscribedKeyToServers(cloudKey); + + // If the subscription is specific, may have to also allocate CloudData + if (getRequest->cloudQueryWithAddresses.specificSystems.Size()) + { + CloudData *cloudData; + bool keyDataListExists; + + unsigned int specificSystemIndex; + for (specificSystemIndex=0; specificSystemIndex < getRequest->cloudQueryWithAddresses.specificSystems.Size(); specificSystemIndex++) + { + RakNetGUID specificSystem = getRequest->cloudQueryWithAddresses.specificSystems[specificSystemIndex]; + + unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(specificSystem, &keyDataListExists); + if (keyDataListExists==false) + { + cloudData = RakNet::OP_NEW(_FILE_AND_LINE_); + cloudData->dataLengthBytes=0; + cloudData->allocatedData=0; + cloudData->isUploaded=false; + cloudData->dataPtr=0; + cloudData->serverSystemAddress=UNASSIGNED_SYSTEM_ADDRESS; + cloudData->clientSystemAddress=UNASSIGNED_SYSTEM_ADDRESS; + cloudData->serverGUID=rakPeerInterface->GetMyGUID(); + cloudData->clientGUID=specificSystem; + cloudDataList->keyData.Insert(specificSystem,cloudData,true,_FILE_AND_LINE_); + } + else + { + cloudData = cloudDataList->keyData[keyDataListIndex]; + } + + ++cloudDataList->subscriberCount; + cloudData->specificSubscribers.Insert(packet->guid, packet->guid, true, _FILE_AND_LINE_); + } + } + else + { + ++cloudDataList->subscriberCount; + cloudDataList->nonSpecificSubscribers.Insert(packet->guid, packet->guid, true, _FILE_AND_LINE_); + + // Remove packet->guid from CloudData::specificSubscribers among all instances of cloudDataList->keyData + unsigned int subscribedKeysIndex; + bool subscribedKeysIndexExists; + subscribedKeysIndex = remoteCloudClient->subscribedKeys.GetIndexFromKey(cloudDataList->key, &subscribedKeysIndexExists); + if (subscribedKeysIndexExists) + { + KeySubscriberID* keySubscriberId; + keySubscriberId = remoteCloudClient->subscribedKeys[subscribedKeysIndex]; + unsigned int specificSystemIndex; + for (specificSystemIndex=0; specificSystemIndex < keySubscriberId->specificSystemsSubscribedTo.Size(); specificSystemIndex++) + { + bool keyDataExists; + unsigned int keyDataIndex = cloudDataList->keyData.GetIndexFromKey(keySubscriberId->specificSystemsSubscribedTo[specificSystemIndex], &keyDataExists); + if (keyDataExists) + { + CloudData *keyData = cloudDataList->keyData[keyDataIndex]; + keyData->specificSubscribers.Remove(packet->guid); + --cloudDataList->subscriberCount; + } + } + } + } + } + + if (remoteCloudClient->subscribedKeys.Size()==0) + { + // Didn't do anything + remoteSystems.Remove(packet->guid, _FILE_AND_LINE_); + RakNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); + } + } + + if (remoteServersWithData.Size()==0) + RakNet::OP_DELETE(getRequest, _FILE_AND_LINE_); +} +void CloudServer::OnUnsubscribeRequest(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + + DataStructures::HashIndex remoteSystemIndex = remoteSystems.GetIndexOf(packet->guid); + if (remoteSystemIndex.IsInvalid()==true) + return; + + RemoteCloudClient* remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemIndex); + + uint16_t keyCount, specificSystemCount; + DataStructures::List cloudKeys; + DataStructures::List specificSystems; + uint16_t index; + + CloudKey cloudKey; + bsIn.Read(keyCount); + for (index=0; index < keyCount; index++) + { + cloudKey.Serialize(false, &bsIn); + cloudKeys.Push(cloudKey, _FILE_AND_LINE_); + } + + RakNetGUID specificSystem; + bsIn.Read(specificSystemCount); + for (index=0; index < specificSystemCount; index++) + { + bsIn.Read(specificSystem); + specificSystems.Push(specificSystem, _FILE_AND_LINE_); + } + + for (unsigned int filterIndex=0; filterIndex < queryFilters.Size(); filterIndex++) + { + if (queryFilters[filterIndex]->OnUnsubscribeRequest(packet->guid, packet->systemAddress, cloudKeys, specificSystems )==false) + return; + } + +// CloudDataList *cloudDataList; + bool dataRepositoryExists; +// unsigned int dataRepositoryIndex; + + for (index=0; index < keyCount; index++) + { + CloudKey cloudKey = cloudKeys[index]; + + // dataRepositoryIndex = + dataRepository.GetIndexFromKey(cloudKey, &dataRepositoryExists); + if (dataRepositoryExists==false) + continue; +// cloudDataList = dataRepository[dataRepositoryIndex]; + + unsigned int keySubscriberIndex; + bool hasKeySubscriber; + keySubscriberIndex = remoteCloudClient->subscribedKeys.GetIndexFromKey(cloudKey, &hasKeySubscriber); + + if (hasKeySubscriber==false) + continue; + + UnsubscribeFromKey(remoteCloudClient, packet->guid, keySubscriberIndex, cloudKey, specificSystems); + } + + if (remoteCloudClient->IsUnused()) + { + RakNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); + remoteSystems.RemoveAtIndex(remoteSystemIndex, _FILE_AND_LINE_); + } +} +void CloudServer::OnServerToServerGetRequest(Packet *packet) +{ +// unsigned int remoteServerIndex; + bool objectExists; + //remoteServerIndex = + remoteServers.GetIndexFromKey(packet->guid, &objectExists); + if (objectExists==false) + return; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + CloudQueryWithAddresses cloudQueryWithAddresses; + uint32_t requestId; + cloudQueryWithAddresses.Serialize(false, &bsIn); + bsIn.Read(requestId); + + DataStructures::List cloudDataResultList; + DataStructures::List cloudKeyResultList; + ProcessCloudQueryWithAddresses(cloudQueryWithAddresses, cloudDataResultList, cloudKeyResultList); + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_PROCESS_GET_RESPONSE); + bsOut.Write(requestId); + WriteCloudQueryRowFromResultList(cloudDataResultList, cloudKeyResultList, &bsOut); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); +} +void CloudServer::OnServerToServerGetResponse(Packet *packet) +{ + unsigned int remoteServerIndex; + bool objectExists; + remoteServerIndex = remoteServers.GetIndexFromKey(packet->guid, &objectExists); + if (objectExists==false) + return; + + RemoteServer *remoteServer = remoteServers[remoteServerIndex]; + if (remoteServer==0) + return; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + uint32_t requestId; + bsIn.Read(requestId); + + // Lookup request id + bool hasGetRequest; + unsigned int getRequestIndex; + getRequestIndex = getRequests.GetIndexFromKey(requestId, &hasGetRequest); + if (hasGetRequest==false) + return; + GetRequest *getRequest = getRequests[getRequestIndex]; + bool hasRemoteServer; + unsigned int remoteServerResponsesIndex; + remoteServerResponsesIndex = getRequest->remoteServerResponses.GetIndexFromKey(packet->guid, &hasRemoteServer); + if (hasRemoteServer==false) + return; + BufferedGetResponseFromServer *bufferedGetResponseFromServer; + bufferedGetResponseFromServer = getRequest->remoteServerResponses[remoteServerResponsesIndex]; + if (bufferedGetResponseFromServer->gotResult==true) + return; + bufferedGetResponseFromServer->gotResult=true; + uint32_t numRows; + bufferedGetResponseFromServer->queryResult.SerializeNumRows(false, numRows, &bsIn); + bufferedGetResponseFromServer->queryResult.SerializeCloudQueryRows(false, numRows, &bsIn, this); + + // If all results returned, then also process locally, and return to user + if (getRequest->AllRemoteServersHaveResponded()) + { + ProcessAndTransmitGetRequest(getRequest); + + getRequest->Clear(this); + RakNet::OP_DELETE(getRequest, _FILE_AND_LINE_); + + getRequests.RemoveAtIndex(getRequestIndex); + } +} +void CloudServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + + unsigned int remoteServerIndex; + bool objectExists; + remoteServerIndex = remoteServers.GetIndexFromKey(rakNetGUID, &objectExists); + if (objectExists) + { + // Update remoteServerResponses by removing this server and sending the response if it is now complete + unsigned int getRequestIndex=0; + while (getRequestIndex < getRequests.Size()) + { + GetRequest *getRequest = getRequests[getRequestIndex]; + bool waitingForThisServer; + unsigned int remoteServerResponsesIndex = getRequest->remoteServerResponses.GetIndexFromKey(rakNetGUID, &waitingForThisServer); + if (waitingForThisServer) + { + getRequest->remoteServerResponses[remoteServerResponsesIndex]->Clear(this); + RakNet::OP_DELETE(getRequest->remoteServerResponses[remoteServerResponsesIndex], _FILE_AND_LINE_); + getRequest->remoteServerResponses.RemoveAtIndex(remoteServerResponsesIndex); + + if (getRequest->AllRemoteServersHaveResponded()) + { + ProcessAndTransmitGetRequest(getRequest); + getRequest->Clear(this); + RakNet::OP_DELETE(getRequest, _FILE_AND_LINE_); + + getRequests.RemoveAtIndex(getRequestIndex); + } + else + getRequestIndex++; + } + else + getRequestIndex++; + } + + RakNet::OP_DELETE(remoteServers[remoteServerIndex],_FILE_AND_LINE_); + remoteServers.RemoveAtIndex(remoteServerIndex); + } + + DataStructures::HashIndex remoteSystemIndex = remoteSystems.GetIndexOf(rakNetGUID); + if (remoteSystemIndex.IsInvalid()==false) + { + RemoteCloudClient* remoteCloudClient = remoteSystems.ItemAtIndex(remoteSystemIndex); + unsigned int uploadedKeysIndex; + for (uploadedKeysIndex=0; uploadedKeysIndex < remoteCloudClient->uploadedKeys.Size(); uploadedKeysIndex++) + { + // Delete keys this system has uploaded + bool keyDataRepositoryExists; + unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(remoteCloudClient->uploadedKeys[uploadedKeysIndex], &keyDataRepositoryExists); + if (keyDataRepositoryExists) + { + CloudDataList* cloudDataList = dataRepository[dataRepositoryIndex]; + bool keyDataExists; + unsigned int keyDataIndex = cloudDataList->keyData.GetIndexFromKey(rakNetGUID, &keyDataExists); + if (keyDataExists) + { + CloudData *cloudData = cloudDataList->keyData[keyDataIndex]; + cloudDataList->uploaderCount--; + + NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudData->specificSubscribers, false ); + NotifyClientSubscribersOfDataChange(cloudData, cloudDataList->key, cloudDataList->nonSpecificSubscribers, false ); + NotifyServerSubscribersOfDataChange(cloudData, cloudDataList->key, false ); + + cloudData->Clear(); + + if (cloudData->IsUnused()) + { + RakNet::OP_DELETE(cloudData,_FILE_AND_LINE_); + cloudDataList->keyData.RemoveAtIndex(keyDataIndex); + + if (cloudDataList->IsNotUploaded()) + { + // Tell other servers that this key is no longer uploaded, so they do not request it from us + RemoveUploadedKeyFromServers(cloudDataList->key); + } + + if (cloudDataList->IsUnused()) + { + // Tell other servers that this key is no longer uploaded, so they do not request it from us + RemoveUploadedKeyFromServers(cloudDataList->key); + + RakNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); + dataRepository.RemoveAtIndex(dataRepositoryIndex); + } + } + } + } + } + + unsigned int subscribedKeysIndex; + for (subscribedKeysIndex=0; subscribedKeysIndex < remoteCloudClient->subscribedKeys.Size(); subscribedKeysIndex++) + { + KeySubscriberID* keySubscriberId; + keySubscriberId = remoteCloudClient->subscribedKeys[subscribedKeysIndex]; + + bool keyDataRepositoryExists; + unsigned int keyDataRepositoryIndex = dataRepository.GetIndexFromKey(remoteCloudClient->subscribedKeys[subscribedKeysIndex]->key, &keyDataRepositoryExists); + if (keyDataRepositoryExists) + { + CloudDataList* cloudDataList = dataRepository[keyDataRepositoryIndex]; + if (keySubscriberId->specificSystemsSubscribedTo.Size()==0) + { + cloudDataList->nonSpecificSubscribers.Remove(rakNetGUID); + --cloudDataList->subscriberCount; + } + else + { + unsigned int specificSystemIndex; + for (specificSystemIndex=0; specificSystemIndex < keySubscriberId->specificSystemsSubscribedTo.Size(); specificSystemIndex++) + { + bool keyDataExists; + unsigned int keyDataIndex = cloudDataList->keyData.GetIndexFromKey(keySubscriberId->specificSystemsSubscribedTo[specificSystemIndex], &keyDataExists); + if (keyDataExists) + { + CloudData *keyData = cloudDataList->keyData[keyDataIndex]; + keyData->specificSubscribers.Remove(rakNetGUID); + --cloudDataList->subscriberCount; + } + } + } + } + + RakNet::OP_DELETE(keySubscriberId, _FILE_AND_LINE_); + } + + // Delete and remove from remoteSystems + RakNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); + remoteSystems.RemoveAtIndex(remoteSystemIndex, _FILE_AND_LINE_); + } +} +void CloudServer::OnRakPeerShutdown(void) +{ + Clear(); +} +void CloudServer::Clear(void) +{ + unsigned int i,j; + for (i=0; i < dataRepository.Size(); i++) + { + CloudDataList *cloudDataList = dataRepository[i]; + for (j=0; j < cloudDataList->keyData.Size(); j++) + { + cloudDataList->keyData[j]->Clear(); + RakNet::OP_DELETE(cloudDataList->keyData[j], _FILE_AND_LINE_); + } + RakNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); + } + dataRepository.Clear(false, _FILE_AND_LINE_); + + for (i=0; i < remoteServers.Size(); i++) + { + RakNet::OP_DELETE(remoteServers[i], _FILE_AND_LINE_); + } + remoteServers.Clear(false, _FILE_AND_LINE_); + + for (i=0; i < getRequests.Size(); i++) + { + GetRequest *getRequest = getRequests[i]; + getRequest->Clear(this); + RakNet::OP_DELETE(getRequests[i], _FILE_AND_LINE_); + } + getRequests.Clear(false, _FILE_AND_LINE_); + + DataStructures::List keyList; + DataStructures::List itemList; + remoteSystems.GetAsList(itemList, keyList, _FILE_AND_LINE_); + for (i=0; i < itemList.Size(); i++) + { + RemoteCloudClient* remoteCloudClient = itemList[i]; + for (j=0; j < remoteCloudClient->subscribedKeys.Size(); j++) + { + RakNet::OP_DELETE(remoteCloudClient->subscribedKeys[j], _FILE_AND_LINE_); + } + RakNet::OP_DELETE(remoteCloudClient, _FILE_AND_LINE_); + } + remoteSystems.Clear(_FILE_AND_LINE_); +} +void CloudServer::WriteCloudQueryRowFromResultList(DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut) +{ + bsOut->WriteCasted(cloudKeyResultList.Size()); + unsigned int i; + for (i=0; i < cloudKeyResultList.Size(); i++) + { + WriteCloudQueryRowFromResultList(i, cloudDataResultList, cloudKeyResultList, bsOut); + } +} +void CloudServer::WriteCloudQueryRowFromResultList(unsigned int i, DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList, BitStream *bsOut) +{ + CloudQueryRow cloudQueryRow; + CloudData *cloudData = cloudDataResultList[i]; + cloudQueryRow.key=cloudKeyResultList[i]; + cloudQueryRow.data=cloudData->dataPtr; + cloudQueryRow.length=cloudData->dataLengthBytes; + cloudQueryRow.serverSystemAddress=cloudData->serverSystemAddress; + cloudQueryRow.clientSystemAddress=cloudData->clientSystemAddress; + cloudQueryRow.serverGUID=cloudData->serverGUID; + cloudQueryRow.clientGUID=cloudData->clientGUID; + cloudQueryRow.Serialize(true, bsOut, 0); +} +void CloudServer::NotifyClientSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, DataStructures::OrderedList &subscribers, bool wasUpdated ) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID) ID_CLOUD_SUBSCRIPTION_NOTIFICATION); + bsOut.Write(wasUpdated); + CloudQueryRow row; + row.key=key; + row.data=cloudData->dataPtr; + row.length=cloudData->dataLengthBytes; + row.serverSystemAddress=cloudData->serverSystemAddress; + row.clientSystemAddress=cloudData->clientSystemAddress; + row.serverGUID=cloudData->serverGUID; + row.clientGUID=cloudData->clientGUID; + row.Serialize(true,&bsOut,0); + + unsigned int i; + for (i=0; i < subscribers.Size(); i++) + { + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, subscribers[i], false); + } +} +void CloudServer::NotifyClientSubscribersOfDataChange( CloudQueryRow *row, DataStructures::OrderedList &subscribers, bool wasUpdated ) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID) ID_CLOUD_SUBSCRIPTION_NOTIFICATION); + bsOut.Write(wasUpdated); + row->Serialize(true,&bsOut,0); + + unsigned int i; + for (i=0; i < subscribers.Size(); i++) + { + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, subscribers[i], false); + } +} +void CloudServer::NotifyServerSubscribersOfDataChange( CloudData *cloudData, CloudKey &key, bool wasUpdated ) +{ + // Find every server that has subscribed + // Send them change notifications + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_DATA_CHANGED); + bsOut.Write(wasUpdated); + CloudQueryRow row; + row.key=key; + row.data=cloudData->dataPtr; + row.length=cloudData->dataLengthBytes; + row.serverSystemAddress=cloudData->serverSystemAddress; + row.clientSystemAddress=cloudData->clientSystemAddress; + row.serverGUID=cloudData->serverGUID; + row.clientGUID=cloudData->clientGUID; + row.Serialize(true,&bsOut,0); + + unsigned int i; + for (i=0; i < remoteServers.Size(); i++) + { + if (remoteServers[i]->gotSubscribedAndUploadedKeys==false || remoteServers[i]->subscribedKeys.HasData(key)) + { + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, remoteServers[i]->serverAddress, false); + } + } +} +void CloudServer::AddServer(RakNetGUID systemIdentifier) +{ + ConnectionState cs = rakPeerInterface->GetConnectionState(systemIdentifier); + if (cs==IS_DISCONNECTED || cs==IS_NOT_CONNECTED) + return; + bool objectExists; + unsigned int index = remoteServers.GetIndexFromKey(systemIdentifier,&objectExists); + if (objectExists==false) + { + RemoteServer *remoteServer = RakNet::OP_NEW(_FILE_AND_LINE_); + remoteServer->gotSubscribedAndUploadedKeys=false; + remoteServer->serverAddress=systemIdentifier; + remoteServers.InsertAtIndex(remoteServer, index, _FILE_AND_LINE_); + + SendUploadedAndSubscribedKeysToServer(systemIdentifier); + } +} +void CloudServer::RemoveServer(RakNetGUID systemAddress) +{ + bool objectExists; + unsigned int index = remoteServers.GetIndexFromKey(systemAddress,&objectExists); + if (objectExists==true) + { + RakNet::OP_DELETE(remoteServers[index],_FILE_AND_LINE_); + remoteServers.RemoveAtIndex(index); + } +} +void CloudServer::GetRemoteServers(DataStructures::List &remoteServersOut) +{ + remoteServersOut.Clear(true, _FILE_AND_LINE_); + + unsigned int i; + for (i=0; i < remoteServers.Size(); i++) + { + remoteServersOut.Push(remoteServers[i]->serverAddress, _FILE_AND_LINE_); + } +} +void CloudServer::ProcessAndTransmitGetRequest(GetRequest *getRequest) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID) ID_CLOUD_GET_RESPONSE); + + // BufferedGetResponseFromServer getResponse; + CloudQueryResult cloudQueryResult; + cloudQueryResult.cloudQuery=getRequest->cloudQueryWithAddresses.cloudQuery; + cloudQueryResult.subscribeToResults=getRequest->cloudQueryWithAddresses.cloudQuery.subscribeToResults; + cloudQueryResult.SerializeHeader(true, &bsOut); + + DataStructures::List cloudDataResultList; + DataStructures::List cloudKeyResultList; + ProcessCloudQueryWithAddresses(getRequest->cloudQueryWithAddresses, cloudDataResultList, cloudKeyResultList); + bool unlimitedRows=getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn==0; + + uint32_t localNumRows = (uint32_t) cloudDataResultList.Size(); + if (unlimitedRows==false && + localNumRows > getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex && + localNumRows - getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex > getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn ) + localNumRows=getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex + getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn; + + BitSize_t bitStreamOffset = bsOut.GetWriteOffset(); + uint32_t localRowsToWrite; + unsigned int skipRows; + if (localNumRows>getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex) + { + localRowsToWrite=localNumRows-getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex; + skipRows=0; + } + else + { + localRowsToWrite=0; + skipRows=getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex-localNumRows; + } + cloudQueryResult.SerializeNumRows(true, localRowsToWrite, &bsOut); + for (unsigned int i=getRequest->cloudQueryWithAddresses.cloudQuery.startingRowIndex; i < localNumRows; i++) + { + WriteCloudQueryRowFromResultList(i, cloudDataResultList, cloudKeyResultList, &bsOut); + } + + // Append remote systems for remaining rows + if (unlimitedRows==true || getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn>localRowsToWrite) + { + uint32_t remainingRows=0; + uint32_t additionalRowsWritten=0; + if (unlimitedRows==false) + remainingRows=getRequest->cloudQueryWithAddresses.cloudQuery.maxRowsToReturn-localRowsToWrite; + + unsigned int remoteServerResponseIndex; + for (remoteServerResponseIndex=0; remoteServerResponseIndex < getRequest->remoteServerResponses.Size(); remoteServerResponseIndex++) + { + BufferedGetResponseFromServer *bufferedGetResponseFromServer = getRequest->remoteServerResponses[remoteServerResponseIndex]; + unsigned int cloudQueryRowIndex; + for (cloudQueryRowIndex=0; cloudQueryRowIndex < bufferedGetResponseFromServer->queryResult.rowsReturned.Size(); cloudQueryRowIndex++) + { + if (skipRows>0) + { + --skipRows; + continue; + } + bufferedGetResponseFromServer->queryResult.rowsReturned[cloudQueryRowIndex]->Serialize(true, &bsOut, this); + + ++additionalRowsWritten; + if (unlimitedRows==false && --remainingRows==0) + break; + } + + if (unlimitedRows==false && remainingRows==0) + break; + } + + if (additionalRowsWritten>0) + { + BitSize_t curOffset = bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(bitStreamOffset); + localRowsToWrite+=additionalRowsWritten; + cloudQueryResult.SerializeNumRows(true, localRowsToWrite, &bsOut); + bsOut.SetWriteOffset(curOffset); + } + } + + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, getRequest->requestingClient, false); +} +void CloudServer::ProcessCloudQueryWithAddresses( CloudServer::CloudQueryWithAddresses &cloudQueryWithAddresses, DataStructures::List &cloudDataResultList, DataStructures::List &cloudKeyResultList ) +{ + CloudQueryResult cloudQueryResult; + CloudQueryRow cloudQueryRow; + unsigned int queryIndex; + bool dataRepositoryExists; + CloudDataList* cloudDataList; + unsigned int keyDataIndex; + + // If specificSystems list empty, applies to all systems + // For each of keys in cloudQueryWithAddresses, return that data, limited by maxRowsToReturn + for (queryIndex=0; queryIndex < cloudQueryWithAddresses.cloudQuery.keys.Size(); queryIndex++) + { + const CloudKey &key = cloudQueryWithAddresses.cloudQuery.keys[queryIndex]; + + unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(key, &dataRepositoryExists); + if (dataRepositoryExists) + { + cloudDataList=dataRepository[dataRepositoryIndex]; + + if (cloudDataList->uploaderCount>0) + { + // Return all keyData that was uploaded by specificSystems, or all if not specified + if (cloudQueryWithAddresses.specificSystems.Size()>0) + { + // Return data for matching systems + unsigned int specificSystemIndex; + for (specificSystemIndex=0; specificSystemIndex < cloudQueryWithAddresses.specificSystems.Size(); specificSystemIndex++) + { + bool uploaderExists; + keyDataIndex = cloudDataList->keyData.GetIndexFromKey(cloudQueryWithAddresses.specificSystems[specificSystemIndex], &uploaderExists); + if (uploaderExists) + { + cloudDataResultList.Push(cloudDataList->keyData[keyDataIndex], _FILE_AND_LINE_); + cloudKeyResultList.Push(key, _FILE_AND_LINE_); + } + } + } + else + { + // Return data for all systems + for (keyDataIndex=0; keyDataIndex < cloudDataList->keyData.Size(); keyDataIndex++) + { + cloudDataResultList.Push(cloudDataList->keyData[keyDataIndex], _FILE_AND_LINE_); + cloudKeyResultList.Push(key, _FILE_AND_LINE_); + } + } + } + } + } +} +void CloudServer::SendUploadedAndSubscribedKeysToServer( RakNetGUID systemAddress ) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_ADD_UPLOADED_AND_SUBSCRIBED_KEYS); + bsOut.WriteCasted(dataRepository.Size()); + for (unsigned int i=0; i < dataRepository.Size(); i++) + dataRepository[i]->key.Serialize(true, &bsOut); + + BitSize_t startOffset, endOffset; + uint16_t subscribedKeyCount=0; + startOffset=bsOut.GetWriteOffset(); + bsOut.WriteCasted(subscribedKeyCount); + for (unsigned int i=0; i < dataRepository.Size(); i++) + { + if (dataRepository[i]->subscriberCount>0) + { + dataRepository[i]->key.Serialize(true, &bsOut); + subscribedKeyCount++; + } + } + endOffset=bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(startOffset); + bsOut.WriteCasted(subscribedKeyCount); + bsOut.SetWriteOffset(endOffset); + + if (dataRepository.Size()>0 || subscribedKeyCount>0) + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemAddress, false); +} +void CloudServer::SendUploadedKeyToServers( CloudKey &cloudKey ) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_ADD_UPLOADED_KEY); + cloudKey.Serialize(true, &bsOut); + for (unsigned int i=0; i < remoteServers.Size(); i++) + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, remoteServers[i]->serverAddress, false); +} +void CloudServer::SendSubscribedKeyToServers( CloudKey &cloudKey ) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_ADD_SUBSCRIBED_KEY); + cloudKey.Serialize(true, &bsOut); + for (unsigned int i=0; i < remoteServers.Size(); i++) + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, remoteServers[i]->serverAddress, false); +} +void CloudServer::RemoveUploadedKeyFromServers( CloudKey &cloudKey ) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_REMOVE_UPLOADED_KEY); + cloudKey.Serialize(true, &bsOut); + for (unsigned int i=0; i < remoteServers.Size(); i++) + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, remoteServers[i]->serverAddress, false); +} +void CloudServer::RemoveSubscribedKeyFromServers( CloudKey &cloudKey ) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_CLOUD_SERVER_TO_SERVER_COMMAND); + bsOut.Write((MessageID)STSC_REMOVE_SUBSCRIBED_KEY); + cloudKey.Serialize(true, &bsOut); + for (unsigned int i=0; i < remoteServers.Size(); i++) + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, remoteServers[i]->serverAddress, false); +} +void CloudServer::OnSendUploadedAndSubscribedKeysToServer( Packet *packet ) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + bool objectExists; + unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); + if (objectExists==false) + return; + RemoteServer *remoteServer = remoteServers[index]; + remoteServer->gotSubscribedAndUploadedKeys=true; + +// unsigned int insertionIndex; + bool alreadyHasKey; + uint16_t numUploadedKeys, numSubscribedKeys; + bsIn.Read(numUploadedKeys); + for (uint16_t i=0; i < numUploadedKeys; i++) + { + CloudKey cloudKey; + cloudKey.Serialize(false, &bsIn); + + // insertionIndex = + remoteServer->uploadedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); + if (alreadyHasKey==false) + remoteServer->uploadedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); + } + + bsIn.Read(numSubscribedKeys); + for (uint16_t i=0; i < numSubscribedKeys; i++) + { + CloudKey cloudKey; + cloudKey.Serialize(false, &bsIn); + + //insertionIndex = + remoteServer->subscribedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); + if (alreadyHasKey==false) + remoteServer->subscribedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); + } + + // Potential todo - join servers + // For each uploaded key that we subscribe to, query it + // For each subscribed key that we have, send it +} +void CloudServer::OnSendUploadedKeyToServers( Packet *packet ) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + bool objectExists; + unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); + if (objectExists==false) + return; + RemoteServer *remoteServer = remoteServers[index]; + CloudKey cloudKey; + cloudKey.Serialize(false, &bsIn); +// unsigned int insertionIndex; + bool alreadyHasKey; +// insertionIndex = + remoteServer->uploadedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); + if (alreadyHasKey==false) + remoteServer->uploadedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); +} +void CloudServer::OnSendSubscribedKeyToServers( Packet *packet ) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + bool objectExists; + unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); + if (objectExists==false) + return; + RemoteServer *remoteServer = remoteServers[index]; + CloudKey cloudKey; + cloudKey.Serialize(false, &bsIn); +// unsigned int insertionIndex; + bool alreadyHasKey; +// insertionIndex = + remoteServer->subscribedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); + + // Do not need to send current values, the Get request will do that as the Get request is sent at the same time + if (alreadyHasKey==false) + remoteServer->subscribedKeys.Insert(cloudKey,cloudKey,true,_FILE_AND_LINE_); +} +void CloudServer::OnRemoveUploadedKeyFromServers( Packet *packet ) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + bool objectExists; + unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); + if (objectExists==false) + return; + RemoteServer *remoteServer = remoteServers[index]; + CloudKey cloudKey; + cloudKey.Serialize(false, &bsIn); + unsigned int insertionIndex; + bool alreadyHasKey; + insertionIndex = remoteServer->uploadedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); + if (alreadyHasKey==true) + remoteServer->uploadedKeys.RemoveAtIndex(insertionIndex); +} +void CloudServer::OnRemoveSubscribedKeyFromServers( Packet *packet ) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + bool objectExists; + unsigned int index = remoteServers.GetIndexFromKey(packet->guid,&objectExists); + if (objectExists==false) + return; + RemoteServer *remoteServer = remoteServers[index]; + CloudKey cloudKey; + cloudKey.Serialize(false, &bsIn); + unsigned int insertionIndex; + bool alreadyHasKey; + insertionIndex = remoteServer->subscribedKeys.GetIndexFromKey(cloudKey, &alreadyHasKey); + if (alreadyHasKey==true) + remoteServer->subscribedKeys.RemoveAtIndex(insertionIndex); +} +void CloudServer::OnServerDataChanged( Packet *packet ) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + bool objectExists; + remoteServers.GetIndexFromKey(packet->guid,&objectExists); + if (objectExists==false) + return; + + // Find everyone that cares about this change and relay + bool wasUpdated=false; + bsIn.Read(wasUpdated); + CloudQueryRow row; + row.Serialize(false, &bsIn, this); + + CloudDataList *cloudDataList; + bool dataRepositoryExists; + unsigned int dataRepositoryIndex; + dataRepositoryIndex = dataRepository.GetIndexFromKey(row.key, &dataRepositoryExists); + if (dataRepositoryExists==false) + { + DeallocateRowData(row.data); + return; + } + cloudDataList = dataRepository[dataRepositoryIndex]; + CloudData *cloudData; + bool keyDataListExists; + unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(row.clientGUID, &keyDataListExists); + if (keyDataListExists==true) + { + cloudData = cloudDataList->keyData[keyDataListIndex]; + NotifyClientSubscribersOfDataChange(&row, cloudData->specificSubscribers, wasUpdated ); + } + + NotifyClientSubscribersOfDataChange(&row, cloudDataList->nonSpecificSubscribers, wasUpdated ); + DeallocateRowData(row.data); +} +void CloudServer::GetServersWithUploadedKeys( + DataStructures::List &keys, + DataStructures::List &remoteServersWithData + ) +{ + remoteServersWithData.Clear(true, _FILE_AND_LINE_); + + unsigned int i,j; + for (i=0; i < remoteServers.Size(); i++) + { + remoteServers[i]->workingFlag=false; + } + + for (i=0; i < remoteServers.Size(); i++) + { + if (remoteServers[i]->workingFlag==false) + { + if (remoteServers[i]->gotSubscribedAndUploadedKeys==false) + { + remoteServers[i]->workingFlag=true; + remoteServersWithData.Push(remoteServers[i], _FILE_AND_LINE_); + } + else + { + remoteServers[i]->workingFlag=false; + for (j=0; j < keys.Size(); j++) + { + if (remoteServers[i]->workingFlag==false && remoteServers[i]->uploadedKeys.HasData(keys[j])) + { + remoteServers[i]->workingFlag=true; + remoteServersWithData.Push(remoteServers[i], _FILE_AND_LINE_); + break; + } + } + } + } + } +} + +CloudServer::CloudDataList *CloudServer::GetOrAllocateCloudDataList(CloudKey key, bool *dataRepositoryExists, unsigned int &dataRepositoryIndex) +{ + CloudDataList *cloudDataList; + + dataRepositoryIndex = dataRepository.GetIndexFromKey(key, dataRepositoryExists); + if (*dataRepositoryExists==false) + { + cloudDataList = RakNet::OP_NEW(_FILE_AND_LINE_); + cloudDataList->key=key; + cloudDataList->uploaderCount=0; + cloudDataList->subscriberCount=0; + dataRepository.InsertAtIndex(cloudDataList,dataRepositoryIndex,_FILE_AND_LINE_); + } + else + { + cloudDataList = dataRepository[dataRepositoryIndex]; + } + + return cloudDataList; +} + +void CloudServer::UnsubscribeFromKey(RemoteCloudClient *remoteCloudClient, RakNetGUID remoteCloudClientGuid, unsigned int keySubscriberIndex, CloudKey &cloudKey, DataStructures::List &specificSystems) +{ + KeySubscriberID* keySubscriberId = remoteCloudClient->subscribedKeys[keySubscriberIndex]; + + // If removing specific systems, but global subscription, fail + if (keySubscriberId->specificSystemsSubscribedTo.Size()==0 && specificSystems.Size()>0) + return; + + bool dataRepositoryExists; + CloudDataList *cloudDataList; + unsigned int dataRepositoryIndex = dataRepository.GetIndexFromKey(cloudKey, &dataRepositoryExists); + if (dataRepositoryExists==false) + return; + + unsigned int i,j; + + cloudDataList = dataRepository[dataRepositoryIndex]; + if (specificSystems.Size()==0) + { + // Remove global subscriber. If returns false, have to remove specific subscribers + if (cloudDataList->RemoveSubscriber(remoteCloudClientGuid)==false) + { + for (i=0; i < keySubscriberId->specificSystemsSubscribedTo.Size(); i++) + { + RemoveSpecificSubscriber(keySubscriberId->specificSystemsSubscribedTo[i], cloudDataList, remoteCloudClientGuid); + } + } + keySubscriberId->specificSystemsSubscribedTo.Clear(true, _FILE_AND_LINE_); + } + else + { + for (j=0; j < specificSystems.Size(); j++) + { + unsigned int specificSystemsSubscribedToIndex; + bool hasSpecificSystemsSubscribedTo; + specificSystemsSubscribedToIndex=keySubscriberId->specificSystemsSubscribedTo.GetIndexFromKey(specificSystems[j], &hasSpecificSystemsSubscribedTo); + if (hasSpecificSystemsSubscribedTo) + { + RemoveSpecificSubscriber(specificSystems[j], cloudDataList, remoteCloudClientGuid); + keySubscriberId->specificSystemsSubscribedTo.RemoveAtIndex(specificSystemsSubscribedToIndex); + } + } + } + + if (keySubscriberId->specificSystemsSubscribedTo.Size()==0) + { + RakNet::OP_DELETE(keySubscriberId, _FILE_AND_LINE_); + remoteCloudClient->subscribedKeys.RemoveAtIndex(keySubscriberIndex); + } + + if (cloudDataList->subscriberCount==0) + RemoveSubscribedKeyFromServers(cloudKey); + + if (cloudDataList->IsUnused()) + { + RakNet::OP_DELETE(cloudDataList, _FILE_AND_LINE_); + dataRepository.RemoveAtIndex(dataRepositoryIndex); + } +} +void CloudServer::RemoveSpecificSubscriber(RakNetGUID specificSubscriber, CloudDataList *cloudDataList, RakNetGUID remoteCloudClientGuid) +{ + bool keyDataListExists; + unsigned int keyDataListIndex = cloudDataList->keyData.GetIndexFromKey(specificSubscriber, &keyDataListExists); + if (keyDataListExists==false) + return; + CloudData *cloudData = cloudDataList->keyData[keyDataListIndex]; + bool hasSpecificSubscriber; + unsigned int specificSubscriberIndex = cloudData->specificSubscribers.GetIndexFromKey(remoteCloudClientGuid, &hasSpecificSubscriber); + if (hasSpecificSubscriber) + { + cloudData->specificSubscribers.RemoveAtIndex(specificSubscriberIndex); + cloudDataList->subscriberCount--; + + if (cloudData->IsUnused()) + { + RakNet::OP_DELETE(cloudData, _FILE_AND_LINE_); + cloudDataList->keyData.RemoveAtIndex(keyDataListIndex); + } + } +} + +void CloudServer::ForceExternalSystemAddress(SystemAddress forcedAddress) +{ + forceAddress=forcedAddress; +} +void CloudServer::AddQueryFilter(CloudServerQueryFilter* filter) +{ + if (queryFilters.GetIndexOf(filter)!=(unsigned int) -1) + return; + queryFilters.Push(filter, _FILE_AND_LINE_); +} +void CloudServer::RemoveQueryFilter(CloudServerQueryFilter* filter) +{ + unsigned int index; + index = queryFilters.GetIndexOf(filter); + if (index != (unsigned int) -1) + queryFilters.RemoveAtIndex(index); +} +void CloudServer::RemoveAllQueryFilters(void) +{ + queryFilters.Clear(true, _FILE_AND_LINE_); +} + +#endif diff --git a/src/raknet/CommandParserInterface.cpp b/src/raknet/CommandParserInterface.cpp new file mode 100644 index 0000000..d55f2ab --- /dev/null +++ b/src/raknet/CommandParserInterface.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/CommandParserInterface.hpp" +#include "include/raknet/TransportInterface.hpp" +#include +#include "include/raknet/RakAssert.hpp" +#include + + +#if defined(WINDOWS_STORE_RT) +#elif defined(_WIN32) +// IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib +// winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly +#include + +#else +#include +#include +#include +#endif + +#include "include/raknet/LinuxStrings.hpp" + +using namespace RakNet; + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +const unsigned char CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS=255; + +int RakNet::RegisteredCommandComp( const char* const & key, const RegisteredCommand &data ) +{ + return _stricmp(key,data.command); +} + +CommandParserInterface::CommandParserInterface() {} +CommandParserInterface::~CommandParserInterface() {} + +void CommandParserInterface::ParseConsoleString(char *str, const char delineator, unsigned char delineatorToggle, unsigned *numParameters, char **parameterList, unsigned parameterListLength) +{ + unsigned strIndex, parameterListIndex; + unsigned strLen; + bool replaceDelineator=true; + + strLen = (unsigned) strlen(str); + + // Replace every instance of delineator, \n, \r with 0 + for (strIndex=0; strIndex < strLen; strIndex++) + { + if (str[strIndex]==delineator && replaceDelineator) + str[strIndex]=0; + + if (str[strIndex]=='\n' || str[strIndex]=='\r') + str[strIndex]=0; + + if (str[strIndex]==delineatorToggle) + { + str[strIndex]=0; + replaceDelineator=!replaceDelineator; + } + } + + // Fill up parameterList starting at each non-0 + for (strIndex=0, parameterListIndex=0; strIndex < strLen; ) + { + if (str[strIndex]!=0) + { + parameterList[parameterListIndex]=str+strIndex; + parameterListIndex++; + RakAssert(parameterListIndex < parameterListLength); + if (parameterListIndex >= parameterListLength) + break; + + strIndex++; + while (str[strIndex]!=0 && strIndex < strLen) + strIndex++; + } + else + strIndex++; + } + + parameterList[parameterListIndex]=0; + *numParameters=parameterListIndex; +} +void CommandParserInterface::SendCommandList(TransportInterface *transport, const SystemAddress &systemAddress) +{ + unsigned i; + if (commandList.Size()) + { + for (i=0; i < commandList.Size(); i++) + { + transport->Send(systemAddress, "%s", commandList[i].command); + if (i < commandList.Size()-1) + transport->Send(systemAddress, ", "); + } + transport->Send(systemAddress, "\r\n"); + } + else + transport->Send(systemAddress, "No registered commands\r\n"); +} +void CommandParserInterface::RegisterCommand(unsigned char parameterCount, const char *command, const char *commandHelp) +{ + RegisteredCommand rc; + rc.command=command; + rc.commandHelp=commandHelp; + rc.parameterCount=parameterCount; + commandList.Insert( command, rc, true, _FILE_AND_LINE_); +} +bool CommandParserInterface::GetRegisteredCommand(const char *command, RegisteredCommand *rc) +{ + bool objectExists; + unsigned index; + index=commandList.GetIndexFromKey(command, &objectExists); + if (objectExists) + *rc=commandList[index]; + return objectExists; +} +void CommandParserInterface::OnTransportChange(TransportInterface *transport) +{ + (void) transport; +} +void CommandParserInterface::OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport) +{ + (void) systemAddress; + (void) transport; +} +void CommandParserInterface::OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport) +{ + (void) systemAddress; + (void) transport; +} +void CommandParserInterface::ReturnResult(bool res, const char *command,TransportInterface *transport, const SystemAddress &systemAddress) +{ + if (res) + transport->Send(systemAddress, "%s returned true.\r\n", command); + else + transport->Send(systemAddress, "%s returned false.\r\n", command); +} +void CommandParserInterface::ReturnResult(int res, const char *command,TransportInterface *transport, const SystemAddress &systemAddress) +{ + transport->Send(systemAddress, "%s returned %i.\r\n", command, res); +} +void CommandParserInterface::ReturnResult(const char *command, TransportInterface *transport, const SystemAddress &systemAddress) +{ + transport->Send(systemAddress, "Successfully called %s.\r\n", command); +} +void CommandParserInterface::ReturnResult(char *res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress) +{ + transport->Send(systemAddress, "%s returned %s.\r\n", command, res); +} +void CommandParserInterface::ReturnResult(SystemAddress res, const char *command, TransportInterface *transport, const SystemAddress &systemAddress) +{ + char addr[128]; + systemAddress.ToString(false,addr); + char addr2[128]; + res.ToString(false,addr2); + transport->Send(systemAddress, "%s returned %s %s:%i\r\n", command,addr,addr2,res.GetPort()); +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + diff --git a/src/raknet/ConnectionGraph2.cpp b/src/raknet/ConnectionGraph2.cpp new file mode 100644 index 0000000..38f1765 --- /dev/null +++ b/src/raknet/ConnectionGraph2.cpp @@ -0,0 +1,309 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_ConnectionGraph2==1 + +#include "include/raknet/ConnectionGraph2.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/BitStream.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(ConnectionGraph2,ConnectionGraph2) + +int RakNet::ConnectionGraph2::RemoteSystemComp( const RakNetGUID &key, RemoteSystem * const &data ) +{ + if (key < data->guid) + return -1; + if (key > data->guid) + return 1; + return 0; +} + +int RakNet::ConnectionGraph2::SystemAddressAndGuidComp( const SystemAddressAndGuid &key, const SystemAddressAndGuid &data ) +{ + if (key.guiddata.guid) + return 1; + return 0; +} +ConnectionGraph2::ConnectionGraph2() +{ + autoProcessNewConnections=true; +} +ConnectionGraph2::~ConnectionGraph2() +{ + +} +bool ConnectionGraph2::GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid, SystemAddress *saOut, RakNetGUID *guidOut, unsigned int *outLength) +{ + if ((saOut==0 && guidOut==0) || outLength==0 || *outLength==0 || remoteSystemGuid==UNASSIGNED_RAKNET_GUID) + { + *outLength=0; + return false; + } + + bool objectExists; + unsigned int idx = remoteSystems.GetIndexFromKey(remoteSystemGuid, &objectExists); + if (objectExists==false) + { + *outLength=0; + return false; + } + + unsigned int idx2; + if (remoteSystems[idx]->remoteConnections.Size() < *outLength) + *outLength=remoteSystems[idx]->remoteConnections.Size(); + for (idx2=0; idx2 < *outLength; idx2++) + { + if (guidOut) + guidOut[idx2]=remoteSystems[idx]->remoteConnections[idx2].guid; + if (saOut) + saOut[idx2]=remoteSystems[idx]->remoteConnections[idx2].systemAddress; + } + return true; +} +bool ConnectionGraph2::ConnectionExists(RakNetGUID g1, RakNetGUID g2) +{ + if (g1==g2) + return false; + + bool objectExists; + unsigned int idx = remoteSystems.GetIndexFromKey(g1, &objectExists); + if (objectExists==false) + { + return false; + } + SystemAddressAndGuid sag; + sag.guid=g2; + return remoteSystems[idx]->remoteConnections.HasData(sag); +} +uint16_t ConnectionGraph2::GetPingBetweenSystems(RakNetGUID g1, RakNetGUID g2) const +{ + if (g1==g2) + return 0; + + if (g1==rakPeerInterface->GetMyGUID()) + return (uint16_t) rakPeerInterface->GetAveragePing(g2); + if (g2==rakPeerInterface->GetMyGUID()) + return (uint16_t) rakPeerInterface->GetAveragePing(g1); + + bool objectExists; + unsigned int idx = remoteSystems.GetIndexFromKey(g1, &objectExists); + if (objectExists==false) + { + return (uint16_t) -1; + } + + SystemAddressAndGuid sag; + sag.guid=g2; + unsigned int idx2 = remoteSystems[idx]->remoteConnections.GetIndexFromKey(sag, &objectExists); + if (objectExists==false) + { + return (uint16_t) -1; + } + return remoteSystems[idx]->remoteConnections[idx2].sendersPingToThatSystem; +} + +/// Returns the system with the lowest total ping among all its connections. This can be used as the 'best host' for a peer to peer session +RakNetGUID ConnectionGraph2::GetLowestAveragePingSystem(void) const +{ + float lowestPing=-1.0; + unsigned int lowestPingIdx=(unsigned int) -1; + float thisAvePing=0.0f; + unsigned int idx, idx2; + int ap, count=0; + + for (idx=0; idxGetAveragePing(remoteSystems[idx]->guid); + if (ap!=-1) + { + thisAvePing+=(float) ap; + count++; + } + } + + if (count>0) + { + lowestPing=thisAvePing/count; + } + + for (idx=0; idxremoteConnections.Size(); idx2++) + { + ap=remoteSystem->remoteConnections[idx2].sendersPingToThatSystem; + if (ap!=-1) + { + thisAvePing+=(float) ap; + count++; + } + } + + if (count>0 && (lowestPing==-1.0f || thisAvePing/count < lowestPing)) + { + lowestPing=thisAvePing/count; + lowestPingIdx=idx; + } + } + + if (lowestPingIdx==(unsigned int) -1) + return rakPeerInterface->GetMyGUID(); + return remoteSystems[lowestPingIdx]->guid; +} + +void ConnectionGraph2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + // Send notice to all existing connections + RakNet::BitStream bs; + if (lostConnectionReason==LCR_CONNECTION_LOST) + bs.Write((MessageID)ID_REMOTE_CONNECTION_LOST); + else + bs.Write((MessageID)ID_REMOTE_DISCONNECTION_NOTIFICATION); + bs.Write(systemAddress); + bs.Write(rakNetGUID); + SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,true); + + bool objectExists; + unsigned int idx = remoteSystems.GetIndexFromKey(rakNetGUID, &objectExists); + if (objectExists) + { + RakNet::OP_DELETE(remoteSystems[idx],_FILE_AND_LINE_); + remoteSystems.RemoveAtIndex(idx); + } +} +void ConnectionGraph2::SetAutoProcessNewConnections(bool b) +{ + autoProcessNewConnections=b; +} +bool ConnectionGraph2::GetAutoProcessNewConnections(void) const +{ + return autoProcessNewConnections; +} +void ConnectionGraph2::AddParticipant(const SystemAddress &systemAddress, RakNetGUID rakNetGUID) +{ + // Relay the new connection to other systems. + RakNet::BitStream bs; + bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION); + bs.Write((uint32_t)1); + bs.Write(systemAddress); + bs.Write(rakNetGUID); + bs.WriteCasted(rakPeerInterface->GetAveragePing(rakNetGUID)); + SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,true); + + // Send everyone to the new guy + DataStructures::List addresses; + DataStructures::List guids; + rakPeerInterface->GetSystemList(addresses, guids); + bs.Reset(); + bs.Write((MessageID)ID_REMOTE_NEW_INCOMING_CONNECTION); + BitSize_t writeOffset = bs.GetWriteOffset(); + bs.Write((uint32_t) addresses.Size()); + + unsigned int i; + uint32_t count=0; + for (i=0; i < addresses.Size(); i++) + { + if (addresses[i]==systemAddress) + continue; + + bs.Write(addresses[i]); + bs.Write(guids[i]); + bs.WriteCasted(rakPeerInterface->GetAveragePing(guids[i])); + count++; + } + + if (count>0) + { + BitSize_t writeOffset2 = bs.GetWriteOffset(); + bs.SetWriteOffset(writeOffset); + bs.Write(count); + bs.SetWriteOffset(writeOffset2); + SendUnified(&bs,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,false); + } + + bool objectExists; + unsigned int ii = remoteSystems.GetIndexFromKey(rakNetGUID, &objectExists); + if (objectExists==false) + { + RemoteSystem* remoteSystem = RakNet::OP_NEW(_FILE_AND_LINE_); + remoteSystem->guid=rakNetGUID; + remoteSystems.InsertAtIndex(remoteSystem,ii,_FILE_AND_LINE_); + } +} +void ConnectionGraph2::GetParticipantList(DataStructures::OrderedList &participantList) +{ + participantList.Clear(true, _FILE_AND_LINE_); + unsigned int i; + for (i=0; i < remoteSystems.Size(); i++) + participantList.InsertAtEnd(remoteSystems[i]->guid, _FILE_AND_LINE_); +} +void ConnectionGraph2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) isIncoming; + if (autoProcessNewConnections) + AddParticipant(systemAddress, rakNetGUID); +} +PluginReceiveResult ConnectionGraph2::OnReceive(Packet *packet) +{ + if (packet->data[0]==ID_REMOTE_CONNECTION_LOST || packet->data[0]==ID_REMOTE_DISCONNECTION_NOTIFICATION) + { + bool objectExists; + unsigned idx = remoteSystems.GetIndexFromKey(packet->guid, &objectExists); + if (objectExists) + { + RakNet::BitStream bs(packet->data,packet->length,false); + bs.IgnoreBytes(1); + SystemAddressAndGuid saag; + bs.Read(saag.systemAddress); + bs.Read(saag.guid); + unsigned long idx2 = remoteSystems[idx]->remoteConnections.GetIndexFromKey(saag, &objectExists); + if (objectExists) + remoteSystems[idx]->remoteConnections.RemoveAtIndex(idx2); + } + } + else if (packet->data[0]==ID_REMOTE_NEW_INCOMING_CONNECTION) + { + bool objectExists; + unsigned idx = remoteSystems.GetIndexFromKey(packet->guid, &objectExists); + if (objectExists) + { + uint32_t numAddresses; + RakNet::BitStream bs(packet->data,packet->length,false); + bs.IgnoreBytes(1); + bs.Read(numAddresses); + for (unsigned int idx2=0; idx2 < numAddresses; idx2++) + { + SystemAddressAndGuid saag; + bs.Read(saag.systemAddress); + bs.Read(saag.guid); + bs.Read(saag.sendersPingToThatSystem); + bool objectExists; + unsigned int ii = remoteSystems[idx]->remoteConnections.GetIndexFromKey(saag, &objectExists); + if (objectExists==false) + remoteSystems[idx]->remoteConnections.InsertAtIndex(saag,ii,_FILE_AND_LINE_); + } + } + } + + return RR_CONTINUE_PROCESSING; +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/ConsoleServer.cpp b/src/raknet/ConsoleServer.cpp new file mode 100644 index 0000000..0ed9422 --- /dev/null +++ b/src/raknet/ConsoleServer.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_ConsoleServer==1 + +#include "include/raknet/ConsoleServer.hpp" +#include "include/raknet/TransportInterface.hpp" +#include "include/raknet/CommandParserInterface.hpp" +#include +#include + +#define COMMAND_DELINATOR ' ' +#define COMMAND_DELINATOR_TOGGLE '"' + +#include "include/raknet/LinuxStrings.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(ConsoleServer,ConsoleServer); + +ConsoleServer::ConsoleServer() +{ + transport=0; + password[0]=0; + prompt=0; +} +ConsoleServer::~ConsoleServer() +{ + if (prompt) + rakFree_Ex(prompt, _FILE_AND_LINE_); +} +void ConsoleServer::SetTransportProvider(TransportInterface *transportInterface, unsigned short port) +{ + // Replace the current TransportInterface, stopping the old one, if present, and starting the new one. + if (transportInterface) + { + if (transport) + { + RemoveCommandParser(transport->GetCommandParser()); + transport->Stop(); + } + transport=transportInterface; + transport->Start(port, true); + + unsigned i; + for (i=0; i < commandParserList.Size(); i++) + commandParserList[i]->OnTransportChange(transport); + + // The transport itself might have a command parser - for example password for the RakNet transport + AddCommandParser(transport->GetCommandParser()); + } +} +void ConsoleServer::AddCommandParser(CommandParserInterface *commandParserInterface) +{ + if (commandParserInterface==0) + return; + + // Non-duplicate insertion + unsigned i; + for (i=0; i < commandParserList.Size(); i++) + { + if (commandParserList[i]==commandParserInterface) + return; + + if (_stricmp(commandParserList[i]->GetName(), commandParserInterface->GetName())==0) + { + // Naming conflict between two command parsers + RakAssert(0); + return; + } + } + + commandParserList.Insert(commandParserInterface, _FILE_AND_LINE_); + if (transport) + commandParserInterface->OnTransportChange(transport); +} +void ConsoleServer::RemoveCommandParser(CommandParserInterface *commandParserInterface) +{ + if (commandParserInterface==0) + return; + + // Overwrite the element we are removing from the back of the list and delete the back of the list + unsigned i; + for (i=0; i < commandParserList.Size(); i++) + { + if (commandParserList[i]==commandParserInterface) + { + commandParserList[i]=commandParserList[commandParserList.Size()-1]; + commandParserList.RemoveFromEnd(); + return; + } + } +} +void ConsoleServer::Update(void) +{ + unsigned i; + char *parameterList[20]; // Up to 20 parameters + unsigned numParameters; + RakNet::SystemAddress newOrLostConnectionId; + RakNet::Packet *p; + RakNet::RegisteredCommand rc; + + p = transport->Receive(); + newOrLostConnectionId=transport->HasNewIncomingConnection(); + + if (newOrLostConnectionId!=UNASSIGNED_SYSTEM_ADDRESS) + { + for (i=0; i < commandParserList.Size(); i++) + { + commandParserList[i]->OnNewIncomingConnection(newOrLostConnectionId, transport); + } + + transport->Send(newOrLostConnectionId, "Connected to remote command console.\r\nType 'help' for help.\r\n"); + ListParsers(newOrLostConnectionId); + ShowPrompt(newOrLostConnectionId); + } + + newOrLostConnectionId=transport->HasLostConnection(); + if (newOrLostConnectionId!=UNASSIGNED_SYSTEM_ADDRESS) + { + for (i=0; i < commandParserList.Size(); i++) + commandParserList[i]->OnConnectionLost(newOrLostConnectionId, transport); + } + + while (p) + { + bool commandParsed=false; + char copy[REMOTE_MAX_TEXT_INPUT]; + memcpy(copy, p->data, p->length); + copy[p->length]=0; + RakNet::CommandParserInterface::ParseConsoleString((char*)p->data, COMMAND_DELINATOR, COMMAND_DELINATOR_TOGGLE, &numParameters, parameterList, 20); // Up to 20 parameters + if (numParameters==0) + { + transport->DeallocatePacket(p); + p = transport->Receive(); + continue; + } + if (_stricmp(*parameterList, "help")==0 && numParameters<=2) + { + // Find the parser specified and display help for it + if (numParameters==1) + { + transport->Send(p->systemAddress, "\r\nINSTRUCTIONS:\r\n"); + transport->Send(p->systemAddress, "Enter commands on your keyboard, using spaces to delineate parameters.\r\n"); + transport->Send(p->systemAddress, "You can use quotation marks to toggle space delineation.\r\n"); + transport->Send(p->systemAddress, "You can connect multiple times from the same computer.\r\n"); + transport->Send(p->systemAddress, "You can direct commands to a parser by prefixing the parser name or number.\r\n"); + transport->Send(p->systemAddress, "COMMANDS:\r\n"); + transport->Send(p->systemAddress, "help Show this display.\r\n"); + transport->Send(p->systemAddress, "help Show help on a particular parser.\r\n"); + transport->Send(p->systemAddress, "help Show help on a particular command.\r\n"); + transport->Send(p->systemAddress, "quit Disconnects from the server.\r\n"); + transport->Send(p->systemAddress, "[] [] Execute a command\r\n"); + transport->Send(p->systemAddress, "[] [] Execute a command\r\n"); + ListParsers(p->systemAddress); + //ShowPrompt(p->systemAddress); + } + else // numParameters == 2, including the help tag + { + for (i=0; i < commandParserList.Size(); i++) + { + if (_stricmp(parameterList[1], commandParserList[i]->GetName())==0) + { + commandParsed=true; + commandParserList[i]->SendHelp(transport, p->systemAddress); + transport->Send(p->systemAddress, "COMMAND LIST:\r\n"); + commandParserList[i]->SendCommandList(transport, p->systemAddress); + transport->Send(p->systemAddress, "\r\n"); + break; + } + } + + if (commandParsed==false) + { + // Try again, for all commands for all parsers. + RakNet::RegisteredCommand rc; + for (i=0; i < commandParserList.Size(); i++) + { + if (commandParserList[i]->GetRegisteredCommand(parameterList[1], &rc)) + { + if (rc.parameterCount==RakNet::CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS) + transport->Send(p->systemAddress, "(Variable parms): %s %s\r\n", rc.command, rc.commandHelp); + else + transport->Send(p->systemAddress, "(%i parms): %s %s\r\n", rc.parameterCount, rc.command, rc.commandHelp); + commandParsed=true; + break; + } + } + } + + if (commandParsed==false) + { + // Don't know what to do + transport->Send(p->systemAddress, "Unknown help topic: %s.\r\n", parameterList[1]); + } + //ShowPrompt(p->systemAddress); + } + } + else if (_stricmp(*parameterList, "quit")==0 && numParameters==1) + { + transport->Send(p->systemAddress, "Goodbye!\r\n"); + transport->CloseConnection(p->systemAddress); + } + else + { + bool tryAllParsers=true; + bool failed=false; + + if (numParameters >=2) // At minimum + { + unsigned commandParserIndex=(unsigned)-1; + // Prefixing with numbers directs to a particular parser + if (**parameterList>='0' && **parameterList<='9') + { + commandParserIndex=atoi(*parameterList); // Use specified parser unless it's an invalid number + commandParserIndex--; // Subtract 1 since we displayed numbers starting at index+1 + if (commandParserIndex >= commandParserList.Size()) + { + transport->Send(p->systemAddress, "Invalid index.\r\n"); + failed=true; + } + } + else + { + // // Prefixing with the name of a command parser directs to that parser. See if the first word matches a parser + for (i=0; i < commandParserList.Size(); i++) + { + if (_stricmp(parameterList[0], commandParserList[i]->GetName())==0) + { + commandParserIndex=i; // Matches parser at index i + break; + } + } + } + + if (failed==false) + { + // -1 means undirected, so otherwise this is directed to a target + if (commandParserIndex!=(unsigned)-1) + { + // Only this parser should use this command + tryAllParsers=false; + if (commandParserList[commandParserIndex]->GetRegisteredCommand(parameterList[1], &rc)) + { + commandParsed=true; + if (rc.parameterCount==CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS || rc.parameterCount==numParameters-2) + commandParserList[commandParserIndex]->OnCommand(rc.command, numParameters-2, parameterList+2, transport, p->systemAddress, copy); + else + transport->Send(p->systemAddress, "Invalid parameter count.\r\n(%i parms): %s %s\r\n", rc.parameterCount, rc.command, rc.commandHelp); + } + } + } + } + + if (failed == false && tryAllParsers) + { + for (i=0; i < commandParserList.Size(); i++) + { + // Undirected command. Try all the parsers to see if they understand the command + // Pass the 1nd element as the command, and the remainder as the parameter list + if (commandParserList[i]->GetRegisteredCommand(parameterList[0], &rc)) + { + commandParsed=true; + + if (rc.parameterCount==CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS || rc.parameterCount==numParameters-1) + commandParserList[i]->OnCommand(rc.command, numParameters-1, parameterList+1, transport, p->systemAddress, copy); + else + transport->Send(p->systemAddress, "Invalid parameter count.\r\n(%i parms): %s %s\r\n", rc.parameterCount, rc.command, rc.commandHelp); + } + } + } + if (commandParsed==false && commandParserList.Size() > 0) + { + transport->Send(p->systemAddress, "Unknown command: Type 'help' for help.\r\n"); + } + + } + + ShowPrompt(p->systemAddress); + + transport->DeallocatePacket(p); + p = transport->Receive(); + } +} + +void ConsoleServer::ListParsers(SystemAddress systemAddress) +{ + transport->Send(systemAddress,"INSTALLED PARSERS:\r\n"); + unsigned i; + for (i=0; i < commandParserList.Size(); i++) + { + transport->Send(systemAddress, "%i. %s\r\n", i+1, commandParserList[i]->GetName()); + } +} +void ConsoleServer::ShowPrompt(SystemAddress systemAddress) +{ + transport->Send(systemAddress, prompt); +} +void ConsoleServer::SetPrompt(const char *_prompt) +{ + if (prompt) + rakFree_Ex(prompt,_FILE_AND_LINE_); + if (_prompt && _prompt[0]) + { + size_t len = strlen(_prompt); + prompt = (char*) rakMalloc_Ex(len+1,_FILE_AND_LINE_); + strcpy(prompt,_prompt); + } + else + prompt=0; +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/DR_SHA1.cpp b/src/raknet/DR_SHA1.cpp new file mode 100644 index 0000000..f457845 --- /dev/null +++ b/src/raknet/DR_SHA1.cpp @@ -0,0 +1,312 @@ +/* + 100% free public domain implementation of the SHA-1 algorithm + by Dominik Reichl + Web: http://www.dominik-reichl.de/ + + See header file for version history and test vectors. +*/ + +// If compiling with MFC, you might want to add #include "include/raknet/StdAfx.hpp" + +#define _CRT_SECURE_NO_WARNINGS +#include "include/raknet/DR_SHA1.hpp" +#include + +#define SHA1_MAX_FILE_BUFFER (32 * 20 * 820) + +// Rotate p_val32 by p_nBits bits to the left +#ifndef ROL32 +#ifdef _MSC_VER +#define ROL32(p_val32,p_nBits) _rotl(p_val32,p_nBits) +#else +#define ROL32(p_val32,p_nBits) (((p_val32)<<(p_nBits))|((p_val32)>>(32-(p_nBits)))) +#endif +#endif + +#ifdef SHA1_LITTLE_ENDIAN +#define SHABLK0(i) (m_block->l[i] = \ + (ROL32(m_block->l[i],24) & 0xFF00FF00) | (ROL32(m_block->l[i],8) & 0x00FF00FF)) +#else +#define SHABLK0(i) (m_block->l[i]) +#endif + +#define SHABLK(i) (m_block->l[i&15] = ROL32(m_block->l[(i+13)&15] ^ \ + m_block->l[(i+8)&15] ^ m_block->l[(i+2)&15] ^ m_block->l[i&15],1)) + +// SHA-1 rounds +#define S_R0(v,w,x,y,z,i) {z+=((w&(x^y))^y)+SHABLK0(i)+0x5A827999+ROL32(v,5);w=ROL32(w,30);} +#define S_R1(v,w,x,y,z,i) {z+=((w&(x^y))^y)+SHABLK(i)+0x5A827999+ROL32(v,5);w=ROL32(w,30);} +#define S_R2(v,w,x,y,z,i) {z+=(w^x^y)+SHABLK(i)+0x6ED9EBA1+ROL32(v,5);w=ROL32(w,30);} +#define S_R3(v,w,x,y,z,i) {z+=(((w|x)&y)|(w&x))+SHABLK(i)+0x8F1BBCDC+ROL32(v,5);w=ROL32(w,30);} +#define S_R4(v,w,x,y,z,i) {z+=(w^x^y)+SHABLK(i)+0xCA62C1D6+ROL32(v,5);w=ROL32(w,30);} + +#pragma warning(push) +// Disable compiler warning 'Conditional expression is constant' +#pragma warning(disable: 4127) + +CSHA1::CSHA1() +{ + m_block = (SHA1_WORKSPACE_BLOCK*)m_workspace; + + Reset(); +} + +#ifdef SHA1_WIPE_VARIABLES +CSHA1::~CSHA1() +{ + Reset(); +} +#endif + +void CSHA1::Reset() +{ + // SHA1 initialization constants + m_state[0] = 0x67452301; + m_state[1] = 0xEFCDAB89; + m_state[2] = 0x98BADCFE; + m_state[3] = 0x10325476; + m_state[4] = 0xC3D2E1F0; + + m_count[0] = 0; + m_count[1] = 0; +} + +void CSHA1::Transform(UINT_32* pState, const UINT_8* pBuffer) +{ + UINT_32 a = pState[0], b = pState[1], c = pState[2], d = pState[3], e = pState[4]; + + memcpy(m_block, pBuffer, 64); + + // 4 rounds of 20 operations each, loop unrolled + S_R0(a,b,c,d,e, 0); S_R0(e,a,b,c,d, 1); S_R0(d,e,a,b,c, 2); S_R0(c,d,e,a,b, 3); + S_R0(b,c,d,e,a, 4); S_R0(a,b,c,d,e, 5); S_R0(e,a,b,c,d, 6); S_R0(d,e,a,b,c, 7); + S_R0(c,d,e,a,b, 8); S_R0(b,c,d,e,a, 9); S_R0(a,b,c,d,e,10); S_R0(e,a,b,c,d,11); + S_R0(d,e,a,b,c,12); S_R0(c,d,e,a,b,13); S_R0(b,c,d,e,a,14); S_R0(a,b,c,d,e,15); + S_R1(e,a,b,c,d,16); S_R1(d,e,a,b,c,17); S_R1(c,d,e,a,b,18); S_R1(b,c,d,e,a,19); + S_R2(a,b,c,d,e,20); S_R2(e,a,b,c,d,21); S_R2(d,e,a,b,c,22); S_R2(c,d,e,a,b,23); + S_R2(b,c,d,e,a,24); S_R2(a,b,c,d,e,25); S_R2(e,a,b,c,d,26); S_R2(d,e,a,b,c,27); + S_R2(c,d,e,a,b,28); S_R2(b,c,d,e,a,29); S_R2(a,b,c,d,e,30); S_R2(e,a,b,c,d,31); + S_R2(d,e,a,b,c,32); S_R2(c,d,e,a,b,33); S_R2(b,c,d,e,a,34); S_R2(a,b,c,d,e,35); + S_R2(e,a,b,c,d,36); S_R2(d,e,a,b,c,37); S_R2(c,d,e,a,b,38); S_R2(b,c,d,e,a,39); + S_R3(a,b,c,d,e,40); S_R3(e,a,b,c,d,41); S_R3(d,e,a,b,c,42); S_R3(c,d,e,a,b,43); + S_R3(b,c,d,e,a,44); S_R3(a,b,c,d,e,45); S_R3(e,a,b,c,d,46); S_R3(d,e,a,b,c,47); + S_R3(c,d,e,a,b,48); S_R3(b,c,d,e,a,49); S_R3(a,b,c,d,e,50); S_R3(e,a,b,c,d,51); + S_R3(d,e,a,b,c,52); S_R3(c,d,e,a,b,53); S_R3(b,c,d,e,a,54); S_R3(a,b,c,d,e,55); + S_R3(e,a,b,c,d,56); S_R3(d,e,a,b,c,57); S_R3(c,d,e,a,b,58); S_R3(b,c,d,e,a,59); + S_R4(a,b,c,d,e,60); S_R4(e,a,b,c,d,61); S_R4(d,e,a,b,c,62); S_R4(c,d,e,a,b,63); + S_R4(b,c,d,e,a,64); S_R4(a,b,c,d,e,65); S_R4(e,a,b,c,d,66); S_R4(d,e,a,b,c,67); + S_R4(c,d,e,a,b,68); S_R4(b,c,d,e,a,69); S_R4(a,b,c,d,e,70); S_R4(e,a,b,c,d,71); + S_R4(d,e,a,b,c,72); S_R4(c,d,e,a,b,73); S_R4(b,c,d,e,a,74); S_R4(a,b,c,d,e,75); + S_R4(e,a,b,c,d,76); S_R4(d,e,a,b,c,77); S_R4(c,d,e,a,b,78); S_R4(b,c,d,e,a,79); + + // Add the working vars back into state + pState[0] += a; + pState[1] += b; + pState[2] += c; + pState[3] += d; + pState[4] += e; + + // Wipe variables +#ifdef SHA1_WIPE_VARIABLES + a = b = c = d = e = 0; +#endif +} + +void CSHA1::Update(const UINT_8* pbData, UINT_32 uLen) +{ + UINT_32 j = ((m_count[0] >> 3) & 0x3F); + + if((m_count[0] += (uLen << 3)) < (uLen << 3)) + ++m_count[1]; // Overflow + + m_count[1] += (uLen >> 29); + + UINT_32 i; + if((j + uLen) > 63) + { + i = 64 - j; + memcpy(&m_buffer[j], pbData, i); + Transform(m_state, m_buffer); + + for( ; (i + 63) < uLen; i += 64) + Transform(m_state, &pbData[i]); + + j = 0; + } + else i = 0; + + if((uLen - i) != 0) + memcpy(&m_buffer[j], &pbData[i], uLen - i); +} + +#ifdef SHA1_UTILITY_FUNCTIONS +bool CSHA1::HashFile(const TCHAR* tszFileName) +{ + if(tszFileName == NULL) return false; + + FILE* fpIn = _tfopen(tszFileName, _T("rb")); + if(fpIn == NULL) return false; + + UINT_8* pbData = new UINT_8[SHA1_MAX_FILE_BUFFER]; + if(pbData == NULL) { fclose(fpIn); return false; } + + bool bSuccess = true; + while(true) + { + const size_t uRead = fread(pbData, 1, SHA1_MAX_FILE_BUFFER, fpIn); + + if(uRead > 0) + Update(pbData, static_cast(uRead)); + + if(uRead < SHA1_MAX_FILE_BUFFER) + { + if(feof(fpIn) == 0) bSuccess = false; + break; + } + } + + fclose(fpIn); + delete[] pbData; + return bSuccess; +} +#endif + +void CSHA1::Final() +{ + UINT_32 i; + + UINT_8 pbFinalCount[8]; + for(i = 0; i < 8; ++i) + pbFinalCount[i] = static_cast((m_count[((i >= 4) ? 0 : 1)] >> + ((3 - (i & 3)) * 8) ) & 0xFF); // Endian independent + + Update((UINT_8*)"\200", 1); + + while((m_count[0] & 504) != 448) + Update((UINT_8*)"\0", 1); + + Update(pbFinalCount, 8); // Cause a Transform() + + for(i = 0; i < 20; ++i) + m_digest[i] = static_cast((m_state[i >> 2] >> ((3 - + (i & 3)) * 8)) & 0xFF); + + // Wipe variables for security reasons +#ifdef SHA1_WIPE_VARIABLES + memset(m_buffer, 0, 64); + memset(m_state, 0, 20); + memset(m_count, 0, 8); + memset(pbFinalCount, 0, 8); + Transform(m_state, m_buffer); +#endif +} + +#ifdef SHA1_UTILITY_FUNCTIONS +bool CSHA1::ReportHash(TCHAR* tszReport, REPORT_TYPE rtReportType) const +{ + if(tszReport == NULL) return false; + + TCHAR tszTemp[16]; + + if((rtReportType == REPORT_HEX) || (rtReportType == REPORT_HEX_SHORT)) + { + _sntprintf(tszTemp, 15, _T("%02X"), m_digest[0]); + _tcscpy(tszReport, tszTemp); + + const TCHAR* lpFmt = ((rtReportType == REPORT_HEX) ? _T(" %02X") : _T("%02X")); + for(size_t i = 1; i < 20; ++i) + { + _sntprintf(tszTemp, 15, lpFmt, m_digest[i]); + _tcscat(tszReport, tszTemp); + } + } + else if(rtReportType == REPORT_DIGIT) + { + _sntprintf(tszTemp, 15, _T("%u"), m_digest[0]); + _tcscpy(tszReport, tszTemp); + + for(size_t i = 1; i < 20; ++i) + { + _sntprintf(tszTemp, 15, _T(" %u"), m_digest[i]); + _tcscat(tszReport, tszTemp); + } + } + else return false; + + return true; +} +#endif + +#ifdef SHA1_STL_FUNCTIONS +bool CSHA1::ReportHashStl(std::basic_string& strOut, REPORT_TYPE rtReportType) const +{ + TCHAR tszOut[84]; + const bool bResult = ReportHash(tszOut, rtReportType); + if(bResult) strOut = tszOut; + return bResult; +} +#endif + +bool CSHA1::GetHash(UINT_8* pbDest20) const +{ + if(pbDest20 == NULL) return false; + memcpy(pbDest20, m_digest, 20); + return true; +} + +// Get the raw message digest +// Added by Kevin to be quicker +unsigned char * CSHA1::GetHash( void ) const +{ + return ( unsigned char * ) m_digest; +} + +// http://cseweb.ucsd.edu/~mihir/papers/hmac-cb.pdf +// Sample code: http://www.opensource.apple.com/source/freeradius/freeradius-11/freeradius/src/lib/hmac.c +void CSHA1::HMAC(unsigned char *sharedKey, int sharedKeyLength, unsigned char *data, int dataLength, unsigned char output[SHA1_LENGTH]) +{ + // 1. Append zeros to the end of K to create a 64 byte string + static const int sha1BlockLength=64; + + if (sharedKeyLength > sha1BlockLength) + sharedKeyLength = sha1BlockLength; + + // ipad = the byte 0x36 repeated 64 times + // opad = the byte 0x5C repeated 64 times + unsigned char keyWithIpad[sha1BlockLength]; + unsigned char keyWithOpad[sha1BlockLength]; + + memset( keyWithIpad, 0, sizeof(keyWithIpad)); + memset( keyWithOpad, 0, sizeof(keyWithOpad)); + memcpy( keyWithIpad, sharedKey, sharedKeyLength); + memcpy( keyWithOpad, sharedKey, sharedKeyLength); + + for (int i = 0; i < sha1BlockLength; i++) { + keyWithIpad[i] ^= 0x36; + keyWithOpad[i] ^= 0x5c; + } + + // 3. Append the data stream Text to the 64 byte string resulting from step (2) + // 4. Apply H to the stream generated in step (3) + CSHA1 firstHash; + firstHash.Reset(); + firstHash.Update( keyWithIpad, sha1BlockLength ); + firstHash.Update( data, dataLength ); + firstHash.Final(); + + // 6. Append the H (hash) result from step (4) to the 64 byte string resulting from step (5) + // 7. Apply H to the stream generated in step (6) and output the result + CSHA1 secondHash; + secondHash.Reset(); + secondHash.Update( keyWithOpad, sha1BlockLength ); + secondHash.Update( firstHash.GetHash(), SHA1_LENGTH ); + secondHash.Final(); + + memcpy(output, secondHash.GetHash(), SHA1_LENGTH); + + // char report[128]; + // memset(report,0,128); + // secondHash.ReportHash( report, 0 ); +} + +#pragma warning(pop) diff --git a/src/raknet/DS_BytePool.cpp b/src/raknet/DS_BytePool.cpp new file mode 100644 index 0000000..abf733b --- /dev/null +++ b/src/raknet/DS_BytePool.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/DS_BytePool.hpp" +#include "include/raknet/RakAssert.hpp" +#ifndef __APPLE__ +// Use stdlib and not malloc for compatibility +#include +#endif + +using namespace DataStructures; + +BytePool::BytePool() +{ + pool128.SetPageSize(8192*4); + pool512.SetPageSize(8192*4); + pool2048.SetPageSize(8192*4); + pool8192.SetPageSize(8192*4); +} +BytePool::~BytePool() +{ +} +void BytePool::SetPageSize(int size) +{ + pool128.SetPageSize(size); + pool512.SetPageSize(size); + pool2048.SetPageSize(size); + pool8192.SetPageSize(size); +} +unsigned char *BytePool::Allocate(int bytesWanted, const char *file, unsigned int line) +{ +#ifdef _DISABLE_BYTE_POOL + return rakMalloc_Ex(bytesWanted, _FILE_AND_LINE_); +#endif + unsigned char *out; + if (bytesWanted <= 127) + { + #ifdef _THREADSAFE_BYTE_POOL + mutex128.Lock(); + #endif + out = (unsigned char*) pool128.Allocate(file, line); + #ifdef _THREADSAFE_BYTE_POOL + mutex128.Unlock(); + #endif + out[0]=0; + return ((unsigned char*) out)+1; + } + if (bytesWanted <= 511) + { + #ifdef _THREADSAFE_BYTE_POOL + mutex512.Lock(); + #endif + out = (unsigned char*) pool512.Allocate(file, line); + #ifdef _THREADSAFE_BYTE_POOL + mutex512.Unlock(); + #endif + out[0]=1; + return ((unsigned char*) out)+1; + } + if (bytesWanted <= 2047) + { + #ifdef _THREADSAFE_BYTE_POOL + mutex2048.Lock(); + #endif + out = (unsigned char*) pool2048.Allocate(file, line); + #ifdef _THREADSAFE_BYTE_POOL + mutex2048.Unlock(); + #endif + out[0]=2; + return ((unsigned char*) out)+1; + } + if (bytesWanted <= 8191) + { + #ifdef _THREADSAFE_BYTE_POOL + mutex8192.Lock(); + #endif + out = (unsigned char*) pool8192.Allocate(file, line); + #ifdef _THREADSAFE_BYTE_POOL + mutex8192.Unlock(); + #endif + out[0]=3; + return ((unsigned char*) out)+1; + } + + out = (unsigned char*) rakMalloc_Ex(bytesWanted+1, _FILE_AND_LINE_); + out[0]=(unsigned char)255; + return out+1; +} +void BytePool::Release(unsigned char *data, const char *file, unsigned int line) +{ +#ifdef _DISABLE_BYTE_POOL + _rakFree_Ex(data, _FILE_AND_LINE_ ); +#endif + unsigned char *realData = data-1; + switch (realData[0]) + { + case 0: + #ifdef _THREADSAFE_BYTE_POOL + mutex128.Lock(); + #endif + pool128.Release((unsigned char(*)[128]) realData, file, line ); + #ifdef _THREADSAFE_BYTE_POOL + mutex128.Unlock(); + #endif + break; + case 1: + #ifdef _THREADSAFE_BYTE_POOL + mutex512.Lock(); + #endif + pool512.Release((unsigned char(*)[512]) realData, file, line ); + #ifdef _THREADSAFE_BYTE_POOL + mutex512.Unlock(); + #endif + break; + case 2: + #ifdef _THREADSAFE_BYTE_POOL + mutex2048.Lock(); + #endif + pool2048.Release((unsigned char(*)[2048]) realData, file, line ); + #ifdef _THREADSAFE_BYTE_POOL + mutex2048.Unlock(); + #endif + break; + case 3: + #ifdef _THREADSAFE_BYTE_POOL + mutex8192.Lock(); + #endif + pool8192.Release((unsigned char(*)[8192]) realData, file, line ); + #ifdef _THREADSAFE_BYTE_POOL + mutex8192.Unlock(); + #endif + break; + case 255: + rakFree_Ex(realData, file, line ); + break; + default: + RakAssert(0); + break; + } +} +void BytePool::Clear(const char *file, unsigned int line) +{ + (void) file; + (void) line; + +#ifdef _THREADSAFE_BYTE_POOL + pool128.Clear(file, line); + pool512.Clear(file, line); + pool2048.Clear(file, line); + pool8192.Clear(file, line); +#endif +} diff --git a/src/raknet/DS_ByteQueue.cpp b/src/raknet/DS_ByteQueue.cpp new file mode 100644 index 0000000..d52f9a3 --- /dev/null +++ b/src/raknet/DS_ByteQueue.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/DS_ByteQueue.hpp" +#include // Memmove +#include // realloc +#include + + +using namespace DataStructures; + +ByteQueue::ByteQueue() +{ + readOffset=writeOffset=lengthAllocated=0; + data=0; +} +ByteQueue::~ByteQueue() +{ + Clear(_FILE_AND_LINE_); + + +} +void ByteQueue::WriteBytes(const char *in, unsigned length, const char *file, unsigned int line) +{ + unsigned bytesWritten; + bytesWritten=GetBytesWritten(); + if (lengthAllocated==0 || length > lengthAllocated-bytesWritten-1) + { + unsigned oldLengthAllocated=lengthAllocated; + // Always need to waste 1 byte for the math to work, else writeoffset==readoffset + unsigned newAmountToAllocate=length+oldLengthAllocated+1; + if (newAmountToAllocate<256) + newAmountToAllocate=256; + lengthAllocated=lengthAllocated + newAmountToAllocate; + data=(char*)rakRealloc_Ex(data, lengthAllocated, file, line); + if (writeOffset < readOffset) + { + if (writeOffset <= newAmountToAllocate) + { + memcpy(data + oldLengthAllocated, data, writeOffset); + writeOffset=readOffset+bytesWritten; + } + else + { + memcpy(data + oldLengthAllocated, data, newAmountToAllocate); + memmove(data, data+newAmountToAllocate, writeOffset-newAmountToAllocate); + writeOffset-=newAmountToAllocate; + } + } + } + + if (length <= lengthAllocated-writeOffset) + memcpy(data+writeOffset, in, length); + else + { + // Wrap + memcpy(data+writeOffset, in, lengthAllocated-writeOffset); + memcpy(data, in+(lengthAllocated-writeOffset), length-(lengthAllocated-writeOffset)); + } + writeOffset=(writeOffset+length) % lengthAllocated; +} +bool ByteQueue::ReadBytes(char *out, unsigned maxLengthToRead, bool peek) +{ + unsigned bytesWritten = GetBytesWritten(); + unsigned bytesToRead = bytesWritten < maxLengthToRead ? bytesWritten : maxLengthToRead; + if (bytesToRead==0) + return false; + if (writeOffset>=readOffset) + { + memcpy(out, data+readOffset, bytesToRead); + } + else + { + unsigned availableUntilWrap = lengthAllocated-readOffset; + if (bytesToRead <= availableUntilWrap) + { + memcpy(out, data+readOffset, bytesToRead); + } + else + { + memcpy(out, data+readOffset, availableUntilWrap); + memcpy(out+availableUntilWrap, data, bytesToRead-availableUntilWrap); + } + } + + if (peek==false) + IncrementReadOffset(bytesToRead); + + return true; +} +char* ByteQueue::PeekContiguousBytes(unsigned int *outLength) const +{ + if (writeOffset>=readOffset) + *outLength=writeOffset-readOffset; + else + *outLength=lengthAllocated-readOffset; + return data+readOffset; +} +void ByteQueue::Clear(const char *file, unsigned int line) +{ + if (lengthAllocated) + rakFree_Ex(data, file, line ); + readOffset=writeOffset=lengthAllocated=0; + data=0; +} +unsigned ByteQueue::GetBytesWritten(void) const +{ + if (writeOffset>=readOffset) + return writeOffset-readOffset; + else + return writeOffset+(lengthAllocated-readOffset); +} +void ByteQueue::IncrementReadOffset(unsigned length) +{ + readOffset=(readOffset+length) % lengthAllocated; +} +void ByteQueue::DecrementReadOffset(unsigned length) +{ + if (length>readOffset) + readOffset=lengthAllocated-(length-readOffset); + else + readOffset-=length; +} +void ByteQueue::Print(void) +{ + unsigned i; + for (i=readOffset; i!=writeOffset; i++) + RAKNET_DEBUG_PRINTF("%i ", data[i]); + RAKNET_DEBUG_PRINTF("\n"); +} diff --git a/src/raknet/DS_HuffmanEncodingTree.cpp b/src/raknet/DS_HuffmanEncodingTree.cpp new file mode 100644 index 0000000..c4b8c6e --- /dev/null +++ b/src/raknet/DS_HuffmanEncodingTree.cpp @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/DS_HuffmanEncodingTree.hpp" +#include "include/raknet/DS_Queue.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/RakAssert.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +HuffmanEncodingTree::HuffmanEncodingTree() +{ + root = 0; +} + +HuffmanEncodingTree::~HuffmanEncodingTree() +{ + FreeMemory(); +} + +void HuffmanEncodingTree::FreeMemory( void ) +{ + if ( root == 0 ) + return ; + + // Use an in-order traversal to delete the tree + DataStructures::Queue nodeQueue; + + HuffmanEncodingTreeNode *node; + + nodeQueue.Push( root, _FILE_AND_LINE_ ); + + while ( nodeQueue.Size() > 0 ) + { + node = nodeQueue.Pop(); + + if ( node->left ) + nodeQueue.Push( node->left, _FILE_AND_LINE_ ); + + if ( node->right ) + nodeQueue.Push( node->right, _FILE_AND_LINE_ ); + + RakNet::OP_DELETE(node, _FILE_AND_LINE_); + } + + // Delete the encoding table + for ( int i = 0; i < 256; i++ ) + rakFree_Ex(encodingTable[ i ].encoding, _FILE_AND_LINE_ ); + + root = 0; +} + + +////#include + +// Given a frequency table of 256 elements, all with a frequency of 1 or more, generate the tree +void HuffmanEncodingTree::GenerateFromFrequencyTable( unsigned int frequencyTable[ 256 ] ) +{ + int counter; + HuffmanEncodingTreeNode * node; + HuffmanEncodingTreeNode *leafList[ 256 ]; // Keep a copy of the pointers to all the leaves so we can generate the encryption table bottom-up, which is easier + // 1. Make 256 trees each with a weight equal to the frequency of the corresponding character + DataStructures::LinkedList huffmanEncodingTreeNodeList; + + FreeMemory(); + + for ( counter = 0; counter < 256; counter++ ) + { + node = RakNet::OP_NEW( _FILE_AND_LINE_ ); + node->left = 0; + node->right = 0; + node->value = (unsigned char) counter; + node->weight = frequencyTable[ counter ]; + + if ( node->weight == 0 ) + node->weight = 1; // 0 weights are illegal + + leafList[ counter ] = node; // Used later to generate the encryption table + + InsertNodeIntoSortedList( node, &huffmanEncodingTreeNodeList ); // Insert and maintain sort order. + } + + + // 2. While there is more than one tree, take the two smallest trees and merge them so that the two trees are the left and right + // children of a new node, where the new node has the weight the sum of the weight of the left and right child nodes. +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while ( 1 ) + { + huffmanEncodingTreeNodeList.Beginning(); + HuffmanEncodingTreeNode *lesser, *greater; + lesser = huffmanEncodingTreeNodeList.Pop(); + greater = huffmanEncodingTreeNodeList.Pop(); + node = RakNet::OP_NEW( _FILE_AND_LINE_ ); + node->left = lesser; + node->right = greater; + node->weight = lesser->weight + greater->weight; + lesser->parent = node; // This is done to make generating the encryption table easier + greater->parent = node; // This is done to make generating the encryption table easier + + if ( huffmanEncodingTreeNodeList.Size() == 0 ) + { + // 3. Assign the one remaining node in the list to the root node. + root = node; + root->parent = 0; + break; + } + + // Put the new node back into the list at the correct spot to maintain the sort. Linear search time + InsertNodeIntoSortedList( node, &huffmanEncodingTreeNodeList ); + } + + bool tempPath[ 256 ]; // Maximum path length is 256 + unsigned short tempPathLength; + HuffmanEncodingTreeNode *currentNode; + RakNet::BitStream bitStream; + + // Generate the encryption table. From before, we have an array of pointers to all the leaves which contain pointers to their parents. + // This can be done more efficiently but this isn't bad and it's way easier to program and debug + + for ( counter = 0; counter < 256; counter++ ) + { + // Already done at the end of the loop and before it! + tempPathLength = 0; + + // Set the current node at the leaf + currentNode = leafList[ counter ]; + + do + { + if ( currentNode->parent->left == currentNode ) // We're storing the paths in reverse order.since we are going from the leaf to the root + tempPath[ tempPathLength++ ] = false; + else + tempPath[ tempPathLength++ ] = true; + + currentNode = currentNode->parent; + } + + while ( currentNode != root ); + + // Write to the bitstream in the reverse order that we stored the path, which gives us the correct order from the root to the leaf + while ( tempPathLength-- > 0 ) + { + if ( tempPath[ tempPathLength ] ) // Write 1's and 0's because writing a bool will write the BitStream TYPE_CHECKING validation bits if that is defined along with the actual data bit, which is not what we want + bitStream.Write1(); + else + bitStream.Write0(); + } + + // Read data from the bitstream, which is written to the encoding table in bits and bitlength. Note this function allocates the encodingTable[counter].encoding pointer + encodingTable[ counter ].bitLength = ( unsigned char ) bitStream.CopyData( &encodingTable[ counter ].encoding ); + + // Reset the bitstream for the next iteration + bitStream.Reset(); + } +} + +// Pass an array of bytes to array and a preallocated BitStream to receive the output +void HuffmanEncodingTree::EncodeArray( unsigned char *input, size_t sizeInBytes, RakNet::BitStream * output ) +{ + unsigned counter; + + // For each input byte, Write out the corresponding series of 1's and 0's that give the encoded representation + for ( counter = 0; counter < sizeInBytes; counter++ ) + { + output->WriteBits( encodingTable[ input[ counter ] ].encoding, encodingTable[ input[ counter ] ].bitLength, false ); // Data is left aligned + } + + // Byte align the output so the unassigned remaining bits don't equate to some actual value + if ( output->GetNumberOfBitsUsed() % 8 != 0 ) + { + // Find an input that is longer than the remaining bits. Write out part of it to pad the output to be byte aligned. + unsigned char remainingBits = (unsigned char) ( 8 - ( output->GetNumberOfBitsUsed() % 8 ) ); + + for ( counter = 0; counter < 256; counter++ ) + if ( encodingTable[ counter ].bitLength > remainingBits ) + { + output->WriteBits( encodingTable[ counter ].encoding, remainingBits, false ); // Data is left aligned + break; + } + +#ifdef _DEBUG + RakAssert( counter != 256 ); // Given 256 elements, we should always be able to find an input that would be >= 7 bits + +#endif + + } +} + +unsigned HuffmanEncodingTree::DecodeArray( RakNet::BitStream * input, BitSize_t sizeInBits, size_t maxCharsToWrite, unsigned char *output ) +{ + HuffmanEncodingTreeNode * currentNode; + + unsigned outputWriteIndex; + outputWriteIndex = 0; + currentNode = root; + + // For each bit, go left if it is a 0 and right if it is a 1. When we reach a leaf, that gives us the desired value and we restart from the root + + for ( unsigned counter = 0; counter < sizeInBits; counter++ ) + { + if ( input->ReadBit() == false ) // left! + currentNode = currentNode->left; + else + currentNode = currentNode->right; + + if ( currentNode->left == 0 && currentNode->right == 0 ) // Leaf + { + + if ( outputWriteIndex < maxCharsToWrite ) + output[ outputWriteIndex ] = currentNode->value; + + outputWriteIndex++; + + currentNode = root; + } + } + + return outputWriteIndex; +} + +// Pass an array of encoded bytes to array and a preallocated BitStream to receive the output +void HuffmanEncodingTree::DecodeArray( unsigned char *input, BitSize_t sizeInBits, RakNet::BitStream * output ) +{ + HuffmanEncodingTreeNode * currentNode; + + if ( sizeInBits <= 0 ) + return ; + + RakNet::BitStream bitStream( input, BITS_TO_BYTES(sizeInBits), false ); + + currentNode = root; + + // For each bit, go left if it is a 0 and right if it is a 1. When we reach a leaf, that gives us the desired value and we restart from the root + for ( unsigned counter = 0; counter < sizeInBits; counter++ ) + { + if ( bitStream.ReadBit() == false ) // left! + currentNode = currentNode->left; + else + currentNode = currentNode->right; + + if ( currentNode->left == 0 && currentNode->right == 0 ) // Leaf + { + output->WriteBits( &( currentNode->value ), sizeof( char ) * 8, true ); // Use WriteBits instead of Write(char) because we want to avoid TYPE_CHECKING + currentNode = root; + } + } +} + +// Insertion sort. Slow but easy to write in this case +void HuffmanEncodingTree::InsertNodeIntoSortedList( HuffmanEncodingTreeNode * node, DataStructures::LinkedList *huffmanEncodingTreeNodeList ) const +{ + if ( huffmanEncodingTreeNodeList->Size() == 0 ) + { + huffmanEncodingTreeNodeList->Insert( node ); + return ; + } + + huffmanEncodingTreeNodeList->Beginning(); + + unsigned counter = 0; +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while ( 1 ) + { + if ( huffmanEncodingTreeNodeList->Peek()->weight < node->weight ) + ++( *huffmanEncodingTreeNodeList ); + else + { + huffmanEncodingTreeNodeList->Insert( node ); + break; + } + + // Didn't find a spot in the middle - add to the end + if ( ++counter == huffmanEncodingTreeNodeList->Size() ) + { + huffmanEncodingTreeNodeList->End(); + + huffmanEncodingTreeNodeList->Add( node ) + + ; // Add to the end + break; + } + } +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif diff --git a/src/raknet/DS_Table.cpp b/src/raknet/DS_Table.cpp new file mode 100644 index 0000000..7da9497 --- /dev/null +++ b/src/raknet/DS_Table.cpp @@ -0,0 +1,1131 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/DS_Table.hpp" +#include "include/raknet/DS_OrderedList.hpp" +#include +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/Itoa.hpp" + +using namespace DataStructures; + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +void ExtendRows(Table::Row* input, int index) +{ + (void) index; + input->cells.Insert(RakNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_ ); +} +void FreeRow(Table::Row* input, int index) +{ + (void) index; + + unsigned i; + for (i=0; i < input->cells.Size(); i++) + { + RakNet::OP_DELETE(input->cells[i], _FILE_AND_LINE_); + } + RakNet::OP_DELETE(input, _FILE_AND_LINE_); +} +Table::Cell::Cell() +{ + isEmpty=true; + c=0; + ptr=0; + i=0.0; +} +Table::Cell::~Cell() +{ + Clear(); +} +Table::Cell& Table::Cell::operator = ( const Table::Cell& input ) +{ + isEmpty=input.isEmpty; + i=input.i; + ptr=input.ptr; + if (c) + rakFree_Ex(c, _FILE_AND_LINE_); + if (input.c) + { + c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ ); + memcpy(c, input.c, (int) i); + } + else + c=0; + return *this; +} +Table::Cell::Cell( const Table::Cell & input) +{ + isEmpty=input.isEmpty; + i=input.i; + ptr=input.ptr; + if (input.c) + { + if (c) + rakFree_Ex(c, _FILE_AND_LINE_); + c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ ); + memcpy(c, input.c, (int) i); + } +} +void Table::Cell::Set(double input) +{ + Clear(); + i=input; + c=0; + ptr=0; + isEmpty=false; +} +void Table::Cell::Set(unsigned int input) +{ + Set((int) input); +} +void Table::Cell::Set(int input) +{ + Clear(); + i=(double) input; + c=0; + ptr=0; + isEmpty=false; +} + +void Table::Cell::Set(const char *input) +{ + Clear(); + + if (input) + { + i=(int)strlen(input)+1; + c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ ); + strcpy(c, input); + } + else + { + c=0; + i=0; + } + ptr=0; + isEmpty=false; +} +void Table::Cell::Set(const char *input, int inputLength) +{ + Clear(); + if (input) + { + c = (char*) rakMalloc_Ex( inputLength, _FILE_AND_LINE_ ); + i=inputLength; + memcpy(c, input, inputLength); + } + else + { + c=0; + i=0; + } + ptr=0; + isEmpty=false; +} +void Table::Cell::SetPtr(void* p) +{ + Clear(); + c=0; + ptr=p; + isEmpty=false; +} +void Table::Cell::Get(int *output) +{ + RakAssert(isEmpty==false); + int o = (int) i; + *output=o; +} +void Table::Cell::Get(double *output) +{ + RakAssert(isEmpty==false); + *output=i; +} +void Table::Cell::Get(char *output) +{ + RakAssert(isEmpty==false); + strcpy(output, c); +} +void Table::Cell::Get(char *output, int *outputLength) +{ + RakAssert(isEmpty==false); + memcpy(output, c, (int) i); + if (outputLength) + *outputLength=(int) i; +} +RakNet::RakString Table::Cell::ToString(ColumnType columnType) +{ + if (isEmpty) + return RakNet::RakString(); + + if (columnType==NUMERIC) + { + return RakNet::RakString("%f", i); + } + else if (columnType==STRING) + { + return RakNet::RakString(c); + } + else if (columnType==BINARY) + { + return RakNet::RakString(""); + } + else if (columnType==POINTER) + { + return RakNet::RakString("%p", ptr); + } + + return RakNet::RakString(); +} +Table::Cell::Cell(double numericValue, char *charValue, void *ptr, ColumnType type) +{ + SetByType(numericValue,charValue,ptr,type); +} +void Table::Cell::SetByType(double numericValue, char *charValue, void *ptr, ColumnType type) +{ + isEmpty=true; + if (type==NUMERIC) + { + Set(numericValue); + } + else if (type==STRING) + { + Set(charValue); + } + else if (type==BINARY) + { + Set(charValue, (int) numericValue); + } + else if (type==POINTER) + { + SetPtr(ptr); + } + else + { + ptr=(void*) charValue; + } +} +Table::ColumnType Table::Cell::EstimateColumnType(void) const +{ + if (c) + { + if (i!=0.0f) + return BINARY; + else + return STRING; + } + + if (ptr) + return POINTER; + return NUMERIC; +} +void Table::Cell::Clear(void) +{ + if (isEmpty==false && c) + { + rakFree_Ex(c, _FILE_AND_LINE_); + c=0; + } + isEmpty=true; +} +Table::ColumnDescriptor::ColumnDescriptor() +{ + +} +Table::ColumnDescriptor::~ColumnDescriptor() +{ + +} +Table::ColumnDescriptor::ColumnDescriptor(const char cn[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType ct) +{ + columnType=ct; + strcpy(columnName, cn); +} +void Table::Row::UpdateCell(unsigned columnIndex, double value) +{ + cells[columnIndex]->Clear(); + cells[columnIndex]->Set(value); + +// cells[columnIndex]->i=value; +// cells[columnIndex]->c=0; +// cells[columnIndex]->isEmpty=false; +} +void Table::Row::UpdateCell(unsigned columnIndex, const char *str) +{ + cells[columnIndex]->Clear(); + cells[columnIndex]->Set(str); +} +void Table::Row::UpdateCell(unsigned columnIndex, int byteLength, const char *data) +{ + cells[columnIndex]->Clear(); + cells[columnIndex]->Set(data,byteLength); +} +Table::Table() +{ +} +Table::~Table() +{ + Clear(); +} +unsigned Table::AddColumn(const char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType columnType) +{ + if (columnName[0]==0) + return (unsigned) -1; + + // Add this column. + columns.Insert(Table::ColumnDescriptor(columnName, columnType), _FILE_AND_LINE_); + + // Extend the rows by one + rows.ForEachData(ExtendRows); + + return columns.Size()-1; +} +void Table::RemoveColumn(unsigned columnIndex) +{ + if (columnIndex >= columns.Size()) + return; + + columns.RemoveAtIndex(columnIndex); + + // Remove this index from each row. + int i; + DataStructures::Page *cur = rows.GetListHead(); + while (cur) + { + for (i=0; i < cur->size; i++) + { + RakNet::OP_DELETE(cur->data[i]->cells[columnIndex], _FILE_AND_LINE_); + cur->data[i]->cells.RemoveAtIndex(columnIndex); + } + + cur=cur->next; + } +} +unsigned Table::ColumnIndex(const char *columnName) const +{ + unsigned columnIndex; + for (columnIndex=0; columnIndex= columns.Size()) + return 0; + else + return (char*)columns[index].columnName; +} +Table::ColumnType Table::GetColumnType(unsigned index) const +{ + if (index >= columns.Size()) + return (Table::ColumnType) 0; + else + return columns[index].columnType; +} +unsigned Table::GetColumnCount(void) const +{ + return columns.Size(); +} +unsigned Table::GetRowCount(void) const +{ + return rows.Size(); +} +Table::Row* Table::AddRow(unsigned rowId) +{ + Row *newRow; + newRow = RakNet::OP_NEW( _FILE_AND_LINE_ ); + if (rows.Insert(rowId, newRow)==false) + { + RakNet::OP_DELETE(newRow, _FILE_AND_LINE_); + return 0; // Already exists + } + unsigned rowIndex; + for (rowIndex=0; rowIndex < columns.Size(); rowIndex++) + newRow->cells.Insert( RakNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_ ); + return newRow; +} +Table::Row* Table::AddRow(unsigned rowId, DataStructures::List &initialCellValues) +{ + Row *newRow = RakNet::OP_NEW( _FILE_AND_LINE_ ); + unsigned rowIndex; + for (rowIndex=0; rowIndex < columns.Size(); rowIndex++) + { + if (rowIndex < initialCellValues.Size() && initialCellValues[rowIndex].isEmpty==false) + { + Table::Cell *c; + c = RakNet::OP_NEW(_FILE_AND_LINE_); + c->SetByType(initialCellValues[rowIndex].i,initialCellValues[rowIndex].c,initialCellValues[rowIndex].ptr,columns[rowIndex].columnType); + newRow->cells.Insert(c, _FILE_AND_LINE_ ); + } + else + newRow->cells.Insert(RakNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_ ); + } + rows.Insert(rowId, newRow); + return newRow; +} +Table::Row* Table::AddRow(unsigned rowId, DataStructures::List &initialCellValues, bool copyCells) +{ + Row *newRow = RakNet::OP_NEW( _FILE_AND_LINE_ ); + unsigned rowIndex; + for (rowIndex=0; rowIndex < columns.Size(); rowIndex++) + { + if (rowIndex < initialCellValues.Size() && initialCellValues[rowIndex] && initialCellValues[rowIndex]->isEmpty==false) + { + if (copyCells==false) + newRow->cells.Insert(RakNet::OP_NEW_4( _FILE_AND_LINE_, initialCellValues[rowIndex]->i, initialCellValues[rowIndex]->c, initialCellValues[rowIndex]->ptr, columns[rowIndex].columnType), _FILE_AND_LINE_); + else + { + Table::Cell *c = RakNet::OP_NEW( _FILE_AND_LINE_ ); + newRow->cells.Insert(c, _FILE_AND_LINE_); + *c=*(initialCellValues[rowIndex]); + } + } + else + newRow->cells.Insert(RakNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_); + } + rows.Insert(rowId, newRow); + return newRow; +} +Table::Row* Table::AddRowColumns(unsigned rowId, Row *row, DataStructures::List columnIndices) +{ + Row *newRow = RakNet::OP_NEW( _FILE_AND_LINE_ ); + unsigned columnIndex; + for (columnIndex=0; columnIndex < columnIndices.Size(); columnIndex++) + { + if (row->cells[columnIndices[columnIndex]]->isEmpty==false) + { + newRow->cells.Insert(RakNet::OP_NEW_4( _FILE_AND_LINE_, + row->cells[columnIndices[columnIndex]]->i, + row->cells[columnIndices[columnIndex]]->c, + row->cells[columnIndices[columnIndex]]->ptr, + columns[columnIndex].columnType + ), _FILE_AND_LINE_); + } + else + { + newRow->cells.Insert(RakNet::OP_NEW(_FILE_AND_LINE_), _FILE_AND_LINE_); + } + } + rows.Insert(rowId, newRow); + return newRow; +} +bool Table::RemoveRow(unsigned rowId) +{ + Row *out; + if (rows.Delete(rowId, out)) + { + DeleteRow(out); + return true; + } + return false; +} +void Table::RemoveRows(Table *tableContainingRowIDs) +{ + unsigned i; + DataStructures::Page *cur = tableContainingRowIDs->GetRows().GetListHead(); + while (cur) + { + for (i=0; i < (unsigned)cur->size; i++) + { + rows.Delete(cur->keys[i]); + } + cur=cur->next; + } + return; +} +bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, int value) +{ + RakAssert(columns[columnIndex].columnType==NUMERIC); + + Row *row = GetRowByID(rowId); + if (row) + { + row->UpdateCell(columnIndex, value); + return true; + } + return false; +} +bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, char *str) +{ + RakAssert(columns[columnIndex].columnType==STRING); + + Row *row = GetRowByID(rowId); + if (row) + { + row->UpdateCell(columnIndex, str); + return true; + } + return false; +} +bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, int byteLength, char *data) +{ + RakAssert(columns[columnIndex].columnType==BINARY); + + Row *row = GetRowByID(rowId); + if (row) + { + row->UpdateCell(columnIndex, byteLength, data); + return true; + } + return false; +} +bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int value) +{ + RakAssert(columns[columnIndex].columnType==NUMERIC); + + Row *row = GetRowByIndex(rowIndex,0); + if (row) + { + row->UpdateCell(columnIndex, value); + return true; + } + return false; +} +bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, char *str) +{ + RakAssert(columns[columnIndex].columnType==STRING); + + Row *row = GetRowByIndex(rowIndex,0); + if (row) + { + row->UpdateCell(columnIndex, str); + return true; + } + return false; +} +bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int byteLength, char *data) +{ + RakAssert(columns[columnIndex].columnType==BINARY); + + Row *row = GetRowByIndex(rowIndex,0); + if (row) + { + row->UpdateCell(columnIndex, byteLength, data); + return true; + } + return false; +} +void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, int *output) +{ + RakAssert(columns[columnIndex].columnType==NUMERIC); + + Row *row = GetRowByIndex(rowIndex,0); + if (row) + { + row->cells[columnIndex]->Get(output); + } +} +void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output) +{ + RakAssert(columns[columnIndex].columnType==STRING); + + Row *row = GetRowByIndex(rowIndex,0); + if (row) + { + row->cells[columnIndex]->Get(output); + } +} +void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output, int *outputLength) +{ + RakAssert(columns[columnIndex].columnType==BINARY); + + Row *row = GetRowByIndex(rowIndex,0); + if (row) + { + row->cells[columnIndex]->Get(output, outputLength); + } +} +Table::FilterQuery::FilterQuery() +{ + columnName[0]=0; +} +Table::FilterQuery::~FilterQuery() +{ + +} +Table::FilterQuery::FilterQuery(unsigned column, Cell *cell, FilterQueryType op) +{ + columnIndex=column; + cellValue=cell; + operation=op; +} +Table::Row* Table::GetRowByID(unsigned rowId) const +{ + Row *row; + if (rows.Get(rowId, row)) + return row; + return 0; +} + +Table::Row* Table::GetRowByIndex(unsigned rowIndex, unsigned *key) const +{ + DataStructures::Page *cur = rows.GetListHead(); + while (cur) + { + if (rowIndex < (unsigned)cur->size) + { + if (key) + *key=cur->keys[rowIndex]; + return cur->data[rowIndex]; + } + if (rowIndex <= (unsigned)cur->size) + rowIndex-=cur->size; + else + return 0; + cur=cur->next; + } + return 0; +} + +void Table::QueryTable(unsigned *columnIndicesSubset, unsigned numColumnSubset, FilterQuery *inclusionFilters, unsigned numInclusionFilters, unsigned *rowIds, unsigned numRowIDs, Table *result) +{ + unsigned i; + DataStructures::List columnIndicesToReturn; + + // Clear the result table. + result->Clear(); + + if (columnIndicesSubset && numColumnSubset>0) + { + for (i=0; i < numColumnSubset; i++) + { + if (columnIndicesSubset[i]AddColumn(columns[columnIndicesToReturn[i]].columnName,columns[columnIndicesToReturn[i]].columnType); + } + + // Get the column indices of the filter queries. + DataStructures::List inclusionFilterColumnIndices; + if (inclusionFilters && numInclusionFilters>0) + { + for (i=0; i < numInclusionFilters; i++) + { + if (inclusionFilters[i].columnName[0]) + inclusionFilters[i].columnIndex=ColumnIndex(inclusionFilters[i].columnName); + if (inclusionFilters[i].columnIndex *cur = rows.GetListHead(); + while (cur) + { + for (i=0; i < (unsigned)cur->size; i++) + { + QueryRow(inclusionFilterColumnIndices, columnIndicesToReturn, cur->keys[i], cur->data[i], inclusionFilters, result); + } + cur=cur->next; + } + } + else + { + // Specific rows + Row *row; + for (i=0; i < numRowIDs; i++) + { + if (rows.Get(rowIds[i], row)) + { + QueryRow(inclusionFilterColumnIndices, columnIndicesToReturn, rowIds[i], row, inclusionFilters, result); + } + } + } +} + +void Table::QueryRow(DataStructures::List &inclusionFilterColumnIndices, DataStructures::List &columnIndicesToReturn, unsigned key, Table::Row* row, FilterQuery *inclusionFilters, Table *result) +{ + bool pass=false; + unsigned columnIndex; + unsigned j; + + // If no inclusion filters, just add the row + if (inclusionFilterColumnIndices.Size()==0) + { + result->AddRowColumns(key, row, columnIndicesToReturn); + } + else + { + // Go through all inclusion filters. Only add this row if all filters pass. + for (j=0; jcells[columnIndex]->isEmpty==false ) + { + if (columns[inclusionFilterColumnIndices[j]].columnType==STRING && + (row->cells[columnIndex]->c==0 || + inclusionFilters[j].cellValue->c==0) ) + continue; + + switch (inclusionFilters[j].operation) + { + case QF_EQUAL: + switch(columns[inclusionFilterColumnIndices[j]].columnType) + { + case NUMERIC: + pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i; + break; + case STRING: + pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)==0; + break; + case BINARY: + pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i && + memcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c, (int) row->cells[columnIndex]->i)==0; + break; + case POINTER: + pass=row->cells[columnIndex]->ptr==inclusionFilters[j].cellValue->ptr; + break; + } + break; + case QF_NOT_EQUAL: + switch(columns[inclusionFilterColumnIndices[j]].columnType) + { + case NUMERIC: + pass=row->cells[columnIndex]->i!=inclusionFilters[j].cellValue->i; + break; + case STRING: + pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)!=0; + break; + case BINARY: + pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i && + memcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c, (int) row->cells[columnIndex]->i)==0; + break; + case POINTER: + pass=row->cells[columnIndex]->ptr!=inclusionFilters[j].cellValue->ptr; + break; + } + break; + case QF_GREATER_THAN: + switch(columns[inclusionFilterColumnIndices[j]].columnType) + { + case NUMERIC: + pass=row->cells[columnIndex]->i>inclusionFilters[j].cellValue->i; + break; + case STRING: + pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)>0; + break; + case BINARY: + break; + case POINTER: + pass=row->cells[columnIndex]->ptr>inclusionFilters[j].cellValue->ptr; + break; + } + break; + case QF_GREATER_THAN_EQ: + switch(columns[inclusionFilterColumnIndices[j]].columnType) + { + case NUMERIC: + pass=row->cells[columnIndex]->i>=inclusionFilters[j].cellValue->i; + break; + case STRING: + pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)>=0; + break; + case BINARY: + break; + case POINTER: + pass=row->cells[columnIndex]->ptr>=inclusionFilters[j].cellValue->ptr; + break; + } + break; + case QF_LESS_THAN: + switch(columns[inclusionFilterColumnIndices[j]].columnType) + { + case NUMERIC: + pass=row->cells[columnIndex]->ii; + break; + case STRING: + pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)<0; + break; + case BINARY: + break; + case POINTER: + pass=row->cells[columnIndex]->ptrptr; + break; + } + break; + case QF_LESS_THAN_EQ: + switch(columns[inclusionFilterColumnIndices[j]].columnType) + { + case NUMERIC: + pass=row->cells[columnIndex]->i<=inclusionFilters[j].cellValue->i; + break; + case STRING: + pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)<=0; + break; + case BINARY: + break; + case POINTER: + pass=row->cells[columnIndex]->ptr<=inclusionFilters[j].cellValue->ptr; + break; + } + break; + case QF_IS_EMPTY: + pass=false; + break; + case QF_NOT_EMPTY: + pass=true; + break; + default: + pass=false; + RakAssert(0); + break; + } + } + else + { + if (inclusionFilters[j].operation==QF_IS_EMPTY) + pass=true; + else + pass=false; // No value for this cell + } + + if (pass==false) + break; + } + + if (pass) + { + result->AddRowColumns(key, row, columnIndicesToReturn); + } + } +} + +static Table::SortQuery *_sortQueries; +static unsigned _numSortQueries; +static DataStructures::List *_columnIndices; +static DataStructures::List *_columns; +int RowSort(Table::Row* const &first, Table::Row* const &second) // first is the one inserting, second is the one already there. +{ + unsigned i, columnIndex; + for (i=0; i<_numSortQueries; i++) + { + columnIndex=(*_columnIndices)[i]; + if (columnIndex==(unsigned)-1) + continue; + + if (first->cells[columnIndex]->isEmpty==true && second->cells[columnIndex]->isEmpty==false) + return 1; // Empty cells always go at the end + + if (first->cells[columnIndex]->isEmpty==false && second->cells[columnIndex]->isEmpty==true) + return -1; // Empty cells always go at the end + + if (_sortQueries[i].operation==Table::QS_INCREASING_ORDER) + { + if ((*_columns)[columnIndex].columnType==Table::NUMERIC) + { + if (first->cells[columnIndex]->i>second->cells[columnIndex]->i) + return 1; + if (first->cells[columnIndex]->icells[columnIndex]->i) + return -1; + } + else + { + // String + if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)>0) + return 1; + if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)<0) + return -1; + } + } + else + { + if ((*_columns)[columnIndex].columnType==Table::NUMERIC) + { + if (first->cells[columnIndex]->icells[columnIndex]->i) + return 1; + if (first->cells[columnIndex]->i>second->cells[columnIndex]->i) + return -1; + } + else + { + // String + if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)<0) + return 1; + if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)>0) + return -1; + } + } + } + + return 0; +} +void Table::SortTable(Table::SortQuery *sortQueries, unsigned numSortQueries, Table::Row** out) +{ + unsigned i; + unsigned outLength; + DataStructures::List columnIndices; + _sortQueries=sortQueries; + _numSortQueries=numSortQueries; + _columnIndices=&columnIndices; + _columns=&columns; + bool anyValid=false; + + for (i=0; i < numSortQueries; i++) + { + if (sortQueries[i].columnIndex *cur; + cur = rows.GetListHead(); + if (anyValid==false) + { + outLength=0; + while (cur) + { + for (i=0; i < (unsigned)cur->size; i++) + { + out[(outLength)++]=cur->data[i]; + } + cur=cur->next; + } + return; + } + + // Start adding to ordered list. + DataStructures::OrderedList orderedList; + while (cur) + { + for (i=0; i < (unsigned)cur->size; i++) + { + RakAssert(cur->data[i]); + orderedList.Insert(cur->data[i],cur->data[i], true, _FILE_AND_LINE_); + } + cur=cur->next; + } + + outLength=0; + for (i=0; i < orderedList.Size(); i++) + out[(outLength)++]=orderedList[i]; +} +void Table::PrintColumnHeaders(char *out, int outLength, char columnDelineator) const +{ + if (outLength<=0) + return; + if (outLength==1) + { + *out=0; + return; + } + + unsigned i; + out[0]=0; + int len; + for (i=0; i < columns.Size(); i++) + { + if (i!=0) + { + len = (int) strlen(out); + if (len < outLength-1) + sprintf(out+len, "%c", columnDelineator); + else + return; + } + + len = (int) strlen(out); + if (len < outLength-(int) strlen(columns[i].columnName)) + sprintf(out+len, "%s", columns[i].columnName); + else + return; + } +} +void Table::PrintRow(char *out, int outLength, char columnDelineator, bool printDelineatorForBinary, Table::Row* inputRow) const +{ + if (outLength<=0) + return; + if (outLength==1) + { + *out=0; + return; + } + + if (inputRow->cells.Size()!=columns.Size()) + { + strncpy(out, "Cell width does not match column width.\n", outLength); + out[outLength-1]=0; + return; + } + + char buff[512]; + unsigned i; + int len; + out[0]=0; + for (i=0; i < columns.Size(); i++) + { + if (columns[i].columnType==NUMERIC) + { + if (inputRow->cells[i]->isEmpty==false) + { + sprintf(buff, "%f", inputRow->cells[i]->i); + len=(int)strlen(buff); + } + else + len=0; + if (i+1!=columns.Size()) + buff[len++]=columnDelineator; + buff[len]=0; + } + else if (columns[i].columnType==STRING) + { + if (inputRow->cells[i]->isEmpty==false && inputRow->cells[i]->c) + { + strncpy(buff, inputRow->cells[i]->c, 512-2); + buff[512-2]=0; + len=(int)strlen(buff); + } + else + len=0; + if (i+1!=columns.Size()) + buff[len++]=columnDelineator; + buff[len]=0; + } + else if (columns[i].columnType==POINTER) + { + if (inputRow->cells[i]->isEmpty==false && inputRow->cells[i]->ptr) + { + sprintf(buff, "%p", inputRow->cells[i]->ptr); + len=(int)strlen(buff); + } + else + len=0; + if (i+1!=columns.Size()) + buff[len++]=columnDelineator; + buff[len]=0; + } + else + { + if (printDelineatorForBinary) + { + if (i+1!=columns.Size()) + buff[0]=columnDelineator; + buff[1]=0; + } + else + buff[0]=0; + + } + + len=(int)strlen(out); + if (outLength==len+1) + break; + strncpy(out+len, buff, outLength-len); + out[outLength-1]=0; + } +} + +void Table::Clear(void) +{ + rows.ForEachData(FreeRow); + rows.Clear(); + columns.Clear(true, _FILE_AND_LINE_); +} +const List& Table::GetColumns(void) const +{ + return columns; +} +const DataStructures::BPlusTree& Table::GetRows(void) const +{ + return rows; +} +DataStructures::Page * Table::GetListHead(void) +{ + return rows.GetListHead(); +} +unsigned Table::GetAvailableRowId(void) const +{ + bool setKey=false; + unsigned key=0; + int i; + DataStructures::Page *cur = rows.GetListHead(); + + while (cur) + { + for (i=0; i < cur->size; i++) + { + if (setKey==false) + { + key=cur->keys[i]+1; + setKey=true; + } + else + { + if (key!=cur->keys[i]) + return key; + key++; + } + } + + cur=cur->next; + } + return key; +} +void Table::DeleteRow(Table::Row *row) +{ + unsigned rowIndex; + for (rowIndex=0; rowIndex < row->cells.Size(); rowIndex++) + { + RakNet::OP_DELETE(row->cells[rowIndex], _FILE_AND_LINE_); + } + RakNet::OP_DELETE(row, _FILE_AND_LINE_); +} +Table& Table::operator = ( const Table& input ) +{ + Clear(); + + unsigned int i; + for (i=0; i < input.GetColumnCount(); i++) + AddColumn(input.ColumnName(i), input.GetColumnType(i)); + + DataStructures::Page *cur = input.GetRows().GetListHead(); + while (cur) + { + for (i=0; i < (unsigned int) cur->size; i++) + { + AddRow(cur->keys[i], cur->data[i]->cells, false); + } + + cur=cur->next; + } + + return *this; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif diff --git a/src/raknet/DataCompressor.cpp b/src/raknet/DataCompressor.cpp new file mode 100644 index 0000000..ce6cce0 --- /dev/null +++ b/src/raknet/DataCompressor.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/DataCompressor.hpp" +#include "include/raknet/DS_HuffmanEncodingTree.hpp" +#include "include/raknet/RakAssert.hpp" +#include // Use string.h rather than memory.h for a console + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(DataCompressor,DataCompressor) + +void DataCompressor::Compress( unsigned char *userData, unsigned sizeInBytes, RakNet::BitStream * output ) +{ + // Don't use this for small files as you will just make them bigger! + RakAssert(sizeInBytes > 2048); + + unsigned int frequencyTable[ 256 ]; + unsigned int i; + memset(frequencyTable,0,256*sizeof(unsigned int)); + for (i=0; i < sizeInBytes; i++) + ++frequencyTable[userData[i]]; + HuffmanEncodingTree tree; + BitSize_t writeOffset1, writeOffset2, bitsUsed1, bitsUsed2; + tree.GenerateFromFrequencyTable(frequencyTable); + output->WriteCompressed(sizeInBytes); + for (i=0; i < 256; i++) + output->WriteCompressed(frequencyTable[i]); + output->AlignWriteToByteBoundary(); + writeOffset1=output->GetWriteOffset(); + output->Write((unsigned int)0); // Dummy value + bitsUsed1=output->GetNumberOfBitsUsed(); + tree.EncodeArray(userData, sizeInBytes, output); + bitsUsed2=output->GetNumberOfBitsUsed(); + writeOffset2=output->GetWriteOffset(); + output->SetWriteOffset(writeOffset1); + output->Write(bitsUsed2-bitsUsed1); // Go back and write how many bits were used for the encoding + output->SetWriteOffset(writeOffset2); +} + +unsigned DataCompressor::DecompressAndAllocate( RakNet::BitStream * input, unsigned char **output ) +{ + HuffmanEncodingTree tree; + unsigned int bitsUsed, destinationSizeInBytes; + unsigned int decompressedBytes; + unsigned int frequencyTable[ 256 ]; + unsigned i; + + input->ReadCompressed(destinationSizeInBytes); + for (i=0; i < 256; i++) + input->ReadCompressed(frequencyTable[i]); + input->AlignReadToByteBoundary(); + if (input->Read(bitsUsed)==false) + { + // Read error +#ifdef _DEBUG + RakAssert(0); +#endif + return 0; + } + *output = (unsigned char*) rakMalloc_Ex(destinationSizeInBytes, _FILE_AND_LINE_); + tree.GenerateFromFrequencyTable(frequencyTable); + decompressedBytes=tree.DecodeArray(input, bitsUsed, destinationSizeInBytes, *output ); + RakAssert(decompressedBytes==destinationSizeInBytes); + return destinationSizeInBytes; +} diff --git a/src/raknet/DirectoryDeltaTransfer.cpp b/src/raknet/DirectoryDeltaTransfer.cpp new file mode 100644 index 0000000..4ad4df0 --- /dev/null +++ b/src/raknet/DirectoryDeltaTransfer.cpp @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_DirectoryDeltaTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 + +#include "include/raknet/DirectoryDeltaTransfer.hpp" +#include "include/raknet/FileList.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/FileListTransfer.hpp" +#include "include/raknet/FileListTransferCBInterface.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/FileOperations.hpp" +#include "include/raknet/IncrementalReadInterface.hpp" + +using namespace RakNet; + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +class DDTCallback : public FileListTransferCBInterface +{ +public: + unsigned subdirLen; + char outputSubdir[512]; + FileListTransferCBInterface *onFileCallback; + + DDTCallback() {} + virtual ~DDTCallback() {} + + virtual bool OnFile(OnFileStruct *onFileStruct) + { + char fullPathToDir[1024]; + + if (onFileStruct->fileName && onFileStruct->fileData && subdirLen < strlen(onFileStruct->fileName)) + { + strcpy(fullPathToDir, outputSubdir); + strcat(fullPathToDir, onFileStruct->fileName+subdirLen); + WriteFileWithDirectories(fullPathToDir, (char*)onFileStruct->fileData, (unsigned int ) onFileStruct->byteLengthOfThisFile); + } + else + fullPathToDir[0]=0; + + return onFileCallback->OnFile(onFileStruct); + } + + virtual void OnFileProgress(FileProgressStruct *fps) + { + char fullPathToDir[1024]; + + if (fps->onFileStruct->fileName && subdirLen < strlen(fps->onFileStruct->fileName)) + { + strcpy(fullPathToDir, outputSubdir); + strcat(fullPathToDir, fps->onFileStruct->fileName+subdirLen); + } + else + fullPathToDir[0]=0; + + onFileCallback->OnFileProgress(fps); + } + virtual bool OnDownloadComplete(DownloadCompleteStruct *dcs) + { + return onFileCallback->OnDownloadComplete(dcs); + } +}; + +STATIC_FACTORY_DEFINITIONS(DirectoryDeltaTransfer,DirectoryDeltaTransfer); + +DirectoryDeltaTransfer::DirectoryDeltaTransfer() +{ + applicationDirectory[0]=0; + fileListTransfer=0; + availableUploads = RakNet::OP_NEW( _FILE_AND_LINE_ ); + priority=HIGH_PRIORITY; + orderingChannel=0; + incrementalReadInterface=0; +} +DirectoryDeltaTransfer::~DirectoryDeltaTransfer() +{ + RakNet::OP_DELETE(availableUploads, _FILE_AND_LINE_); +} +void DirectoryDeltaTransfer::SetFileListTransferPlugin(FileListTransfer *flt) +{ + if (fileListTransfer) + { + DataStructures::List fileListProgressList; + fileListTransfer->GetCallbacks(fileListProgressList); + unsigned int i; + for (i=0; i < fileListProgressList.Size(); i++) + availableUploads->RemoveCallback(fileListProgressList[i]); + } + + fileListTransfer=flt; + + if (flt) + { + DataStructures::List fileListProgressList; + flt->GetCallbacks(fileListProgressList); + unsigned int i; + for (i=0; i < fileListProgressList.Size(); i++) + availableUploads->AddCallback(fileListProgressList[i]); + } + else + { + availableUploads->ClearCallbacks(); + } +} +void DirectoryDeltaTransfer::SetApplicationDirectory(const char *pathToApplication) +{ + if (pathToApplication==0 || pathToApplication[0]==0) + applicationDirectory[0]=0; + else + { + strncpy(applicationDirectory, pathToApplication, 510); + if (applicationDirectory[strlen(applicationDirectory)-1]!='/' && applicationDirectory[strlen(applicationDirectory)-1]!='\\') + strcat(applicationDirectory, "/"); + applicationDirectory[511]=0; + } +} +void DirectoryDeltaTransfer::SetUploadSendParameters(PacketPriority _priority, char _orderingChannel) +{ + priority=_priority; + orderingChannel=_orderingChannel; +} +void DirectoryDeltaTransfer::AddUploadsFromSubdirectory(const char *subdir) +{ + availableUploads->AddFilesFromDirectory(applicationDirectory, subdir, true, false, true, FileListNodeContext(0,0,0,0)); +} +unsigned short DirectoryDeltaTransfer::DownloadFromSubdirectory(FileList &localFiles, const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, PacketPriority _priority, char _orderingChannel, FileListProgress *cb) +{ + RakAssert(host!=UNASSIGNED_SYSTEM_ADDRESS); + + DDTCallback *transferCallback; + + localFiles.AddCallback(cb); + + // Prepare the callback data + transferCallback = RakNet::OP_NEW( _FILE_AND_LINE_ ); + if (subdir && subdir[0]) + { + transferCallback->subdirLen=(unsigned int)strlen(subdir); + if (subdir[transferCallback->subdirLen-1]!='/' && subdir[transferCallback->subdirLen-1]!='\\') + transferCallback->subdirLen++; + } + else + transferCallback->subdirLen=0; + if (prependAppDirToOutputSubdir) + strcpy(transferCallback->outputSubdir, applicationDirectory); + else + transferCallback->outputSubdir[0]=0; + if (outputSubdir) + strcat(transferCallback->outputSubdir, outputSubdir); + if (transferCallback->outputSubdir[strlen(transferCallback->outputSubdir)-1]!='/' && transferCallback->outputSubdir[strlen(transferCallback->outputSubdir)-1]!='\\') + strcat(transferCallback->outputSubdir, "/"); + transferCallback->onFileCallback=onFileCallback; + + // Setup the transfer plugin to get the response to this download request + unsigned short setId = fileListTransfer->SetupReceive(transferCallback, true, host); + + // Send to the host, telling it to process this request + RakNet::BitStream outBitstream; + outBitstream.Write((MessageID)ID_DDT_DOWNLOAD_REQUEST); + outBitstream.Write(setId); + StringCompressor::Instance()->EncodeString(subdir, 256, &outBitstream); + StringCompressor::Instance()->EncodeString(outputSubdir, 256, &outBitstream); + localFiles.Serialize(&outBitstream); + SendUnified(&outBitstream, _priority, RELIABLE_ORDERED, _orderingChannel, host, false); + + return setId; +} +unsigned short DirectoryDeltaTransfer::DownloadFromSubdirectory(const char *subdir, const char *outputSubdir, bool prependAppDirToOutputSubdir, SystemAddress host, FileListTransferCBInterface *onFileCallback, PacketPriority _priority, char _orderingChannel, FileListProgress *cb) +{ + FileList localFiles; + // Get a hash of all the files that we already have (if any) + localFiles.AddFilesFromDirectory(prependAppDirToOutputSubdir ? applicationDirectory : 0, outputSubdir, true, false, true, FileListNodeContext(0,0,0,0)); + return DownloadFromSubdirectory(localFiles, subdir, outputSubdir, prependAppDirToOutputSubdir, host, onFileCallback, _priority, _orderingChannel, cb); +} +void DirectoryDeltaTransfer::GenerateHashes(FileList &localFiles, const char *outputSubdir, bool prependAppDirToOutputSubdir) +{ + localFiles.AddFilesFromDirectory(prependAppDirToOutputSubdir ? applicationDirectory : 0, outputSubdir, true, false, true, FileListNodeContext(0,0,0,0)); +} +void DirectoryDeltaTransfer::ClearUploads(void) +{ + availableUploads->Clear(); +} +void DirectoryDeltaTransfer::OnDownloadRequest(Packet *packet) +{ + char subdir[256]; + char remoteSubdir[256]; + RakNet::BitStream inBitstream(packet->data, packet->length, false); + FileList remoteFileHash; + FileList delta; + unsigned short setId; + inBitstream.IgnoreBits(8); + inBitstream.Read(setId); + StringCompressor::Instance()->DecodeString(subdir, 256, &inBitstream); + StringCompressor::Instance()->DecodeString(remoteSubdir, 256, &inBitstream); + if (remoteFileHash.Deserialize(&inBitstream)==false) + { +#ifdef _DEBUG + RakAssert(0); +#endif + return; + } + + availableUploads->GetDeltaToCurrent(&remoteFileHash, &delta, subdir, remoteSubdir); + if (incrementalReadInterface==0) + delta.PopulateDataFromDisk(applicationDirectory, true, false, true); + else + delta.FlagFilesAsReferences(); + + // This will call the ddtCallback interface that was passed to FileListTransfer::SetupReceive on the remote system + fileListTransfer->Send(&delta, rakPeerInterface, packet->systemAddress, setId, priority, orderingChannel, incrementalReadInterface, chunkSize); +} +PluginReceiveResult DirectoryDeltaTransfer::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_DDT_DOWNLOAD_REQUEST: + OnDownloadRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + return RR_CONTINUE_PROCESSING; +} + +unsigned DirectoryDeltaTransfer::GetNumberOfFilesForUpload(void) const +{ + return availableUploads->fileList.Size(); +} + +void DirectoryDeltaTransfer::SetDownloadRequestIncrementalReadInterface(IncrementalReadInterface *_incrementalReadInterface, unsigned int _chunkSize) +{ + incrementalReadInterface=_incrementalReadInterface; + chunkSize=_chunkSize; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/DynDNS.cpp b/src/raknet/DynDNS.cpp new file mode 100644 index 0000000..4c4c808 --- /dev/null +++ b/src/raknet/DynDNS.cpp @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_DynDNS==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#include "include/raknet/TCPInterface.hpp" +#include "include/raknet/RakNetSocket2.hpp" +#include "include/raknet/DynDNS.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/Base64Encoder.hpp" + +using namespace RakNet; + +struct DynDnsResult +{ + const char *description; + const char *code; + DynDnsResultCode resultCode; +}; + +DynDnsResult resultTable[13] = +{ + // See http://www.dyndns.com/developers/specs/flow.pdf + {"DNS update success.\nPlease wait up to 60 seconds for the change to take effect.\n", "good", RC_SUCCESS}, // Even with success, it takes time for the cache to update! + {"No change", "nochg", RC_NO_CHANGE}, + {"Host has been blocked. You will need to contact DynDNS to reenable.", "abuse", RC_ABUSE}, + {"Useragent is blocked", "badagent", RC_BAD_AGENT}, + {"Username/password pair bad", "badauth", RC_BAD_AUTH}, + {"Bad system parameter", "badsys", RC_BAD_SYS}, + {"DNS inconsistency", "dnserr", RC_DNS_ERROR}, + {"Paid account feature", "!donator", RC_NOT_DONATOR}, + {"No such host in system", "nohost", RC_NO_HOST}, + {"Invalid hostname format", "notfqdn", RC_NOT_FQDN}, + {"Serious error", "numhost", RC_NUM_HOST}, + {"This host exists, but does not belong to you", "!yours", RC_NOT_YOURS}, + {"911", "911", RC_911} +}; +DynDNS::DynDNS() +{ + connectPhase=CP_IDLE; + tcp=0; +} +DynDNS::~DynDNS() +{ + if (tcp) + RakNet::OP_DELETE(tcp, _FILE_AND_LINE_); +} +void DynDNS::Stop(void) +{ + tcp->Stop(); + connectPhase = CP_IDLE; + RakNet::OP_DELETE(tcp, _FILE_AND_LINE_); + tcp=0; +} + + +// newIPAddress is optional - if left out, DynDNS will use whatever it receives +void DynDNS::UpdateHostIPAsynch(const char *dnsHost, const char *newIPAddress, const char *usernameAndPassword ) +{ + myIPStr[0]=0; + + if (tcp==0) + tcp = RakNet::OP_NEW(_FILE_AND_LINE_); + connectPhase = CP_IDLE; + host = dnsHost; + + if (tcp->Start(0, 1)==false) + { + SetCompleted(RC_TCP_FAILED_TO_START, "TCP failed to start"); + return; + } + + connectPhase = CP_CONNECTING_TO_CHECKIP; + tcp->Connect("checkip.dyndns.org", 80, false); + + // See https://www.dyndns.com/developers/specs/syntax.html + getString="GET /nic/update?hostname="; + getString+=dnsHost; + if (newIPAddress) + { + getString+="&myip="; + getString+=newIPAddress; + } + getString+="&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG HTTP/1.0\n"; + getString+="Host: members.dyndns.org\n"; + getString+="Authorization: Basic "; + char outputData[512]; + Base64Encoding((const unsigned char*) usernameAndPassword, (int) strlen(usernameAndPassword), outputData); + getString+=outputData; + getString+="User-Agent: Jenkins Software LLC - PC - 1.0\n\n"; +} +void DynDNS::Update(void) +{ + if (connectPhase==CP_IDLE) + return; + + serverAddress=tcp->HasFailedConnectionAttempt(); + if (serverAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + SetCompleted(RC_TCP_DID_NOT_CONNECT, "Could not connect to DynDNS"); + return; + } + + serverAddress=tcp->HasCompletedConnectionAttempt(); + if (serverAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + if (connectPhase == CP_CONNECTING_TO_CHECKIP) + { + checkIpAddress=serverAddress; + connectPhase = CP_WAITING_FOR_CHECKIP_RESPONSE; + tcp->Send("GET\n\n", (unsigned int) strlen("GET\n\n"), serverAddress, false); // Needs 2 newlines! This is not documented and wasted a lot of my time + } + else + { + connectPhase = CP_WAITING_FOR_DYNDNS_RESPONSE; + tcp->Send(getString.C_String(), (unsigned int) getString.GetLength(), serverAddress, false); + } + phaseTimeout=RakNet::GetTime()+1000; + } + + if (connectPhase==CP_WAITING_FOR_CHECKIP_RESPONSE && RakNet::GetTime()>phaseTimeout) + { + connectPhase = CP_CONNECTING_TO_DYNDNS; + tcp->CloseConnection(checkIpAddress); + tcp->Connect("members.dyndns.org", 80, false); + } + else if (connectPhase==CP_WAITING_FOR_DYNDNS_RESPONSE && RakNet::GetTime()>phaseTimeout) + { + SetCompleted(RC_DYNDNS_TIMEOUT, "DynDNS did not respond"); + return; + } + + Packet *packet = tcp->Receive(); + if (packet) + { + if (connectPhase==CP_WAITING_FOR_DYNDNS_RESPONSE) + { + unsigned int i; + + char *result; + result=strstr((char*) packet->data, "Connection: close"); + if (result!=0) + { + result+=strlen("Connection: close"); + while (*result && ((*result=='\r') || (*result=='\n') || (*result==' ')) ) + result++; + for (i=0; i < 13; i++) + { + if (strncmp(resultTable[i].code, result, strlen(resultTable[i].code))==0) + { + if (resultTable[i].resultCode==RC_SUCCESS) + { + // Read my external IP into myIPStr + // Advance until we hit a number + while (*result && ((*result<'0') || (*result>'9')) ) + result++; + if (*result) + { + SystemAddress parser; + parser.FromString(result); + parser.ToString(false, myIPStr); + } + } + tcp->DeallocatePacket(packet); + SetCompleted(resultTable[i].resultCode, resultTable[i].description); + break; + } + } + if (i==13) + { + tcp->DeallocatePacket(packet); + SetCompleted(RC_UNKNOWN_RESULT, "DynDNS returned unknown result"); + } + } + else + { + tcp->DeallocatePacket(packet); + SetCompleted(RC_PARSING_FAILURE, "Parsing failure on returned string from DynDNS"); + } + + return; + } + else + { + /* + HTTP/1.1 200 OK + Content-Type: text/html + Server: DynDNS-CheckIP/1.0 + Connection: close + Cache-Control: no-cache + Pragma: no-cache + Content-Length: 105 + + Current IP CheckCurrent IP Address: 98.1 + 89.219.22 + + + Connection to host lost. + */ + + char *result; + result=strstr((char*) packet->data, "Current IP Address: "); + if (result!=0) + { + result+=strlen("Current IP Address: "); + SystemAddress myIp; + myIp.FromString(result); + myIp.ToString(false, myIPStr); + + char existingHost[65]; + existingHost[0]=0; + // Resolve DNS we are setting. If equal to current then abort + RakNetSocket2::DomainNameToIP(host.C_String(), existingHost); + if (existingHost && strcmp(existingHost, myIPStr)==0) + { + // DynDNS considers setting the IP to what it is already set abuse + tcp->DeallocatePacket(packet); + SetCompleted(RC_DNS_ALREADY_SET, "No action needed"); + return; + } + } + + tcp->DeallocatePacket(packet); + tcp->CloseConnection(packet->systemAddress); + + connectPhase = CP_CONNECTING_TO_DYNDNS; + tcp->Connect("members.dyndns.org", 80, false); + } + } + + if (tcp->HasLostConnection()!=UNASSIGNED_SYSTEM_ADDRESS) + { + if (connectPhase==CP_WAITING_FOR_DYNDNS_RESPONSE) + { + SetCompleted(RC_CONNECTION_LOST_WITHOUT_RESPONSE, "Connection lost to DynDNS during GET operation"); + } + } +} + + +#endif // _RAKNET_SUPPORT_DynDNS diff --git a/src/raknet/EmailSender.cpp b/src/raknet/EmailSender.cpp new file mode 100644 index 0000000..60cbc3a --- /dev/null +++ b/src/raknet/EmailSender.cpp @@ -0,0 +1,377 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_EmailSender==1 && _RAKNET_SUPPORT_TCPInterface==1 && _RAKNET_SUPPORT_FileOperations==1 + +// Useful sites +// http://www.faqs.org\rfcs\rfc2821.html +// http://www2.rad.com\networks/1995/mime/examples.htm + +#include "include/raknet/EmailSender.hpp" +#include "include/raknet/TCPInterface.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/Rand.hpp" +#include "include/raknet/FileList.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/Base64Encoder.hpp" +#include + + + + + +#include "include/raknet/RakSleep.hpp" + +using namespace RakNet; + + +STATIC_FACTORY_DEFINITIONS(EmailSender,EmailSender); + +const char *EmailSender::Send(const char *hostAddress, unsigned short hostPort, const char *sender, const char *recipient, const char *senderName, const char *recipientName, const char *subject, const char *body, FileList *attachedFiles, bool doPrintf, const char *password) +{ + RakNet::Packet *packet; + char query[1024]; + TCPInterface tcpInterface; + SystemAddress emailServer; + if (tcpInterface.Start(0, 0)==false) + return "Unknown error starting TCP"; + emailServer=tcpInterface.Connect(hostAddress, hostPort,true); + if (emailServer==UNASSIGNED_SYSTEM_ADDRESS) + return "Failed to connect to host"; +#if OPEN_SSL_CLIENT_SUPPORT==1 + tcpInterface.StartSSLClient(emailServer); +#endif + RakNet::TimeMS timeoutTime = RakNet::GetTimeMS()+3000; + packet=0; + while (RakNet::GetTimeMS() < timeoutTime) + { + packet = tcpInterface.Receive(); + if (packet) + { + if (doPrintf) + { + RAKNET_DEBUG_PRINTF("%s", packet->data); + tcpInterface.DeallocatePacket(packet); + } + break; + } + RakSleep(250); + } + + if (packet==0) + return "Timeout while waiting for initial data from server."; + + tcpInterface.Send("EHLO\r\n", 6, emailServer,false); + const char *response; + bool authenticate=false; +#ifdef _MSC_VER +#pragma warning(disable:4127) // conditional expression is constant +#endif + while (1) + { + response=GetResponse(&tcpInterface, emailServer, doPrintf); + + if (response!=0 && strcmp(response, "AUTHENTICATE")==0) + { + authenticate=true; + break; + } + + // Something other than continue? + if (response!=0 && strcmp(response, "CONTINUE")!=0) + return response; + + // Success? + if (response==0) + break; + } + + if (authenticate) + { + sprintf(query, "EHLO %s\r\n", sender); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + response=GetResponse(&tcpInterface, emailServer, doPrintf); + if (response!=0) + return response; + if (password==0) + return "Password needed"; + char *outputData = RakNet::OP_NEW_ARRAY((const int) (strlen(sender)+strlen(password)+2)*3, _FILE_AND_LINE_ ); + RakNet::BitStream bs; + char zero=0; + bs.Write(&zero,1); + bs.Write(sender,(const unsigned int)strlen(sender)); + //bs.Write("jms1@jms1.net",(const unsigned int)strlen("jms1@jms1.net")); + bs.Write(&zero,1); + bs.Write(password,(const unsigned int)strlen(password)); + bs.Write(&zero,1); + //bs.Write("not.my.real.password",(const unsigned int)strlen("not.my.real.password")); + Base64Encoding((const unsigned char*)bs.GetData(), bs.GetNumberOfBytesUsed(), outputData); + sprintf(query, "AUTH PLAIN %s", outputData); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + response=GetResponse(&tcpInterface, emailServer, doPrintf); + if (response!=0) + return response; + } + + + if (sender) + sprintf(query, "MAIL From: <%s>\r\n", sender); + else + sprintf(query, "MAIL From: <>\r\n"); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + response=GetResponse(&tcpInterface, emailServer, doPrintf); + if (response!=0) + return response; + + if (recipient) + sprintf(query, "RCPT TO: <%s>\r\n", recipient); + else + sprintf(query, "RCPT TO: <>\r\n"); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + response=GetResponse(&tcpInterface, emailServer, doPrintf); + if (response!=0) + return response; + + tcpInterface.Send("DATA\r\n", (unsigned int)strlen("DATA\r\n"), emailServer,false); + + // Wait for 354... + + response=GetResponse(&tcpInterface, emailServer, doPrintf); + if (response!=0) + return response; + + if (subject) + { + sprintf(query, "Subject: %s\r\n", subject); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + } + if (senderName) + { + sprintf(query, "From: %s\r\n", senderName); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + } + if (recipientName) + { + sprintf(query, "To: %s\r\n", recipientName); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + } + + const int boundarySize=60; + char boundary[boundarySize+1]; + int i,j; + if (attachedFiles && attachedFiles->fileList.Size()) + { + rakNetRandom.SeedMT((unsigned int) RakNet::GetTimeMS()); + // Random multipart message boundary + for (i=0; i < boundarySize; i++) + boundary[i]=Base64Map()[rakNetRandom.RandomMT()%64]; + boundary[boundarySize]=0; + } + + sprintf(query, "MIME-version: 1.0\r\n"); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + + if (attachedFiles && attachedFiles->fileList.Size()) + { + sprintf(query, "Content-type: multipart/mixed; BOUNDARY=\"%s\"\r\n\r\n", boundary); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + + sprintf(query, "This is a multi-part message in MIME format.\r\n\r\n--%s\r\n", boundary); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + } + + sprintf(query, "Content-Type: text/plain; charset=\"US-ASCII\"\r\n\r\n"); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + + // Write the body of the email, doing some lame shitty shit where I have to make periods at the start of a newline have a second period. + char *newBody; + int bodyLength; + bodyLength=(int)strlen(body); + newBody = (char*) rakMalloc_Ex( bodyLength*3, _FILE_AND_LINE_ ); + if (bodyLength>=0) + newBody[0]=body[0]; + for (i=1, j=1; i < bodyLength; i++) + { + // Transform \n . \r \n into \n . . \r \n + if (i < bodyLength-2 && + body[i-1]=='\n' && + body[i+0]=='.' && + body[i+1]=='\r' && + body[i+2]=='\n') + { + newBody[j++]='.'; + newBody[j++]='.'; + newBody[j++]='\r'; + newBody[j++]='\n'; + i+=2; + } + // Transform \n . . \r \n into \n . . . \r \n + // Having to process .. is a bug in the mail server - the spec says ONLY \r\n.\r\n should be transformed + else if (i <= bodyLength-3 && + body[i-1]=='\n' && + body[i+0]=='.' && + body[i+1]=='.' && + body[i+2]=='\r' && + body[i+3]=='\n') + { + newBody[j++]='.'; + newBody[j++]='.'; + newBody[j++]='.'; + newBody[j++]='\r'; + newBody[j++]='\n'; + i+=3; + } + // Transform \n . \n into \n . . \r \n (this is a bug in the mail server - the spec says do not count \n alone but it does) + else if (i < bodyLength-1 && + body[i-1]=='\n' && + body[i+0]=='.' && + body[i+1]=='\n') + { + newBody[j++]='.'; + newBody[j++]='.'; + newBody[j++]='\r'; + newBody[j++]='\n'; + i+=1; + } + // Transform \n . . \n into \n . . . \r \n (this is a bug in the mail server - the spec says do not count \n alone but it does) + // In fact having to process .. is a bug too - because the spec says ONLY \r\n.\r\n should be transformed + else if (i <= bodyLength-2 && + body[i-1]=='\n' && + body[i+0]=='.' && + body[i+1]=='.' && + body[i+2]=='\n') + { + newBody[j++]='.'; + newBody[j++]='.'; + newBody[j++]='.'; + newBody[j++]='\r'; + newBody[j++]='\n'; + i+=2; + } + else + newBody[j++]=body[i]; + } + + newBody[j++]='\r'; + newBody[j++]='\n'; + tcpInterface.Send(newBody, j, emailServer,false); + + rakFree_Ex(newBody, _FILE_AND_LINE_ ); + int outputOffset; + + // What a pain in the rear. I have to map the binary to printable characters using 6 bits per character. + if (attachedFiles && attachedFiles->fileList.Size()) + { + for (i=0; i < (int) attachedFiles->fileList.Size(); i++) + { + // Write boundary + sprintf(query, "\r\n--%s\r\n", boundary); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + + sprintf(query, "Content-Type: APPLICATION/Octet-Stream; SizeOnDisk=%i; name=\"%s\"\r\nContent-Transfer-Encoding: BASE64\r\nContent-Description: %s\r\n\r\n", attachedFiles->fileList[i].dataLengthBytes, attachedFiles->fileList[i].filename.C_String(), attachedFiles->fileList[i].filename.C_String()); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + + newBody = (char*) rakMalloc_Ex( (size_t) (attachedFiles->fileList[i].dataLengthBytes*3)/2, _FILE_AND_LINE_ ); + + outputOffset=Base64Encoding((const unsigned char*) attachedFiles->fileList[i].data, (int) attachedFiles->fileList[i].dataLengthBytes, newBody); + + // Send the base64 mapped file. + tcpInterface.Send(newBody, outputOffset, emailServer,false); + rakFree_Ex(newBody, _FILE_AND_LINE_ ); + + } + + // Write last boundary + sprintf(query, "\r\n--%s--\r\n", boundary); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + } + + + sprintf(query, "\r\n.\r\n"); + tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false); + response=GetResponse(&tcpInterface, emailServer, doPrintf); + if (response!=0) + return response; + + tcpInterface.Send("QUIT\r\n", (unsigned int)strlen("QUIT\r\n"), emailServer,false); + + RakSleep(30); + if (doPrintf) + { + packet = tcpInterface.Receive(); + while (packet) + { + RAKNET_DEBUG_PRINTF("%s", packet->data); + tcpInterface.DeallocatePacket(packet); + packet = tcpInterface.Receive(); + } + } + tcpInterface.Stop(); + return 0; // Success +} + +const char *EmailSender::GetResponse(TCPInterface *tcpInterface, const SystemAddress &emailServer, bool doPrintf) +{ + RakNet::Packet *packet; + RakNet::TimeMS timeout; + timeout=RakNet::GetTimeMS()+5000; +#ifdef _MSC_VER + #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + if (tcpInterface->HasLostConnection()==emailServer) + return "Connection to server lost."; + packet = tcpInterface->Receive(); + if (packet) + { + if (doPrintf) + { + RAKNET_DEBUG_PRINTF("%s", packet->data); + } +#if OPEN_SSL_CLIENT_SUPPORT==1 + if (strstr((const char*)packet->data, "220")) + { + tcpInterface->StartSSLClient(packet->systemAddress); + return "AUTHENTICATE"; // OK + } +// if (strstr((const char*)packet->data, "250-AUTH LOGIN PLAIN")) +// { +// tcpInterface->StartSSLClient(packet->systemAddress); +// return "AUTHENTICATE"; // OK +// } +#endif + if (strstr((const char*)packet->data, "235")) + return 0; // Authentication accepted + if (strstr((const char*)packet->data, "354")) + return 0; // Go ahead +#if OPEN_SSL_CLIENT_SUPPORT==1 + if (strstr((const char*)packet->data, "250-STARTTLS")) + { + tcpInterface->Send("STARTTLS\r\n", (unsigned int) strlen("STARTTLS\r\n"), packet->systemAddress, false); + return "CONTINUE"; + } +#endif + if (strstr((const char*)packet->data, "250")) + return 0; // OK + if (strstr((const char*)packet->data, "550")) + return "Failed on error code 550"; + if (strstr((const char*)packet->data, "553")) + return "Failed on error code 553"; + } + if (RakNet::GetTimeMS() > timeout) + return "Timed out"; + RakSleep(100); + } +} + + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/EpochTimeToString.cpp b/src/raknet/EpochTimeToString.cpp new file mode 100644 index 0000000..7cf0c35 --- /dev/null +++ b/src/raknet/EpochTimeToString.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/FormatString.hpp" +#include "include/raknet/EpochTimeToString.hpp" +#include +#include +#include +// localtime +#include +#include "include/raknet/LinuxStrings.hpp" + +char * EpochTimeToString(long long time) +{ + static int textIndex=0; + static char text[4][64]; + + if (++textIndex==4) + textIndex=0; + + struct tm * timeinfo; + time_t t = time; + timeinfo = localtime ( &t ); + strftime (text[textIndex],64,"%c.",timeinfo); + + /* + time_t + // Copied from the docs + struct tm *newtime; + newtime = _localtime64(& time); + asctime_s( text[textIndex], sizeof(text[textIndex]), newtime ); + + while (text[textIndex][0] && (text[textIndex][strlen(text[textIndex])-1]=='\n' || text[textIndex][strlen(text[textIndex])-1]=='\r')) + text[textIndex][strlen(text[textIndex])-1]=0; + */ + + return text[textIndex]; +} diff --git a/src/raknet/FileList.cpp b/src/raknet/FileList.cpp new file mode 100644 index 0000000..715c3b6 --- /dev/null +++ b/src/raknet/FileList.cpp @@ -0,0 +1,818 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/FileList.hpp" + +#if _RAKNET_SUPPORT_FileOperations==1 + +#include // RAKNET_DEBUG_PRINTF +#include "include/raknet/RakAssert.hpp" +#if defined(ANDROID) +#include +#elif defined(_WIN32) || defined(__CYGWIN__) +#include + + +#elif !defined ( __APPLE__ ) && !defined ( __APPLE_CC__ ) && !defined ( __PPC__ ) && !defined ( __FreeBSD__ ) && !defined ( __S3E__ ) +#include +#endif + + +#ifdef _WIN32 +// For mkdir +#include + + +#else +#include +#endif + +//#include "include/raknet/DR_SHA1.hpp" +#include "include/raknet/DS_Queue.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/FileOperations.hpp" +#include "include/raknet/SuperFastHash.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/LinuxStrings.hpp" + +#define MAX_FILENAME_LENGTH 512 +static const unsigned HASH_LENGTH=4; + +using namespace RakNet; + +// alloca + +#if defined(_WIN32) +#include + + +#else + #if !defined ( __FreeBSD__ ) + #include + #endif +#include +#include +#include +#include "include/raknet/_FindFirst.hpp" +#include //defines intptr_t +#endif + +#include "include/raknet/RakAlloca.hpp" + +//int RAK_DLL_EXPORT FileListNodeComp( char * const &key, const FileListNode &data ) +//{ +// return strcmp(key, data.filename); +//} + + +STATIC_FACTORY_DEFINITIONS(FileListProgress,FileListProgress) +STATIC_FACTORY_DEFINITIONS(FLP_Printf,FLP_Printf) +STATIC_FACTORY_DEFINITIONS(FileList,FileList) + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +/// First callback called when FileList::AddFilesFromDirectory() starts +void FLP_Printf::OnAddFilesFromDirectoryStarted(FileList *fileList, char *dir) { + (void) fileList; + RAKNET_DEBUG_PRINTF("Adding files from directory %s\n",dir);} + +/// Called for each directory, when that directory begins processing +void FLP_Printf::OnDirectory(FileList *fileList, char *dir, unsigned int directoriesRemaining) { + (void) fileList; + RAKNET_DEBUG_PRINTF("Adding %s. %i remaining.\n", dir, directoriesRemaining);} +void FLP_Printf::OnFilePushesComplete( SystemAddress systemAddress, unsigned short setID ) +{ + (void) setID; + + char str[32]; + systemAddress.ToString(true, (char*) str); + RAKNET_DEBUG_PRINTF("File pushes complete to %s\n", str); +} +void FLP_Printf::OnSendAborted( SystemAddress systemAddress ) +{ + char str[32]; + systemAddress.ToString(true, (char*) str); + RAKNET_DEBUG_PRINTF("Send aborted to %s\n", str); +} +FileList::FileList() +{ +} +FileList::~FileList() +{ + Clear(); +} +void FileList::AddFile(const char *filepath, const char *filename, FileListNodeContext context) +{ + if (filepath==0 || filename==0) + return; + + char *data; + //std::fstream file; + //file.open(filename, std::ios::in | std::ios::binary); + + FILE *fp = fopen(filepath, "rb"); + if (fp==0) + return; + fseek(fp, 0, SEEK_END); + int length = ftell(fp); + fseek(fp, 0, SEEK_SET); + + if (length > (int) ((unsigned int)-1 / 8)) + { + // If this assert hits, split up your file. You could also change BitSize_t in RakNetTypes.h to unsigned long long but this is not recommended for performance reasons + RakAssert("Cannot add files over 536 MB" && 0); + fclose(fp); + return; + } + + +#if USE_ALLOCA==1 + bool usedAlloca=false; + if (length < MAX_ALLOCA_STACK_ALLOCATION) + { + data = ( char* ) alloca( length ); + usedAlloca=true; + } + else +#endif + { + data = (char*) rakMalloc_Ex( length, _FILE_AND_LINE_ ); + RakAssert(data); + } + + fread(data, 1, length, fp); + AddFile(filename, filepath, data, length, length, context); + fclose(fp); + +#if USE_ALLOCA==1 + if (usedAlloca==false) +#endif + rakFree_Ex(data, _FILE_AND_LINE_ ); + +} +void FileList::AddFile(const char *filename, const char *fullPathToFile, const char *data, const unsigned dataLength, const unsigned fileLength, FileListNodeContext context, bool isAReference, bool takeDataPointer) +{ + if (filename==0) + return; + if (strlen(filename)>MAX_FILENAME_LENGTH) + { + // Should be enough for anyone + RakAssert(0); + return; + } + // If adding a reference, do not send data + RakAssert(isAReference==false || data==0); + // Avoid duplicate insertions unless the data is different, in which case overwrite the old data + unsigned i; + for (i=0; i dirList; + char root[260]; + char fullPath[520]; + _finddata_t fileInfo; + intptr_t dir; + FILE *fp; + char *dirSoFar, *fileData; + dirSoFar=(char*) rakMalloc_Ex( 520, _FILE_AND_LINE_ ); + RakAssert(dirSoFar); + + if (applicationDirectory) + strcpy(root, applicationDirectory); + else + root[0]=0; + + int rootLen=(int)strlen(root); + if (rootLen) + { + strcpy(dirSoFar, root); + if (FixEndingSlash(dirSoFar)) + rootLen++; + } + else + dirSoFar[0]=0; + + if (subDirectory) + { + strcat(dirSoFar, subDirectory); + FixEndingSlash(dirSoFar); + } + for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) + fileListProgressCallbacks[flpcIndex]->OnAddFilesFromDirectoryStarted(this, dirSoFar); + // RAKNET_DEBUG_PRINTF("Adding files from directory %s\n",dirSoFar); + dirList.Push(dirSoFar, _FILE_AND_LINE_ ); + while (dirList.Size()) + { + dirSoFar=dirList.Pop(); + strcpy(fullPath, dirSoFar); + // Changed from *.* to * for Linux compatibility + strcat(fullPath, "*"); + + + dir=_findfirst(fullPath, &fileInfo ); + if (dir==-1) + { + _findclose(dir); + rakFree_Ex(dirSoFar, _FILE_AND_LINE_ ); + unsigned i; + for (i=0; i < dirList.Size(); i++) + rakFree_Ex(dirList[i], _FILE_AND_LINE_ ); + return; + } + +// RAKNET_DEBUG_PRINTF("Adding %s. %i remaining.\n", fullPath, dirList.Size()); + for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) + fileListProgressCallbacks[flpcIndex]->OnDirectory(this, fullPath, dirList.Size()); + + do + { + // no guarantee these entries are first... + if (strcmp("." , fileInfo.name) == 0 || + strcmp("..", fileInfo.name) == 0) + { + continue; + } + + if ((fileInfo.attrib & (_A_HIDDEN | _A_SUBDIR | _A_SYSTEM))==0) + { + strcpy(fullPath, dirSoFar); + strcat(fullPath, fileInfo.name); + fileData=0; + + for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) + fileListProgressCallbacks[flpcIndex]->OnFile(this, dirSoFar, fileInfo.name, fileInfo.size); + + if (writeData && writeHash) + { + fp = fopen(fullPath, "rb"); + if (fp) + { + fileData= (char*) rakMalloc_Ex( fileInfo.size+HASH_LENGTH, _FILE_AND_LINE_ ); + RakAssert(fileData); + fread(fileData+HASH_LENGTH, fileInfo.size, 1, fp); + fclose(fp); + + unsigned int hash = SuperFastHash(fileData+HASH_LENGTH, fileInfo.size); + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); + memcpy(fileData, &hash, HASH_LENGTH); + + // sha1.Reset(); + // sha1.Update( ( unsigned char* ) fileData+HASH_LENGTH, fileInfo.size ); + // sha1.Final(); + // memcpy(fileData, sha1.GetHash(), HASH_LENGTH); + // File data and hash + AddFile((const char*)fullPath+rootLen, fullPath, fileData, fileInfo.size+HASH_LENGTH, fileInfo.size, context); + } + } + else if (writeHash) + { +// sha1.Reset(); +// DR_SHA1.hashFile((char*)fullPath); +// sha1.Final(); + + unsigned int hash = SuperFastHashFile(fullPath); + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); + + // Hash only + // AddFile((const char*)fullPath+rootLen, (const char*)sha1.GetHash(), HASH_LENGTH, fileInfo.size, context); + AddFile((const char*)fullPath+rootLen, fullPath, (const char*)&hash, HASH_LENGTH, fileInfo.size, context); + } + else if (writeData) + { + fileData= (char*) rakMalloc_Ex( fileInfo.size, _FILE_AND_LINE_ ); + RakAssert(fileData); + fp = fopen(fullPath, "rb"); + fread(fileData, fileInfo.size, 1, fp); + fclose(fp); + + // File data only + AddFile(fullPath+rootLen, fullPath, fileData, fileInfo.size, fileInfo.size, context); + } + else + { + // Just the filename + AddFile(fullPath+rootLen, fullPath, 0, 0, fileInfo.size, context); + } + + if (fileData) + rakFree_Ex(fileData, _FILE_AND_LINE_ ); + } + else if ((fileInfo.attrib & _A_SUBDIR) && (fileInfo.attrib & (_A_HIDDEN | _A_SYSTEM))==0 && recursive) + { + char *newDir=(char*) rakMalloc_Ex( 520, _FILE_AND_LINE_ ); + RakAssert(newDir); + strcpy(newDir, dirSoFar); + strcat(newDir, fileInfo.name); + strcat(newDir, "/"); + dirList.Push(newDir, _FILE_AND_LINE_ ); + } + + } while (_findnext(dir, &fileInfo ) != -1); + + _findclose(dir); + rakFree_Ex(dirSoFar, _FILE_AND_LINE_ ); + } + +} +void FileList::Clear(void) +{ + unsigned i; + for (i=0; iWriteCompressed(fileList.Size()); + unsigned i; + for (i=0; i < fileList.Size(); i++) + { + outBitStream->WriteCompressed(fileList[i].context.op); + outBitStream->WriteCompressed(fileList[i].context.flnc_extraData1); + outBitStream->WriteCompressed(fileList[i].context.flnc_extraData2); + StringCompressor::Instance()->EncodeString(fileList[i].filename.C_String(), MAX_FILENAME_LENGTH, outBitStream); + + bool writeFileData = (fileList[i].dataLengthBytes>0)==true; + outBitStream->Write(writeFileData); + if (writeFileData) + { + outBitStream->WriteCompressed(fileList[i].dataLengthBytes); + outBitStream->Write(fileList[i].data, fileList[i].dataLengthBytes); + } + + outBitStream->Write((bool)(fileList[i].fileLengthBytes==fileList[i].dataLengthBytes)); + if (fileList[i].fileLengthBytes!=fileList[i].dataLengthBytes) + outBitStream->WriteCompressed(fileList[i].fileLengthBytes); + } +} +bool FileList::Deserialize(RakNet::BitStream *inBitStream) +{ + bool b, dataLenNonZero=false, fileLenMatchesDataLen=false; + char filename[512]; + uint32_t fileListSize; + FileListNode n; + b=inBitStream->ReadCompressed(fileListSize); +#ifdef _DEBUG + RakAssert(b); + RakAssert(fileListSize < 10000); +#endif + if (b==false || fileListSize > 10000) + return false; // Sanity check + Clear(); + unsigned i; + for (i=0; i < fileListSize; i++) + { + inBitStream->ReadCompressed(n.context.op); + inBitStream->ReadCompressed(n.context.flnc_extraData1); + inBitStream->ReadCompressed(n.context.flnc_extraData2); + StringCompressor::Instance()->DecodeString((char*)filename, MAX_FILENAME_LENGTH, inBitStream); + inBitStream->Read(dataLenNonZero); + if (dataLenNonZero) + { + inBitStream->ReadCompressed(n.dataLengthBytes); + // sanity check + if (n.dataLengthBytes>2000000000) + { +#ifdef _DEBUG + RakAssert(n.dataLengthBytes<=2000000000); +#endif + return false; + } + n.data=(char*) rakMalloc_Ex( (size_t) n.dataLengthBytes, _FILE_AND_LINE_ ); + RakAssert(n.data); + inBitStream->Read(n.data, n.dataLengthBytes); + } + else + { + n.dataLengthBytes=0; + n.data=0; + } + + b=inBitStream->Read(fileLenMatchesDataLen); + if (fileLenMatchesDataLen) + n.fileLengthBytes=(unsigned) n.dataLengthBytes; + else + b=inBitStream->ReadCompressed(n.fileLengthBytes); +#ifdef _DEBUG + RakAssert(b); +#endif + if (b==0) + { + Clear(); + return false; + } + n.filename=filename; + n.fullPathToFile=filename; + fileList.Insert(n, _FILE_AND_LINE_); + } + + return true; +} +void FileList::GetDeltaToCurrent(FileList *input, FileList *output, const char *dirSubset, const char *remoteSubdir) +{ + // For all files in this list that do not match the input list, write them to the output list. + // dirSubset allows checking only a portion of the files in this list. + unsigned thisIndex, inputIndex; + unsigned dirSubsetLen, localPathLen, remoteSubdirLen; + bool match; + if (dirSubset) + dirSubsetLen = (unsigned int) strlen(dirSubset); + else + dirSubsetLen = 0; + if (remoteSubdir && remoteSubdir[0]) + { + remoteSubdirLen=(unsigned int) strlen(remoteSubdir); + if (IsSlash(remoteSubdir[remoteSubdirLen-1])) + remoteSubdirLen--; + } + else + remoteSubdirLen=0; + + for (thisIndex=0; thisIndex < fileList.Size(); thisIndex++) + { + localPathLen = (unsigned int) fileList[thisIndex].filename.GetLength(); + while (localPathLen>0) + { + if (IsSlash(fileList[thisIndex].filename[localPathLen-1])) + { + localPathLen--; + break; + } + localPathLen--; + } + + // fileList[thisIndex].filename has to match dirSubset and be shorter or equal to it in length. + if (dirSubsetLen>0 && + (localPathLendirSubsetLen && IsSlash(fileList[thisIndex].filename[dirSubsetLen])==false))) + continue; + + match=false; + for (inputIndex=0; inputIndex < input->fileList.Size(); inputIndex++) + { + // If the filenames, hashes, and lengths match then skip this element in fileList. Otherwise write it to output + if (_stricmp(input->fileList[inputIndex].filename.C_String()+remoteSubdirLen,fileList[thisIndex].filename.C_String()+dirSubsetLen)==0) + { + match=true; + if (input->fileList[inputIndex].fileLengthBytes==fileList[thisIndex].fileLengthBytes && + input->fileList[inputIndex].dataLengthBytes==fileList[thisIndex].dataLengthBytes && + memcmp(input->fileList[inputIndex].data,fileList[thisIndex].data,(size_t) fileList[thisIndex].dataLengthBytes)==0) + { + // File exists on both machines and is the same. + break; + } + else + { + // File exists on both machines and is not the same. + output->AddFile(fileList[thisIndex].filename, fileList[thisIndex].fullPathToFile, 0,0, fileList[thisIndex].fileLengthBytes, FileListNodeContext(0,0,0,0), false); + break; + } + } + } + if (match==false) + { + // Other system does not have the file at all + output->AddFile(fileList[thisIndex].filename, fileList[thisIndex].fullPathToFile, 0,0, fileList[thisIndex].fileLengthBytes, FileListNodeContext(0,0,0,0), false); + } + } +} +void FileList::ListMissingOrChangedFiles(const char *applicationDirectory, FileList *missingOrChangedFiles, bool alwaysWriteHash, bool neverWriteHash) +{ + unsigned fileLength; +// CSHA1 sha1; + FILE *fp; + char fullPath[512]; + unsigned i; +// char *fileData; + + for (i=0; i < fileList.Size(); i++) + { + strcpy(fullPath, applicationDirectory); + FixEndingSlash(fullPath); + strcat(fullPath,fileList[i].filename); + fp=fopen(fullPath, "rb"); + if (fp==0) + { + missingOrChangedFiles->AddFile(fileList[i].filename, fileList[i].fullPathToFile, 0, 0, 0, FileListNodeContext(0,0,0,0), false); + } + else + { + fseek(fp, 0, SEEK_END); + fileLength = ftell(fp); + fseek(fp, 0, SEEK_SET); + + if (fileLength != fileList[i].fileLengthBytes && alwaysWriteHash==false) + { + missingOrChangedFiles->AddFile(fileList[i].filename, fileList[i].fullPathToFile, 0, 0, fileLength, FileListNodeContext(0,0,0,0), false); + } + else + { + +// fileData= (char*) rakMalloc_Ex( fileLength, _FILE_AND_LINE_ ); +// fread(fileData, fileLength, 1, fp); + +// sha1.Reset(); +// sha1.Update( ( unsigned char* ) fileData, fileLength ); +// sha1.Final(); + +// rakFree_Ex(fileData, _FILE_AND_LINE_ ); + + unsigned int hash = SuperFastHashFilePtr(fp); + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); + + //if (fileLength != fileList[i].fileLength || memcmp( sha1.GetHash(), fileList[i].data, HASH_LENGTH)!=0) + if (fileLength != fileList[i].fileLengthBytes || memcmp( &hash, fileList[i].data, HASH_LENGTH)!=0) + { + if (neverWriteHash==false) + // missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)sha1.GetHash(), HASH_LENGTH, fileLength, 0); + missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)fileList[i].fullPathToFile, (const char *) &hash, HASH_LENGTH, fileLength, FileListNodeContext(0,0,0,0), false); + else + missingOrChangedFiles->AddFile((const char*)fileList[i].filename, (const char*)fileList[i].fullPathToFile, 0, 0, fileLength, FileListNodeContext(0,0,0,0), false); + } + } + fclose(fp); + } + } +} +void FileList::PopulateDataFromDisk(const char *applicationDirectory, bool writeFileData, bool writeFileHash, bool removeUnknownFiles) +{ + FILE *fp; + char fullPath[512]; + unsigned i; +// CSHA1 sha1; + + i=0; + while (i < fileList.Size()) + { + rakFree_Ex(fileList[i].data, _FILE_AND_LINE_ ); + strcpy(fullPath, applicationDirectory); + FixEndingSlash(fullPath); + strcat(fullPath,fileList[i].filename.C_String()); + fp=fopen(fullPath, "rb"); + if (fp) + { + if (writeFileHash || writeFileData) + { + fseek(fp, 0, SEEK_END); + fileList[i].fileLengthBytes = ftell(fp); + fseek(fp, 0, SEEK_SET); + if (writeFileHash) + { + if (writeFileData) + { + // Hash + data so offset the data by HASH_LENGTH + fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes+HASH_LENGTH, _FILE_AND_LINE_ ); + RakAssert(fileList[i].data); + fread(fileList[i].data+HASH_LENGTH, fileList[i].fileLengthBytes, 1, fp); +// sha1.Reset(); +// sha1.Update((unsigned char*)fileList[i].data+HASH_LENGTH, fileList[i].fileLength); +// sha1.Final(); + unsigned int hash = SuperFastHash(fileList[i].data+HASH_LENGTH, fileList[i].fileLengthBytes); + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); +// memcpy(fileList[i].data, sha1.GetHash(), HASH_LENGTH); + memcpy(fileList[i].data, &hash, HASH_LENGTH); + } + else + { + // Hash only + fileList[i].dataLengthBytes=HASH_LENGTH; + if (fileList[i].fileLengthBytes < HASH_LENGTH) + fileList[i].data=(char*) rakMalloc_Ex( HASH_LENGTH, _FILE_AND_LINE_ ); + else + fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes, _FILE_AND_LINE_ ); + RakAssert(fileList[i].data); + fread(fileList[i].data, fileList[i].fileLengthBytes, 1, fp); + // sha1.Reset(); + // sha1.Update((unsigned char*)fileList[i].data, fileList[i].fileLength); + // sha1.Final(); + unsigned int hash = SuperFastHash(fileList[i].data, fileList[i].fileLengthBytes); + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &hash, sizeof(hash)); + // memcpy(fileList[i].data, sha1.GetHash(), HASH_LENGTH); + memcpy(fileList[i].data, &hash, HASH_LENGTH); + } + } + else + { + // Data only + fileList[i].dataLengthBytes=fileList[i].fileLengthBytes; + fileList[i].data=(char*) rakMalloc_Ex( fileList[i].fileLengthBytes, _FILE_AND_LINE_ ); + RakAssert(fileList[i].data); + fread(fileList[i].data, fileList[i].fileLengthBytes, 1, fp); + } + + fclose(fp); + i++; + } + else + { + fileList[i].data=0; + fileList[i].dataLengthBytes=0; + } + } + else + { + if (removeUnknownFiles) + { + fileList.RemoveAtIndex(i); + } + else + i++; + } + } +} +void FileList::FlagFilesAsReferences(void) +{ + for (unsigned int i=0; i < fileList.Size(); i++) + { + fileList[i].isAReference=true; + fileList[i].dataLengthBytes=fileList[i].fileLengthBytes; + } +} +void FileList::WriteDataToDisk(const char *applicationDirectory) +{ + char fullPath[512]; + unsigned i,j; + + for (i=0; i < fileList.Size(); i++) + { + strcpy(fullPath, applicationDirectory); + FixEndingSlash(fullPath); + strcat(fullPath,fileList[i].filename.C_String()); + + // Security - Don't allow .. in the filename anywhere so you can't write outside of the root directory + for (j=1; j < fileList[i].filename.GetLength(); j++) + { + if (fileList[i].filename[j]=='.' && fileList[i].filename[j-1]=='.') + { +#ifdef _DEBUG + RakAssert(0); +#endif + // Just cancel the write entirely + return; + } + } + + WriteFileWithDirectories(fullPath, fileList[i].data, (unsigned int) fileList[i].dataLengthBytes); + } +} + +#ifdef _MSC_VER +#pragma warning( disable : 4996 ) // unlink declared deprecated by Microsoft in order to make it harder to be cross platform. I don't agree it's deprecated. +#endif +void FileList::DeleteFiles(const char *applicationDirectory) +{ + + + + char fullPath[512]; + unsigned i,j; + + for (i=0; i < fileList.Size(); i++) + { + // The filename should not have .. in the path - if it does ignore it + for (j=1; j < fileList[i].filename.GetLength(); j++) + { + if (fileList[i].filename[j]=='.' && fileList[i].filename[j-1]=='.') + { +#ifdef _DEBUG + RakAssert(0); +#endif + // Just cancel the deletion entirely + return; + } + } + + strcpy(fullPath, applicationDirectory); + FixEndingSlash(fullPath); + strcat(fullPath, fileList[i].filename.C_String()); + + // Do not rename to _unlink as linux uses unlink +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) + int result = _unlink(fullPath); +#else + int result = unlink(fullPath); +#endif + if (result!=0) + { + RAKNET_DEBUG_PRINTF("FileList::DeleteFiles: unlink (%s) failed.\n", fullPath); + } + } + +} + +void FileList::AddCallback(FileListProgress *cb) +{ + if (cb==0) + return; + + if ((unsigned int) fileListProgressCallbacks.GetIndexOf(cb)==(unsigned int)-1) + fileListProgressCallbacks.Push(cb, _FILE_AND_LINE_); +} +void FileList::RemoveCallback(FileListProgress *cb) +{ + unsigned int idx = fileListProgressCallbacks.GetIndexOf(cb); + if (idx!=(unsigned int) -1) + fileListProgressCallbacks.RemoveAtIndex(idx); +} +void FileList::ClearCallbacks(void) +{ + fileListProgressCallbacks.Clear(true, _FILE_AND_LINE_); +} +void FileList::GetCallbacks(DataStructures::List &callbacks) +{ + callbacks = fileListProgressCallbacks; +} + + +bool FileList::FixEndingSlash(char *str) +{ +#ifdef _WIN32 + if (str[strlen(str)-1]!='/' && str[strlen(str)-1]!='\\') + { + strcat(str, "\\"); // Only \ works with system commands, used by AutopatcherClient + return true; + } +#else + if (str[strlen(str)-1]!='\\' && str[strlen(str)-1]!='/') + { + strcat(str, "/"); // Only / works with Linux + return true; + } +#endif + + return false; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_FileOperations diff --git a/src/raknet/FileListTransfer.cpp b/src/raknet/FileListTransfer.cpp new file mode 100644 index 0000000..1359c13 --- /dev/null +++ b/src/raknet/FileListTransfer.cpp @@ -0,0 +1,1165 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_FileListTransfer==1 && _RAKNET_SUPPORT_FileOperations==1 + +#include "include/raknet/FileListTransfer.hpp" +#include "include/raknet/DS_HuffmanEncodingTree.hpp" +#include "include/raknet/FileListTransferCBInterface.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/FileList.hpp" +#include "include/raknet/DS_Queue.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakNetTypes.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/RakNetStatistics.hpp" +#include "include/raknet/IncrementalReadInterface.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakAlloca.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +namespace RakNet +{ + +struct FLR_MemoryBlock +{ + char *flrMemoryBlock; +}; + +struct FileListReceiver +{ + FileListReceiver(); + ~FileListReceiver(); + FileListTransferCBInterface *downloadHandler; + SystemAddress allowedSender; + unsigned short setID; + unsigned setCount; + unsigned setTotalCompressedTransmissionLength; + unsigned setTotalFinalLength; + unsigned setTotalDownloadedLength; + bool gotSetHeader; + bool deleteDownloadHandler; + bool isCompressed; + int filesReceived; + DataStructures::Map pushedFiles; + + // Notifications + unsigned int partLength; + +}; + +} // namespace RakNet + +using namespace RakNet; + +FileListReceiver::FileListReceiver() {filesReceived=0; setTotalDownloadedLength=0; partLength=1; DataStructures::Map::IMPLEMENT_DEFAULT_COMPARISON();} +FileListReceiver::~FileListReceiver() { + unsigned int i=0; + for (i=0; i < pushedFiles.Size(); i++) + rakFree_Ex(pushedFiles[i].flrMemoryBlock, _FILE_AND_LINE_ ); +} + +STATIC_FACTORY_DEFINITIONS(FileListTransfer,FileListTransfer) + +void FileListTransfer::FileToPushRecipient::DeleteThis(void) +{ +//// filesToPushMutex.Lock(); + for (unsigned int j=0; j < filesToPush.Size(); j++) + RakNet::OP_DELETE(filesToPush[j],_FILE_AND_LINE_); +//// filesToPushMutex.Unlock(); + RakNet::OP_DELETE(this,_FILE_AND_LINE_); +} +void FileListTransfer::FileToPushRecipient::AddRef(void) +{ + refCountMutex.Lock(); + ++refCount; + refCountMutex.Unlock(); +} +void FileListTransfer::FileToPushRecipient::Deref(void) +{ + refCountMutex.Lock(); + --refCount; + if (refCount==0) + { + refCountMutex.Unlock(); + DeleteThis(); + return; + } + refCountMutex.Unlock(); +} +FileListTransfer::FileListTransfer() +{ + setId=0; + DataStructures::Map::IMPLEMENT_DEFAULT_COMPARISON(); +} +FileListTransfer::~FileListTransfer() +{ + threadPool.StopThreads(); + Clear(); +} +void FileListTransfer::StartIncrementalReadThreads(int numThreads, int threadPriority) +{ + (void) threadPriority; + + threadPool.StartThreads(numThreads, 0); +} +unsigned short FileListTransfer::SetupReceive(FileListTransferCBInterface *handler, bool deleteHandler, SystemAddress allowedSender) +{ + if (rakPeerInterface && rakPeerInterface->GetConnectionState(allowedSender)!=IS_CONNECTED) + return (unsigned short)-1; + FileListReceiver *receiver; + + if (fileListReceivers.Has(setId)) + { + receiver=fileListReceivers.Get(setId); + receiver->downloadHandler->OnDereference(); + if (receiver->deleteDownloadHandler) + RakNet::OP_DELETE(receiver->downloadHandler, _FILE_AND_LINE_); + RakNet::OP_DELETE(receiver, _FILE_AND_LINE_); + fileListReceivers.Delete(setId); + } + + unsigned short oldId; + receiver = RakNet::OP_NEW( _FILE_AND_LINE_ ); + RakAssert(handler); + receiver->downloadHandler=handler; + receiver->allowedSender=allowedSender; + receiver->gotSetHeader=false; + receiver->deleteDownloadHandler=deleteHandler; + receiver->setID=setId; + fileListReceivers.Set(setId, receiver); + oldId=setId; + if (++setId==(unsigned short)-1) + setId=0; + return oldId; +} + +void FileListTransfer::Send(FileList *fileList, RakNet::RakPeerInterface *rakPeer, SystemAddress recipient, unsigned short setID, PacketPriority priority, char orderingChannel, IncrementalReadInterface *_incrementalReadInterface, unsigned int _chunkSize) +{ + for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) + fileList->AddCallback(fileListProgressCallbacks[flpcIndex]); + + unsigned int i, totalLength; + RakNet::BitStream outBitstream; + bool sendReference; + const char *dataBlocks[2]; + int lengths[2]; + totalLength=0; + for (i=0; i < fileList->fileList.Size(); i++) + { + const FileListNode &fileListNode = fileList->fileList[i]; + totalLength+=fileListNode.dataLengthBytes; + } + + // Write the chunk header, which contains the frequency table, the total number of files, and the total number of bytes + bool anythingToWrite; + outBitstream.Write((MessageID)ID_FILE_LIST_TRANSFER_HEADER); + outBitstream.Write(setID); + anythingToWrite=fileList->fileList.Size()>0; + outBitstream.Write(anythingToWrite); + if (anythingToWrite) + { + outBitstream.WriteCompressed(fileList->fileList.Size()); + outBitstream.WriteCompressed(totalLength); + + if (rakPeer) + rakPeer->Send(&outBitstream, priority, RELIABLE_ORDERED, orderingChannel, recipient, false); + else + SendUnified(&outBitstream, priority, RELIABLE_ORDERED, orderingChannel, recipient, false); + + DataStructures::Queue filesToPush; + + for (i=0; i < fileList->fileList.Size(); i++) + { + sendReference = fileList->fileList[i].isAReference && _incrementalReadInterface!=0; + if (sendReference) + { + FileToPush *fileToPush = RakNet::OP_NEW(_FILE_AND_LINE_); + fileToPush->fileListNode.context=fileList->fileList[i].context; + fileToPush->setIndex=i; + fileToPush->fileListNode.filename=fileList->fileList[i].filename; + fileToPush->fileListNode.fullPathToFile=fileList->fileList[i].fullPathToFile; + fileToPush->fileListNode.fileLengthBytes=fileList->fileList[i].fileLengthBytes; + fileToPush->fileListNode.dataLengthBytes=fileList->fileList[i].dataLengthBytes; + // fileToPush->systemAddress=recipient; + //fileToPush->setID=setID; + fileToPush->packetPriority=priority; + fileToPush->orderingChannel=orderingChannel; + fileToPush->currentOffset=0; + fileToPush->incrementalReadInterface=_incrementalReadInterface; + fileToPush->chunkSize=_chunkSize; + filesToPush.Push(fileToPush,_FILE_AND_LINE_); + } + else + { + outBitstream.Reset(); + outBitstream.Write((MessageID)ID_FILE_LIST_TRANSFER_FILE); + outBitstream << fileList->fileList[i].context; + // outBitstream.Write(fileList->fileList[i].context); + outBitstream.Write(setID); + StringCompressor::Instance()->EncodeString(fileList->fileList[i].filename, 512, &outBitstream); + + outBitstream.WriteCompressed(i); + outBitstream.WriteCompressed(fileList->fileList[i].dataLengthBytes); // Original length in bytes + + outBitstream.AlignWriteToByteBoundary(); + + dataBlocks[0]=(char*) outBitstream.GetData(); + lengths[0]=outBitstream.GetNumberOfBytesUsed(); + dataBlocks[1]=fileList->fileList[i].data; + lengths[1]=fileList->fileList[i].dataLengthBytes; + SendListUnified(dataBlocks,lengths,2,priority, RELIABLE_ORDERED, orderingChannel, recipient, false); + } + } + + if (filesToPush.IsEmpty()==false) + { + FileToPushRecipient *ftpr; + + fileToPushRecipientListMutex.Lock(); + for (unsigned int i=0; i < fileToPushRecipientList.Size(); i++) + { + if (fileToPushRecipientList[i]->systemAddress==recipient && fileToPushRecipientList[i]->setId==setId) + { +// ftpr=fileToPushRecipientList[i]; +// ftpr->AddRef(); +// break; + RakAssert("setId already in use for this recipient" && 0); + } + } + fileToPushRecipientListMutex.Unlock(); + + //if (ftpr==0) + //{ + ftpr = RakNet::OP_NEW(_FILE_AND_LINE_); + ftpr->systemAddress=recipient; + ftpr->setId=setID; + ftpr->refCount=2; // Allocated and in the list + fileToPushRecipientList.Push(ftpr, _FILE_AND_LINE_); + //} + while (filesToPush.IsEmpty()==false) + { + ////ftpr->filesToPushMutex.Lock(); + ftpr->filesToPush.Push(filesToPush.Pop(), _FILE_AND_LINE_); + ////ftpr->filesToPushMutex.Unlock(); + } + // ftpr out of scope + ftpr->Deref(); + SendIRIToAddress(recipient, setID); + return; + } + else + { + for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) + fileListProgressCallbacks[flpcIndex]->OnFilePushesComplete(recipient, setID); + } + } + else + { + for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) + fileListProgressCallbacks[flpcIndex]->OnFilePushesComplete(recipient, setID); + + if (rakPeer) + rakPeer->Send(&outBitstream, priority, RELIABLE_ORDERED, orderingChannel, recipient, false); + else + SendUnified(&outBitstream, priority, RELIABLE_ORDERED, orderingChannel, recipient, false); + } +} + +bool FileListTransfer::DecodeSetHeader(Packet *packet) +{ + bool anythingToWrite=false; + unsigned short setID; + RakNet::BitStream inBitStream(packet->data, packet->length, false); + inBitStream.IgnoreBits(8); + inBitStream.Read(setID); + FileListReceiver *fileListReceiver; + if (fileListReceivers.Has(setID)==false) + { + // If this assert hits you didn't call SetupReceive +#ifdef _DEBUG + RakAssert(0); +#endif + return false; + } + fileListReceiver=fileListReceivers.Get(setID); + if (fileListReceiver->allowedSender!=packet->systemAddress) + { +#ifdef _DEBUG + RakAssert(0); +#endif + return false; + } + +#ifdef _DEBUG + RakAssert(fileListReceiver->gotSetHeader==false); +#endif + + inBitStream.Read(anythingToWrite); + + if (anythingToWrite) + { + inBitStream.ReadCompressed(fileListReceiver->setCount); + if (inBitStream.ReadCompressed(fileListReceiver->setTotalFinalLength)) + { + fileListReceiver->setTotalCompressedTransmissionLength=fileListReceiver->setTotalFinalLength; + fileListReceiver->gotSetHeader=true; + return true; + } + + } + else + { + FileListTransferCBInterface::DownloadCompleteStruct dcs; + dcs.setID=fileListReceiver->setID; + dcs.numberOfFilesInThisSet=fileListReceiver->setCount; + dcs.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; + dcs.senderSystemAddress=packet->systemAddress; + dcs.senderGuid=packet->guid; + + if (fileListReceiver->downloadHandler->OnDownloadComplete(&dcs)==false) + { + fileListReceiver->downloadHandler->OnDereference(); + fileListReceivers.Delete(setID); + if (fileListReceiver->deleteDownloadHandler) + RakNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); + RakNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); + } + + return true; + } + + return false; +} + +bool FileListTransfer::DecodeFile(Packet *packet, bool isTheFullFile) +{ + FileListTransferCBInterface::OnFileStruct onFileStruct; + RakNet::BitStream inBitStream(packet->data, packet->length, false); + inBitStream.IgnoreBits(8); + + onFileStruct.senderSystemAddress=packet->systemAddress; + onFileStruct.senderGuid=packet->guid; + + unsigned int partCount=0; + unsigned int partTotal=0; + unsigned int partLength=0; + onFileStruct.fileData=0; + if (isTheFullFile==false) + { + // Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp + inBitStream.ReadBits( (unsigned char* ) &partCount, BYTES_TO_BITS(sizeof(partCount)), true ); + inBitStream.ReadBits( (unsigned char* ) &partTotal, BYTES_TO_BITS(sizeof(partTotal)), true ); + inBitStream.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true ); + inBitStream.IgnoreBits(8); + // The header is appended to every chunk, which we continue to read after this statement flrMemoryBlock + } + inBitStream >> onFileStruct.context; + // inBitStream.Read(onFileStruct.context); + inBitStream.Read(onFileStruct.setID); + FileListReceiver *fileListReceiver; + if (fileListReceivers.Has(onFileStruct.setID)==false) + { + return false; + } + fileListReceiver=fileListReceivers.Get(onFileStruct.setID); + if (fileListReceiver->allowedSender!=packet->systemAddress) + { +#ifdef _DEBUG + RakAssert(0); +#endif + return false; + } + +#ifdef _DEBUG + RakAssert(fileListReceiver->gotSetHeader==true); +#endif + + if (StringCompressor::Instance()->DecodeString(onFileStruct.fileName, 512, &inBitStream)==false) + { +#ifdef _DEBUG + RakAssert(0); +#endif + return false; + } + + inBitStream.ReadCompressed(onFileStruct.fileIndex); + inBitStream.ReadCompressed(onFileStruct.byteLengthOfThisFile); + + onFileStruct.numberOfFilesInThisSet=fileListReceiver->setCount; + onFileStruct.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; + + if (isTheFullFile) + { + onFileStruct.bytesDownloadedForThisFile=onFileStruct.byteLengthOfThisFile; + fileListReceiver->setTotalDownloadedLength+=onFileStruct.byteLengthOfThisFile; + onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength; + } + else + { + onFileStruct.bytesDownloadedForThisFile=partLength*partCount; + onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength+onFileStruct.bytesDownloadedForThisFile; + } + + // User callback for this file. + if (isTheFullFile) + { + inBitStream.AlignReadToByteBoundary(); + onFileStruct.fileData = (char*) rakMalloc_Ex( (size_t) onFileStruct.byteLengthOfThisFile, _FILE_AND_LINE_ ); + inBitStream.Read((char*)onFileStruct.fileData, onFileStruct.byteLengthOfThisFile); + + FileListTransferCBInterface::FileProgressStruct fps; + fps.onFileStruct=&onFileStruct; + fps.partCount=1; + fps.partTotal=1; + fps.dataChunkLength=onFileStruct.byteLengthOfThisFile; + fps.firstDataChunk=onFileStruct.fileData; + fps.iriDataChunk=onFileStruct.fileData; + fps.allocateIrIDataChunkAutomatically=true; + fps.iriWriteOffset=0; + fps.senderSystemAddress=packet->systemAddress; + fps.senderGuid=packet->guid; + fileListReceiver->downloadHandler->OnFileProgress(&fps); + + // Got a complete file + // Either we are using IncrementalReadInterface and it was a small file or + // We are not using IncrementalReadInterface + if (fileListReceiver->downloadHandler->OnFile(&onFileStruct)) + rakFree_Ex(onFileStruct.fileData, _FILE_AND_LINE_ ); + + fileListReceiver->filesReceived++; + + // If this set is done, free the memory for it. + if ((int) fileListReceiver->setCount==fileListReceiver->filesReceived) + { + FileListTransferCBInterface::DownloadCompleteStruct dcs; + dcs.setID=fileListReceiver->setID; + dcs.numberOfFilesInThisSet=fileListReceiver->setCount; + dcs.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; + dcs.senderSystemAddress=packet->systemAddress; + dcs.senderGuid=packet->guid; + + if (fileListReceiver->downloadHandler->OnDownloadComplete(&dcs)==false) + { + fileListReceiver->downloadHandler->OnDereference(); + if (fileListReceiver->deleteDownloadHandler) + RakNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); + fileListReceivers.Delete(onFileStruct.setID); + RakNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); + } + } + + } + else + { + inBitStream.AlignReadToByteBoundary(); + + char *firstDataChunk; + unsigned int unreadBits = inBitStream.GetNumberOfUnreadBits(); + unsigned int unreadBytes = BITS_TO_BYTES(unreadBits); + firstDataChunk=(char*) inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()); + + FileListTransferCBInterface::FileProgressStruct fps; + fps.onFileStruct=&onFileStruct; + fps.partCount=partCount; + fps.partTotal=partTotal; + fps.dataChunkLength=unreadBytes; + fps.firstDataChunk=firstDataChunk; + fps.iriDataChunk=0; + fps.allocateIrIDataChunkAutomatically=true; + fps.iriWriteOffset=0; + fps.senderSystemAddress=packet->systemAddress; + fps.senderGuid=packet->guid; + + // Remote system is sending a complete file, but the file is large enough that we get ID_PROGRESS_NOTIFICATION from the transport layer + fileListReceiver->downloadHandler->OnFileProgress(&fps); + + } + + return true; +} +PluginReceiveResult FileListTransfer::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_FILE_LIST_TRANSFER_HEADER: + DecodeSetHeader(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_FILE_LIST_TRANSFER_FILE: + DecodeFile(packet, true); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_FILE_LIST_REFERENCE_PUSH: + OnReferencePush(packet, true); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_FILE_LIST_REFERENCE_PUSH_ACK: + OnReferencePushAck(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_DOWNLOAD_PROGRESS: + if (packet->length>sizeof(MessageID)+sizeof(unsigned int)*3) + { + if (packet->data[sizeof(MessageID)+sizeof(unsigned int)*3]==ID_FILE_LIST_TRANSFER_FILE) + { + DecodeFile(packet, false); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + if (packet->data[sizeof(MessageID)+sizeof(unsigned int)*3]==ID_FILE_LIST_REFERENCE_PUSH) + { + OnReferencePush(packet, false); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + break; + } + + return RR_CONTINUE_PROCESSING; +} +void FileListTransfer::OnRakPeerShutdown(void) +{ + threadPool.StopThreads(); + threadPool.ClearInput(); + Clear(); +} +void FileListTransfer::Clear(void) +{ + unsigned i; + for (i=0; i < fileListReceivers.Size(); i++) + { + fileListReceivers[i]->downloadHandler->OnDereference(); + if (fileListReceivers[i]->deleteDownloadHandler) + RakNet::OP_DELETE(fileListReceivers[i]->downloadHandler, _FILE_AND_LINE_); + RakNet::OP_DELETE(fileListReceivers[i], _FILE_AND_LINE_); + } + fileListReceivers.Clear(); + + fileToPushRecipientListMutex.Lock(); + for (unsigned int i=0; i < fileToPushRecipientList.Size(); i++) + { + FileToPushRecipient *ftpr = fileToPushRecipientList[i]; + // Taken out of the list + ftpr->Deref(); + } + fileToPushRecipientList.Clear(false,_FILE_AND_LINE_); + fileToPushRecipientListMutex.Unlock(); + + //filesToPush.Clear(false, _FILE_AND_LINE_); +} +void FileListTransfer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) rakNetGUID; + + RemoveReceiver(systemAddress); +} +void FileListTransfer::CancelReceive(unsigned short setId) +{ + if (fileListReceivers.Has(setId)==false) + { +#ifdef _DEBUG + RakAssert(0); +#endif + return; + } + FileListReceiver *fileListReceiver=fileListReceivers.Get(setId); + fileListReceiver->downloadHandler->OnDereference(); + if (fileListReceiver->deleteDownloadHandler) + RakNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); + RakNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); + fileListReceivers.Delete(setId); +} +void FileListTransfer::RemoveReceiver(SystemAddress systemAddress) +{ + unsigned i; + i=0; + threadPool.LockInput(); + while (i < threadPool.InputSize()) + { + if (threadPool.GetInputAtIndex(i).systemAddress==systemAddress) + { + threadPool.RemoveInputAtIndex(i); + } + else + i++; + } + threadPool.UnlockInput(); + + i=0; + while (i < fileListReceivers.Size()) + { + if (fileListReceivers[i]->allowedSender==systemAddress) + { + fileListReceivers[i]->downloadHandler->OnDereference(); + if (fileListReceivers[i]->deleteDownloadHandler) + RakNet::OP_DELETE(fileListReceivers[i]->downloadHandler, _FILE_AND_LINE_); + RakNet::OP_DELETE(fileListReceivers[i], _FILE_AND_LINE_); + fileListReceivers.RemoveAtIndex(i); + } + else + i++; + } + + fileToPushRecipientListMutex.Lock(); + i=0; + while (i < fileToPushRecipientList.Size()) + { + if (fileToPushRecipientList[i]->systemAddress==systemAddress) + { + FileToPushRecipient *ftpr = fileToPushRecipientList[i]; + + // Tell the user that this recipient was lost + for (unsigned int flpcIndex=0; flpcIndex < fileListProgressCallbacks.Size(); flpcIndex++) + fileListProgressCallbacks[flpcIndex]->OnSendAborted(ftpr->systemAddress); + + fileToPushRecipientList.RemoveAtIndex(i); + // Taken out of the list + ftpr->Deref(); + } + else + { + i++; + } + } + fileToPushRecipientListMutex.Unlock(); +} +bool FileListTransfer::IsHandlerActive(unsigned short setId) +{ + return fileListReceivers.Has(setId); +} +void FileListTransfer::AddCallback(FileListProgress *cb) +{ + if (cb==0) + return; + + if (fileListProgressCallbacks.GetIndexOf(cb)==(unsigned int) -1) + fileListProgressCallbacks.Push(cb, _FILE_AND_LINE_); +} +void FileListTransfer::RemoveCallback(FileListProgress *cb) +{ + unsigned int idx = fileListProgressCallbacks.GetIndexOf(cb); + if (idx!=(unsigned int) -1) + fileListProgressCallbacks.RemoveAtIndex(idx); +} +void FileListTransfer::ClearCallbacks(void) +{ + fileListProgressCallbacks.Clear(true, _FILE_AND_LINE_); +} +void FileListTransfer::GetCallbacks(DataStructures::List &callbacks) +{ + callbacks = fileListProgressCallbacks; +} + +void FileListTransfer::Update(void) +{ + unsigned i; + i=0; + while (i < fileListReceivers.Size()) + { + if (fileListReceivers[i]->downloadHandler->Update()==false) + { + fileListReceivers[i]->downloadHandler->OnDereference(); + if (fileListReceivers[i]->deleteDownloadHandler) + RakNet::OP_DELETE(fileListReceivers[i]->downloadHandler, _FILE_AND_LINE_); + RakNet::OP_DELETE(fileListReceivers[i], _FILE_AND_LINE_); + fileListReceivers.RemoveAtIndex(i); + } + else + i++; + } +} +void FileListTransfer::OnReferencePush(Packet *packet, bool isTheFullFile) +{ + RakNet::BitStream refPushAck; + if (isTheFullFile==false) + { + // 12/23/09 Why do I care about ID_DOWNLOAD_PROGRESS for reference pushes? + // 2/16/2012 I care because a reference push is 16 megabytes by default. Also, if it is the last file "if (ftpr->filesToPush.Size()<2)" or total file size exceeds smallFileTotalSize it always sends a reference push. +// return; + } + + FileListTransferCBInterface::OnFileStruct onFileStruct; + RakNet::BitStream inBitStream(packet->data, packet->length, false); + inBitStream.IgnoreBits(8); + + unsigned int partCount=0; + unsigned int partTotal=1; + unsigned int partLength=0; + onFileStruct.fileData=0; + if (isTheFullFile==false) + { + // Disable endian swapping on reading this, as it's generated locally in ReliabilityLayer.cpp + inBitStream.ReadBits( (unsigned char* ) &partCount, BYTES_TO_BITS(sizeof(partCount)), true ); + inBitStream.ReadBits( (unsigned char* ) &partTotal, BYTES_TO_BITS(sizeof(partTotal)), true ); + inBitStream.ReadBits( (unsigned char* ) &partLength, BYTES_TO_BITS(sizeof(partLength)), true ); + inBitStream.IgnoreBits(8); + // The header is appended to every chunk, which we continue to read after this statement flrMemoryBlock + } + + inBitStream >> onFileStruct.context; + inBitStream.Read(onFileStruct.setID); + + // This is not a progress notification, it is actually the entire packet + if (isTheFullFile==true) + { + refPushAck.Write((MessageID)ID_FILE_LIST_REFERENCE_PUSH_ACK); + refPushAck.Write(onFileStruct.setID); + SendUnified(&refPushAck,HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, false); + } + + // inBitStream.Read(onFileStruct.context); + FileListReceiver *fileListReceiver; + if (fileListReceivers.Has(onFileStruct.setID)==false) + { + return; + } + fileListReceiver=fileListReceivers.Get(onFileStruct.setID); + if (fileListReceiver->allowedSender!=packet->systemAddress) + { +#ifdef _DEBUG + RakAssert(0); +#endif + return; + } + +#ifdef _DEBUG + RakAssert(fileListReceiver->gotSetHeader==true); +#endif + + if (StringCompressor::Instance()->DecodeString(onFileStruct.fileName, 512, &inBitStream)==false) + { +#ifdef _DEBUG + RakAssert(0); +#endif + return; + } + + inBitStream.ReadCompressed(onFileStruct.fileIndex); + inBitStream.ReadCompressed(onFileStruct.byteLengthOfThisFile); + unsigned int offset; + unsigned int chunkLength; + inBitStream.ReadCompressed(offset); + inBitStream.ReadCompressed(chunkLength); + + bool lastChunk=false; + inBitStream.Read(lastChunk); + bool finished = lastChunk && isTheFullFile; + + if (isTheFullFile==false) + fileListReceiver->partLength=partLength; + + FLR_MemoryBlock mb; + if (fileListReceiver->pushedFiles.Has(onFileStruct.fileIndex)==false) + { + mb.flrMemoryBlock=(char*) rakMalloc_Ex(onFileStruct.byteLengthOfThisFile, _FILE_AND_LINE_); + fileListReceiver->pushedFiles.SetNew(onFileStruct.fileIndex, mb); + } + else + { + mb=fileListReceiver->pushedFiles.Get(onFileStruct.fileIndex); + } + + unsigned int unreadBits = inBitStream.GetNumberOfUnreadBits(); + unsigned int unreadBytes = BITS_TO_BYTES(unreadBits); + unsigned int amountToRead; + if (isTheFullFile) + amountToRead=chunkLength; + else + amountToRead=unreadBytes; + + inBitStream.AlignReadToByteBoundary(); + + FileListTransferCBInterface::FileProgressStruct fps; + + if (isTheFullFile) + { + if (mb.flrMemoryBlock) + { + // Either the very first block, or a subsequent block and allocateIrIDataChunkAutomatically was true for the first block + memcpy(mb.flrMemoryBlock+offset, inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()), amountToRead); + fps.iriDataChunk=mb.flrMemoryBlock+offset; + } + else + { + // In here mb.flrMemoryBlock is null + // This means the first block explicitly deallocated the memory, and no blocks will be permanently held by RakNet + fps.iriDataChunk=(char*) inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()); + } + + onFileStruct.bytesDownloadedForThisFile=offset+chunkLength; + fileListReceiver->setTotalDownloadedLength+=chunkLength; + onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength; + } + else + { + onFileStruct.bytesDownloadedForThisFile=offset+partLength*partCount; + onFileStruct.bytesDownloadedForThisSet=fileListReceiver->setTotalDownloadedLength+partCount*partLength; + fps.iriDataChunk=(char*) inBitStream.GetData()+BITS_TO_BYTES(inBitStream.GetReadOffset()); + } + + onFileStruct.numberOfFilesInThisSet=fileListReceiver->setCount; +// onFileStruct.setTotalCompressedTransmissionLength=fileListReceiver->setTotalCompressedTransmissionLength; + onFileStruct.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; + // Note: mb.flrMemoryBlock may be null here + onFileStruct.fileData=mb.flrMemoryBlock; + onFileStruct.senderSystemAddress=packet->systemAddress; + onFileStruct.senderGuid=packet->guid; + + unsigned int totalNotifications; + unsigned int currentNotificationIndex; + if (chunkLength==0 || chunkLength==onFileStruct.byteLengthOfThisFile) + totalNotifications=1; + else + totalNotifications = onFileStruct.byteLengthOfThisFile / chunkLength + 1; + + if (chunkLength==0) + currentNotificationIndex = 0; + else + currentNotificationIndex = offset / chunkLength; + + fps.onFileStruct=&onFileStruct; + fps.partCount=currentNotificationIndex; + fps.partTotal=totalNotifications; + fps.dataChunkLength=amountToRead; + fps.firstDataChunk=mb.flrMemoryBlock; + fps.allocateIrIDataChunkAutomatically=true; + fps.onFileStruct->fileData=mb.flrMemoryBlock; + fps.iriWriteOffset=offset; + fps.senderSystemAddress=packet->systemAddress; + fps.senderGuid=packet->guid; + + if (finished) + { + char *oldFileData=fps.onFileStruct->fileData; + if (fps.partCount==0) + fps.firstDataChunk=fps.iriDataChunk; + if (fps.partTotal==1) + fps.onFileStruct->fileData=fps.iriDataChunk; + fileListReceiver->downloadHandler->OnFileProgress(&fps); + + // Incremental read interface sent us a file chunk + // This is the last file chunk we were waiting for to consider the file done + if (fileListReceiver->downloadHandler->OnFile(&onFileStruct)) + rakFree_Ex(oldFileData, _FILE_AND_LINE_ ); + fileListReceiver->pushedFiles.Delete(onFileStruct.fileIndex); + + fileListReceiver->filesReceived++; + + // If this set is done, free the memory for it. + if ((int) fileListReceiver->setCount==fileListReceiver->filesReceived) + { + FileListTransferCBInterface::DownloadCompleteStruct dcs; + dcs.setID=fileListReceiver->setID; + dcs.numberOfFilesInThisSet=fileListReceiver->setCount; + dcs.byteLengthOfThisSet=fileListReceiver->setTotalFinalLength; + dcs.senderSystemAddress=packet->systemAddress; + dcs.senderGuid=packet->guid; + + if (fileListReceiver->downloadHandler->OnDownloadComplete(&dcs)==false) + { + fileListReceiver->downloadHandler->OnDereference(); + fileListReceivers.Delete(onFileStruct.setID); + if (fileListReceiver->deleteDownloadHandler) + RakNet::OP_DELETE(fileListReceiver->downloadHandler, _FILE_AND_LINE_); + RakNet::OP_DELETE(fileListReceiver, _FILE_AND_LINE_); + } + } + } + else + { + if (isTheFullFile) + { + // 12/23/09 Don't use OnReferencePush anymore, just use OnFileProgress + fileListReceiver->downloadHandler->OnFileProgress(&fps); + + if (fps.allocateIrIDataChunkAutomatically==false) + { + rakFree_Ex(fileListReceiver->pushedFiles.Get(onFileStruct.fileIndex).flrMemoryBlock, _FILE_AND_LINE_ ); + fileListReceiver->pushedFiles.Get(onFileStruct.fileIndex).flrMemoryBlock=0; + } + } + else + { + // This is a download progress notification for a file chunk using incremental read interface + // We don't have all the data for this chunk yet + + totalNotifications = onFileStruct.byteLengthOfThisFile / fileListReceiver->partLength + 1; + if (isTheFullFile==false) + currentNotificationIndex = (offset+partCount*fileListReceiver->partLength) / fileListReceiver->partLength ; + else + currentNotificationIndex = (offset+chunkLength) / fileListReceiver->partLength ; + unreadBytes = onFileStruct.byteLengthOfThisFile - ((currentNotificationIndex+1) * fileListReceiver->partLength); + fps.partCount=currentNotificationIndex; + fps.partTotal=totalNotifications; + +// 2/19/2013 Why was this check here? It prevent smaller progress notifications +// if (rakPeerInterface) + { + // Thus chunk is incomplete + fps.iriDataChunk=0; + + fileListReceiver->downloadHandler->OnFileProgress(&fps); + } + } + } + + return; +} +namespace RakNet +{ + +/* +SendIRIToAddress - executes from Send(). = +1, Find the recipient to send for +2. Send ID_FILE_LIST_TRANSFER_FILE for each small file in the queue of ifles to be sent +3. If the file we are working on is done, remove it from the list +4. Send ID_FILE_LIST_REFERENCE_PUSH for the file we are working on + +File sender: +ID_FILE_LIST_REFERENCE_PUSH sent from end of SendIRIToAddressCB + +Recipient: +send ID_FILE_LIST_REFERENCE_PUSH_ACK sent from OnReferencePush() when 2nd parameter is true. + +File sender: +Got ID_FILE_LIST_REFERENCE_PUSH_ACK. Calls OnReferencePushAck, calls SendIRIToAddress, calls SendIRIToAddressCB +*/ + +int SendIRIToAddressCB(FileListTransfer::ThreadData threadData, bool *returnOutput, void* perThreadData) +{ + (void) perThreadData; + + FileListTransfer *fileListTransfer = threadData.fileListTransfer; + SystemAddress systemAddress = threadData.systemAddress; + unsigned short setId = threadData.setId; + *returnOutput=false; + + // Was previously using GetStatistics to get outgoing buffer size, but TCP with UnifiedSend doesn't have this + unsigned int bytesRead; + const char *dataBlocks[2]; + int lengths[2]; + unsigned int smallFileTotalSize=0; + RakNet::BitStream outBitstream; + unsigned int ftpIndex; + + fileListTransfer->fileToPushRecipientListMutex.Lock(); + for (ftpIndex=0; ftpIndex < fileListTransfer->fileToPushRecipientList.Size(); ftpIndex++) + { + FileListTransfer::FileToPushRecipient *ftpr = fileListTransfer->fileToPushRecipientList[ftpIndex]; + // Referenced by both ftpr and list + ftpr->AddRef(); + + fileListTransfer->fileToPushRecipientListMutex.Unlock(); + + if (ftpr->systemAddress==systemAddress && ftpr->setId==setId) + { + FileListTransfer::FileToPush *ftp; + ////ftpr->filesToPushMutex.Lock(); + ftp = ftpr->filesToPush.Pop(); + ////ftpr->filesToPushMutex.Unlock(); + + // Read and send chunk. If done, delete at this index + void *buff = rakMalloc_Ex(ftp->chunkSize, _FILE_AND_LINE_); + if (buff==0) + { + ////ftpr->filesToPushMutex.Lock(); + ftpr->filesToPush.PushAtHead(ftp,0,_FILE_AND_LINE_); + ////ftpr->filesToPushMutex.Unlock(); + + ftpr->Deref(); + notifyOutOfMemory(_FILE_AND_LINE_); + return 0; + } + + // Read the next file chunk + bytesRead=ftp->incrementalReadInterface->GetFilePart(ftp->fileListNode.fullPathToFile, ftp->currentOffset, ftp->chunkSize, buff, ftp->fileListNode.context); + + bool done = ftp->fileListNode.dataLengthBytes == ftp->currentOffset+bytesRead; + while (done && ftp->currentOffset==0 && smallFileTotalSizechunkSize) + { + ////ftpr->filesToPushMutex.Lock(); + // The reason for 2 is that ID_FILE_LIST_REFERENCE_PUSH gets ID_FILE_LIST_REFERENCE_PUSH_ACK. WIthout ID_FILE_LIST_REFERENCE_PUSH_ACK, SendIRIToAddressCB would not be called again + if (ftpr->filesToPush.Size()<2) + { + ////ftpr->filesToPushMutex.Unlock(); + break; + } + ////ftpr->filesToPushMutex.Unlock(); + + // Send all small files at once, rather than wait for ID_FILE_LIST_REFERENCE_PUSH. But at least one ID_FILE_LIST_REFERENCE_PUSH must be sent + outBitstream.Reset(); + outBitstream.Write((MessageID)ID_FILE_LIST_TRANSFER_FILE); + // outBitstream.Write(ftp->fileListNode.context); + outBitstream << ftp->fileListNode.context; + outBitstream.Write(setId); + StringCompressor::Instance()->EncodeString(ftp->fileListNode.filename, 512, &outBitstream); + outBitstream.WriteCompressed(ftp->setIndex); + outBitstream.WriteCompressed(ftp->fileListNode.dataLengthBytes); // Original length in bytes + outBitstream.AlignWriteToByteBoundary(); + dataBlocks[0]=(char*) outBitstream.GetData(); + lengths[0]=outBitstream.GetNumberOfBytesUsed(); + dataBlocks[1]=(const char*) buff; + lengths[1]=bytesRead; + + fileListTransfer->SendListUnified(dataBlocks,lengths,2,ftp->packetPriority, RELIABLE_ORDERED, ftp->orderingChannel, systemAddress, false); + + // LWS : fixed freed pointer reference +// unsigned int chunkSize = ftp->chunkSize; + RakNet::OP_DELETE(ftp,_FILE_AND_LINE_); + smallFileTotalSize+=bytesRead; + //done = bytesRead!=ftp->chunkSize; + ////ftpr->filesToPushMutex.Lock(); + ftp = ftpr->filesToPush.Pop(); + ////ftpr->filesToPushMutex.Unlock(); + + bytesRead=ftp->incrementalReadInterface->GetFilePart(ftp->fileListNode.fullPathToFile, ftp->currentOffset, ftp->chunkSize, buff, ftp->fileListNode.context); + done = ftp->fileListNode.dataLengthBytes == ftp->currentOffset+bytesRead; + } + + + outBitstream.Reset(); + outBitstream.Write((MessageID)ID_FILE_LIST_REFERENCE_PUSH); + // outBitstream.Write(ftp->fileListNode.context); + outBitstream << ftp->fileListNode.context; + outBitstream.Write(setId); + StringCompressor::Instance()->EncodeString(ftp->fileListNode.filename, 512, &outBitstream); + outBitstream.WriteCompressed(ftp->setIndex); + outBitstream.WriteCompressed(ftp->fileListNode.dataLengthBytes); // Original length in bytes + outBitstream.WriteCompressed(ftp->currentOffset); + ftp->currentOffset+=bytesRead; + outBitstream.WriteCompressed(bytesRead); + outBitstream.Write(done); + + for (unsigned int flpcIndex=0; flpcIndex < fileListTransfer->fileListProgressCallbacks.Size(); flpcIndex++) + fileListTransfer->fileListProgressCallbacks[flpcIndex]->OnFilePush(ftp->fileListNode.filename, ftp->fileListNode.fileLengthBytes, ftp->currentOffset-bytesRead, bytesRead, done, systemAddress, setId); + + dataBlocks[0]=(char*) outBitstream.GetData(); + lengths[0]=outBitstream.GetNumberOfBytesUsed(); + dataBlocks[1]=(char*) buff; + lengths[1]=bytesRead; + //rakPeerInterface->SendList(dataBlocks,lengths,2,ftp->packetPriority, RELIABLE_ORDERED, ftp->orderingChannel, ftp->systemAddress, false); + char orderingChannel = ftp->orderingChannel; + PacketPriority packetPriority = ftp->packetPriority; + + // Mutex state: FileToPushRecipient (ftpr) has AddRef. fileToPushRecipientListMutex not locked. + if (done) + { + // Done + //unsigned short setId = ftp->setID; + RakNet::OP_DELETE(ftp,_FILE_AND_LINE_); + + ////ftpr->filesToPushMutex.Lock(); + if (ftpr->filesToPush.Size()==0) + { + ////ftpr->filesToPushMutex.Unlock(); + + for (unsigned int flpcIndex=0; flpcIndex < fileListTransfer->fileListProgressCallbacks.Size(); flpcIndex++) + fileListTransfer->fileListProgressCallbacks[flpcIndex]->OnFilePushesComplete(systemAddress, setId); + + // Remove ftpr from fileToPushRecipientList + fileListTransfer->RemoveFromList(ftpr); + } + else + { + ////ftpr->filesToPushMutex.Unlock(); + } + } + else + { + ////ftpr->filesToPushMutex.Lock(); + ftpr->filesToPush.PushAtHead(ftp,0,_FILE_AND_LINE_); + ////ftpr->filesToPushMutex.Unlock(); + } + // ftpr out of scope + ftpr->Deref(); + + // 2/12/2012 Moved this line at after the if (done) block above. + // See http://www.jenkinssoftware.com/forum/index.php?topic=4768.msg19738#msg19738 + fileListTransfer->SendListUnified(dataBlocks,lengths,2, packetPriority, RELIABLE_ORDERED, orderingChannel, systemAddress, false); + + rakFree_Ex(buff, _FILE_AND_LINE_ ); + return 0; + } + else + { + ftpr->Deref(); + fileListTransfer->fileToPushRecipientListMutex.Lock(); + } + } + + fileListTransfer->fileToPushRecipientListMutex.Unlock(); + + return 0; +} +} +void FileListTransfer::SendIRIToAddress(SystemAddress systemAddress, unsigned short setId) +{ + ThreadData threadData; + threadData.fileListTransfer=this; + threadData.systemAddress=systemAddress; + threadData.setId=setId; + + if (threadPool.WasStarted()) + { + threadPool.AddInput(SendIRIToAddressCB, threadData); + } + else + { + bool doesNothing; + SendIRIToAddressCB(threadData, &doesNothing, 0); + } +} +void FileListTransfer::OnReferencePushAck(Packet *packet) +{ + RakNet::BitStream inBitStream(packet->data, packet->length, false); + inBitStream.IgnoreBits(8); + unsigned short setId; + inBitStream.Read(setId); + SendIRIToAddress(packet->systemAddress, setId); +} +void FileListTransfer::RemoveFromList(FileToPushRecipient *ftpr) +{ + fileToPushRecipientListMutex.Lock(); + for (unsigned int i=0; i < fileToPushRecipientList.Size(); i++) + { + if (fileToPushRecipientList[i]==ftpr) + { + fileToPushRecipientList.RemoveAtIndex(i); + // List no longer references + ftpr->Deref(); + fileToPushRecipientListMutex.Unlock(); + return; + } + } + fileToPushRecipientListMutex.Unlock(); +} +unsigned int FileListTransfer::GetPendingFilesToAddress(SystemAddress recipient) +{ + fileToPushRecipientListMutex.Lock(); + for (unsigned int i=0; i < fileToPushRecipientList.Size(); i++) + { + if (fileToPushRecipientList[i]->systemAddress==recipient) + { + unsigned int size = fileToPushRecipientList[i]->filesToPush.Size(); + fileToPushRecipientListMutex.Unlock(); + return size; + } + } + fileToPushRecipientListMutex.Unlock(); + + return 0; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/FileOperations.cpp b/src/raknet/FileOperations.cpp new file mode 100644 index 0000000..6a26874 --- /dev/null +++ b/src/raknet/FileOperations.cpp @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/FileOperations.hpp" +#if _RAKNET_SUPPORT_FileOperations==1 +#include "include/raknet/RakMemoryOverride.hpp" +#include "include/raknet/_FindFirst.hpp" // For linux +#include +#include +#ifdef _WIN32 +// For mkdir +#include +#include +#else +#include +#include +#include "include/raknet/_FindFirst.hpp" +#endif +#include + +#ifndef MAX_PATH +#define MAX_PATH 260 +#endif + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +#ifdef _MSC_VER +#pragma warning( disable : 4996 ) // mkdir declared deprecated by Microsoft in order to make it harder to be cross platform. I don't agree it's deprecated. +#endif +bool WriteFileWithDirectories( const char *path, char *data, unsigned dataLength ) +{ + int index; + FILE *fp; + char pathCopy[MAX_PATH]; + int res; + + if ( path == 0 || path[ 0 ] == 0 ) + return false; + + strcpy( pathCopy, path ); + + // Ignore first / if there is one + if (pathCopy[0]) + { + index = 1; + while ( pathCopy[ index ] ) + { + if ( pathCopy[ index ] == '/' || pathCopy[ index ] == '\\') + { + pathCopy[ index ] = 0; + + #ifdef _WIN32 + res = _mkdir( pathCopy ); + #else + + res = mkdir( pathCopy, 0744 ); + #endif + if (res<0 && errno!=EEXIST && errno!=EACCES) + { + return false; + } + + pathCopy[ index ] = '/'; + } + + index++; + } + } + + if (data) + { + fp = fopen( path, "wb" ); + + if ( fp == 0 ) + { + return false; + } + + fwrite( data, 1, dataLength, fp ); + + fclose( fp ); + } + else + { +#ifdef _WIN32 +#pragma warning( disable : 4996 ) // mkdir declared deprecated by Microsoft in order to make it harder to be cross platform. I don't agree it's deprecated. + res = _mkdir( pathCopy ); +#else + res = mkdir( pathCopy, 0744 ); +#endif + + if (res<0 && errno!=EEXIST) + { + return false; + } + } + + return true; +} +bool IsSlash(unsigned char c) +{ + return c=='/' || c=='\\'; +} + +void AddSlash( char *input ) +{ + if (input==0 || input[0]==0) + return; + + int lastCharIndex=(int) strlen(input)-1; + if (input[lastCharIndex]=='\\') + input[lastCharIndex]='/'; + else if (input[lastCharIndex]!='/') + { + input[lastCharIndex+1]='/'; + input[lastCharIndex+2]=0; + } +} +bool DirectoryExists(const char *directory) +{ + _finddata_t fileInfo; + intptr_t dir; + char baseDirWithStars[560]; + strcpy(baseDirWithStars, directory); + AddSlash(baseDirWithStars); + strcat(baseDirWithStars, "*.*"); + dir=_findfirst(baseDirWithStars, &fileInfo ); + if (dir==-1) + return false; + _findclose(dir); + return true; +} +void QuoteIfSpaces(char *str) +{ + unsigned i; + bool hasSpace=false; + for (i=0; str[i]; i++) + { + if (str[i]==' ') + { + hasSpace=true; + break; + } + } + if (hasSpace) + { + int len=(int)strlen(str); + memmove(str+1, str, len); + str[0]='\"'; + str[len]='\"'; + str[len+1]=0; + } +} +unsigned int GetFileLength(const char *path) +{ + FILE *fp = fopen(path, "rb"); + if (fp==0) return 0; + fseek(fp, 0, SEEK_END); + unsigned int fileLength = ftell(fp); + fclose(fp); + return fileLength; + +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_FileOperations + diff --git a/src/raknet/FormatString.cpp b/src/raknet/FormatString.cpp new file mode 100644 index 0000000..cd1fdb1 --- /dev/null +++ b/src/raknet/FormatString.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/FormatString.hpp" +#include +#include +#include +#include "include/raknet/LinuxStrings.hpp" + +char * FormatString(const char *format, ...) +{ + static int textIndex=0; + static char text[4][8096]; + va_list ap; + va_start(ap, format); + + if (++textIndex==4) + textIndex=0; + _vsnprintf(text[textIndex], 8096, format, ap); + va_end(ap); + text[textIndex][8096-1]=0; + + return text[textIndex]; +} + +char * FormatStringTS(char *output, const char *format, ...) +{ + va_list ap; + va_start(ap, format); + _vsnprintf(output, 512, format, ap); + va_end(ap); + return output; +} diff --git a/src/raknet/FullyConnectedMesh2.cpp b/src/raknet/FullyConnectedMesh2.cpp new file mode 100644 index 0000000..859683b --- /dev/null +++ b/src/raknet/FullyConnectedMesh2.cpp @@ -0,0 +1,1423 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_FullyConnectedMesh2==1 + +#include "include/raknet/FullyConnectedMesh2.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/Rand.hpp" +#include "include/raknet/DS_OrderedList.hpp" + +using namespace RakNet; + +int FCM2ParticipantComp( FullyConnectedMesh2::FCM2Participant * const &key, FullyConnectedMesh2::FCM2Participant * const &data ) +{ + if (key->fcm2Guid < data->fcm2Guid) + return -1; + if (key->fcm2Guid > data->fcm2Guid) + return 1; + return 0; +} + +STATIC_FACTORY_DEFINITIONS(FullyConnectedMesh2,FullyConnectedMesh2); + +FullyConnectedMesh2::FullyConnectedMesh2() +{ + startupTime=0; + totalConnectionCount=0; + ourFCMGuid=0; + autoParticipateConnections=true; + + + + + connectOnNewRemoteConnections=true; + + hostRakNetGuid=UNASSIGNED_RAKNET_GUID; +} +FullyConnectedMesh2::~FullyConnectedMesh2() +{ + Clear(); +} +RakNetGUID FullyConnectedMesh2::GetConnectedHost(void) const +{ + if (ourFCMGuid==0) + return UNASSIGNED_RAKNET_GUID; + return hostRakNetGuid; +} +SystemAddress FullyConnectedMesh2::GetConnectedHostAddr(void) const +{ + if (ourFCMGuid==0) + return UNASSIGNED_SYSTEM_ADDRESS; + return rakPeerInterface->GetSystemAddressFromGuid(hostRakNetGuid); +} +RakNetGUID FullyConnectedMesh2::GetHostSystem(void) const +{ + if (ourFCMGuid==0) + return rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); + + return hostRakNetGuid; +} +bool FullyConnectedMesh2::IsHostSystem(void) const +{ + return GetHostSystem()==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); +} +void FullyConnectedMesh2::GetHostOrder(DataStructures::List &hostList) +{ + hostList.Clear(true, _FILE_AND_LINE_); + + if (ourFCMGuid==0 || fcm2ParticipantList.Size()==0) + { + hostList.Push(rakPeerInterface->GetMyGUID(), _FILE_AND_LINE_); + return; + } + + FCM2Participant fcm2; + fcm2.fcm2Guid=ourFCMGuid; + fcm2.rakNetGuid=rakPeerInterface->GetMyGUID(); + + DataStructures::OrderedList olist; + olist.Insert(&fcm2, &fcm2, true, _FILE_AND_LINE_); + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + olist.Insert(fcm2ParticipantList[i], fcm2ParticipantList[i], true, _FILE_AND_LINE_); + + for (unsigned int i=0; i < olist.Size(); i++) + { + hostList.Push(olist[i]->rakNetGuid, _FILE_AND_LINE_); + } +} +bool FullyConnectedMesh2::IsConnectedHost(void) const +{ + return GetConnectedHost()==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); +} +void FullyConnectedMesh2::SetAutoparticipateConnections(bool b) +{ + autoParticipateConnections=b; +} +void FullyConnectedMesh2::ResetHostCalculation(void) +{ + hostRakNetGuid=UNASSIGNED_RAKNET_GUID; + startupTime=RakNet::GetTimeUS(); + totalConnectionCount=0; + ourFCMGuid=0; + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + SendFCMGuidRequest(fcm2ParticipantList[i]->rakNetGuid); +} +// bool FullyConnectedMesh2::AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid, BitStream *userContext ) +bool FullyConnectedMesh2::AddParticipantInternal( RakNetGUID rakNetGuid, FCM2Guid theirFCMGuid ) +{ + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + { + if (fcm2ParticipantList[i]->rakNetGuid==rakNetGuid) + { + if (theirFCMGuid!=0) + fcm2ParticipantList[i]->fcm2Guid=theirFCMGuid; + /* + fcm2ParticipantList[i]->userContext.Reset(); + if (userContext) + { + userContext->ResetReadPointer(); + fcm2ParticipantList[i]->userContext.Write(userContext); + } + */ + return false; + } + } + + FCM2Participant *participant = RakNet::OP_NEW(_FILE_AND_LINE_); + participant->rakNetGuid=rakNetGuid; + participant->fcm2Guid=theirFCMGuid; + /* + if (userContext) + { + userContext->ResetReadPointer(); + participant->userContext.Write(userContext); + } + */ + fcm2ParticipantList.Push(participant,_FILE_AND_LINE_); + + SendFCMGuidRequest(rakNetGuid); + + return true; +} +void FullyConnectedMesh2::AddParticipant( RakNetGUID rakNetGuid ) +{ + if (rakPeerInterface->GetConnectionState(rakPeerInterface->GetSystemAddressFromGuid(rakNetGuid))!=IS_CONNECTED) + { +#ifdef DEBUG_FCM2 + printf("AddParticipant to %s failed (not connected)\n", rakNetGuid.ToString()); +#endif + return; + } + + // Need to query other system for userdata before calling AddParticipantInternal + // But maybe I can call with no data, and piggyback on ID_FCM2_REQUEST_FCMGUID + //AddParticipantInternal(rakNetGuid,0,0); + AddParticipantInternal(rakNetGuid,0); +} +void FullyConnectedMesh2::GetParticipantList(DataStructures::List &participantList) +{ + participantList.Clear(true, _FILE_AND_LINE_); + unsigned int i; + for (i=0; i < fcm2ParticipantList.Size(); i++) + participantList.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); +} +bool FullyConnectedMesh2::HasParticipant(RakNetGUID participantGuid) +{ + unsigned int i; + for (i=0; i < fcm2ParticipantList.Size(); i++) + { + if (fcm2ParticipantList[i]->rakNetGuid==participantGuid) + return true; + } + return false; +} +/* +bool FullyConnectedMesh2::GetParticipantContext(RakNetGUID participantGuid, BitStream *userContext) +{ + unsigned int i; + for (i=0; i < fcm2ParticipantList.Size(); i++) + { + if (fcm2ParticipantList[i]->rakNetGuid==participantGuid) + { + if (fcm2ParticipantList[i]->userContext.GetNumberOfBitsUsed() > 0) + { + userContext->Write(fcm2ParticipantList[i]->userContext); + fcm2ParticipantList[i]->userContext.ResetReadPointer(); + return true; + } + return false; + } + } + return false; +} +void FullyConnectedMesh2::SetMyContext(BitStream *userContext) +{ + if (userContext==0) + { + if (myContext.GetNumberOfBitsUsed()==0) + return; + myContext.Reset(); + } + else + { + myContext.Write(userContext); + userContext->ResetReadPointer(); + } + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_FCM2_UPDATE_USER_CONTEXT); + bsOut.Write(myContext); + myContext.ResetReadPointer(); + + unsigned int idx; + for (idx=0; idx < fcm2ParticipantList.Size(); idx++) + { + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,fcm2ParticipantList[idx]->rakNetGuid,false); + } +} +*/ +PluginReceiveResult FullyConnectedMesh2::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_REMOTE_NEW_INCOMING_CONNECTION: + { + if (connectOnNewRemoteConnections) + ConnectToRemoteNewIncomingConnections(packet); + } + break; + case ID_FCM2_REQUEST_FCMGUID: + OnRequestFCMGuid(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + //case ID_FCM2_UPDATE_USER_CONTEXT: + // OnUpdateUserContext(packet); + // return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_FCM2_RESPOND_CONNECTION_COUNT: + OnRespondConnectionCount(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_FCM2_INFORM_FCMGUID: + OnInformFCMGuid(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT: + OnUpdateMinTotalConnectionCount(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_FCM2_NEW_HOST: + if (packet->wasGeneratedLocally==false) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + break; + case ID_FCM2_VERIFIED_JOIN_START: + return OnVerifiedJoinStart(packet); + case ID_FCM2_VERIFIED_JOIN_CAPABLE: + return OnVerifiedJoinCapable(packet); + case ID_FCM2_VERIFIED_JOIN_FAILED: + OnVerifiedJoinFailed(packet->guid, true); + return RR_CONTINUE_PROCESSING; + case ID_FCM2_VERIFIED_JOIN_ACCEPTED: + if (packet->wasGeneratedLocally==false) + OnVerifiedJoinAccepted(packet); + return RR_CONTINUE_PROCESSING; + case ID_FCM2_VERIFIED_JOIN_REJECTED: + OnVerifiedJoinRejected(packet); + return RR_CONTINUE_PROCESSING; + + case ID_NAT_TARGET_UNRESPONSIVE: + case ID_NAT_TARGET_NOT_CONNECTED: + case ID_NAT_CONNECTION_TO_TARGET_LOST: + { + RakNet::RakNetGUID g; + RakNet::BitStream b(packet->data, packet->length, false); + b.IgnoreBits(8); // Ignore the ID_... + b.Read(g); + UpdateVerifiedJoinInProgressMember(g, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); + return RR_CONTINUE_PROCESSING; + } + case ID_NAT_PUNCHTHROUGH_FAILED: + UpdateVerifiedJoinInProgressMember(packet->guid, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); + return RR_CONTINUE_PROCESSING; + } + + return RR_CONTINUE_PROCESSING; +} +void FullyConnectedMesh2::OnRakPeerStartup(void) +{ + Clear(); + startupTime=RakNet::GetTimeUS(); +} +void FullyConnectedMesh2::OnAttach(void) +{ + Clear(); + // In case Startup() was called first + if (rakPeerInterface->IsActive()) + startupTime=RakNet::GetTimeUS(); +} +void FullyConnectedMesh2::OnRakPeerShutdown(void) +{ + Clear(); + startupTime=0; +} +void FullyConnectedMesh2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + (void) rakNetGUID; + + unsigned int idx; + idx=0; + while (idx < joinsInProgress.Size()) + { + if (joinsInProgress[idx]->requester==rakNetGUID) + { + Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); + p->data[0]=ID_FCM2_VERIFIED_JOIN_FAILED; + p->systemAddress=systemAddress; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=rakNetGUID; + p->wasGeneratedLocally=true; + rakPeerInterface->PushBackPacket(p, true); + + for (unsigned int j=0; j < joinsInProgress[idx]->vjipMembers.Size(); j++) + { + if ( joinsInProgress[idx]->vjipMembers[j].userData != 0) + { + RakNet::OP_DELETE(joinsInProgress[idx]->vjipMembers[j].userData, _FILE_AND_LINE_); + } + } + + RakNet::OP_DELETE(joinsInProgress[idx], _FILE_AND_LINE_); + joinsInProgress.RemoveAtIndex(idx); + } + else + { + idx++; + } + } + + UpdateVerifiedJoinInProgressMember(rakNetGUID, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); + + for (idx=0; idx < fcm2ParticipantList.Size(); idx++) + { + if (fcm2ParticipantList[idx]->rakNetGuid==rakNetGUID) + { + fcm2ParticipantList[idx]=fcm2ParticipantList[fcm2ParticipantList.Size()-1]; +#ifdef DEBUG_FCM2 + printf("Popping participant %s\n", fcm2ParticipantList[fcm2ParticipantList.Size()-1].rakNetGuid.ToString()); +#endif + + fcm2ParticipantList.Pop(); + if (rakNetGUID==hostRakNetGuid && ourFCMGuid!=0) + { + if (fcm2ParticipantList.Size()==0) + { + hostRakNetGuid=rakPeerInterface->GetMyGUID(); + hostFCM2Guid=ourFCMGuid; + } + else + { + CalculateHost(&hostRakNetGuid, &hostFCM2Guid); + } + PushNewHost(hostRakNetGuid, rakNetGUID); + } + return; + } + } + +} +RakNet::TimeUS FullyConnectedMesh2::GetElapsedRuntime(void) +{ + RakNet::TimeUS curTime=RakNet::GetTimeUS(); + if (curTime>startupTime) + return curTime-startupTime; + else + return 0; +} +void FullyConnectedMesh2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) isIncoming; + (void) rakNetGUID; + (void) systemAddress; + + UpdateVerifiedJoinInProgressMember(rakNetGUID, rakNetGUID, JIPS_CONNECTED); + + if (autoParticipateConnections) + AddParticipant(rakNetGUID); +} +void FullyConnectedMesh2::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) +{ + if (failedConnectionAttemptReason==FCAR_ALREADY_CONNECTED) + { + UpdateVerifiedJoinInProgressMember(packet->guid, packet->guid, JIPS_CONNECTED); + } + else + { + UpdateVerifiedJoinInProgressMember(packet->systemAddress, UNASSIGNED_RAKNET_GUID, JIPS_FAILED); + } +} +void FullyConnectedMesh2::Clear(void) +{ + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + { + delete fcm2ParticipantList[i]; + } + fcm2ParticipantList.Clear(false, _FILE_AND_LINE_); + + for (unsigned int i=0; i < joinsInProgress.Size(); i++) + { + for (unsigned int j=0; j < joinsInProgress[i]->vjipMembers.Size(); j++) + { + if ( joinsInProgress[i]->vjipMembers[j].userData != 0) + { + RakNet::OP_DELETE(joinsInProgress[i]->vjipMembers[j].userData, _FILE_AND_LINE_); + } + } + + RakNet::OP_DELETE(joinsInProgress[i], _FILE_AND_LINE_); + } + joinsInProgress.Clear(true, _FILE_AND_LINE_); + + totalConnectionCount=0; + ourFCMGuid=0; + lastPushedHost=UNASSIGNED_RAKNET_GUID; +} +void FullyConnectedMesh2::PushNewHost(const RakNetGUID &guid, RakNetGUID oldHost) +{ + Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(oldHost)); + RakNet::BitStream bs(p->data,p->length,false); + bs.SetWriteOffset(0); + bs.Write((MessageID)ID_FCM2_NEW_HOST); + bs.Write(oldHost); + p->systemAddress=rakPeerInterface->GetSystemAddressFromGuid(guid); + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=guid; + p->wasGeneratedLocally=true; + rakPeerInterface->PushBackPacket(p, true); + + lastPushedHost=guid; +} +void FullyConnectedMesh2::SendFCMGuidRequest(RakNetGUID rakNetGuid) +{ + if (rakNetGuid==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) + return; + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_FCM2_REQUEST_FCMGUID); + if (ourFCMGuid==0) + { + bsOut.Write(false); + bsOut.Write(GetElapsedRuntime()); + } + else + { + bsOut.Write(true); + bsOut.Write(totalConnectionCount); + bsOut.Write(ourFCMGuid); + } + bsOut.Write(myContext); + myContext.ResetReadPointer(); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,rakNetGuid,false); +} +void FullyConnectedMesh2::SendOurFCMGuid(SystemAddress addr) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_FCM2_INFORM_FCMGUID); + RakAssert(ourFCMGuid!=0); // Can't inform others of our FCM2Guid if it's unset! + bsOut.Write(ourFCMGuid); + bsOut.Write(totalConnectionCount); + bsOut.Write(myContext); + myContext.ResetReadPointer(); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,addr,false); +} +void FullyConnectedMesh2::SendConnectionCountResponse(SystemAddress addr, unsigned int responseTotalConnectionCount) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_FCM2_RESPOND_CONNECTION_COUNT); + bsOut.Write(responseTotalConnectionCount); + //bsOut.Write(myContext); + //myContext.ResetReadPointer(); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,addr,false); +} +void FullyConnectedMesh2::AssignOurFCMGuid(void) +{ + // Only assigned once ever + RakAssert(ourFCMGuid==0); + unsigned int randomNumber = randomMT(); + randomNumber ^= (unsigned int) (RakNet::GetTimeUS() & 0xFFFFFFFF); + randomNumber ^= (unsigned int) (rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS).g & 0xFFFFFFFF); + ourFCMGuid |= randomNumber; + uint64_t reponse64 = totalConnectionCount; + ourFCMGuid |= reponse64<<32; +} +void FullyConnectedMesh2::CalculateHost(RakNetGUID *rakNetGuid, FCM2Guid *fcm2Guid) +{ + // Can't calculate host without knowing our own + RakAssert(ourFCMGuid!=0); + + // Can't calculate host without being connected to anyone else + RakAssert(fcm2ParticipantList.Size()>0); + + // Return the lowest value of all FCM2Guid + FCM2Guid lowestFCMGuid=ourFCMGuid; + // SystemAddress associatedSystemAddress=UNASSIGNED_SYSTEM_ADDRESS; + RakNetGUID associatedRakNetGuid=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); + + unsigned int idx; + for (idx=0; idx < fcm2ParticipantList.Size(); idx++) + { + if (fcm2ParticipantList[idx]->fcm2Guid!=0 && fcm2ParticipantList[idx]->fcm2Guidfcm2Guid; + associatedRakNetGuid=fcm2ParticipantList[idx]->rakNetGuid; + } + } + + *rakNetGuid=associatedRakNetGuid; + *fcm2Guid=lowestFCMGuid; +} +void FullyConnectedMesh2::OnRequestFCMGuid(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + bool hasRemoteFCMGuid=false; + bsIn.Read(hasRemoteFCMGuid); + RakNet::TimeUS senderElapsedRuntime=0; + unsigned int remoteTotalConnectionCount=0; + FCM2Guid theirFCMGuid=0; + if (hasRemoteFCMGuid) + { + bsIn.Read(remoteTotalConnectionCount); + bsIn.Read(theirFCMGuid); + } + else + { + bsIn.Read(senderElapsedRuntime); + } + /* + BitStream remoteContext; + bsIn.Read(remoteContext); + AddParticipantInternal(packet->guid,theirFCMGuid, &remoteContext); + */ + AddParticipantInternal(packet->guid,theirFCMGuid); + if (ourFCMGuid==0) + { + if (hasRemoteFCMGuid==false) + { + // Nobody has a fcmGuid + + RakNet::TimeUS ourElapsedRuntime = GetElapsedRuntime(); + if (ourElapsedRuntime>senderElapsedRuntime) + { + // We are probably host + SendConnectionCountResponse(packet->systemAddress, 2); + } + else + { + // They are probably host + SendConnectionCountResponse(packet->systemAddress, 1); + } + } + else + { + // They have a fcmGuid, we do not + IncrementTotalConnectionCount(remoteTotalConnectionCount+1); + + AssignOurFCMGuid(); + unsigned int idx; + for (idx=0; idx < fcm2ParticipantList.Size(); idx++) + SendOurFCMGuid(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[idx]->rakNetGuid)); + } + } + else + { + if (hasRemoteFCMGuid==false) + { + // We have a fcmGuid they do not + SendConnectionCountResponse(packet->systemAddress, totalConnectionCount+1); + } + else + { + // We both have fcmGuids + IncrementTotalConnectionCount(remoteTotalConnectionCount); + + SendOurFCMGuid(packet->systemAddress); + } + } + CalculateAndPushHost(); +} +/* +void FullyConnectedMesh2::OnUpdateUserContext(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + BitStream remoteContext; + bsIn.Read(remoteContext); + + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + { + if (fcm2ParticipantList[i]->rakNetGuid==packet->guid) + { + fcm2ParticipantList[i]->userContext.Reset(); + remoteContext.Read(fcm2ParticipantList[i]->userContext); + break; + } + } +} +*/ +void FullyConnectedMesh2::OnRespondConnectionCount(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + unsigned int responseTotalConnectionCount; + bsIn.Read(responseTotalConnectionCount); + /* + BitStream remoteContext; + bsIn.Read(remoteContext); + + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + { + if (fcm2ParticipantList[i]->rakNetGuid==packet->guid) + { + fcm2ParticipantList[i]->userContext.Reset(); + remoteContext.Read(fcm2ParticipantList[i]->userContext); + break; + } + } + */ + + IncrementTotalConnectionCount(responseTotalConnectionCount); + bool wasAssigned; + if (ourFCMGuid==0) + { + wasAssigned=true; + AssignOurFCMGuid(); + } + else + wasAssigned=false; + + // 1 is returned to give us lower priority, but the actual minimum is 2 + IncrementTotalConnectionCount(2); + + if (wasAssigned==true) + { + unsigned int idx; + for (idx=0; idx < fcm2ParticipantList.Size(); idx++) + SendOurFCMGuid(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[idx]->rakNetGuid)); + CalculateAndPushHost(); + } +} +void FullyConnectedMesh2::OnInformFCMGuid(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + + FCM2Guid theirFCMGuid; + unsigned int theirTotalConnectionCount; + bsIn.Read(theirFCMGuid); + bsIn.Read(theirTotalConnectionCount); + + BitStream remoteContext; + bsIn.Read(remoteContext); + + IncrementTotalConnectionCount(theirTotalConnectionCount); + + //if (AddParticipantInternal(packet->guid,theirFCMGuid, &remoteContext)) + if (AddParticipantInternal(packet->guid,theirFCMGuid)) + { + // 1/19/2010 - Relay increased total connection count in case new participant only connects to part of the mesh + unsigned int idx; + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT); + bsOut.Write(totalConnectionCount); + for (idx=0; idx < fcm2ParticipantList.Size(); idx++) + { + if (packet->guid!=fcm2ParticipantList[idx]->rakNetGuid) + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,fcm2ParticipantList[idx]->rakNetGuid,false); + } + } + + if (ourFCMGuid==0) + { + AssignOurFCMGuid(); + unsigned int idx; + for (idx=0; idx < fcm2ParticipantList.Size(); idx++) + SendOurFCMGuid(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[idx]->rakNetGuid)); + } + + CalculateAndPushHost(); +} +void FullyConnectedMesh2::OnUpdateMinTotalConnectionCount(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + unsigned int newMin; + bsIn.Read(newMin); + IncrementTotalConnectionCount(newMin); +} +void FullyConnectedMesh2::GetParticipantCount(unsigned int *participantListSize) const +{ + *participantListSize=fcm2ParticipantList.Size(); +} + +unsigned int FullyConnectedMesh2::GetParticipantCount(void) const +{ + return fcm2ParticipantList.Size(); +} +void FullyConnectedMesh2::CalculateAndPushHost(void) +{ + RakNetGUID newHostGuid; + FCM2Guid newFcmGuid; + if (ParticipantListComplete()) + { + CalculateHost(&newHostGuid, &newFcmGuid); + if (newHostGuid!=lastPushedHost) + { + hostRakNetGuid=newHostGuid; + hostFCM2Guid=newFcmGuid; + PushNewHost(hostRakNetGuid, lastPushedHost); + } + } +} +bool FullyConnectedMesh2::ParticipantListComplete(void) +{ + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + { + if (fcm2ParticipantList[i]->fcm2Guid==0) + return false; + } + return true; +} +void FullyConnectedMesh2::IncrementTotalConnectionCount(unsigned int i) +{ + if (i>totalConnectionCount) + { + totalConnectionCount=i; + // printf("totalConnectionCount=%i\n",i); + } +} +void FullyConnectedMesh2::SetConnectOnNewRemoteConnection(bool attemptConnection, RakNet::RakString pw) +{ + connectOnNewRemoteConnections=attemptConnection; + connectionPassword=pw; +} + +void FullyConnectedMesh2::ConnectToRemoteNewIncomingConnections(Packet *packet) +{ + unsigned int count; + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + bsIn.Read(count); + SystemAddress remoteAddress; + RakNetGUID remoteGuid; + char str[64]; + for (unsigned int i=0; i < count; i++) + { + bsIn.Read(remoteAddress); + bsIn.Read(remoteGuid); + remoteAddress.ToString(false,str); + rakPeerInterface->Connect(str,remoteAddress.GetPort(),connectionPassword.C_String(),(int) connectionPassword.GetLength()); + } +} +unsigned int FullyConnectedMesh2::GetTotalConnectionCount(void) const +{ + return totalConnectionCount; +} +void FullyConnectedMesh2::StartVerifiedJoin(RakNetGUID client) +{ + // Assert is because there is no point calling StartVerifiedJoin() if this client is already a participant + RakAssert(HasParticipant(client)==false); + RakAssert(client!=rakPeerInterface->GetMyGUID()); + + BitStream bsOut; + bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_START); + bsOut.WriteCasted(fcm2ParticipantList.Size()); + unsigned int i; + for (i=0; i < fcm2ParticipantList.Size(); i++) + { + bsOut.Write(fcm2ParticipantList[i]->rakNetGuid); + bsOut.Write(rakPeerInterface->GetSystemAddressFromGuid(fcm2ParticipantList[i]->rakNetGuid)); + + BitStream vjsOut; + //WriteVJSUserData(&vjsOut, fcm2ParticipantList[i]->rakNetGuid, &fcm2ParticipantList[i]->userContext ); + WriteVJSUserData(&vjsOut, fcm2ParticipantList[i]->rakNetGuid ); + bsOut.Write(vjsOut.GetNumberOfBitsUsed()); + bsOut.Write(&vjsOut); + bsOut.AlignWriteToByteBoundary(); + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, client, false); +} +void FullyConnectedMesh2::RespondOnVerifiedJoinCapable(Packet *packet, bool accept, BitStream *additionalData) +{ + VerifiedJoinInProgress vjip; + DecomposeJoinCapable(packet, &vjip); + + DataStructures::List participatingMembersOnClientSucceeded; + DataStructures::List participatingMembersOnClientFailed; + DataStructures::List participatingMembersNotOnClient; + DataStructures::List clientMembersNotParticipatingSucceeded; + DataStructures::List clientMembersNotParticipatingFailed; + CategorizeVJIP(&vjip, + participatingMembersOnClientSucceeded, + participatingMembersOnClientFailed, + participatingMembersNotOnClient, + clientMembersNotParticipatingSucceeded, + clientMembersNotParticipatingFailed); + + if (participatingMembersNotOnClient.Size()>0) + { + BitStream bsOut; + bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_START); + bsOut.WriteCasted(participatingMembersNotOnClient.Size()); + unsigned int i; + for (i=0; i < participatingMembersNotOnClient.Size(); i++) + { + bsOut.Write(participatingMembersNotOnClient[i]); + bsOut.Write(rakPeerInterface->GetSystemAddressFromGuid(participatingMembersNotOnClient[i])); + + bool written=false; + for (unsigned int j=0; j < fcm2ParticipantList.Size(); j++) + { + if (fcm2ParticipantList[j]->rakNetGuid == participatingMembersNotOnClient[i]) + { + written=true; + + BitStream vjsOut; + //WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid, &fcm2ParticipantList[j]->userContext ); + WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid ); + bsOut.Write(vjsOut.GetNumberOfBitsUsed()); + bsOut.Write(&vjsOut); + bsOut.AlignWriteToByteBoundary(); + break; + } + } + RakAssert(written==true); + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + return; + } + + RakAssert(participatingMembersOnClientFailed.Size()==0); + RakAssert(participatingMembersNotOnClient.Size()==0); + + RakNet::BitStream bsOut; + if (accept) + { + bsOut.Write((MessageID)ID_FCM2_VERIFIED_JOIN_ACCEPTED); + bsOut.Write(packet->guid); + + // Tell client to disconnect from clientMembersNotParticipatingSucceeded + bsOut.WriteCasted(clientMembersNotParticipatingSucceeded.Size()); + for (unsigned int i=0; i < clientMembersNotParticipatingSucceeded.Size(); i++) + bsOut.Write(clientMembersNotParticipatingSucceeded[i]); + + // Tell client to call AddParticipant() for participatingMembersOnClientSucceeded + bsOut.WriteCasted(participatingMembersOnClientSucceeded.Size()); + for (unsigned int i=0; i < participatingMembersOnClientSucceeded.Size(); i++) + bsOut.Write(participatingMembersOnClientSucceeded[i]); + + if (additionalData) + bsOut.Write(additionalData); + + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, fcm2ParticipantList[i]->rakNetGuid, false); + + // Process immediately + // This is so if another ID_FCM2_VERIFIED_JOIN_CAPABLE is buffered, it responds with ID_FCM2_VERIFIED_JOIN_START + AddParticipant(packet->guid); + + Packet *p = AllocatePacketUnified(bsOut.GetNumberOfBytesUsed()); + memcpy(p->data, bsOut.GetData(), bsOut.GetNumberOfBytesUsed()); + p->systemAddress=packet->systemAddress; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=packet->guid; + p->wasGeneratedLocally=true; + rakPeerInterface->PushBackPacket(p, true); + } + else + { + // Tell client rejected, otherwise process the same as ID_FCM2_VERIFIED_JOIN_FAILED + bsOut.Write((MessageID)ID_FCM2_VERIFIED_JOIN_REJECTED); + if (additionalData) + bsOut.Write(additionalData); + } + + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); +} +void FullyConnectedMesh2::GetVerifiedJoinRequiredProcessingList(RakNetGUID host, DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &userData) +{ + addresses.Clear(true, _FILE_AND_LINE_); + guids.Clear(true, _FILE_AND_LINE_); + + unsigned int curIndex = GetJoinsInProgressIndex(host); + if (curIndex!=(unsigned int) -1) + { + VerifiedJoinInProgress *vjip = joinsInProgress[curIndex]; + unsigned int j; + for (j=0; j < vjip->vjipMembers.Size(); j++) + { + if (vjip->vjipMembers[j].joinInProgressState==JIPS_PROCESSING) + { + addresses.Push(vjip->vjipMembers[j].systemAddress, _FILE_AND_LINE_); + guids.Push(vjip->vjipMembers[j].guid, _FILE_AND_LINE_); + userData.Push(vjip->vjipMembers[j].userData, _FILE_AND_LINE_); + } + } + } +} +void FullyConnectedMesh2::GetVerifiedJoinAcceptedAdditionalData(Packet *packet, bool *thisSystemAccepted, DataStructures::List &systemsAccepted, BitStream *additionalData) +{ + systemsAccepted.Clear(true, _FILE_AND_LINE_); + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + RakNetGUID systemToAddGuid; + bsIn.Read(systemToAddGuid); + *thisSystemAccepted = systemToAddGuid == rakPeerInterface->GetMyGUID(); + unsigned short listSize; + bsIn.Read(listSize); + bsIn.IgnoreBytes(listSize*RakNetGUID::size()); + bsIn.Read(listSize); + if (systemToAddGuid==rakPeerInterface->GetMyGUID()) + { + for (unsigned short i=0; i < listSize; i++) + { + bsIn.Read(systemToAddGuid); + systemsAccepted.Push(systemToAddGuid, _FILE_AND_LINE_); + } + systemsAccepted.Push(packet->guid, _FILE_AND_LINE_); + } + else + { + systemsAccepted.Push(systemToAddGuid, _FILE_AND_LINE_); + bsIn.IgnoreBytes(listSize*RakNetGUID::size()); + } + if (additionalData) + { + additionalData->Reset(); + additionalData->Write(bsIn); + } +} +void FullyConnectedMesh2::GetVerifiedJoinRejectedAdditionalData(Packet *packet, BitStream *additionalData) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + if (additionalData) + { + additionalData->Reset(); + additionalData->Write(bsIn); + } +} +PluginReceiveResult FullyConnectedMesh2::OnVerifiedJoinStart(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + + unsigned short listSize; + bsIn.Read(listSize); + + unsigned int curIndex = GetJoinsInProgressIndex(packet->guid); + if (curIndex!=(unsigned int) -1) + { + // Got update to existing list + + VerifiedJoinInProgress *vjip = joinsInProgress[curIndex]; +// if (vjip->sentResults==false) +// { +// // Got ID_FCM2_VERIFIED_JOIN_START twice before sending ID_FCM2_VERIFIED_JOIN_CAPABLE +// RakAssert(vjip->sentResults!=false); +// return RR_STOP_PROCESSING_AND_DEALLOCATE; +// } + + for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) + { + vjip->vjipMembers[i].workingFlag=false; + } + + // Server has updated list of participants + for (unsigned short i=0; i < listSize; i++) + { + VerifiedJoinInProgressMember vjipm; + ReadVerifiedJoinInProgressMember(&bsIn, &vjipm); + + unsigned int j; + if (vjipm.guid!=UNASSIGNED_RAKNET_GUID) + j = GetVerifiedJoinInProgressMemberIndex(vjipm.guid, vjip); + else + j = GetVerifiedJoinInProgressMemberIndex(vjipm.systemAddress, vjip); + + if (j==(unsigned int)-1) + { + // New + vjipm.workingFlag=true; + + // 11/13/2013 - ReadVerifiedJoinInProgressMember already sets joinInProgressState + // http://www.jenkinssoftware.com/forum/index.php?topic=5211.0 + // vjipm.joinInProgressState=JIPS_PROCESSING; + vjip->vjipMembers.Push(vjipm, _FILE_AND_LINE_); + + // Allow resend of ID_FCM2_VERIFIED_JOIN_CAPABLE + //vjip->sentResults=false; + } + else + { + vjip->vjipMembers[j].workingFlag=true; + } + } + + for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) + { + if (vjip->vjipMembers[i].workingFlag==false) + vjip->vjipMembers[i].joinInProgressState=JIPS_UNNECESSARY; + } + + if (ProcessVerifiedJoinInProgressIfCompleted(vjip)) + { + // Completed + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + // Else tell user about new list + return RR_CONTINUE_PROCESSING; + } + + VerifiedJoinInProgress *vjip = RakNet::OP_NEW(_FILE_AND_LINE_); + vjip->requester=packet->guid; + if (listSize==0) + { + //vjip->sentResults=true; + + // Send back result + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_FCM2_VERIFIED_JOIN_CAPABLE); + bsOut.WriteCasted(0); + WriteVJCUserData(&bsOut); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + //vjip->sentResults=true; + joinsInProgress.Push(vjip, _FILE_AND_LINE_); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + //vjip->sentResults=false; + + for (unsigned short i=0; i < listSize; i++) + { + VerifiedJoinInProgressMember vjipm; + ReadVerifiedJoinInProgressMember(&bsIn, &vjipm); + vjip->vjipMembers.Push(vjipm, _FILE_AND_LINE_); + } + + joinsInProgress.Push(vjip, _FILE_AND_LINE_); + + // 11/13/2013 - ReadVerifiedJoinInProgressMember may set JIPS_CONNECTED, so this may already be done + // http://www.jenkinssoftware.com/forum/index.php?topic=5211.0 + if (ProcessVerifiedJoinInProgressIfCompleted(vjip)) + { + // Completed + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + return RR_CONTINUE_PROCESSING; +} +void FullyConnectedMesh2::SkipToVJCUserData(RakNet::BitStream *bsIn) +{ + bsIn->IgnoreBytes(sizeof(MessageID)); + unsigned short listSize; + bsIn->Read(listSize); + for (unsigned short i=0; i < listSize; i++) + { + bsIn->IgnoreBytes(RakNetGUID::size()); + bsIn->IgnoreBytes(SystemAddress::size()); + bsIn->IgnoreBytes(sizeof(unsigned char)); + } +} +void FullyConnectedMesh2::DecomposeJoinCapable(Packet *packet, VerifiedJoinInProgress *vjip) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + + unsigned short listSize; + bsIn.Read(listSize); + + for (unsigned short i=0; i < listSize; i++) + { + VerifiedJoinInProgressMember member; + bsIn.Read(member.guid); + bsIn.Read(member.systemAddress); + bsIn.ReadCasted(member.joinInProgressState); + member.userData = 0; + member.workingFlag=false; + vjip->vjipMembers.Push(member, _FILE_AND_LINE_); + } +} +PluginReceiveResult FullyConnectedMesh2::OnVerifiedJoinCapable(Packet *packet) +{ + VerifiedJoinInProgress vjip; + DecomposeJoinCapable(packet, &vjip); + + // If this assert hits, AddParticipant() was called on this system, or another system, which it should not have been. + RakAssert(HasParticipant(packet->guid)==false); + + DataStructures::List participatingMembersOnClientSucceeded; + DataStructures::List participatingMembersOnClientFailed; + DataStructures::List participatingMembersNotOnClient; + DataStructures::List clientMembersNotParticipatingSucceeded; + DataStructures::List clientMembersNotParticipatingFailed; + CategorizeVJIP(&vjip, + participatingMembersOnClientSucceeded, + participatingMembersOnClientFailed, + participatingMembersNotOnClient, + clientMembersNotParticipatingSucceeded, + clientMembersNotParticipatingFailed); + + if (participatingMembersOnClientFailed.Size()>0) + { + // Send ID_FCM2_VERIFIED_JOIN_FAILED with GUIDs to disconnect + BitStream bsOut; + bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_FAILED); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + if (participatingMembersNotOnClient.Size()>0) + { + BitStream bsOut; + bsOut.Write((MessageID) ID_FCM2_VERIFIED_JOIN_START); + bsOut.WriteCasted(participatingMembersNotOnClient.Size()); + unsigned int i; + for (i=0; i < participatingMembersNotOnClient.Size(); i++) + { + bsOut.Write(participatingMembersNotOnClient[i]); + bsOut.Write(rakPeerInterface->GetSystemAddressFromGuid(participatingMembersNotOnClient[i])); + + bool written=false; + for (unsigned int j=0; j < fcm2ParticipantList.Size(); j++) + { + if (fcm2ParticipantList[j]->rakNetGuid == participatingMembersNotOnClient[i]) + { + written=true; + + BitStream vjsOut; + //WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid, &fcm2ParticipantList[j]->userContext ); + WriteVJSUserData(&vjsOut, fcm2ParticipantList[j]->rakNetGuid ); + bsOut.Write(vjsOut.GetNumberOfBitsUsed()); + bsOut.Write(&vjsOut); + bsOut.AlignWriteToByteBoundary(); + break; + } + } + RakAssert(written); + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + // Let server decide if to accept or reject via RespondOnVerifiedJoinCapable + return RR_CONTINUE_PROCESSING; +} +void FullyConnectedMesh2::OnVerifiedJoinFailed(RakNetGUID hostGuid, bool callCloseConnection) +{ + unsigned int curIndex = GetJoinsInProgressIndex(hostGuid); + if (curIndex==(unsigned int) -1) + return; + + if (callCloseConnection) + { + VerifiedJoinInProgress *vjip = joinsInProgress[curIndex]; + for (unsigned int j=0; j < vjip->vjipMembers.Size(); j++) + { + if (vjip->vjipMembers[j].joinInProgressState!=JIPS_FAILED) + { + rakPeerInterface->CloseConnection(vjip->vjipMembers[j].guid, true); + } + + if (vjip->vjipMembers[j].userData != 0) + RakNet::OP_DELETE(vjip->vjipMembers[j].userData, _FILE_AND_LINE_); + } + } + + for (unsigned int j=0; j < joinsInProgress[curIndex]->vjipMembers.Size(); j++) + { + if ( joinsInProgress[curIndex]->vjipMembers[j].userData != 0) + { + RakNet::OP_DELETE(joinsInProgress[curIndex]->vjipMembers[j].userData, _FILE_AND_LINE_); + } + } + + + // Clear joinsInProgress for packet->guid + RakNet::OP_DELETE(joinsInProgress[curIndex], _FILE_AND_LINE_); + joinsInProgress.RemoveAtIndex(curIndex); +} +void FullyConnectedMesh2::OnVerifiedJoinAccepted(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + + RakNetGUID systemToAddGuid; + bsIn.Read(systemToAddGuid); + + if (systemToAddGuid==rakPeerInterface->GetMyGUID()) + { + // My own system + unsigned int curIndex = GetJoinsInProgressIndex(packet->guid); + if (curIndex==(unsigned int)-1) + return; + + unsigned short listSize; + bsIn.Read(listSize); + for (unsigned short i=0; i < listSize; i++) + { + // List of clientMembersNotParticipatingSucceeded + RakNetGUID guid; + bsIn.Read(guid); + rakPeerInterface->CloseConnection(guid, true); + } + + bsIn.Read(listSize); + for (unsigned short i=0; i < listSize; i++) + { + // List of participatingMembersOnClientSucceeded + RakNetGUID guid; + bsIn.Read(guid); + AddParticipant(guid); + } + AddParticipant(packet->guid); + + for (unsigned int j=0; j < joinsInProgress[curIndex]->vjipMembers.Size(); j++) + { + if ( joinsInProgress[curIndex]->vjipMembers[j].userData != 0) + { + RakNet::OP_DELETE(joinsInProgress[curIndex]->vjipMembers[j].userData, _FILE_AND_LINE_); + } + } + + // Clear joinsInProgress for packet->guid + RakNet::OP_DELETE(joinsInProgress[curIndex], _FILE_AND_LINE_); + joinsInProgress.RemoveAtIndex(curIndex); + } + else + { + // Another system + ConnectionState cs = rakPeerInterface->GetConnectionState(systemToAddGuid); + RakAssert(cs==IS_CONNECTED); + if (cs==IS_CONNECTED) + AddParticipant(systemToAddGuid); + } +} +void FullyConnectedMesh2::OnVerifiedJoinRejected(Packet *packet) +{ + OnVerifiedJoinFailed(packet->guid, true); +} +unsigned int FullyConnectedMesh2::GetJoinsInProgressIndex(RakNetGUID requester) const +{ + for (unsigned int i=0; i < joinsInProgress.Size(); i++) + { + if (joinsInProgress[i]->requester==requester) + return i; + } + return (unsigned int) -1; +} +void FullyConnectedMesh2::UpdateVerifiedJoinInProgressMember(const AddressOrGUID systemIdentifier, RakNetGUID guidToAssign, FullyConnectedMesh2::JoinInProgressState newState) +{ + bool anythingChanged; + + for (unsigned int i=0; i < joinsInProgress.Size(); i++) + { + VerifiedJoinInProgress *vjip = joinsInProgress[i]; + //if (vjip->sentResults==true) + // continue; + anythingChanged=false; + + unsigned int j; + j = GetVerifiedJoinInProgressMemberIndex(systemIdentifier, vjip); + if (j!=(unsigned int)-1) + { + if (vjip->vjipMembers[j].guid==UNASSIGNED_RAKNET_GUID && guidToAssign!=UNASSIGNED_RAKNET_GUID) + vjip->vjipMembers[j].guid = guidToAssign; + + if (vjip->vjipMembers[j].joinInProgressState==JIPS_PROCESSING) + { + anythingChanged=true; + vjip->vjipMembers[j].joinInProgressState=newState; + } + } + + if (anythingChanged) + { + ProcessVerifiedJoinInProgressIfCompleted(vjip); + } + } +} +bool FullyConnectedMesh2::ProcessVerifiedJoinInProgressIfCompleted(VerifiedJoinInProgress *vjip) +{ + //if (vjip->sentResults) + // return true; + + // If no systems in processing state, send results to server + // Return true if this was done + bool anyProcessing=false; + for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) + { + if (vjip->vjipMembers[i].joinInProgressState==JIPS_PROCESSING) + { + anyProcessing=true; + break; + } + } + + if (anyProcessing==true) + return false; + + // Send results to server + BitStream bsOut; + WriteVerifiedJoinCapable(&bsOut, vjip); + WriteVJCUserData(&bsOut); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, vjip->requester, false); + + //vjip->sentResults=true; + return true; +} +void FullyConnectedMesh2::WriteVerifiedJoinCapable(RakNet::BitStream *bsOut, VerifiedJoinInProgress *vjip) +{ + bsOut->Write((MessageID) ID_FCM2_VERIFIED_JOIN_CAPABLE); + bsOut->WriteCasted(vjip->vjipMembers.Size()); + unsigned int i; + for (i=0; i < vjip->vjipMembers.Size(); i++) + { + bsOut->Write(vjip->vjipMembers[i].guid); + bsOut->Write(vjip->vjipMembers[i].systemAddress); + bsOut->WriteCasted(vjip->vjipMembers[i].joinInProgressState); + } +} + +void FullyConnectedMesh2::ReadVerifiedJoinInProgressMember(RakNet::BitStream *bsIn, VerifiedJoinInProgressMember *vjipm) +{ + bsIn->Read(vjipm->guid); + bsIn->Read(vjipm->systemAddress); + ConnectionState cs = rakPeerInterface->GetConnectionState(vjipm->guid); + if (cs==IS_CONNECTED) + vjipm->joinInProgressState=JIPS_CONNECTED; + else if (cs==IS_DISCONNECTING || cs==IS_SILENTLY_DISCONNECTING) + vjipm->joinInProgressState=JIPS_FAILED; + else + vjipm->joinInProgressState=JIPS_PROCESSING; + + BitSize_t vjsUserDataSize; + bsIn->Read(vjsUserDataSize); + if (vjsUserDataSize > 0) + { + vjipm->userData = RakNet::OP_NEW(_FILE_AND_LINE_); + bsIn->Read(vjipm->userData, vjsUserDataSize); + } + else + vjipm->userData = 0; + bsIn->AlignReadToByteBoundary(); +} + +unsigned int FullyConnectedMesh2::GetVerifiedJoinInProgressMemberIndex(const AddressOrGUID systemIdentifier, VerifiedJoinInProgress *vjip) +{ + for (unsigned int j=0; j < vjip->vjipMembers.Size(); j++) + { + if ((systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID && vjip->vjipMembers[j].guid==systemIdentifier.rakNetGuid) || + (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && vjip->vjipMembers[j].systemAddress==systemIdentifier.systemAddress)) + { + return j; + } + } + return (unsigned int) -1; +} + +void FullyConnectedMesh2::CategorizeVJIP(VerifiedJoinInProgress *vjip, + DataStructures::List &participatingMembersOnClientSucceeded, + DataStructures::List &participatingMembersOnClientFailed, + DataStructures::List &participatingMembersNotOnClient, + DataStructures::List &clientMembersNotParticipatingSucceeded, + DataStructures::List &clientMembersNotParticipatingFailed) +{ + for (unsigned int i=0; i < vjip->vjipMembers.Size(); i++) + vjip->vjipMembers[i].workingFlag=false; + + for (unsigned int i=0; i < fcm2ParticipantList.Size(); i++) + { + unsigned int j = GetVerifiedJoinInProgressMemberIndex(fcm2ParticipantList[i]->rakNetGuid, vjip); + if (j==(unsigned int)-1) + { + participatingMembersNotOnClient.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); + } + else + { + if (vjip->vjipMembers[j].joinInProgressState==JIPS_FAILED) + participatingMembersOnClientFailed.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); + else + participatingMembersOnClientSucceeded.Push(fcm2ParticipantList[i]->rakNetGuid, _FILE_AND_LINE_); + vjip->vjipMembers[j].workingFlag=true; + } + } + + + for (unsigned int j=0; j < vjip->vjipMembers.Size(); j++) + { + if (vjip->vjipMembers[j].workingFlag==false) + { + if (vjip->vjipMembers[j].joinInProgressState==JIPS_FAILED) + clientMembersNotParticipatingFailed.Push(vjip->vjipMembers[j].guid, _FILE_AND_LINE_); + else + clientMembersNotParticipatingSucceeded.Push(vjip->vjipMembers[j].guid, _FILE_AND_LINE_); + } + } +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/GetTime.cpp b/src/raknet/GetTime.cpp new file mode 100644 index 0000000..7a670c7 --- /dev/null +++ b/src/raknet/GetTime.cpp @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#if defined(_WIN32) +#include "include/raknet/WindowsIncludes.hpp" + + #if !defined(WINDOWS_PHONE_8) + // To call timeGetTime + // on Code::Blocks, this needs to be libwinmm.a instead + #pragma comment(lib, "Winmm.lib") + #endif + +#endif + +#include "include/raknet/GetTime.hpp" + + + + +#if defined(_WIN32) +//DWORD mProcMask; +//DWORD mSysMask; +//HANDLE mThread; + + + + + + + + + +#else +#include +#include +RakNet::TimeUS initialTime; +#endif + +static bool initialized=false; + +#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 +#include "include/raknet/SimpleMutex.hpp" +RakNet::TimeUS lastNormalizedReturnedValue=0; +RakNet::TimeUS lastNormalizedInputValue=0; +/// This constraints timer forward jumps to 1 second, and does not let it jump backwards +/// See http://support.microsoft.com/kb/274323 where the timer can sometimes jump forward by hours or days +/// This also has the effect where debugging a sending system won't treat the time spent halted past 1 second as elapsed network time +RakNet::TimeUS NormalizeTime(RakNet::TimeUS timeIn) +{ + RakNet::TimeUS diff, lastNormalizedReturnedValueCopy; + static RakNet::SimpleMutex mutex; + + mutex.Lock(); + if (timeIn>=lastNormalizedInputValue) + { + diff = timeIn-lastNormalizedInputValue; + if (diff > GET_TIME_SPIKE_LIMIT) + lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; + else + lastNormalizedReturnedValue+=diff; + } + else + lastNormalizedReturnedValue+=GET_TIME_SPIKE_LIMIT; + + lastNormalizedInputValue=timeIn; + lastNormalizedReturnedValueCopy=lastNormalizedReturnedValue; + mutex.Unlock(); + + return lastNormalizedReturnedValueCopy; +} +#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 +RakNet::Time RakNet::GetTime( void ) +{ + return (RakNet::Time)(GetTimeUS()/1000); +} +RakNet::TimeMS RakNet::GetTimeMS( void ) +{ + return (RakNet::TimeMS)(GetTimeUS()/1000); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#if defined(_WIN32) +RakNet::TimeUS GetTimeUS_Windows( void ) +{ + if ( initialized == false) + { + initialized = true; + + // Save the current process +#if !defined(_WIN32_WCE) +// HANDLE mProc = GetCurrentProcess(); + + // Get the current Affinity +#if _MSC_VER >= 1400 && defined (_M_X64) +// GetProcessAffinityMask(mProc, (PDWORD_PTR)&mProcMask, (PDWORD_PTR)&mSysMask); +#else +// GetProcessAffinityMask(mProc, &mProcMask, &mSysMask); +#endif +// mThread = GetCurrentThread(); + +#endif // _WIN32_WCE + } + + // 9/26/2010 In China running LuDaShi, QueryPerformanceFrequency has to be called every time because CPU clock speeds can be different + RakNet::TimeUS curTime; + LARGE_INTEGER PerfVal; + LARGE_INTEGER yo1; + + QueryPerformanceFrequency( &yo1 ); + QueryPerformanceCounter( &PerfVal ); + + __int64 quotient, remainder; + quotient=((PerfVal.QuadPart) / yo1.QuadPart); + remainder=((PerfVal.QuadPart) % yo1.QuadPart); + curTime = (RakNet::TimeUS) quotient*(RakNet::TimeUS)1000000 + (remainder*(RakNet::TimeUS)1000000 / yo1.QuadPart); + +#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 + return NormalizeTime(curTime); +#else + return curTime; +#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 +} +#elif defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) +RakNet::TimeUS GetTimeUS_Linux( void ) +{ + timeval tp; + if ( initialized == false) + { + gettimeofday( &tp, 0 ); + initialized=true; + // I do this because otherwise RakNet::Time in milliseconds won't work as it will underflow when dividing by 1000 to do the conversion + initialTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec ); + } + + // GCC + RakNet::TimeUS curTime; + gettimeofday( &tp, 0 ); + + curTime = ( tp.tv_sec ) * (RakNet::TimeUS) 1000000 + ( tp.tv_usec ); + +#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 + return NormalizeTime(curTime - initialTime); +#else + return curTime - initialTime; +#endif // #if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 +} +#endif + +RakNet::TimeUS RakNet::GetTimeUS( void ) +{ + + + + + + +#if defined(_WIN32) + return GetTimeUS_Windows(); +#else + return GetTimeUS_Linux(); +#endif +} +bool RakNet::GreaterThan(RakNet::Time a, RakNet::Time b) +{ + // a > b? + const RakNet::Time halfSpan =(RakNet::Time) (((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2); + return b!=a && b-a>halfSpan; +} +bool RakNet::LessThan(RakNet::Time a, RakNet::Time b) +{ + // a < b? + const RakNet::Time halfSpan = ((RakNet::Time)(const RakNet::Time)-1)/(RakNet::Time)2; + return b!=a && b-a /* getche() */ +#elif defined(__S3E__) + +#else + +#include "include/raknet/Getche.hpp" + +char getche() +{ + + + struct termios oldt, + newt; + char ch; + tcgetattr( STDIN_FILENO, &oldt ); + newt = oldt; + newt.c_lflag &= ~( ICANON | ECHO ); + tcsetattr( STDIN_FILENO, TCSANOW, &newt ); + ch = getchar(); + tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); + return ch; + +} +#endif diff --git a/src/raknet/Gets.cpp b/src/raknet/Gets.cpp new file mode 100644 index 0000000..494aa51 --- /dev/null +++ b/src/raknet/Gets.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +char * Gets ( char * str, int num ) +{ + fgets(str, num, stdin); + if (str[0]=='\n' || str[0]=='\r') + str[0]=0; + + size_t len=strlen(str); + if (len>0 && (str[len-1]=='\n' || str[len-1]=='\r')) + str[len-1]=0; + if (len>1 && (str[len-2]=='\n' || str[len-2]=='\r')) + str[len-2]=0; + + return str; +} + +#ifdef __cplusplus +} +#endif diff --git a/src/raknet/GridSectorizer.cpp b/src/raknet/GridSectorizer.cpp new file mode 100644 index 0000000..32d94ec --- /dev/null +++ b/src/raknet/GridSectorizer.cpp @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/GridSectorizer.hpp" +//#include +#include + +GridSectorizer::GridSectorizer() +{ + grid=0; +} +GridSectorizer::~GridSectorizer() +{ + if (grid) + RakNet::OP_DELETE_ARRAY(grid, _FILE_AND_LINE_); +} +void GridSectorizer::Init(const float _maxCellWidth, const float _maxCellHeight, const float minX, const float minY, const float maxX, const float maxY) +{ + RakAssert(_maxCellWidth > 0.0f && _maxCellHeight > 0.0f); + if (grid) + RakNet::OP_DELETE_ARRAY(grid, _FILE_AND_LINE_); + + cellOriginX=minX; + cellOriginY=minY; + gridWidth=maxX-minX; + gridHeight=maxY-minY; + gridCellWidthCount=(int) ceil(gridWidth/_maxCellWidth); + gridCellHeightCount=(int) ceil(gridHeight/_maxCellHeight); + // Make the cells slightly smaller, so we allocate an extra unneeded cell if on the edge. This way we don't go outside the array on rounding errors. + cellWidth=gridWidth/gridCellWidthCount; + cellHeight=gridHeight/gridCellHeightCount; + invCellWidth = 1.0f / cellWidth; + invCellHeight = 1.0f / cellHeight; + +#ifdef _USE_ORDERED_LIST + grid = RakNet::OP_NEW>(gridCellWidthCount*gridCellHeightCount, _FILE_AND_LINE_ ); + DataStructures::OrderedList::IMPLEMENT_DEFAULT_COMPARISON(); +#else + grid = RakNet::OP_NEW_ARRAY >(gridCellWidthCount*gridCellHeightCount, _FILE_AND_LINE_ ); +#endif +} +void GridSectorizer::AddEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY) +{ + RakAssert(cellWidth>0.0f); + RakAssert(minX < maxX && minY < maxY); + + int xStart, yStart, xEnd, yEnd, xCur, yCur; + xStart=WorldToCellXOffsetAndClamped(minX); + yStart=WorldToCellYOffsetAndClamped(minY); + xEnd=WorldToCellXOffsetAndClamped(maxX); + yEnd=WorldToCellYOffsetAndClamped(maxY); + + for (xCur=xStart; xCur <= xEnd; ++xCur) + { + for (yCur=yStart; yCur <= yEnd; ++yCur) + { +#ifdef _USE_ORDERED_LIST + grid[yCur*gridCellWidthCount+xCur].Insert(entry,entry, true); +#else + grid[yCur*gridCellWidthCount+xCur].Insert(entry, _FILE_AND_LINE_); +#endif + } + } +} +#ifdef _USE_ORDERED_LIST +void GridSectorizer::RemoveEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY) +{ + RakAssert(cellWidth>0.0f); + RakAssert(minX <= maxX && minY <= maxY); + + int xStart, yStart, xEnd, yEnd, xCur, yCur; + xStart=WorldToCellXOffsetAndClamped(minX); + yStart=WorldToCellYOffsetAndClamped(minY); + xEnd=WorldToCellXOffsetAndClamped(maxX); + yEnd=WorldToCellYOffsetAndClamped(maxY); + + for (xCur=xStart; xCur <= xEnd; ++xCur) + { + for (yCur=yStart; yCur <= yEnd; ++yCur) + { + grid[yCur*gridCellWidthCount+xCur].RemoveIfExists(entry); + } + } +} +void GridSectorizer::MoveEntry(void *entry, const float sourceMinX, const float sourceMinY, const float sourceMaxX, const float sourceMaxY, + const float destMinX, const float destMinY, const float destMaxX, const float destMaxY) +{ + RakAssert(cellWidth>0.0f); + RakAssert(sourceMinX < sourceMaxX && sourceMinY < sourceMaxY); + RakAssert(destMinX < destMaxX && destMinY < destMaxY); + + if (PositionCrossesCells(sourceMinX, sourceMinY, destMinX, destMinY)==false && + PositionCrossesCells(destMinX, destMinY, destMinX, destMinY)==false) + return; + + int xStartSource, yStartSource, xEndSource, yEndSource; + int xStartDest, yStartDest, xEndDest, yEndDest; + int xCur, yCur; + xStartSource=WorldToCellXOffsetAndClamped(sourceMinX); + yStartSource=WorldToCellYOffsetAndClamped(sourceMinY); + xEndSource=WorldToCellXOffsetAndClamped(sourceMaxX); + yEndSource=WorldToCellYOffsetAndClamped(sourceMaxY); + + xStartDest=WorldToCellXOffsetAndClamped(destMinX); + yStartDest=WorldToCellYOffsetAndClamped(destMinY); + xEndDest=WorldToCellXOffsetAndClamped(destMaxX); + yEndDest=WorldToCellYOffsetAndClamped(destMaxY); + + // Remove source that is not in dest + for (xCur=xStartSource; xCur <= xEndSource; ++xCur) + { + for (yCur=yStartSource; yCur <= yEndSource; ++yCur) + { + if (xCur < xStartDest || xCur > xEndDest || + yCur < yStartDest || yCur > yEndDest) + { + grid[yCur*gridCellWidthCount+xCur].RemoveIfExists(entry); + } + } + } + + // Add dest that is not in source + for (xCur=xStartDest; xCur <= xEndDest; ++xCur) + { + for (yCur=yStartDest; yCur <= yEndDest; ++yCur) + { + if (xCur < xStartSource || xCur > xEndSource || + yCur < yStartSource || yCur > yEndSource) + { + grid[yCur*gridCellWidthCount+xCur].Insert(entry,entry, true); + } + } + } +} +#endif +void GridSectorizer::GetEntries(DataStructures::List& intersectionList, const float minX, const float minY, const float maxX, const float maxY) +{ +#ifdef _USE_ORDERED_LIST + DataStructures::OrderedList* cell; +#else + DataStructures::List* cell; +#endif + int xStart, yStart, xEnd, yEnd, xCur, yCur; + unsigned index; + xStart=WorldToCellXOffsetAndClamped(minX); + yStart=WorldToCellYOffsetAndClamped(minY); + xEnd=WorldToCellXOffsetAndClamped(maxX); + yEnd=WorldToCellYOffsetAndClamped(maxY); + + intersectionList.Clear(true, _FILE_AND_LINE_); + for (xCur=xStart; xCur <= xEnd; ++xCur) + { + for (yCur=yStart; yCur <= yEnd; ++yCur) + { + cell = grid+yCur*gridCellWidthCount+xCur; + for (index=0; index < cell->Size(); ++index) + intersectionList.Insert(cell->operator [](index), _FILE_AND_LINE_); + } + } +} +bool GridSectorizer::PositionCrossesCells(const float originX, const float originY, const float destinationX, const float destinationY) const +{ + return originX/cellWidth!=destinationX/cellWidth || originY/cellHeight!=destinationY/cellHeight; +} +int GridSectorizer::WorldToCellX(const float input) const +{ + return (int)((input-cellOriginX)*invCellWidth); +} +int GridSectorizer::WorldToCellY(const float input) const +{ + return (int)((input-cellOriginY)*invCellHeight); +} +int GridSectorizer::WorldToCellXOffsetAndClamped(const float input) const +{ + int cell=WorldToCellX(input); + cell = cell > 0 ? cell : 0; // __max(cell,0); + cell = gridCellWidthCount-1 < cell ? gridCellWidthCount-1 : cell; // __min(gridCellWidthCount-1, cell); + return cell; +} +int GridSectorizer::WorldToCellYOffsetAndClamped(const float input) const +{ + int cell=WorldToCellY(input); + cell = cell > 0 ? cell : 0; // __max(cell,0); + cell = gridCellHeightCount-1 < cell ? gridCellHeightCount-1 : cell; // __min(gridCellHeightCount-1, cell); + return cell; +} +void GridSectorizer::Clear(void) +{ + int cur; + int count = gridCellWidthCount*gridCellHeightCount; + for (cur=0; cur +#include +#include +#include + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(HTTPConnection,HTTPConnection); + +HTTPConnection::HTTPConnection() : connectionState(CS_NONE) +{ + tcp=0; +} + +void HTTPConnection::Init(TCPInterface* _tcp, const char *_host, unsigned short _port) +{ + tcp=_tcp; + host=_host; + port=_port; +} + +void HTTPConnection::Post(const char *remote_path, const char *data, const char *_contentType) +{ + OutgoingCommand op; + op.contentType=_contentType; + op.data=data; + op.remotePath=remote_path; + op.isPost=true; + outgoingCommand.Push(op, _FILE_AND_LINE_ ); + //printf("Adding outgoing post\n"); +} + +void HTTPConnection::Get(const char *path) +{ + OutgoingCommand op; + op.remotePath=path; + op.isPost=false; + outgoingCommand.Push(op, _FILE_AND_LINE_ ); +} + +bool HTTPConnection::HasBadResponse(int *code, RakNet::RakString *data) +{ + if(badResponses.IsEmpty()) + return false; + + if (code) + *code = badResponses.Peek().code; + if (data) + *data = badResponses.Pop().data; + return true; +} +void HTTPConnection::CloseConnection() +{ + connectionState=CS_DISCONNECTING; +} +void HTTPConnection::Update(void) +{ + SystemAddress sa; + sa = tcp->HasCompletedConnectionAttempt(); + while (sa!=UNASSIGNED_SYSTEM_ADDRESS) + { +// printf("Connected\n"); + connectionState=CS_CONNECTED; + server=sa; + sa = tcp->HasCompletedConnectionAttempt(); + } + + sa = tcp->HasFailedConnectionAttempt(); + while (sa!=UNASSIGNED_SYSTEM_ADDRESS) + { + //printf("Failed connected\n"); + CloseConnection(); + sa = tcp->HasFailedConnectionAttempt(); + } + + sa = tcp->HasLostConnection(); + while (sa!=UNASSIGNED_SYSTEM_ADDRESS) + { + //printf("Lost connection\n"); + CloseConnection(); + sa = tcp->HasLostConnection(); + } + + + switch (connectionState) + { + case CS_NONE: + { + if (outgoingCommand.IsEmpty()) + return; + + //printf("Connecting\n"); + server = tcp->Connect(host, port, false); + connectionState = CS_CONNECTING; + } + break; + case CS_DISCONNECTING: + { + if (tcp->ReceiveHasPackets()==false) + { + if (incomingData.IsEmpty()==false) + { + results.Push(incomingData, _FILE_AND_LINE_ ); + } + incomingData.Clear(); + tcp->CloseConnection(server); + connectionState=CS_NONE; + } + } + break; + case CS_CONNECTING: + { + } + break; + case CS_CONNECTED: + { + //printf("Connected\n"); + if (outgoingCommand.IsEmpty()) + { + //printf("Closed connection (nothing to do)\n"); + CloseConnection(); + return; + } + +#if OPEN_SSL_CLIENT_SUPPORT==1 + tcp->StartSSLClient(server); +#endif + + //printf("Sending request\n"); + currentProcessingCommand = outgoingCommand.Pop(); + RakString request; + if (currentProcessingCommand.isPost) + { + request.Set("POST %s HTTP/1.0\r\n" + "Host: %s:%i\r\n" + "Content-Type: %s\r\n" + "Content-Length: %u\r\n" + "\r\n" + "%s", + currentProcessingCommand.remotePath.C_String(), + host.C_String(), + port, + currentProcessingCommand.contentType.C_String(), + (unsigned) currentProcessingCommand.data.GetLength(), + currentProcessingCommand.data.C_String()); + } + else + { + // request.Set("GET %s\r\n", host.C_String()); + // http://www.jenkinssoftware.com/forum/index.php?topic=4601.0;topicseen + request.Set("GET %s HTTP/1.0\r\n" + "Host: %s:%i\r\n" + "\r\n", + currentProcessingCommand.remotePath.C_String(), + host.C_String(), + port); + } + + // printf(request.C_String()); + // request.URLEncode(); + tcp->Send(request.C_String(), (unsigned int) request.GetLength(), server,false); + connectionState=CS_PROCESSING; + } + break; + case CS_PROCESSING: + { + } + } + +// if (connectionState==CS_PROCESSING && currentProcessingCommand.data.IsEmpty()==false) +// outgoingCommand.PushAtHead(currentProcessingCommand); +} +bool HTTPConnection::HasRead(void) const +{ + return results.IsEmpty()==false; +} +RakString HTTPConnection::Read(void) +{ + if (results.IsEmpty()) + return RakString(); + + RakNet::RakString resultStr = results.Pop(); + // const char *start_of_body = strstr(resultStr.C_String(), "\r\n\r\n"); + const char *start_of_body = strpbrk(resultStr.C_String(), "\001\002\003%"); + + if(start_of_body) + return RakNet::RakString::NonVariadic(start_of_body); + else + return resultStr; +} +SystemAddress HTTPConnection::GetServerAddress(void) const +{ + return server; +} +void HTTPConnection::ProcessTCPPacket(Packet *packet) +{ + RakAssert(packet); + + // read all the packets possible + if(packet->systemAddress == server) + { + if(incomingData.GetLength() == 0) + { + int response_code = atoi((char *)packet->data + strlen("HTTP/1.0 ")); + + if(response_code > 299) + { + badResponses.Push(BadResponse(packet->data, response_code), _FILE_AND_LINE_ ); + //printf("Closed connection (Bad response 2)\n"); + CloseConnection(); + return; + } + } + + RakNet::RakString incomingTemp = RakNet::RakString::NonVariadic((const char*) packet->data); + incomingTemp.URLDecode(); + incomingData += incomingTemp; + + // printf((const char*) packet->data); + // printf("\n"); + + RakAssert(strlen((char *)packet->data) == packet->length); // otherwise it contains Null bytes + + const char *start_of_body = strstr(incomingData, "\r\n\r\n"); + + // besides having the server close the connection, they may + // provide a length header and supply that many bytes + if( + // Why was start_of_body here? Makes the GET command fail + // start_of_body && + connectionState == CS_PROCESSING) + { + /* + // The stupid programmer that wrote this originally didn't think that just because the header contains this value doesn't mean you got the whole message + if (strstr((const char*) packet->data, "\r\nConnection: close\r\n")) + { + CloseConnection(); + } + else + { + */ + long length_of_headers; + if (start_of_body) + { + length_of_headers = (long)(start_of_body + 4 - incomingData.C_String()); + const char *length_header = strstr(incomingData, "\r\nLength: "); + + if(length_header) + { + long length = atol(length_header + 10) + length_of_headers; + + if((long) incomingData.GetLength() >= length) + { + //printf("Closed connection (Got all data due to length header)\n"); + CloseConnection(); + } + } + } + else + { + // No processing needed + } + + + //} + } + } +} + +bool HTTPConnection::IsBusy(void) const +{ + return connectionState != CS_NONE; +} + +int HTTPConnection::GetState(void) const +{ + return connectionState; +} + + +HTTPConnection::~HTTPConnection(void) +{ + if (tcp) + tcp->CloseConnection(server); +} + + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/HTTPConnection2.cpp b/src/raknet/HTTPConnection2.cpp new file mode 100644 index 0000000..2d3a7a9 --- /dev/null +++ b/src/raknet/HTTPConnection2.cpp @@ -0,0 +1,621 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#include "include/raknet/HTTPConnection2.hpp" +#include "include/raknet/TCPInterface.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(HTTPConnection2,HTTPConnection2); + +HTTPConnection2::HTTPConnection2() +{ +} +HTTPConnection2::~HTTPConnection2() +{ + +} +bool HTTPConnection2::TransmitRequest(const char* stringToTransmit, const char* host, unsigned short port, bool useSSL, int ipVersion, SystemAddress useAddress, void *userData) +{ + Request *request = RakNet::OP_NEW(_FILE_AND_LINE_); + request->host=host; + request->chunked = false; + if (useAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + request->hostEstimatedAddress=useAddress; + if (IsConnected(useAddress)==false) + { + RakNet::OP_DELETE(request, _FILE_AND_LINE_); + return false; + } + } + else + { + if (request->hostEstimatedAddress.FromString(host, '|', ipVersion)==false) + { + RakNet::OP_DELETE(request, _FILE_AND_LINE_); + return false; + } + } + request->hostEstimatedAddress.SetPortHostOrder(port); + request->port=port; + request->stringToTransmit=stringToTransmit; + request->contentLength=-1; + request->contentOffset=0; + request->useSSL=useSSL; + request->ipVersion=ipVersion; + request->userData=userData; + + if (IsConnected(request->hostEstimatedAddress)) + { + sentRequestsMutex.Lock(); + if (sentRequests.Size()==0) + { + request->hostCompletedAddress=request->hostEstimatedAddress; + sentRequests.Push(request, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + + SendRequest(request); + } + else + { + // Request pending, push it + pendingRequestsMutex.Lock(); + pendingRequests.Push(request, _FILE_AND_LINE_); + pendingRequestsMutex.Unlock(); + + sentRequestsMutex.Unlock(); + } + } + else + { + pendingRequestsMutex.Lock(); + pendingRequests.Push(request, _FILE_AND_LINE_); + pendingRequestsMutex.Unlock(); + + if (ipVersion!=6) + { + tcpInterface->Connect(host, port, false, AF_INET); + } + else + { + #if RAKNET_SUPPORT_IPV6 + tcpInterface->Connect(host, port, false, AF_INET6); + #else + RakAssert("HTTPConnection2::TransmitRequest needs define RAKNET_SUPPORT_IPV6" && 0); + #endif + } + } + return true; +} +bool HTTPConnection2::GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, int &contentOffset ) +{ + void *userData; + return GetResponse(stringTransmitted, hostTransmitted, responseReceived, hostReceived, contentOffset, &userData); + +} +bool HTTPConnection2::GetResponse( RakString &stringTransmitted, RakString &hostTransmitted, RakString &responseReceived, SystemAddress &hostReceived, int &contentOffset, void **userData ) +{ + completedRequestsMutex.Lock(); + if (completedRequests.Size()>0) + { + Request *completedRequest = completedRequests[0]; + completedRequests.RemoveAtIndexFast(0); + completedRequestsMutex.Unlock(); + + responseReceived = completedRequest->stringReceived; + hostReceived = completedRequest->hostCompletedAddress; + stringTransmitted = completedRequest->stringToTransmit; + hostTransmitted = completedRequest->host; + contentOffset = completedRequest->contentOffset; + *userData = completedRequest->userData; + + RakNet::OP_DELETE(completedRequest, _FILE_AND_LINE_); + return true; + } + else + { + completedRequestsMutex.Unlock(); + } + return false; +} +bool HTTPConnection2::IsBusy(void) const +{ + return pendingRequests.Size()>0 || sentRequests.Size()>0; +} +bool HTTPConnection2::HasResponse(void) const +{ + return completedRequests.Size()>0; +} +int ReadChunkSize( char *txtStart, char **txtEnd ) +{ +// char lengthStr[32]; +// memset(lengthStr, 0, 32); +// memcpy(lengthStr, txtStart, txtEnd - txtStart); + return strtoul(txtStart, txtEnd,16); + // return atoi(lengthStr); +} +void ReadChunkBlock( size_t ¤tChunkSize, size_t &bytesReadSoFar, char *txtIn, RakString &txtOut) +{ + size_t bytesToRead; + size_t sLen; + + do + { + bytesToRead = currentChunkSize - bytesReadSoFar; + sLen = strlen(txtIn); + if (sLen < bytesToRead) + bytesToRead = sLen; + txtOut.AppendBytes(txtIn, bytesToRead); + txtIn += bytesToRead; + bytesReadSoFar += bytesToRead; + if (*txtIn == 0) + { + // currentChunkSize=0; + return; + } + // char *newLine = strstr(txtIn, "\r\n"); + if (txtIn[0] && txtIn[0]=='\r' && txtIn[1] && txtIn[1]=='\n' ) + txtIn += 2; // Newline + char *newLine; + currentChunkSize = ReadChunkSize(txtIn, &newLine); + RakAssert(currentChunkSize < 50000); // Sanity check + if (currentChunkSize == 0) + return; + if (newLine == 0) + return; + bytesReadSoFar=0; + txtIn = newLine + 2; + } while (txtIn); +} +PluginReceiveResult HTTPConnection2::OnReceive(Packet *packet) +{ + unsigned int i; + + bool locked=true; + sentRequestsMutex.Lock(); + for (i=0; i < sentRequests.Size(); i++) + { + Request *sentRequest = sentRequests[i]; + if (sentRequest->hostCompletedAddress==packet->systemAddress) + { + sentRequests.RemoveAtIndexFast(i); + locked=false; + sentRequestsMutex.Unlock(); + + /* + static FILE * pFile = 0; + if (pFile==0) + { + long lSize; + char * buffer; + size_t result; + + pFile = fopen ( "string_received.txt" , "rb" ); + if (pFile==NULL) {fputs ("File error",stderr); exit (1);} + + // obtain file size: + fseek (pFile , 0 , SEEK_END); + lSize = ftell (pFile); + rewind (pFile); + + // allocate memory to contain the whole file: + buffer = (char*) malloc (sizeof(char)*lSize); + if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);} + + // copy the file into the buffer: + result = fread (buffer,1,lSize,pFile); + if (result != lSize) {fputs ("Reading error",stderr); exit (3);} + + packet->data=(unsigned char*) buffer; + packet->length=lSize; + } + */ + + + const char *isFirstChunk = strstr((char*) packet->data, "Transfer-Encoding: chunked"); + if (isFirstChunk) + { + //printf((char*) packet->data); + + locked=false; + sentRequestsMutex.Unlock(); + + sentRequest->chunked = true; + char *chunkStrStart = strstr((char*) packet->data, "\r\n\r\n"); + RakAssert(chunkStrStart); + + chunkStrStart += 4; // strlen("\r\n\r\n"); + char *body_header; // = strstr(chunkStrStart, "\r\n"); + sentRequest->thisChunkSize = ReadChunkSize(chunkStrStart, &body_header); + sentRequest->bytesReadForThisChunk = 0; + sentRequest->contentOffset = 0; + + if (sentRequest->thisChunkSize == 0) + { + // Done + completedRequestsMutex.Lock(); + completedRequests.Push(sentRequest, _FILE_AND_LINE_); + completedRequestsMutex.Unlock(); + + // If there is another command waiting for this server, send it + SendPendingRequestToConnectedSystem(packet->systemAddress); + } + else + { + + // char *offset = strstr((char*) packet->data+1, "2000"); + + body_header+=2; + ReadChunkBlock(sentRequest->thisChunkSize, sentRequest->bytesReadForThisChunk, body_header, sentRequest->stringReceived); + + if (sentRequest->thisChunkSize==0) + { + // Done + completedRequestsMutex.Lock(); + completedRequests.Push(sentRequest, _FILE_AND_LINE_); + completedRequestsMutex.Unlock(); + + // If there is another command waiting for this server, send it + SendPendingRequestToConnectedSystem(packet->systemAddress); + } + else + { + // Not done + sentRequestsMutex.Lock(); + sentRequests.Push(sentRequest, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + } + } + } + else if (sentRequest->chunked) + { + ReadChunkBlock(sentRequest->thisChunkSize, sentRequest->bytesReadForThisChunk, (char*) packet->data, sentRequest->stringReceived); + + if (sentRequest->thisChunkSize==0) + { + // Done + completedRequestsMutex.Lock(); + completedRequests.Push(sentRequest, _FILE_AND_LINE_); + completedRequestsMutex.Unlock(); + + // If there is another command waiting for this server, send it + SendPendingRequestToConnectedSystem(packet->systemAddress); + } + else + { + // Not done + sentRequestsMutex.Lock(); + sentRequests.Push(sentRequest, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + } + + } + else + { + sentRequest->stringReceived+=packet->data; + + if (sentRequest->contentLength==-1) + { + const char *length_header = strstr(sentRequest->stringReceived.C_String(), "Content-Length: "); + if(length_header) + { + length_header += 16; // strlen("Content-Length: "); + + unsigned int clLength; + for (clLength=0; length_header[clLength] && length_header[clLength] >= '0' && length_header[clLength] <= '9'; clLength++) + ; + if (clLength>0 && (length_header[clLength]=='\r' || length_header[clLength]=='\n')) + { + sentRequest->contentLength = RakString::ReadIntFromSubstring(length_header, 0, clLength); + } + } + } + + // If we know the content length, find \r\n\r\n + if (sentRequest->contentLength != -1) + { + if (sentRequest->contentLength > 0) + { + const char *body_header = strstr(sentRequest->stringReceived.C_String(), "\r\n\r\n"); + if (body_header) + { + body_header += 4; // strlen("\r\n\r\n"); + size_t slen = strlen(body_header); + //RakAssert(slen <= (size_t) sentRequest->contentLength); + if (slen >= (size_t) sentRequest->contentLength) + { + sentRequest->contentOffset = body_header - sentRequest->stringReceived.C_String(); + completedRequestsMutex.Lock(); + completedRequests.Push(sentRequest, _FILE_AND_LINE_); + completedRequestsMutex.Unlock(); + + // If there is another command waiting for this server, send it + SendPendingRequestToConnectedSystem(packet->systemAddress); + } + else + { + sentRequestsMutex.Lock(); + sentRequests.Push(sentRequest, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + } + } + + else + { + sentRequestsMutex.Lock(); + sentRequests.Push(sentRequest, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + } + } + else + { + sentRequest->contentOffset=-1; + completedRequestsMutex.Lock(); + completedRequests.Push(sentRequest, _FILE_AND_LINE_); + completedRequestsMutex.Unlock(); + + // If there is another command waiting for this server, send it + SendPendingRequestToConnectedSystem(packet->systemAddress); + } + } + else + { + const char *firstNewlineSet = strstr(sentRequest->stringReceived.C_String(), "\r\n\r\n"); + if (firstNewlineSet!=0) + { + int offset = firstNewlineSet - sentRequest->stringReceived.C_String(); + if (sentRequest->stringReceived.C_String()[offset+4]==0) + sentRequest->contentOffset=-1; + else + sentRequest->contentOffset=offset+4; + completedRequestsMutex.Lock(); + completedRequests.Push(sentRequest, _FILE_AND_LINE_); + completedRequestsMutex.Unlock(); + + // If there is another command waiting for this server, send it + SendPendingRequestToConnectedSystem(packet->systemAddress); + } + else + { + sentRequestsMutex.Lock(); + sentRequests.Push(sentRequest, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + } + } + } + + + break; + } + } + + if (locked==true) + sentRequestsMutex.Unlock(); + + return RR_CONTINUE_PROCESSING; +} + +void HTTPConnection2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) rakNetGUID; + (void) isIncoming; // unknown + + SendPendingRequestToConnectedSystem(systemAddress); +} +void HTTPConnection2::SendPendingRequestToConnectedSystem(SystemAddress sa) +{ + if (sa==UNASSIGNED_SYSTEM_ADDRESS) + return; + + unsigned int requestsSent=0; + + // Search through requests to find a match for this instance of TCPInterface and SystemAddress + unsigned int i; + i=0; + pendingRequestsMutex.Lock(); + while (i < pendingRequests.Size()) + { + Request *request = pendingRequests[i]; + if (request->hostEstimatedAddress==sa) + { + pendingRequests.RemoveAtIndex(i); + // Send this request + request->hostCompletedAddress=sa; + + sentRequestsMutex.Lock(); + sentRequests.Push(request, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + + pendingRequestsMutex.Unlock(); + +#if OPEN_SSL_CLIENT_SUPPORT==1 + if (request->useSSL) + tcpInterface->StartSSLClient(sa); +#endif + + SendRequest(request); + requestsSent++; + pendingRequestsMutex.Lock(); + break; + } + else + { + i++; + } + } + pendingRequestsMutex.Unlock(); + + if (requestsSent==0) + { + pendingRequestsMutex.Lock(); + if (pendingRequests.Size() > 0) + { + // Just assign + Request *request = pendingRequests[0]; + pendingRequests.RemoveAtIndex(0); + + request->hostCompletedAddress=sa; + + sentRequestsMutex.Lock(); + sentRequests.Push(request, _FILE_AND_LINE_); + sentRequestsMutex.Unlock(); + pendingRequestsMutex.Unlock(); + + // Send +#if OPEN_SSL_CLIENT_SUPPORT==1 + if (request->useSSL) + tcpInterface->StartSSLClient(sa); +#endif + + + SendRequest(request); + } + else + { + pendingRequestsMutex.Unlock(); + } + } +} +void HTTPConnection2::RemovePendingRequest(SystemAddress sa) +{ + unsigned int i; + i=0; + pendingRequestsMutex.Lock(); + for (i=0; i < pendingRequests.Size(); i++) + { + Request *request = pendingRequests[i]; + if (request->hostEstimatedAddress==sa) + { + pendingRequests.RemoveAtIndex(i); + RakNet::OP_DELETE(request, _FILE_AND_LINE_); + } + else + i++; + } + + pendingRequestsMutex.Unlock(); +} +void HTTPConnection2::SendNextPendingRequest(void) +{ + // Send a pending request + pendingRequestsMutex.Lock(); + if (pendingRequests.Size()>0) + { + Request *pendingRequest = pendingRequests.Peek(); + pendingRequestsMutex.Unlock(); + + if (pendingRequest->ipVersion!=6) + { + tcpInterface->Connect(pendingRequest->host.C_String(), pendingRequest->port, false, AF_INET); + } + else + { +#if RAKNET_SUPPORT_IPV6 + tcpInterface->Connect(pendingRequest->host.C_String(), pendingRequest->port, false, AF_INET6); +#else + RakAssert("HTTPConnection2::TransmitRequest needs define RAKNET_SUPPORT_IPV6" && 0); +#endif + } + } + else + { + pendingRequestsMutex.Unlock(); + } +} + +void HTTPConnection2::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) +{ + (void) failedConnectionAttemptReason; + if (packet->systemAddress==UNASSIGNED_SYSTEM_ADDRESS) + return; + + RemovePendingRequest(packet->systemAddress); + + SendNextPendingRequest(); +} +void HTTPConnection2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) rakNetGUID; + + if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) + return; + + // Update sent requests to completed requests + unsigned int i; + i=0; + sentRequestsMutex.Lock(); + while (i < sentRequests.Size()) + { + if (sentRequests[i]->hostCompletedAddress==systemAddress) + { + Request *sentRequest = sentRequests[i]; + if (sentRequest->chunked==false && sentRequest->stringReceived.IsEmpty()==false) + { + if (strstr(sentRequest->stringReceived.C_String(), "Content-Length: ")) + { + char *body_header = strstr((char*) sentRequest->stringReceived.C_String(), "\r\n\r\n"); + if (body_header) + { + body_header += 4; // strlen("\r\n\r\n"); + sentRequest->contentOffset = body_header - sentRequest->stringReceived.C_String(); + } + else + { + sentRequest->contentOffset = 0; + } + + } + else + { + sentRequest->contentOffset = 0; + } + } + + + completedRequestsMutex.Lock(); + completedRequests.Push(sentRequests[i], _FILE_AND_LINE_); + completedRequestsMutex.Unlock(); + + sentRequests.RemoveAtIndexFast(i); + } + else + { + i++; + } + } + sentRequestsMutex.Unlock(); + + SendNextPendingRequest(); +} +bool HTTPConnection2::IsConnected(SystemAddress sa) +{ + SystemAddress remoteSystems[64]; + unsigned short numberOfSystems=64; + tcpInterface->GetConnectionList(remoteSystems, &numberOfSystems); + for (unsigned int i=0; i < numberOfSystems; i++) + { + if (remoteSystems[i]==sa) + { + return true; + } + } + return false; +} +void HTTPConnection2::SendRequest(Request *request) +{ + tcpInterface->Send(request->stringToTransmit.C_String(), (unsigned int) request->stringToTransmit.GetLength(), request->hostCompletedAddress, false); +} + +#endif // #if _RAKNET_SUPPORT_HTTPConnection2==1 && _RAKNET_SUPPORT_TCPInterface==1 diff --git a/src/raknet/IncrementalReadInterface.cpp b/src/raknet/IncrementalReadInterface.cpp new file mode 100644 index 0000000..0e36fbc --- /dev/null +++ b/src/raknet/IncrementalReadInterface.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/IncrementalReadInterface.hpp" +#include + +using namespace RakNet; + +unsigned int IncrementalReadInterface::GetFilePart( const char *filename, unsigned int startReadBytes, unsigned int numBytesToRead, void *preallocatedDestination, FileListNodeContext context) +{ + FILE *fp = fopen(filename, "rb"); + if (fp==0) + return 0; + fseek(fp,startReadBytes,SEEK_SET); + unsigned int numRead = (unsigned int) fread(preallocatedDestination,1,numBytesToRead, fp); + fclose(fp); + return numRead; +} diff --git a/src/raknet/Itoa.cpp b/src/raknet/Itoa.cpp new file mode 100644 index 0000000..86f48fb --- /dev/null +++ b/src/raknet/Itoa.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef __cplusplus +extern "C" { +#endif + +// Fast itoa from http://www.jb.man.ac.uk/~slowe/cpp/itoa.html for Linux since it seems like Linux doesn't support this function. +// I modified it to remove the std dependencies. +char* Itoa( int value, char* result, int base ) + { + // check that the base if valid + if (base < 2 || base > 16) { *result = 0; return result; } + char* out = result; + int quotient = value; + + int absQModB; + + do { + // KevinJ - get rid of this dependency + //*out = "0123456789abcdef"[ std::abs( quotient % base ) ]; + absQModB=quotient % base; + if (absQModB < 0) + absQModB=-absQModB; + *out = "0123456789abcdef"[ absQModB ]; + ++out; + quotient /= base; + } while ( quotient ); + + // Only apply negative sign for base 10 + if ( value < 0 && base == 10) *out++ = '-'; + + // KevinJ - get rid of this dependency + // std::reverse( result, out ); + *out = 0; + + // KevinJ - My own reverse code + char *start = result; + char temp; + out--; + while (start < out) + { + temp=*start; + *start=*out; + *out=temp; + start++; + out--; + } + + return result; +} + +#ifdef __cplusplus +} +#endif diff --git a/src/raknet/LinuxStrings.cpp b/src/raknet/LinuxStrings.cpp new file mode 100644 index 0000000..ca9ad53 --- /dev/null +++ b/src/raknet/LinuxStrings.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#if (defined(__GNUC__) || defined(__ARMCC_VERSION) || defined(__GCCXML__) || defined(__S3E__) ) && !defined(_WIN32) +#include +#ifndef _stricmp +int _stricmp(const char* s1, const char* s2) +{ + return strcasecmp(s1,s2); +} +#endif +int _strnicmp(const char* s1, const char* s2, size_t n) +{ + return strncasecmp(s1,s2,n); +} +#ifndef _vsnprintf +#define _vsnprintf vsnprintf +#endif +#ifndef __APPLE__ +char *_strlwr(char * str ) +{ + if (str==0) + return 0; + for (int i=0; str[i]; i++) + { + if (str[i]>='A' && str[i]<='Z') + str[i]+='a'-'A'; + } + return str; +} +#endif +#endif diff --git a/src/raknet/LocklessTypes.cpp b/src/raknet/LocklessTypes.cpp new file mode 100644 index 0000000..71aca57 --- /dev/null +++ b/src/raknet/LocklessTypes.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/LocklessTypes.hpp" + +using namespace RakNet; + +LocklessUint32_t::LocklessUint32_t() +{ + value=0; +} +LocklessUint32_t::LocklessUint32_t(uint32_t initial) +{ + value=initial; +} +uint32_t LocklessUint32_t::Increment(void) +{ +#ifdef _WIN32 + return (uint32_t) InterlockedIncrement(&value); +#elif defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) + uint32_t v; + mutex.Lock(); + ++value; + v=value; + mutex.Unlock(); + return v; +#else + return __sync_fetch_and_add (&value, (uint32_t) 1); +#endif +} +uint32_t LocklessUint32_t::Decrement(void) +{ +#ifdef _WIN32 + return (uint32_t) InterlockedDecrement(&value); +#elif defined(ANDROID) || defined(__S3E__) || defined(__APPLE__) + uint32_t v; + mutex.Lock(); + --value; + v=value; + mutex.Unlock(); + return v; +#else + return __sync_fetch_and_add (&value, (uint32_t) -1); +#endif +} diff --git a/src/raknet/LogCommandParser.cpp b/src/raknet/LogCommandParser.cpp new file mode 100644 index 0000000..c37c510 --- /dev/null +++ b/src/raknet/LogCommandParser.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_LogCommandParser==1 + +#include "include/raknet/LogCommandParser.hpp" +#include "include/raknet/TransportInterface.hpp" + +#include + +#include +#include +#include + +#include "include/raknet/LinuxStrings.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(LogCommandParser,LogCommandParser); + +LogCommandParser::LogCommandParser() +{ + RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Subscribe","[] - Subscribes to a named channel, or all channels"); + RegisterCommand(CommandParserInterface::VARIABLE_NUMBER_OF_PARAMETERS,"Unsubscribe","[] - Unsubscribes from a named channel, or all channels"); + memset(channelNames,0,sizeof(channelNames)); +} +LogCommandParser::~LogCommandParser() +{ +} +bool LogCommandParser::OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString) +{ + (void) originalString; + + if (strcmp(command, "Subscribe")==0) + { + unsigned channelIndex; + if (numParameters==0) + { + Subscribe(systemAddress, 0); + transport->Send(systemAddress, "Subscribed to all channels.\r\n"); + } + else if (numParameters==1) + { + if ((channelIndex=Subscribe(systemAddress, parameterList[0]))!=(unsigned)-1) + { + transport->Send(systemAddress, "You are now subscribed to channel %s.\r\n", channelNames[channelIndex]); + } + else + { + transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); + PrintChannels(systemAddress, transport); + } + } + else + { + transport->Send(systemAddress, "Subscribe takes either 0 or 1 parameters.\r\n"); + } + } + else if (strcmp(command, "Unsubscribe")==0) + { + unsigned channelIndex; + if (numParameters==0) + { + Unsubscribe(systemAddress, 0); + transport->Send(systemAddress, "Unsubscribed from all channels.\r\n"); + } + else if (numParameters==1) + { + if ((channelIndex=Unsubscribe(systemAddress, parameterList[0]))!=(unsigned)-1) + { + transport->Send(systemAddress, "You are now unsubscribed from channel %s.\r\n", channelNames[channelIndex]); + } + else + { + transport->Send(systemAddress, "Cannot find channel %s.\r\n", parameterList[0]); + PrintChannels(systemAddress, transport); + } + } + else + { + transport->Send(systemAddress, "Unsubscribe takes either 0 or 1 parameters.\r\n"); + } + } + + return true; +} +const char *LogCommandParser::GetName(void) const +{ + return "Logger"; +} +void LogCommandParser::SendHelp(TransportInterface *transport, const SystemAddress &systemAddress) +{ + transport->Send(systemAddress, "The logger will accept user log data via the Log(...) function.\r\n"); + transport->Send(systemAddress, "Each log is associated with a named channel.\r\n"); + transport->Send(systemAddress, "You can subscribe to or unsubscribe from named channels.\r\n"); + PrintChannels(systemAddress, transport); +} +void LogCommandParser::AddChannel(const char *channelName) +{ + unsigned channelIndex=0; + channelIndex = GetChannelIndexFromName(channelName); + // Each channel can only be added once. + RakAssert(channelIndex==(unsigned)-1); + + unsigned i; + for (i=0; i < 32; i++) + { + if (channelNames[i]==0) + { + // Assuming a persistent static string. + channelNames[i]=channelName; + return; + } + } + + // No more available channels - max 32 with this implementation where I save subscribed channels with bit operations + RakAssert(0); +} +void LogCommandParser::WriteLog(const char *channelName, const char *format, ...) +{ + if (channelName==0 || format==0) + return; + + unsigned channelIndex; + channelIndex = GetChannelIndexFromName(channelName); + if (channelIndex==(unsigned)-1) + { + AddChannel(channelName); + } + + char text[REMOTE_MAX_TEXT_INPUT]; + va_list ap; + va_start(ap, format); + _vsnprintf(text, REMOTE_MAX_TEXT_INPUT, format, ap); + va_end(ap); + text[REMOTE_MAX_TEXT_INPUT-1]=0; + + // Make sure that text ends in \r\n + int textLen; + textLen=(int)strlen(text); + if (textLen==0) + return; + if (text[textLen-1]=='\n') + { + text[textLen-1]=0; + } + if (textLen < REMOTE_MAX_TEXT_INPUT-4) + strcat(text, "\r\n"); + else + { + text[textLen-3]='\r'; + text[textLen-2]='\n'; + text[textLen-1]=0; + } + + // For each user that subscribes to this channel, send to them. + unsigned i; + for (i=0; i < remoteUsers.Size(); i++) + { + if (remoteUsers[i].channels & (1 << channelIndex)) + { + trans->Send(remoteUsers[i].systemAddress, text); + } + } +} +void LogCommandParser::PrintChannels(const SystemAddress &systemAddress, TransportInterface *transport) const +{ + unsigned i; + bool anyChannels=false; + transport->Send(systemAddress, "CHANNELS:\r\n"); + for (i=0; i < 32; i++) + { + if (channelNames[i]) + { + transport->Send(systemAddress, "%i. %s\r\n", i+1,channelNames[i]); + anyChannels=true; + } + } + if (anyChannels==false) + transport->Send(systemAddress, "None.\r\n"); +} +void LogCommandParser::OnNewIncomingConnection(const SystemAddress &systemAddress, TransportInterface *transport) +{ + (void) systemAddress; + (void) transport; +} +void LogCommandParser::OnConnectionLost(const SystemAddress &systemAddress, TransportInterface *transport) +{ + (void) transport; + Unsubscribe(systemAddress, 0); +} +unsigned LogCommandParser::Unsubscribe(const SystemAddress &systemAddress, const char *channelName) +{ + unsigned i; + for (i=0; i < remoteUsers.Size(); i++) + { + if (remoteUsers[i].systemAddress==systemAddress) + { + if (channelName==0) + { + // Unsubscribe from all and delete this user. + remoteUsers[i]=remoteUsers[remoteUsers.Size()-1]; + remoteUsers.RemoveFromEnd(); + return 0; + } + else + { + unsigned channelIndex; + channelIndex = GetChannelIndexFromName(channelName); + if (channelIndex!=(unsigned)-1) + { + remoteUsers[i].channels&=0xFFFF ^ (1<filterSetID) + return -1; + else if (key==data->filterSetID) + return 0; + else + return 1; +} +STATIC_FACTORY_DEFINITIONS(MessageFilter,MessageFilter); + +MessageFilter::MessageFilter() +{ + whenLastTimeoutCheck=RakNet::GetTime(); +} +MessageFilter::~MessageFilter() +{ + Clear(); +} +void MessageFilter::SetAutoAddNewConnectionsToFilter(int filterSetID) +{ + autoAddNewConnectionsToFilter=filterSetID; +} +void MessageFilter::SetAllowMessageID(bool allow, int messageIDStart, int messageIDEnd,int filterSetID) +{ + RakAssert(messageIDStart <= messageIDEnd); + FilterSet *filterSet = GetFilterSetByID(filterSetID); + int i; + for (i=messageIDStart; i <= messageIDEnd; ++i) + filterSet->allowedIDs[i]=allow; +} +void MessageFilter::SetAllowRPC4(bool allow, const char* uniqueID, int filterSetID) +{ + FilterSet *filterSet = GetFilterSetByID(filterSetID); + bool objectExists; + unsigned int idx = filterSet->allowedRPC4.GetIndexFromKey(uniqueID, &objectExists); + if (allow) + { + if (objectExists==false) + { + filterSet->allowedRPC4.InsertAtIndex(uniqueID, idx, _FILE_AND_LINE_); + filterSet->allowedIDs[ID_RPC_PLUGIN]=true; + } + } + else + { + if (objectExists==true) + { + filterSet->allowedRPC4.RemoveAtIndex(idx); + if (filterSet->allowedRPC4.Size()==0) + { + filterSet->allowedIDs[ID_RPC_PLUGIN]=false; + } + } + } +} +void MessageFilter::SetActionOnDisallowedMessage(bool kickOnDisallowed, bool banOnDisallowed, RakNet::TimeMS banTimeMS, int filterSetID) +{ + FilterSet *filterSet = GetFilterSetByID(filterSetID); + filterSet->kickOnDisallowedMessage=kickOnDisallowed; + filterSet->disallowedMessageBanTimeMS=banTimeMS; + filterSet->banOnDisallowedMessage=banOnDisallowed; +} +void MessageFilter::SetDisallowedMessageCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData, unsigned char messageID)) +{ + FilterSet *filterSet = GetFilterSetByID(filterSetID); + filterSet->invalidMessageCallback=invalidMessageCallback; + filterSet->disallowedCallbackUserData=userData; +} +void MessageFilter::SetTimeoutCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID systemAddress, int filterSetID, void *userData)) +{ + FilterSet *filterSet = GetFilterSetByID(filterSetID); + filterSet->timeoutCallback=invalidMessageCallback; + filterSet->timeoutUserData=userData; +} +void MessageFilter::SetFilterMaxTime(int allowedTimeMS, bool banOnExceed, RakNet::TimeMS banTimeMS, int filterSetID) +{ + FilterSet *filterSet = GetFilterSetByID(filterSetID); + filterSet->maxMemberTimeMS=allowedTimeMS; + filterSet->banOnFilterTimeExceed=banOnExceed; + filterSet->timeExceedBanTimeMS=banTimeMS; +} +int MessageFilter::GetSystemFilterSet(AddressOrGUID systemAddress) +{ +// bool objectExists; +// unsigned index = systemList.GetIndexFromKey(systemAddress, &objectExists); +// if (objectExists==false) +// return -1; +// else +// return systemList[index].filter->filterSetID; + + DataStructures::HashIndex index = systemList.GetIndexOf(systemAddress); + if (index.IsInvalid()) + return -1; + else + return systemList.ItemAtIndex(index).filter->filterSetID; +} +void MessageFilter::SetSystemFilterSet(AddressOrGUID addressOrGUID, int filterSetID) +{ + // Allocate this filter set if it doesn't exist. + RakAssert(addressOrGUID.IsUndefined()==false); +// bool objectExists; +// unsigned index = systemList.GetIndexFromKey(addressOrGUID, &objectExists); +// if (objectExists==false) + DataStructures::HashIndex index = systemList.GetIndexOf(addressOrGUID); + if (index.IsInvalid()) + { + if (filterSetID<0) + return; + + FilteredSystem filteredSystem; + filteredSystem.filter = GetFilterSetByID(filterSetID); + // filteredSystem.addressOrGUID=addressOrGUID; + filteredSystem.timeEnteredThisSet=RakNet::GetTimeMS(); + // systemList.Insert(addressOrGUID, filteredSystem, true, _FILE_AND_LINE_); + systemList.Push(addressOrGUID,filteredSystem,_FILE_AND_LINE_); + } + else + { + if (filterSetID>=0) + { + FilterSet *filterSet = GetFilterSetByID(filterSetID); + systemList.ItemAtIndex(index).timeEnteredThisSet=RakNet::GetTimeMS(); + systemList.ItemAtIndex(index).filter=filterSet; + } + else + { + systemList.RemoveAtIndex(index, _FILE_AND_LINE_); + } + } +} +unsigned MessageFilter::GetSystemCount(int filterSetID) const +{ + if (filterSetID==-1) + { + return systemList.Size(); + } + else + { + unsigned i; + unsigned count=0; + DataStructures::List< FilteredSystem > itemList; + DataStructures::List< AddressOrGUID > keyList; + systemList.GetAsList(itemList, keyList, _FILE_AND_LINE_); + for (i=0; i < itemList.Size(); i++) + if (itemList[i].filter->filterSetID==filterSetID) + ++count; + return count; + } +} +unsigned MessageFilter::GetFilterSetCount(void) const +{ + return filterList.Size(); +} +int MessageFilter::GetFilterSetIDByIndex(unsigned index) +{ + return filterList[index]->filterSetID; +} +void MessageFilter::DeleteFilterSet(int filterSetID) +{ + FilterSet *filterSet; + bool objectExists; + unsigned i,index; + index = filterList.GetIndexFromKey(filterSetID, &objectExists); + if (objectExists) + { + filterSet=filterList[index]; + DeallocateFilterSet(filterSet); + filterList.RemoveAtIndex(index); + + DataStructures::List< FilteredSystem > itemList; + DataStructures::List< AddressOrGUID > keyList; + systemList.GetAsList(itemList, keyList, _FILE_AND_LINE_); + for (i=0; i < itemList.Size(); i++) + { + if (itemList[i].filter==filterSet) + { + systemList.Remove(keyList[i], _FILE_AND_LINE_); + } + } + + /* + // Don't reference this pointer any longer + i=0; + while (i < systemList.Size()) + { + if (systemList[i].filter==filterSet) + systemList.RemoveAtIndex(i); + else + ++i; + } + */ + } +} +void MessageFilter::Clear(void) +{ + unsigned i; + systemList.Clear(_FILE_AND_LINE_); + for (i=0; i < filterList.Size(); i++) + DeallocateFilterSet(filterList[i]); + filterList.Clear(false, _FILE_AND_LINE_); +} +void MessageFilter::DeallocateFilterSet(FilterSet* filterSet) +{ + RakNet::OP_DELETE(filterSet, _FILE_AND_LINE_); +} +FilterSet* MessageFilter::GetFilterSetByID(int filterSetID) +{ + RakAssert(filterSetID>=0); + bool objectExists; + unsigned index; + index = filterList.GetIndexFromKey(filterSetID, &objectExists); + if (objectExists) + return filterList[index]; + else + { + FilterSet *newFilterSet = RakNet::OP_NEW( _FILE_AND_LINE_ ); + memset(newFilterSet->allowedIDs, 0, MESSAGE_FILTER_MAX_MESSAGE_ID * sizeof(bool)); + newFilterSet->banOnFilterTimeExceed=false; + newFilterSet->kickOnDisallowedMessage=false; + newFilterSet->banOnDisallowedMessage=false; + newFilterSet->disallowedMessageBanTimeMS=0; + newFilterSet->timeExceedBanTimeMS=0; + newFilterSet->maxMemberTimeMS=0; + newFilterSet->filterSetID=filterSetID; + newFilterSet->invalidMessageCallback=0; + newFilterSet->timeoutCallback=0; + newFilterSet->timeoutUserData=0; + filterList.Insert(filterSetID, newFilterSet, true, _FILE_AND_LINE_); + return newFilterSet; + } +} +void MessageFilter::OnInvalidMessage(FilterSet *filterSet, AddressOrGUID systemAddress, unsigned char messageID) +{ + if (filterSet->invalidMessageCallback) + filterSet->invalidMessageCallback(rakPeerInterface, systemAddress, filterSet->filterSetID, filterSet->disallowedCallbackUserData, messageID); + if (filterSet->banOnDisallowedMessage && rakPeerInterface) + { + char str1[64]; + systemAddress.systemAddress.ToString(false, str1); + rakPeerInterface->AddToBanList(str1, filterSet->disallowedMessageBanTimeMS); + } + if (filterSet->kickOnDisallowedMessage) + { + if (rakPeerInterface) + rakPeerInterface->CloseConnection(systemAddress, true, 0); +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else + tcpInterface->CloseConnection(systemAddress.systemAddress); +#endif + } +} +void MessageFilter::Update(void) +{ + // Update all timers for all systems. If those systems' filter sets are expired, take the appropriate action. + RakNet::Time curTime = RakNet::GetTime(); + if (GreaterThan(curTime - 1000, whenLastTimeoutCheck)) + { + DataStructures::List< FilteredSystem > itemList; + DataStructures::List< AddressOrGUID > keyList; + systemList.GetAsList(itemList, keyList, _FILE_AND_LINE_); + + unsigned int index; + for (index=0; index < itemList.Size(); index++) + { + if (itemList[index].filter && + itemList[index].filter->maxMemberTimeMS>0 && + curTime-itemList[index].timeEnteredThisSet >= itemList[index].filter->maxMemberTimeMS) + { + if (itemList[index].filter->timeoutCallback) + itemList[index].filter->timeoutCallback(rakPeerInterface, keyList[index], itemList[index].filter->filterSetID, itemList[index].filter->timeoutUserData); + + if (itemList[index].filter->banOnFilterTimeExceed && rakPeerInterface) + { + char str1[64]; + keyList[index].ToString(false, str1); + rakPeerInterface->AddToBanList(str1, itemList[index].filter->timeExceedBanTimeMS); + } + if (rakPeerInterface) + rakPeerInterface->CloseConnection(keyList[index], true, 0); +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else + tcpInterface->CloseConnection(keyList[index].systemAddress); +#endif + + systemList.Remove(keyList[index], _FILE_AND_LINE_); + } + } + + whenLastTimeoutCheck=curTime+1000; + } +} +void MessageFilter::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) systemAddress; + (void) rakNetGUID; + (void) isIncoming; + + AddressOrGUID aog; + aog.rakNetGuid=rakNetGUID; + aog.systemAddress=systemAddress; + + // New system, automatically assign to filter set if appropriate + if (autoAddNewConnectionsToFilter>=0 && systemList.HasData(aog)==false) + SetSystemFilterSet(aog, autoAddNewConnectionsToFilter); +} +void MessageFilter::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) rakNetGUID; + (void) lostConnectionReason; + + AddressOrGUID aog; + aog.rakNetGuid=rakNetGUID; + aog.systemAddress=systemAddress; + + // Lost system, remove from the list + systemList.Remove(aog, _FILE_AND_LINE_); +} + PluginReceiveResult MessageFilter::OnReceive(Packet *packet) +{ + DataStructures::HashIndex index; + unsigned char messageId; + + switch (packet->data[0]) + { + case ID_NEW_INCOMING_CONNECTION: + case ID_CONNECTION_REQUEST_ACCEPTED: + case ID_CONNECTION_LOST: + case ID_DISCONNECTION_NOTIFICATION: + case ID_CONNECTION_ATTEMPT_FAILED: + case ID_NO_FREE_INCOMING_CONNECTIONS: + case ID_IP_RECENTLY_CONNECTED: + case ID_CONNECTION_BANNED: + case ID_INVALID_PASSWORD: + case ID_UNCONNECTED_PONG: + case ID_ALREADY_CONNECTED: + case ID_ADVERTISE_SYSTEM: + case ID_REMOTE_DISCONNECTION_NOTIFICATION: + case ID_REMOTE_CONNECTION_LOST: + case ID_REMOTE_NEW_INCOMING_CONNECTION: + case ID_DOWNLOAD_PROGRESS: + break; + default: + if (packet->data[0]==ID_TIMESTAMP) + { + if (packet->lengthdata[sizeof(MessageID) + sizeof(RakNet::TimeMS)]; + } + else + messageId=packet->data[0]; + // If this system is filtered, check if this message is allowed. If not allowed, return RR_STOP_PROCESSING_AND_DEALLOCATE + // index = systemList.GetIndexFromKey(packet->addressOrGUID, &objectExists); + index = systemList.GetIndexOf(packet); + if (index.IsInvalid()) + break; + if (systemList.ItemAtIndex(index).filter->allowedIDs[messageId]==false) + { + OnInvalidMessage(systemList.ItemAtIndex(index).filter, packet, packet->data[0]); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + if (packet->data[0]==ID_RPC_PLUGIN) + { + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + RakNet::RakString functionName; + bsIn.ReadCompressed(functionName); + if (systemList.ItemAtIndex(index).filter->allowedRPC4.HasData(functionName)==false) + { + OnInvalidMessage(systemList.ItemAtIndex(index).filter, packet, packet->data[0]); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + + break; + } + + return RR_CONTINUE_PROCESSING; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/NatPunchthroughClient.cpp b/src/raknet/NatPunchthroughClient.cpp new file mode 100644 index 0000000..9f72db2 --- /dev/null +++ b/src/raknet/NatPunchthroughClient.cpp @@ -0,0 +1,1216 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatPunchthroughClient==1 + +#include "include/raknet/NatPunchthroughClient.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/PacketLogger.hpp" +#include "include/raknet/Itoa.hpp" + +using namespace RakNet; + +void NatPunchthroughDebugInterface_Printf::OnClientMessage(const char *msg) +{ + printf("%s\n", msg); +} +#if _RAKNET_SUPPORT_PacketLogger==1 +void NatPunchthroughDebugInterface_PacketLogger::OnClientMessage(const char *msg) +{ + if (pl) + { + pl->WriteMiscellaneous("Nat", msg); + } +} +#endif + +STATIC_FACTORY_DEFINITIONS(NatPunchthroughClient,NatPunchthroughClient); + +NatPunchthroughClient::NatPunchthroughClient() +{ + natPunchthroughDebugInterface=0; + mostRecentExternalPort=0; + sp.nextActionTime=0; + portStride=0; + hasPortStride=UNKNOWN_PORT_STRIDE; +} +NatPunchthroughClient::~NatPunchthroughClient() +{ + rakPeerInterface=0; + Clear(); +} +void NatPunchthroughClient::FindRouterPortStride(const SystemAddress &facilitator) +{ + ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator); + if (cs!=IS_CONNECTED) + return; + if (hasPortStride!=UNKNOWN_PORT_STRIDE) + return; + + hasPortStride=CALCULATING_PORT_STRIDE; + portStrideCalTimeout = RakNet::GetTime()+5000; + + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage(RakString("Calculating port stride from %s", facilitator.ToString(true))); + } + + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_REQUEST_BOUND_ADDRESSES); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,facilitator,false); +} +bool NatPunchthroughClient::OpenNAT(RakNetGUID destination, const SystemAddress &facilitator) +{ + ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator); + if (cs!=IS_CONNECTED) + return false; + if (hasPortStride==UNKNOWN_PORT_STRIDE) + { + FindRouterPortStride(facilitator); + QueueOpenNAT(destination, facilitator); + } + else if (hasPortStride==CALCULATING_PORT_STRIDE) + { + QueueOpenNAT(destination, facilitator); + } + else + { + SendPunchthrough(destination, facilitator); + } + + return true; +} +/* +bool NatPunchthroughClient::OpenNATGroup(DataStructures::List destinationSystems, const SystemAddress &facilitator) +{ + ConnectionState cs = rakPeerInterface->GetConnectionState(facilitator); + if (cs!=IS_CONNECTED) + return false; + + unsigned long i; + for (i=0; i < destinationSystems.Size(); i++) + { + SendPunchthrough(destinationSystems[i], facilitator); + } + + GroupPunchRequest *gpr = RakNet::OP_NEW(_FILE_AND_LINE_); + gpr->facilitator=facilitator; + gpr->pendingList=destinationSystems; + groupPunchRequests.Push(gpr, _FILE_AND_LINE_); + + return true; +} +*/ +void NatPunchthroughClient::SetDebugInterface(NatPunchthroughDebugInterface *i) +{ + natPunchthroughDebugInterface=i; +} +void NatPunchthroughClient::Update(void) +{ + RakNet::Time time = RakNet::GetTime(); + + if (hasPortStride==CALCULATING_PORT_STRIDE && time > portStrideCalTimeout) + { + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage("CALCULATING_PORT_STRIDE timeout"); + } + + SendQueuedOpenNAT(); + hasPortStride=UNKNOWN_PORT_STRIDE; + } + + if (sp.nextActionTime && sp.nextActionTime < time) + { + RakNet::Time delta = time - sp.nextActionTime; + if (sp.testMode==SendPing::TESTING_INTERNAL_IPS) + { + SendOutOfBand(sp.internalIds[sp.attemptCount],ID_NAT_ESTABLISH_UNIDIRECTIONAL); + + if (++sp.retryCount>=pc.UDP_SENDS_PER_PORT_INTERNAL) + { + ++sp.attemptCount; + sp.retryCount=0; + } + + if (sp.attemptCount>=pc.MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK) + { + sp.testMode=SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE; + if (pc.INTERNAL_IP_WAIT_AFTER_ATTEMPTS>0) + { + sp.nextActionTime=time+pc.INTERNAL_IP_WAIT_AFTER_ATTEMPTS-delta; + } + else + { + sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; + sp.attemptCount=0; + sp.sentTTL=false; + } + } + else + { + sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_INTERNAL-delta; + } + } + else if (sp.testMode==SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE) + { + sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; + sp.attemptCount=0; + sp.sentTTL=false; + } + /* + else if (sp.testMode==SendPing::SEND_WITH_TTL) + { + // Send to unused port. We do not want the message to arrive, just to open our router's table + SystemAddress sa=sp.targetAddress; + int ttlSendIndex; + for (ttlSendIndex=0; ttlSendIndex <= pc.MAX_PREDICTIVE_PORT_RANGE; ttlSendIndex++) + { + sa.SetPortHostOrder((unsigned short) (sp.targetAddress.GetPort()+ttlSendIndex)); + SendTTL(sa); + } + + // Only do this stage once + // Wait 250 milliseconds for next stage. The delay is so that even with timing errors both systems send out the + // datagram with TTL before either sends a real one + sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; + sp.nextActionTime=time-delta+250; + } + */ + else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT) + { + if (sp.sentTTL==false) + { + SystemAddress sa=sp.targetAddress; + sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); + SendTTL(sa); + + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage(RakString("Send with TTL 2 to %s", sa.ToString(true))); + } + + sp.nextActionTime = time+pc.EXTERNAL_IP_WAIT_AFTER_FIRST_TTL-delta; + sp.sentTTL=true; + } + else + { + SystemAddress sa=sp.targetAddress; + sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); + SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); + + IncrementExternalAttemptCount(time, delta); + + if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) + { + sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS; + sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta; + + // Skip TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT, etc. + /* + sp.testMode=SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT; + sp.attemptCount=0; + */ + } + } + } + else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT) + { + SystemAddress sa=sp.targetAddress; + if ( sp.targetGuid < rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) ) + sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount)); + else + sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); + SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); + + IncrementExternalAttemptCount(time, delta); + + if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) + { + // From 1024 disabled, never helps as I've seen, but slows down the process by half + sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024; + sp.attemptCount=0; + } + + } + else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024) + { + SystemAddress sa=sp.targetAddress; + if ( sp.targetGuid > rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) ) + sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount)); + else + sa.SetPortHostOrder((unsigned short) (sa.GetPort()+sp.attemptCount)); + SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); + + IncrementExternalAttemptCount(time, delta); + + if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) + { + // From 1024 disabled, never helps as I've seen, but slows down the process by half + sp.testMode=SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024; + sp.attemptCount=0; + } + } + else if (sp.testMode==SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024) + { + SystemAddress sa=sp.targetAddress; + sa.SetPortHostOrder((unsigned short) (1024+sp.attemptCount)); + SendOutOfBand(sa,ID_NAT_ESTABLISH_UNIDIRECTIONAL); + + IncrementExternalAttemptCount(time, delta); + + if (sp.attemptCount>pc.MAX_PREDICTIVE_PORT_RANGE) + { + if (natPunchthroughDebugInterface) + { + char ipAddressString[32]; + sp.targetAddress.ToString(true, ipAddressString); + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Likely bidirectional punchthrough failure to guid %s, system address %s.", guidString, ipAddressString)); + } + + sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS; + sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta; + } + } + else if (sp.testMode==SendPing::WAITING_AFTER_ALL_ATTEMPTS) + { + // Failed. Tell the user + OnPunchthroughFailure(); + // UpdateGroupPunchOnNatResult(sp.facilitator, sp.targetGuid, sp.targetAddress, 1); + } + + if (sp.testMode==SendPing::PUNCHING_FIXED_PORT) + { + SendOutOfBand(sp.targetAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL); + if (++sp.retryCount>=sp.punchingFixedPortAttempts) + { + if (natPunchthroughDebugInterface) + { + char ipAddressString[32]; + sp.targetAddress.ToString(true, ipAddressString); + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Likely unidirectional punchthrough failure to guid %s, system address %s.", guidString, ipAddressString)); + } + + sp.testMode=SendPing::WAITING_AFTER_ALL_ATTEMPTS; + sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_AFTER_ALL_ATTEMPTS-delta; + } + else + { + if ((sp.retryCount%pc.UDP_SENDS_PER_PORT_EXTERNAL)==0) + sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_BETWEEN_PORTS-delta; + else + sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL-delta; + } + } + } + + /* + // Remove elapsed groupRequestsInProgress + unsigned int i; + i=0; + while (i < groupRequestsInProgress.Size()) + { + if (time > groupRequestsInProgress[i].time) + groupRequestsInProgress.RemoveAtIndexFast(i); + else + i++; + } + */ +} +void NatPunchthroughClient::PushFailure(void) +{ + Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); + p->data[0]=ID_NAT_PUNCHTHROUGH_FAILED; + p->systemAddress=sp.targetAddress; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=sp.targetGuid; + if (sp.weAreSender) + p->data[1]=1; + else + p->data[1]=0; + p->wasGeneratedLocally=true; + rakPeerInterface->PushBackPacket(p, true); +} +void NatPunchthroughClient::OnPunchthroughFailure(void) +{ + if (pc.retryOnFailure==false) + { + if (natPunchthroughDebugInterface) + { + char ipAddressString[32]; + sp.targetAddress.ToString(true, ipAddressString); + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Failed punchthrough once. Returning failure to guid %s, system address %s to user.", guidString, ipAddressString)); + } + + PushFailure(); + OnReadyForNextPunchthrough(); + return; + } + + unsigned int i; + for (i=0; i < failedAttemptList.Size(); i++) + { + if (failedAttemptList[i].guid==sp.targetGuid) + { + if (natPunchthroughDebugInterface) + { + char ipAddressString[32]; + sp.targetAddress.ToString(true, ipAddressString); + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Failed punchthrough twice. Returning failure to guid %s, system address %s to user.", guidString, ipAddressString)); + } + + // Failed a second time, so return failed to user + PushFailure(); + + OnReadyForNextPunchthrough(); + + failedAttemptList.RemoveAtIndexFast(i); + return; + } + } + + if (rakPeerInterface->GetConnectionState(sp.facilitator)!=IS_CONNECTED) + { + if (natPunchthroughDebugInterface) + { + char ipAddressString[32]; + sp.targetAddress.ToString(true, ipAddressString); + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Not connected to facilitator, so cannot retry punchthrough after first failure. Returning failure onj guid %s, system address %s to user.", guidString, ipAddressString)); + } + + // Failed, and can't try again because no facilitator + PushFailure(); + return; + } + + if (natPunchthroughDebugInterface) + { + char ipAddressString[32]; + sp.targetAddress.ToString(true, ipAddressString); + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("First punchthrough failure on guid %s, system address %s. Reattempting.", guidString, ipAddressString)); + } + + // Failed the first time. Add to the failure queue and try again + AddrAndGuid aag; + aag.addr=sp.targetAddress; + aag.guid=sp.targetGuid; + failedAttemptList.Push(aag, _FILE_AND_LINE_); + + // Tell the server we are ready + OnReadyForNextPunchthrough(); + + // If we are the sender, try again, immediately if possible, else added to the queue on the faciltiator + if (sp.weAreSender) + SendPunchthrough(sp.targetGuid, sp.facilitator); +} +PluginReceiveResult NatPunchthroughClient::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_NAT_GET_MOST_RECENT_PORT: + { + OnGetMostRecentPort(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case ID_NAT_PUNCHTHROUGH_FAILED: + case ID_NAT_PUNCHTHROUGH_SUCCEEDED: + if (packet->wasGeneratedLocally==false) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + break; + case ID_NAT_RESPOND_BOUND_ADDRESSES: + { + RakNet::BitStream bs(packet->data,packet->length,false); + bs.IgnoreBytes(sizeof(MessageID)); + unsigned char boundAddressCount; + bs.Read(boundAddressCount); + if (boundAddressCount<2) + { + if (natPunchthroughDebugInterface) + natPunchthroughDebugInterface->OnClientMessage(RakString("INCAPABLE_PORT_STRIDE. My external ID is %s", rakPeerInterface->GetExternalID(packet->systemAddress).ToString())); + + hasPortStride=INCAPABLE_PORT_STRIDE; + SendQueuedOpenNAT(); + } + SystemAddress boundAddresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS]; + for (int i=0; i < boundAddressCount && i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + { + bs.Read(boundAddresses[i]); + if (boundAddresses[i]!=packet->systemAddress) + { + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_PING); + uint16_t externalPort = rakPeerInterface->GetExternalID(packet->systemAddress).GetPort(); + outgoingBs.Write( externalPort ); + rakPeerInterface->SendOutOfBand((const char*) boundAddresses[i].ToString(false),boundAddresses[i].GetPort(),(const char*) outgoingBs.GetData(),outgoingBs.GetNumberOfBytesUsed()); + break; + } + } + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_OUT_OF_BAND_INTERNAL: + if (packet->length>=2 && packet->data[1]==ID_NAT_PONG) + { + RakNet::BitStream bs(packet->data,packet->length,false); + bs.IgnoreBytes(sizeof(MessageID)*2); + uint16_t externalPort; + bs.Read(externalPort); + uint16_t externalPort2; + bs.Read(externalPort2); + portStride = externalPort2 - externalPort; + mostRecentExternalPort = externalPort2; + hasPortStride=HAS_PORT_STRIDE; + + if (natPunchthroughDebugInterface) + natPunchthroughDebugInterface->OnClientMessage(RakString("HAS_PORT_STRIDE %i. First external port %i. Second external port %i.", portStride, externalPort, externalPort2)); + + SendQueuedOpenNAT(); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + else if (packet->length>=2 && + (packet->data[1]==ID_NAT_ESTABLISH_UNIDIRECTIONAL || packet->data[1]==ID_NAT_ESTABLISH_BIDIRECTIONAL) && + sp.nextActionTime!=0) + { + RakNet::BitStream bs(packet->data,packet->length,false); + bs.IgnoreBytes(2); + uint16_t sessionId; + bs.Read(sessionId); +// RakAssert(sessionId<100); + if (sessionId!=sp.sessionId) + break; + + char ipAddressString[32]; + packet->systemAddress.ToString(true,ipAddressString); + // sp.targetGuid==packet->guid is because the internal IP addresses reported may include loopbacks not reported by RakPeer::IsLocalIP() + if (packet->data[1]==ID_NAT_ESTABLISH_UNIDIRECTIONAL && sp.targetGuid==packet->guid) + { + + if (sp.testMode!=SendPing::PUNCHING_FIXED_PORT) + { + sp.testMode=SendPing::PUNCHING_FIXED_PORT; + sp.retryCount+=sp.attemptCount*pc.UDP_SENDS_PER_PORT_EXTERNAL; + sp.targetAddress=packet->systemAddress; + // Keeps trying until the other side gives up too, in case it is unidirectional + sp.punchingFixedPortAttempts=pc.UDP_SENDS_PER_PORT_EXTERNAL*(pc.MAX_PREDICTIVE_PORT_RANGE+1); + + if (natPunchthroughDebugInterface) + { + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("PUNCHING_FIXED_PORT: Received ID_NAT_ESTABLISH_UNIDIRECTIONAL from guid %s, system address %s.", guidString, ipAddressString)); + } + } + else { + if (natPunchthroughDebugInterface) + { + char guidString[128]; + sp.targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Received ID_NAT_ESTABLISH_UNIDIRECTIONAL from guid %s, system address %s.", guidString, ipAddressString)); + } + } + + SendOutOfBand(sp.targetAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL); + } + else if (packet->data[1]==ID_NAT_ESTABLISH_BIDIRECTIONAL && + sp.targetGuid==packet->guid) + { + // They send back our port + unsigned short ourExternalPort; + bs.Read(ourExternalPort); + if (mostRecentExternalPort==0) + { + mostRecentExternalPort=ourExternalPort; + + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL mostRecentExternalPort first time set to %i", mostRecentExternalPort)); + } + } + else + { + if (sp.testMode!=SendPing::TESTING_INTERNAL_IPS && sp.testMode!=SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE) + { + if (hasPortStride!=HAS_PORT_STRIDE) + { + portStride = ourExternalPort - mostRecentExternalPort; + hasPortStride=HAS_PORT_STRIDE; + + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage(RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL: Estimated port stride from incoming connection at %i. ourExternalPort=%i mostRecentExternalPort=%i", portStride, ourExternalPort, mostRecentExternalPort)); + } + + SendQueuedOpenNAT(); + } + + //nextExternalPort += portStride * (pc.MAX_PREDICTIVE_PORT_RANGE+1); + mostRecentExternalPort = ourExternalPort; + + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage(RakString("ID_NAT_ESTABLISH_BIDIRECTIONAL: New mostRecentExternalPort %i", mostRecentExternalPort)); + } + } + } + SendOutOfBand(packet->systemAddress,ID_NAT_ESTABLISH_BIDIRECTIONAL); + + // Tell the user about the success + sp.targetAddress=packet->systemAddress; + PushSuccess(); + //UpdateGroupPunchOnNatResult(sp.facilitator, sp.targetGuid, sp.targetAddress, 1); + OnReadyForNextPunchthrough(); + bool removedFromFailureQueue=RemoveFromFailureQueue(); + + if (natPunchthroughDebugInterface) + { + char guidString[128]; + sp.targetGuid.ToString(guidString); + if (removedFromFailureQueue) + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough to guid %s, system address %s succeeded on 2nd attempt.", guidString, ipAddressString)); + else + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough to guid %s, system address %s succeeded on 1st attempt.", guidString, ipAddressString)); + } + } + + // mostRecentNewExternalPort=packet->systemAddress.GetPort(); + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_NAT_ALREADY_IN_PROGRESS: + { + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(sizeof(MessageID)); + RakNetGUID targetGuid; + incomingBs.Read(targetGuid); + // Don't update group, just use later message + // UpdateGroupPunchOnNatResult(packet->systemAddress, targetGuid, UNASSIGNED_SYSTEM_ADDRESS, 2); + if (natPunchthroughDebugInterface) + { + char guidString[128]; + targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough retry to guid %s failed due to ID_NAT_ALREADY_IN_PROGRESS. Returning failure.", guidString)); + } + + } + break; + case ID_NAT_TARGET_NOT_CONNECTED: + case ID_NAT_CONNECTION_TO_TARGET_LOST: + case ID_NAT_TARGET_UNRESPONSIVE: + { + const char *reason; + if (packet->data[0]==ID_NAT_TARGET_NOT_CONNECTED) + reason=(char *)"ID_NAT_TARGET_NOT_CONNECTED"; + else if (packet->data[0]==ID_NAT_CONNECTION_TO_TARGET_LOST) + reason=(char *)"ID_NAT_CONNECTION_TO_TARGET_LOST"; + else + reason=(char *)"ID_NAT_TARGET_UNRESPONSIVE"; + + + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(sizeof(MessageID)); + + RakNetGUID targetGuid; + incomingBs.Read(targetGuid); + //UpdateGroupPunchOnNatResult(packet->systemAddress, targetGuid, UNASSIGNED_SYSTEM_ADDRESS, 2); + + if (packet->data[0]==ID_NAT_CONNECTION_TO_TARGET_LOST || + packet->data[0]==ID_NAT_TARGET_UNRESPONSIVE) + { + uint16_t sessionId; + incomingBs.Read(sessionId); + if (sessionId!=sp.sessionId) + break; + } + + unsigned int i; + for (i=0; i < failedAttemptList.Size(); i++) + { + if (failedAttemptList[i].guid==targetGuid) + { + if (natPunchthroughDebugInterface) + { + char guidString[128]; + targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough retry to guid %s failed due to %s.", guidString, reason)); + + } + + // If the retry target is not connected, or loses connection, or is not responsive, then previous failures cannot be retried. + + // Don't need to return failed, the other messages indicate failure anyway + /* + Packet *p = AllocatePacketUnified(sizeof(MessageID)); + p->data[0]=ID_NAT_PUNCHTHROUGH_FAILED; + p->systemAddress=failedAttemptList[i].addr; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=failedAttemptList[i].guid; + rakPeerInterface->PushBackPacket(p, false); + */ + + failedAttemptList.RemoveAtIndexFast(i); + break; + } + } + + if (natPunchthroughDebugInterface) + { + char guidString[128]; + targetGuid.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Punchthrough attempt to guid %s failed due to %s.", guidString, reason)); + } + + // Stop trying punchthrough + sp.nextActionTime=0; + + /* + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID)); + RakNetGUID failedSystem; + bs.Read(failedSystem); + bool deletedFirst=false; + unsigned int i=0; + while (i < pendingOpenNAT.Size()) + { + if (pendingOpenNAT[i].destination==failedSystem) + { + if (i==0) + deletedFirst=true; + pendingOpenNAT.RemoveAtIndex(i); + } + else + i++; + } + // Failed while in progress. Go to next in attempt queue + if (deletedFirst && pendingOpenNAT.Size()) + { + SendPunchthrough(pendingOpenNAT[0].destination, pendingOpenNAT[0].facilitator); + sp.nextActionTime=0; + } + */ + } + break; + case ID_TIMESTAMP: + if (packet->data[sizeof(MessageID)+sizeof(RakNet::Time)]==ID_NAT_CONNECT_AT_TIME) + { + OnConnectAtTime(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + break; + } + return RR_CONTINUE_PROCESSING; +} +/* +void NatPunchthroughClient::ProcessNextPunchthroughQueue(void) +{ + // Go to the next attempt + if (pendingOpenNAT.Size()) + pendingOpenNAT.RemoveAtIndex(0); + + // Do next punchthrough attempt + if (pendingOpenNAT.Size()) + SendPunchthrough(pendingOpenNAT[0].destination, pendingOpenNAT[0].facilitator); + + sp.nextActionTime=0; +} +*/ +void NatPunchthroughClient::OnConnectAtTime(Packet *packet) +{ +// RakAssert(sp.nextActionTime==0); + + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID)); + bs.Read(sp.nextActionTime); + bs.IgnoreBytes(sizeof(MessageID)); + bs.Read(sp.sessionId); + bs.Read(sp.targetAddress); + int j; +// int k; +// k=0; + for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) + bs.Read(sp.internalIds[j]); + + // Prevents local testing + /* + for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) + { + SystemAddress id; + bs.Read(id); + char str[32]; + id.ToString(false,str); + if (rakPeerInterface->IsLocalIP(str)==false) + sp.internalIds[k++]=id; + } + */ + sp.attemptCount=0; + sp.retryCount=0; + if (pc.MAXIMUM_NUMBER_OF_INTERNAL_IDS_TO_CHECK>0) + { + sp.testMode=SendPing::TESTING_INTERNAL_IPS; + } + else + { + // TESTING: Try sending to unused ports on the remote system to reserve our own ports while not getting banned + //sp.testMode=SendPing::SEND_WITH_TTL; + sp.testMode=SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT; + sp.attemptCount=0; + sp.sentTTL=false; + } + bs.Read(sp.targetGuid); + bs.Read(sp.weAreSender); +} +void NatPunchthroughClient::SendTTL(const SystemAddress &sa) +{ + if (sa==UNASSIGNED_SYSTEM_ADDRESS) + return; + if (sa.GetPort()==0) + return; + + char ipAddressString[32]; + sa.ToString(false, ipAddressString); + // TTL of 1 doesn't get past the router, 2 might hit the other system on a LAN + rakPeerInterface->SendTTL(ipAddressString,sa.GetPort(), 2); +} + +char *TestModeToString(NatPunchthroughClient::SendPing::TestMode tm) +{ + switch (tm) + { + case NatPunchthroughClient::SendPing::TESTING_INTERNAL_IPS: + return "TESTING_INTERNAL_IPS"; + break; + case NatPunchthroughClient::SendPing::WAITING_FOR_INTERNAL_IPS_RESPONSE: + return "WAITING_FOR_INTERNAL_IPS_RESPONSE"; + break; +// case NatPunchthroughClient::SendPing::SEND_WITH_TTL: +// return "SEND_WITH_TTL"; +// break; + case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT: + return "TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT"; + break; + case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT: + return "TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT"; + break; + case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024: + return "TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024"; + break; + case NatPunchthroughClient::SendPing::TESTING_EXTERNAL_IPS_1024_TO_1024: + return "TESTING_EXTERNAL_IPS_1024_TO_1024"; + break; + case NatPunchthroughClient::SendPing::WAITING_AFTER_ALL_ATTEMPTS: + return "WAITING_AFTER_ALL_ATTEMPTS"; + break; + case NatPunchthroughClient::SendPing::PUNCHING_FIXED_PORT: + return "PUNCHING_FIXED_PORT"; + break; + } + return ""; +} +void NatPunchthroughClient::SendOutOfBand(SystemAddress sa, MessageID oobId) +{ + if (sa==UNASSIGNED_SYSTEM_ADDRESS) + return; + if (sa.GetPort()==0) + return; + + RakNet::BitStream oob; + oob.Write(oobId); + oob.Write(sp.sessionId); +// RakAssert(sp.sessionId<100); + if (oobId==ID_NAT_ESTABLISH_BIDIRECTIONAL) + oob.Write(sa.GetPort()); + char ipAddressString[32]; + sa.ToString(false, ipAddressString); + rakPeerInterface->SendOutOfBand((const char*) ipAddressString,sa.GetPort(),(const char*) oob.GetData(),oob.GetNumberOfBytesUsed()); + + if (natPunchthroughDebugInterface) + { + sa.ToString(true,ipAddressString); + char guidString[128]; + sp.targetGuid.ToString(guidString); + + // server - diff = my time + // server = myTime + diff + RakNet::Time clockDifferential = rakPeerInterface->GetClockDifferential(sp.facilitator); + RakNet::Time serverTime = RakNet::GetTime() + clockDifferential; + + if (oobId==ID_NAT_ESTABLISH_UNIDIRECTIONAL) + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("%I64d: %s: OOB ID_NAT_ESTABLISH_UNIDIRECTIONAL to guid %s, system address %s.\n", serverTime, TestModeToString(sp.testMode), guidString, ipAddressString)); + else + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("%I64d: %s: OOB ID_NAT_ESTABLISH_BIDIRECTIONAL to guid %s, system address %s.\n", serverTime, TestModeToString(sp.testMode), guidString, ipAddressString)); + } +} +void NatPunchthroughClient::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) rakNetGUID; + (void) isIncoming; + + // Try to track new port mappings on the router. Not reliable, but better than nothing. + SystemAddress ourExternalId = rakPeerInterface->GetExternalID(systemAddress); + if (ourExternalId!=UNASSIGNED_SYSTEM_ADDRESS && mostRecentExternalPort==0) { + mostRecentExternalPort=ourExternalId.GetPort(); + + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("OnNewConnection mostRecentExternalPort first time set to %i", mostRecentExternalPort)); + } + } + + /* + unsigned int i; + i=0; + while (i < groupRequestsInProgress.Size()) + { + if (groupRequestsInProgress[i].guid==rakNetGUID) + { + groupRequestsInProgress.RemoveAtIndexFast(i); + } + else + { + i++; + } + } + */ +} + +void NatPunchthroughClient::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) systemAddress; + (void) rakNetGUID; + (void) lostConnectionReason; + + if (sp.facilitator==systemAddress) + { + // If we lose the connection to the facilitator, all previous failures not currently in progress are returned as such + unsigned int i=0; + while (i < failedAttemptList.Size()) + { + if (sp.nextActionTime!=0 && sp.targetGuid==failedAttemptList[i].guid) + { + i++; + continue; + } + + PushFailure(); + + failedAttemptList.RemoveAtIndexFast(i); + } + } + + /* + unsigned int i; + i=0; + while (i < groupPunchRequests.Size()) + { + if (groupPunchRequests[i]->facilitator==systemAddress) + { + RakNet::OP_DELETE(groupPunchRequests[i],_FILE_AND_LINE_); + groupPunchRequests.RemoveAtIndexFast(i); + } + else + { + i++; + } + } + */ + +} +void NatPunchthroughClient::GetUPNPPortMappings(char *externalPort, char *internalPort, const SystemAddress &natPunchthroughServerAddress) +{ + DataStructures::List< RakNet::RakNetSocket2* > sockets; + rakPeerInterface->GetSockets(sockets); + Itoa(sockets[0]->GetBoundAddress().GetPort(),internalPort,10); + if (mostRecentExternalPort==0) + mostRecentExternalPort=rakPeerInterface->GetExternalID(natPunchthroughServerAddress).GetPort(); + Itoa(mostRecentExternalPort,externalPort,10); +} +void NatPunchthroughClient::OnFailureNotification(Packet *packet) +{ + RakNet::BitStream incomingBs(packet->data,packet->length,false); + incomingBs.IgnoreBytes(sizeof(MessageID)); + RakNetGUID senderGuid; + incomingBs.Read(senderGuid); + + /* + unsigned int i; + i=0; + while (i < groupRequestsInProgress.Size()) + { + if (groupRequestsInProgress[i].guid==senderGuid) + { + groupRequestsInProgress.RemoveAtIndexFast(i); + break; + } + else + { + i++; + } + } + */ +} +void NatPunchthroughClient::OnGetMostRecentPort(Packet *packet) +{ + RakNet::BitStream incomingBs(packet->data,packet->length,false); + incomingBs.IgnoreBytes(sizeof(MessageID)); + uint16_t sessionId; + incomingBs.Read(sessionId); + + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_GET_MOST_RECENT_PORT); + outgoingBs.Write(sessionId); + if (mostRecentExternalPort==0) + { + mostRecentExternalPort=rakPeerInterface->GetExternalID(packet->systemAddress).GetPort(); + RakAssert(mostRecentExternalPort!=0); + + if (natPunchthroughDebugInterface) + { + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("OnGetMostRecentPort mostRecentExternalPort first time set to %i", mostRecentExternalPort)); + } + } + + unsigned short portWithStride; + if (hasPortStride==HAS_PORT_STRIDE) + portWithStride = mostRecentExternalPort + portStride; + else + portWithStride = mostRecentExternalPort; + outgoingBs.Write(portWithStride); + + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false); + sp.facilitator=packet->systemAddress; +} +/* +unsigned int NatPunchthroughClient::GetPendingOpenNATIndex(RakNetGUID destination, const SystemAddress &facilitator) +{ + unsigned int i; + for (i=0; i < pendingOpenNAT.Size(); i++) + { + if (pendingOpenNAT[i].destination==destination && pendingOpenNAT[i].facilitator==facilitator) + return i; + } + return (unsigned int) -1; +} +*/ +void NatPunchthroughClient::QueueOpenNAT(RakNetGUID destination, const SystemAddress &facilitator) +{ + DSTAndFac daf; + daf.destination=destination; + daf.facilitator=facilitator; + queuedOpenNat.Push(daf, _FILE_AND_LINE_); +} +void NatPunchthroughClient::SendQueuedOpenNAT(void) +{ + while (queuedOpenNat.IsEmpty()==false) + { + DSTAndFac daf = queuedOpenNat.Pop(); + SendPunchthrough(daf.destination, daf.facilitator); + } +} +void NatPunchthroughClient::SendPunchthrough(RakNetGUID destination, const SystemAddress &facilitator) +{ + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_PUNCHTHROUGH_REQUEST); + outgoingBs.Write(destination); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,facilitator,false); + +// RakAssert(rakPeerInterface->GetSystemAddressFromGuid(destination)==UNASSIGNED_SYSTEM_ADDRESS); + + if (natPunchthroughDebugInterface) + { + char guidString[128]; + destination.ToString(guidString); + natPunchthroughDebugInterface->OnClientMessage(RakNet::RakString("Starting ID_NAT_PUNCHTHROUGH_REQUEST to guid %s.", guidString)); + } +} +void NatPunchthroughClient::OnAttach(void) +{ + Clear(); +} +void NatPunchthroughClient::OnDetach(void) +{ + Clear(); +} +void NatPunchthroughClient::OnRakPeerShutdown(void) +{ + Clear(); +} +void NatPunchthroughClient::Clear(void) +{ + OnReadyForNextPunchthrough(); + + failedAttemptList.Clear(false, _FILE_AND_LINE_); + + queuedOpenNat.Clear(_FILE_AND_LINE_); + /* + groupRequestsInProgress.Clear(false, _FILE_AND_LINE_); + unsigned int i; + for (i=0; i < groupPunchRequests.Size(); i++) + { + RakNet::OP_DELETE(groupPunchRequests[i],_FILE_AND_LINE_); + } + groupPunchRequests.Clear(true, _FILE_AND_LINE_); + */ +} +PunchthroughConfiguration* NatPunchthroughClient::GetPunchthroughConfiguration(void) +{ + return &pc; +} +void NatPunchthroughClient::OnReadyForNextPunchthrough(void) +{ + if (rakPeerInterface==0) + return; + + sp.nextActionTime=0; + + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_CLIENT_READY); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,sp.facilitator,false); +} + +void NatPunchthroughClient::PushSuccess(void) +{ + Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); + p->data[0]=ID_NAT_PUNCHTHROUGH_SUCCEEDED; + p->systemAddress=sp.targetAddress; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=sp.targetGuid; + if (sp.weAreSender) + p->data[1]=1; + else + p->data[1]=0; + p->wasGeneratedLocally=true; + rakPeerInterface->PushBackPacket(p, true); +} +bool NatPunchthroughClient::RemoveFromFailureQueue(void) +{ + unsigned int i; + for (i=0; i < failedAttemptList.Size(); i++) + { + if (failedAttemptList[i].guid==sp.targetGuid) + { + // Remove from failure queue + failedAttemptList.RemoveAtIndexFast(i); + return true; + } + } + return false; +} + +void NatPunchthroughClient::IncrementExternalAttemptCount(RakNet::Time time, RakNet::Time delta) +{ + if (++sp.retryCount>=pc.UDP_SENDS_PER_PORT_EXTERNAL) + { + ++sp.attemptCount; + sp.retryCount=0; + sp.nextActionTime=time+pc.EXTERNAL_IP_WAIT_BETWEEN_PORTS-delta; + sp.sentTTL=false; + } + else + { + sp.nextActionTime=time+pc.TIME_BETWEEN_PUNCH_ATTEMPTS_EXTERNAL-delta; + } +} +/* +// 0=failed, 1=success, 2=ignore +void NatPunchthroughClient::UpdateGroupPunchOnNatResult(SystemAddress facilitator, RakNetGUID targetSystem, SystemAddress targetSystemAddress, int result) +{ + GroupPunchRequest *gpr; + unsigned long i,j,k; + i=0; + while (i < groupPunchRequests.Size()) + { + gpr = groupPunchRequests[i]; + if (gpr->facilitator==facilitator) + { + j=0; + while (j < gpr->pendingList.Size()) + { + if (gpr->pendingList[j]==targetSystem) + { + if (result==0) + { + gpr->failedList.Push(targetSystem, _FILE_AND_LINE_); + } + else if (result==1) + { + gpr->passedListGuid.Push(targetSystem, _FILE_AND_LINE_); + gpr->passedListAddress.Push(targetSystemAddress, _FILE_AND_LINE_); + } + else + { + gpr->ignoredList.Push(targetSystem, _FILE_AND_LINE_); + } + gpr->pendingList.RemoveAtIndex(j); + } + else + j++; + } + } + if (gpr->pendingList.Size()==0) + { + RakNet::BitStream output; + if (gpr->failedList.Size()==0) + { + output.Write(ID_NAT_GROUP_PUNCH_SUCCEEDED); + } + else + { + output.Write(ID_NAT_GROUP_PUNCH_FAILED); + } + + output.WriteCasted(gpr->passedListGuid.Size()); + for (k=0; k < gpr->passedListGuid.Size(); k++) + { + output.Write(gpr->passedListGuid[k]); + output.Write(gpr->passedListAddress[k]); + } + output.WriteCasted(gpr->ignoredList.Size()); + for (k=0; k < gpr->ignoredList.Size(); k++) + { + output.Write(gpr->ignoredList[k]); + } + output.WriteCasted(gpr->failedList.Size()); + for (k=0; k < gpr->failedList.Size(); k++) + { + output.Write(gpr->failedList[k]); + } + + Packet *p = AllocatePacketUnified(output.GetNumberOfBytesUsed()); + p->systemAddress=gpr->facilitator; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=rakPeerInterface->GetGuidFromSystemAddress(gpr->facilitator); + p->wasGeneratedLocally=true; + memcpy(p->data, output.GetData(), output.GetNumberOfBytesUsed()); + rakPeerInterface->PushBackPacket(p, true); + + groupPunchRequests.RemoveAtIndex(i); + RakNet::OP_DELETE(gpr, _FILE_AND_LINE_); + } + else + i++; + } +} +*/ + +#endif // _RAKNET_SUPPORT_* + diff --git a/src/raknet/NatPunchthroughServer.cpp b/src/raknet/NatPunchthroughServer.cpp new file mode 100644 index 0000000..2f21d4a --- /dev/null +++ b/src/raknet/NatPunchthroughServer.cpp @@ -0,0 +1,624 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatPunchthroughServer==1 + +#include "include/raknet/NatPunchthroughServer.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MTUSize.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/PacketLogger.hpp" + +using namespace RakNet; + +void NatPunchthroughServerDebugInterface_Printf::OnServerMessage(const char *msg) +{ + printf("%s\n", msg); +} +#if _RAKNET_SUPPORT_PacketLogger==1 +void NatPunchthroughServerDebugInterface_PacketLogger::OnServerMessage(const char *msg) +{ + if (pl) + { + pl->WriteMiscellaneous("Nat", msg); + } +} +#endif + +void NatPunchthroughServer::User::DeleteConnectionAttempt(NatPunchthroughServer::ConnectionAttempt *ca) +{ + unsigned int index = connectionAttempts.GetIndexOf(ca); + if ((unsigned int)index!=(unsigned int)-1) + { + RakNet::OP_DELETE(ca,_FILE_AND_LINE_); + connectionAttempts.RemoveAtIndex(index); + } +} +void NatPunchthroughServer::User::DerefConnectionAttempt(NatPunchthroughServer::ConnectionAttempt *ca) +{ + unsigned int index = connectionAttempts.GetIndexOf(ca); + if ((unsigned int)index!=(unsigned int)-1) + { + connectionAttempts.RemoveAtIndex(index); + } +} +bool NatPunchthroughServer::User::HasConnectionAttemptToUser(User *user) +{ + unsigned int index; + for (index=0; index < connectionAttempts.Size(); index++) + { + if (connectionAttempts[index]->recipient->guid==user->guid || + connectionAttempts[index]->sender->guid==user->guid) + return true; + } + return false; +} +void NatPunchthroughServer::User::LogConnectionAttempts(RakNet::RakString &rs) +{ + rs.Clear(); + unsigned int index; + char guidStr[128], ipStr[128]; + guid.ToString(guidStr); + systemAddress.ToString(true,ipStr); + rs=RakNet::RakString("User systemAddress=%s guid=%s\n", ipStr, guidStr); + rs+=RakNet::RakString("%i attempts in list:\n", connectionAttempts.Size()); + for (index=0; index < connectionAttempts.Size(); index++) + { + rs+=RakNet::RakString("%i. SessionID=%i ", index+1, connectionAttempts[index]->sessionId); + if (connectionAttempts[index]->sender==this) + rs+="(We are sender) "; + else + rs+="(We are recipient) "; + if (isReady) + rs+="(READY TO START) "; + else + rs+="(NOT READY TO START) "; + if (connectionAttempts[index]->attemptPhase==NatPunchthroughServer::ConnectionAttempt::NAT_ATTEMPT_PHASE_NOT_STARTED) + rs+="(NOT_STARTED). "; + else + rs+="(GETTING_RECENT_PORTS). "; + if (connectionAttempts[index]->sender==this) + { + connectionAttempts[index]->recipient->guid.ToString(guidStr); + connectionAttempts[index]->recipient->systemAddress.ToString(true,ipStr); + } + else + { + connectionAttempts[index]->sender->guid.ToString(guidStr); + connectionAttempts[index]->sender->systemAddress.ToString(true,ipStr); + } + + rs+=RakNet::RakString("Target systemAddress=%s, guid=%s.\n", ipStr, guidStr); + } +} + +int RakNet::NatPunchthroughServer::NatPunchthroughUserComp( const RakNetGUID &key, User * const &data ) +{ + if (key < data->guid) + return -1; + if (key > data->guid) + return 1; + return 0; +} + +STATIC_FACTORY_DEFINITIONS(NatPunchthroughServer,NatPunchthroughServer); + +NatPunchthroughServer::NatPunchthroughServer() +{ + lastUpdate=0; + sessionId=0; + natPunchthroughServerDebugInterface=0; + for (int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + boundAddresses[i]=UNASSIGNED_SYSTEM_ADDRESS; + boundAddressCount=0; +} +NatPunchthroughServer::~NatPunchthroughServer() +{ + User *user, *otherUser; + ConnectionAttempt *connectionAttempt; + unsigned int j; + while(users.Size()) + { + user = users[0]; + for (j=0; j < user->connectionAttempts.Size(); j++) + { + connectionAttempt=user->connectionAttempts[j]; + if (connectionAttempt->sender==user) + otherUser=connectionAttempt->recipient; + else + otherUser=connectionAttempt->sender; + otherUser->DeleteConnectionAttempt(connectionAttempt); + } + RakNet::OP_DELETE(user,_FILE_AND_LINE_); + users[0]=users[users.Size()-1]; + users.RemoveAtIndex(users.Size()-1); + } +} +void NatPunchthroughServer::SetDebugInterface(NatPunchthroughServerDebugInterface *i) +{ + natPunchthroughServerDebugInterface=i; +} +void NatPunchthroughServer::Update(void) +{ + ConnectionAttempt *connectionAttempt; + User *user, *recipient; + unsigned int i,j; + RakNet::Time time = RakNet::GetTime(); + if (time > lastUpdate+250) + { + lastUpdate=time; + + for (i=0; i < users.Size(); i++) + { + user=users[i]; + for (j=0; j < user->connectionAttempts.Size(); j++) + { + connectionAttempt=user->connectionAttempts[j]; + if (connectionAttempt->sender==user) + { + if (connectionAttempt->attemptPhase!=ConnectionAttempt::NAT_ATTEMPT_PHASE_NOT_STARTED && + time > connectionAttempt->startTime && + time > 10000 + connectionAttempt->startTime ) // Formerly 5000, but sometimes false positives + { + RakNet::BitStream outgoingBs; + + // that other system might not be running the plugin + outgoingBs.Write((MessageID)ID_NAT_TARGET_UNRESPONSIVE); + outgoingBs.Write(connectionAttempt->recipient->guid); + outgoingBs.Write(connectionAttempt->sessionId); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,connectionAttempt->sender->systemAddress,false); + + // 05/28/09 Previously only told sender about ID_NAT_CONNECTION_TO_TARGET_LOST + // However, recipient may be expecting it due to external code + // In that case, recipient would never get any response if the sender dropped + outgoingBs.Reset(); + outgoingBs.Write((MessageID)ID_NAT_TARGET_UNRESPONSIVE); + outgoingBs.Write(connectionAttempt->sender->guid); + outgoingBs.Write(connectionAttempt->sessionId); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,connectionAttempt->recipient->systemAddress,false); + + connectionAttempt->sender->isReady=true; + connectionAttempt->recipient->isReady=true; + recipient=connectionAttempt->recipient; + + + if (natPunchthroughServerDebugInterface) + { + char str[1024]; + char addr1[128], addr2[128]; + // 8/01/09 Fixed bug where this was after DeleteConnectionAttempt() + connectionAttempt->sender->systemAddress.ToString(true,addr1); + connectionAttempt->recipient->systemAddress.ToString(true,addr2); + sprintf(str, "Sending ID_NAT_TARGET_UNRESPONSIVE to sender %s and recipient %s.", addr1, addr2); + natPunchthroughServerDebugInterface->OnServerMessage(str); + RakNet::RakString log; + connectionAttempt->sender->LogConnectionAttempts(log); + connectionAttempt->recipient->LogConnectionAttempts(log); + } + + + connectionAttempt->sender->DerefConnectionAttempt(connectionAttempt); + connectionAttempt->recipient->DeleteConnectionAttempt(connectionAttempt); + + StartPunchthroughForUser(user); + StartPunchthroughForUser(recipient); + + break; + } + } + } + } + } +} +PluginReceiveResult NatPunchthroughServer::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_NAT_PUNCHTHROUGH_REQUEST: + OnNATPunchthroughRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_NAT_GET_MOST_RECENT_PORT: + OnGetMostRecentPort(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_NAT_CLIENT_READY: + OnClientReady(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_NAT_REQUEST_BOUND_ADDRESSES: + { + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_RESPOND_BOUND_ADDRESSES); + + if (boundAddresses[0]==UNASSIGNED_SYSTEM_ADDRESS) + { + DataStructures::List sockets; + rakPeerInterface->GetSockets(sockets); + for (int i=0; i < sockets.Size() && i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + { + boundAddresses[i]=sockets[i]->GetBoundAddress(); + boundAddressCount++; + } + } + + outgoingBs.Write(boundAddressCount); + for (int i=0; i < boundAddressCount; i++) + { + outgoingBs.Write(boundAddresses[i]); + } + + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false); + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_NAT_PING: + { + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_OUT_OF_BAND_INTERNAL: + if (packet->length>=2 && packet->data[1]==ID_NAT_PING) + { + RakNet::BitStream bs(packet->data,packet->length,false); + bs.IgnoreBytes(sizeof(MessageID)*2); + uint16_t externalPort; + bs.Read(externalPort); + + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_PONG); + outgoingBs.Write(externalPort); + uint16_t externalPort2 = packet->systemAddress.GetPort(); + outgoingBs.Write(externalPort2); + rakPeerInterface->SendOutOfBand((const char*) packet->systemAddress.ToString(false),packet->systemAddress.GetPort(),(const char*) outgoingBs.GetData(),outgoingBs.GetNumberOfBytesUsed()); + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + return RR_CONTINUE_PROCESSING; +} +void NatPunchthroughServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + + unsigned int i=0; + bool objectExists; + i = users.GetIndexFromKey(rakNetGUID, &objectExists); + if (objectExists) + { + RakNet::BitStream outgoingBs; + DataStructures::List freedUpInProgressUsers; + User *user = users[i]; + User *otherUser; + unsigned int connectionAttemptIndex; + ConnectionAttempt *connectionAttempt; + for (connectionAttemptIndex=0; connectionAttemptIndex < user->connectionAttempts.Size(); connectionAttemptIndex++) + { + connectionAttempt=user->connectionAttempts[connectionAttemptIndex]; + outgoingBs.Reset(); + if (connectionAttempt->recipient==user) + { + otherUser=connectionAttempt->sender; + } + else + { + otherUser=connectionAttempt->recipient; + } + + // 05/28/09 Previously only told sender about ID_NAT_CONNECTION_TO_TARGET_LOST + // However, recipient may be expecting it due to external code + // In that case, recipient would never get any response if the sender dropped + outgoingBs.Write((MessageID)ID_NAT_CONNECTION_TO_TARGET_LOST); + outgoingBs.Write(rakNetGUID); + outgoingBs.Write(connectionAttempt->sessionId); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,otherUser->systemAddress,false); + + // 4/22/09 - Bug: was checking inProgress, legacy variable not used elsewhere + if (connectionAttempt->attemptPhase==ConnectionAttempt::NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS) + { + otherUser->isReady=true; + freedUpInProgressUsers.Insert(otherUser, _FILE_AND_LINE_ ); + } + + otherUser->DeleteConnectionAttempt(connectionAttempt); + } + + RakNet::OP_DELETE(users[i], _FILE_AND_LINE_); + users.RemoveAtIndex(i); + + for (i=0; i < freedUpInProgressUsers.Size(); i++) + { + StartPunchthroughForUser(freedUpInProgressUsers[i]); + } + } + + /* + // Also remove from groupPunchthroughRequests + for (i=0; i < users.Size(); i++) + { + bool objectExists; + unsigned int gprIndex; + gprIndex = users[i]->groupPunchthroughRequests.GetIndexFromKey(rakNetGUID, &objectExists); + if (objectExists) + { +// printf("DEBUG %i\n", __LINE__); + + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_TARGET_NOT_CONNECTED); + outgoingBs.Write(rakNetGUID); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,users[i]->systemAddress,false); + + users[i]->groupPunchthroughRequests.RemoveAtIndex(gprIndex); + } + } + */ +} + +void NatPunchthroughServer::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) systemAddress; + (void) isIncoming; + + User *user = RakNet::OP_NEW(_FILE_AND_LINE_); + user->guid=rakNetGUID; + user->mostRecentPort=0; + user->systemAddress=systemAddress; + user->isReady=true; + users.Insert(rakNetGUID, user, true, _FILE_AND_LINE_); + +// printf("Adding to users %s\n", rakNetGUID.ToString()); +// printf("DEBUG users[0] guid=%s\n", users[0]->guid.ToString()); +} +void NatPunchthroughServer::OnNATPunchthroughRequest(Packet *packet) +{ + RakNet::BitStream outgoingBs; + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(sizeof(MessageID)); + RakNetGUID recipientGuid, senderGuid; + incomingBs.Read(recipientGuid); + senderGuid=packet->guid; + unsigned int i; + bool objectExists; + i = users.GetIndexFromKey(senderGuid, &objectExists); + RakAssert(objectExists); + + ConnectionAttempt *ca = RakNet::OP_NEW(_FILE_AND_LINE_); + ca->sender=users[i]; + ca->sessionId=sessionId++; + i = users.GetIndexFromKey(recipientGuid, &objectExists); + if (objectExists==false || ca->sender == ca->recipient) + { +// printf("DEBUG %i\n", __LINE__); +// printf("DEBUG recipientGuid=%s\n", recipientGuid.ToString()); +// printf("DEBUG users[0] guid=%s\n", users[0]->guid.ToString()); + + outgoingBs.Write((MessageID)ID_NAT_TARGET_NOT_CONNECTED); + outgoingBs.Write(recipientGuid); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false); + RakNet::OP_DELETE(ca,_FILE_AND_LINE_); + return; + } + ca->recipient=users[i]; + if (ca->recipient->HasConnectionAttemptToUser(ca->sender)) + { + outgoingBs.Write((MessageID)ID_NAT_ALREADY_IN_PROGRESS); + outgoingBs.Write(recipientGuid); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false); + RakNet::OP_DELETE(ca,_FILE_AND_LINE_); + return; + } + + ca->sender->connectionAttempts.Insert(ca, _FILE_AND_LINE_ ); + ca->recipient->connectionAttempts.Insert(ca, _FILE_AND_LINE_ ); + + StartPunchthroughForUser(ca->sender); +} +void NatPunchthroughServer::OnClientReady(Packet *packet) +{ + unsigned int i; + bool objectExists; + i = users.GetIndexFromKey(packet->guid, &objectExists); + if (objectExists) + { + users[i]->isReady=true; + StartPunchthroughForUser(users[i]); + } +} +void NatPunchthroughServer::OnGetMostRecentPort(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + uint16_t sessionId; + unsigned short mostRecentPort; + bsIn.Read(sessionId); + bsIn.Read(mostRecentPort); + + unsigned int i,j; + User *user; + ConnectionAttempt *connectionAttempt; + bool objectExists; + i = users.GetIndexFromKey(packet->guid, &objectExists); + + if (natPunchthroughServerDebugInterface) + { + RakNet::RakString log; + char addr1[128], addr2[128]; + packet->systemAddress.ToString(true,addr1); + packet->guid.ToString(addr2); + log=RakNet::RakString("Got ID_NAT_GET_MOST_RECENT_PORT from systemAddress %s guid %s. port=%i. sessionId=%i. userFound=%i.", addr1, addr2, mostRecentPort, sessionId, objectExists); + natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); + } + + if (objectExists) + { + user=users[i]; + user->mostRecentPort=mostRecentPort; + RakNet::Time time = RakNet::GetTime(); + + for (j=0; j < user->connectionAttempts.Size(); j++) + { + connectionAttempt=user->connectionAttempts[j]; + if (connectionAttempt->attemptPhase==ConnectionAttempt::NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS && + connectionAttempt->sender->mostRecentPort!=0 && + connectionAttempt->recipient->mostRecentPort!=0 && + // 04/29/08 add sessionId to prevent processing for other systems + connectionAttempt->sessionId==sessionId) + { + SystemAddress senderSystemAddress = connectionAttempt->sender->systemAddress; + SystemAddress recipientSystemAddress = connectionAttempt->recipient->systemAddress; + SystemAddress recipientTargetAddress = recipientSystemAddress; + SystemAddress senderTargetAddress = senderSystemAddress; + recipientTargetAddress.SetPortHostOrder(connectionAttempt->recipient->mostRecentPort); + senderTargetAddress.SetPortHostOrder(connectionAttempt->sender->mostRecentPort); + + // Pick a time far enough in the future that both systems will have gotten the message + int targetPing = rakPeerInterface->GetAveragePing(recipientTargetAddress); + int senderPing = rakPeerInterface->GetAveragePing(senderSystemAddress); + RakNet::Time simultaneousAttemptTime; + if (targetPing==-1 || senderPing==-1) + simultaneousAttemptTime = time + 1500; + else + { + int largerPing = targetPing > senderPing ? targetPing : senderPing; + if (largerPing * 4 < 100) + simultaneousAttemptTime = time + 100; + else + simultaneousAttemptTime = time + (largerPing * 4); + } + + if (natPunchthroughServerDebugInterface) + { + RakNet::RakString log; + char addr1[128], addr2[128]; + recipientSystemAddress.ToString(true,addr1); + connectionAttempt->recipient->guid.ToString(addr2); + log=RakNet::RakString("Sending ID_NAT_CONNECT_AT_TIME to recipient systemAddress %s guid %s", addr1, addr2); + natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); + } + + // Send to recipient timestamped message to connect at time + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_TIMESTAMP); + bsOut.Write(simultaneousAttemptTime); + bsOut.Write((MessageID)ID_NAT_CONNECT_AT_TIME); + bsOut.Write(connectionAttempt->sessionId); + bsOut.Write(senderTargetAddress); // Public IP, using most recent port + for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) // Internal IP + bsOut.Write(rakPeerInterface->GetInternalID(senderSystemAddress,j)); + bsOut.Write(connectionAttempt->sender->guid); + bsOut.Write(false); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,recipientSystemAddress,false); + + + if (natPunchthroughServerDebugInterface) + { + RakNet::RakString log; + char addr1[128], addr2[128]; + senderSystemAddress.ToString(true,addr1); + connectionAttempt->sender->guid.ToString(addr2); + log=RakNet::RakString("Sending ID_NAT_CONNECT_AT_TIME to sender systemAddress %s guid %s", addr1, addr2); + natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); + } + + + // Same for sender + bsOut.Reset(); + bsOut.Write((MessageID)ID_TIMESTAMP); + bsOut.Write(simultaneousAttemptTime); + bsOut.Write((MessageID)ID_NAT_CONNECT_AT_TIME); + bsOut.Write(connectionAttempt->sessionId); + bsOut.Write(recipientTargetAddress); // Public IP, using most recent port + for (j=0; j < MAXIMUM_NUMBER_OF_INTERNAL_IDS; j++) // Internal IP + bsOut.Write(rakPeerInterface->GetInternalID(recipientSystemAddress,j)); + bsOut.Write(connectionAttempt->recipient->guid); + bsOut.Write(true); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,senderSystemAddress,false); + + connectionAttempt->recipient->DerefConnectionAttempt(connectionAttempt); + connectionAttempt->sender->DeleteConnectionAttempt(connectionAttempt); + + // 04/29/08 missing return + return; + } + } + } + else + { + + if (natPunchthroughServerDebugInterface) + { + RakNet::RakString log; + char addr1[128], addr2[128]; + packet->systemAddress.ToString(true,addr1); + packet->guid.ToString(addr2); + log=RakNet::RakString("Ignoring ID_NAT_GET_MOST_RECENT_PORT from systemAddress %s guid %s", addr1, addr2); + natPunchthroughServerDebugInterface->OnServerMessage(log.C_String()); + } + + } +} +void NatPunchthroughServer::StartPunchthroughForUser(User *user) +{ + if (user->isReady==false) + return; + + ConnectionAttempt *connectionAttempt; + User *sender,*recipient,*otherUser; + unsigned int i; + for (i=0; i < user->connectionAttempts.Size(); i++) + { + connectionAttempt=user->connectionAttempts[i]; + if (connectionAttempt->sender==user) + { + otherUser=connectionAttempt->recipient; + sender=user; + recipient=otherUser; + } + else + { + otherUser=connectionAttempt->sender; + recipient=user; + sender=otherUser; + } + + if (otherUser->isReady) + { + if (natPunchthroughServerDebugInterface) + { + char str[1024]; + char addr1[128], addr2[128]; + sender->systemAddress.ToString(true,addr1); + recipient->systemAddress.ToString(true,addr2); + sprintf(str, "Sending NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS to sender %s and recipient %s.", addr1, addr2); + natPunchthroughServerDebugInterface->OnServerMessage(str); + } + + sender->isReady=false; + recipient->isReady=false; + connectionAttempt->attemptPhase=ConnectionAttempt::NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS; + connectionAttempt->startTime=RakNet::GetTime(); + + sender->mostRecentPort=0; + recipient->mostRecentPort=0; + + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_NAT_GET_MOST_RECENT_PORT); + // 4/29/09 Write sessionID so we don't use returned port for a system we don't want + outgoingBs.Write(connectionAttempt->sessionId); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,sender->systemAddress,false); + rakPeerInterface->Send(&outgoingBs,HIGH_PRIORITY,RELIABLE_ORDERED,0,recipient->systemAddress,false); + + // 4/22/09 - BUG: missing break statement here + break; + } + } +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/NatTypeDetectionClient.cpp b/src/raknet/NatTypeDetectionClient.cpp new file mode 100644 index 0000000..d07743c --- /dev/null +++ b/src/raknet/NatTypeDetectionClient.cpp @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatTypeDetectionClient==1 + +#include "include/raknet/NatTypeDetectionClient.hpp" +#include "include/raknet/RakNetSmartPtr.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/SocketIncludes.hpp" +#include "include/raknet/RakString.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/SocketDefines.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(NatTypeDetectionClient,NatTypeDetectionClient); + +NatTypeDetectionClient::NatTypeDetectionClient() +{ + c2=0; +} +NatTypeDetectionClient::~NatTypeDetectionClient() +{ + if (c2!=0) + { + RakNet::OP_DELETE(c2,_FILE_AND_LINE_); + } +} +void NatTypeDetectionClient::DetectNATType(SystemAddress _serverAddress) +{ + if (IsInProgress()) + return; + + if (c2==0) + { + DataStructures::List sockets; + rakPeerInterface->GetSockets(sockets); + //SystemAddress sockAddr; + //SocketLayer::GetSystemAddress(sockets[0], &sockAddr); + char str[64]; + //sockAddr.ToString(false,str); + sockets[0]->GetBoundAddress().ToString(false,str); + c2=CreateNonblockingBoundSocket(str +#ifdef __native_client__ + , sockets[0]->chromeInstance +#endif + ,this + ); + //c2Port=SocketLayer::GetLocalPort(c2); + } + +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + if (c2->IsBerkleySocket()) + ((RNS2_Berkley*) c2)->CreateRecvPollingThread(0); +#endif + + serverAddress=_serverAddress; + + RakNet::BitStream bs; + bs.Write((unsigned char)ID_NAT_TYPE_DETECTION_REQUEST); + bs.Write(true); // IsRequest + bs.Write(c2->GetBoundAddress().GetPort()); + rakPeerInterface->Send(&bs,MEDIUM_PRIORITY,RELIABLE,0,serverAddress,false); +} +void NatTypeDetectionClient::OnCompletion(NATTypeDetectionResult result) +{ + Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)*2); + //printf("Returning nat detection result to the user\n"); + p->data[0]=ID_NAT_TYPE_DETECTION_RESULT; + p->systemAddress=serverAddress; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=rakPeerInterface->GetGuidFromSystemAddress(serverAddress); + p->data[1]=(unsigned char) result; + p->wasGeneratedLocally=true; + rakPeerInterface->PushBackPacket(p, true); + + // Symmetric and port restricted are determined by server, so no need to notify server we are done + if (result!=NAT_TYPE_PORT_RESTRICTED && result!=NAT_TYPE_SYMMETRIC) + { + // Otherwise tell the server we got this message, so it stops sending tests to us + RakNet::BitStream bs; + bs.Write((unsigned char)ID_NAT_TYPE_DETECTION_REQUEST); + bs.Write(false); // Done + rakPeerInterface->Send(&bs,HIGH_PRIORITY,RELIABLE,0,serverAddress,false); + } + + Shutdown(); +} +bool NatTypeDetectionClient::IsInProgress(void) const +{ + return serverAddress!=UNASSIGNED_SYSTEM_ADDRESS; +} +void NatTypeDetectionClient::Update(void) +{ + if (IsInProgress()) + { + RNS2RecvStruct *recvStruct; + bufferedPacketsMutex.Lock(); + if (bufferedPackets.Size()>0) + recvStruct=bufferedPackets.Pop(); + else + recvStruct=0; + bufferedPacketsMutex.Unlock(); + while (recvStruct) + { + if (recvStruct->bytesRead==1 && recvStruct->data[0]==NAT_TYPE_NONE) + { + OnCompletion(NAT_TYPE_NONE); + RakAssert(IsInProgress()==false); + } + DeallocRNS2RecvStruct(recvStruct, _FILE_AND_LINE_); + + bufferedPacketsMutex.Lock(); + if (bufferedPackets.Size()>0) + recvStruct=bufferedPackets.Pop(); + else + recvStruct=0; + bufferedPacketsMutex.Unlock(); + } + } +} +PluginReceiveResult NatTypeDetectionClient::OnReceive(Packet *packet) +{ + if (IsInProgress()) + { + switch (packet->data[0]) + { + case ID_OUT_OF_BAND_INTERNAL: + { + if (packet->length>=3 && packet->data[1]==ID_NAT_TYPE_DETECT) + { + OnCompletion((NATTypeDetectionResult)packet->data[2]); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + break; + case ID_NAT_TYPE_DETECTION_RESULT: + if (packet->wasGeneratedLocally==false) + { + OnCompletion((NATTypeDetectionResult)packet->data[1]); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + else + break; + case ID_NAT_TYPE_DETECTION_REQUEST: + OnTestPortRestricted(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + + return RR_CONTINUE_PROCESSING; +} +void NatTypeDetectionClient::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) rakNetGUID; + + if (IsInProgress() && systemAddress==serverAddress) + Shutdown(); +} +void NatTypeDetectionClient::OnRakPeerShutdown(void) +{ + Shutdown(); +} +void NatTypeDetectionClient::OnDetach(void) +{ + Shutdown(); +} +void NatTypeDetectionClient::OnTestPortRestricted(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + RakNet::RakString s3p4StrAddress; + bsIn.Read(s3p4StrAddress); + unsigned short s3p4Port; + bsIn.Read(s3p4Port); + + DataStructures::List sockets; + rakPeerInterface->GetSockets(sockets); + SystemAddress s3p4Addr = sockets[0]->GetBoundAddress(); + s3p4Addr.FromStringExplicitPort(s3p4StrAddress.C_String(), s3p4Port); + + // Send off the RakNet socket to the specified address, message is unformatted + // Server does this twice, so don't have to unduly worry about packetloss + RakNet::BitStream bsOut; + bsOut.Write((MessageID) NAT_TYPE_PORT_RESTRICTED); + bsOut.Write(rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); +// SocketLayer::SendTo_PC( sockets[0], (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), s3p4Addr, __FILE__, __LINE__ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) bsOut.GetData(); + bsp.length = bsOut.GetNumberOfBytesUsed(); + bsp.systemAddress=s3p4Addr; + sockets[0]->Send(&bsp, _FILE_AND_LINE_); + +} +void NatTypeDetectionClient::Shutdown(void) +{ + serverAddress=UNASSIGNED_SYSTEM_ADDRESS; + if (c2!=0) + { +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + if (c2->IsBerkleySocket()) + ((RNS2_Berkley *)c2)->BlockOnStopRecvPollingThread(); +#endif + + RakNet::OP_DELETE(c2, _FILE_AND_LINE_); + c2=0; + } + + bufferedPacketsMutex.Lock(); + while (bufferedPackets.Size()) + RakNet::OP_DELETE(bufferedPackets.Pop(), _FILE_AND_LINE_); + bufferedPacketsMutex.Unlock(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void NatTypeDetectionClient::DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line) +{ + RakNet::OP_DELETE(s, file, line); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RNS2RecvStruct *NatTypeDetectionClient::AllocRNS2RecvStruct(const char *file, unsigned int line) +{ + return RakNet::OP_NEW(file,line); +} +void NatTypeDetectionClient::OnRNS2Recv(RNS2RecvStruct *recvStruct) +{ + bufferedPacketsMutex.Lock(); + bufferedPackets.Push(recvStruct,_FILE_AND_LINE_); + bufferedPacketsMutex.Unlock(); +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/NatTypeDetectionCommon.cpp b/src/raknet/NatTypeDetectionCommon.cpp new file mode 100644 index 0000000..0c85818 --- /dev/null +++ b/src/raknet/NatTypeDetectionCommon.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NatTypeDetectionCommon.hpp" + +#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 + +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/SocketIncludes.hpp" +#include "include/raknet/SocketDefines.hpp" + +using namespace RakNet; + +bool RakNet::CanConnect(NATTypeDetectionResult type1, NATTypeDetectionResult type2) +{ + /// If one system is NAT_TYPE_SYMMETRIC, the other must be NAT_TYPE_ADDRESS_RESTRICTED or less + /// If one system is NAT_TYPE_PORT_RESTRICTED, the other must be NAT_TYPE_PORT_RESTRICTED or less + bool connectionGraph[NAT_TYPE_COUNT][NAT_TYPE_COUNT] = + { + // None, Full Cone, Address Restricted, Port Restricted, Symmetric, Unknown, InProgress, Supports_UPNP + {true, true, true, true, true, false, false, true}, // None + {true, true, true, true, true, false, false, true}, // Full Cone + {true, true, true, true, true, false, false, true}, // Address restricted + {true, true, true, true, false, false, false, true}, // Port restricted + {true, true, true, false, false, false, false, true}, // Symmetric + {false, false, false, false, false, false, false, false}, // Unknown + {false, false, false, false, false, false, false, false}, // InProgress + {true, true, true, true, true, false, false, true} // Supports_UPNP + }; + + return connectionGraph[(int) type1][(int) type2]; +} + +const char *RakNet::NATTypeDetectionResultToString(NATTypeDetectionResult type) +{ + switch (type) + { + case NAT_TYPE_NONE: + return "None"; + case NAT_TYPE_FULL_CONE: + return "Full cone"; + case NAT_TYPE_ADDRESS_RESTRICTED: + return "Address restricted"; + case NAT_TYPE_PORT_RESTRICTED: + return "Port restricted"; + case NAT_TYPE_SYMMETRIC: + return "Symmetric"; + case NAT_TYPE_UNKNOWN: + return "Unknown"; + case NAT_TYPE_DETECTION_IN_PROGRESS: + return "In Progress"; + case NAT_TYPE_SUPPORTS_UPNP: + return "Supports UPNP"; + case NAT_TYPE_COUNT: + return "NAT_TYPE_COUNT"; + } + return "Error, unknown enum in NATTypeDetectionResult"; +} + +// None and relaxed can connect to anything +// Moderate can connect to moderate or less +// Strict can connect to relaxed or less +const char *RakNet::NATTypeDetectionResultToStringFriendly(NATTypeDetectionResult type) +{ + switch (type) + { + case NAT_TYPE_NONE: + return "Open"; + case NAT_TYPE_FULL_CONE: + return "Relaxed"; + case NAT_TYPE_ADDRESS_RESTRICTED: + return "Relaxed"; + case NAT_TYPE_PORT_RESTRICTED: + return "Moderate"; + case NAT_TYPE_SYMMETRIC: + return "Strict"; + case NAT_TYPE_UNKNOWN: + return "Unknown"; + case NAT_TYPE_DETECTION_IN_PROGRESS: + return "In Progress"; + case NAT_TYPE_SUPPORTS_UPNP: + return "Supports UPNP"; + case NAT_TYPE_COUNT: + return "NAT_TYPE_COUNT"; + } + return "Error, unknown enum in NATTypeDetectionResult"; +} + + +RakNetSocket2* RakNet::CreateNonblockingBoundSocket(const char *bindAddr +#ifdef __native_client__ + ,_PP_Instance_ chromeInstance +#endif + , RNS2EventHandler *eventHandler + ) +{ + RakNetSocket2 *r2 = RakNetSocket2Allocator::AllocRNS2(); +#if defined(__native_client__) + NativeClientBindParameters ncbp; + RNS2_NativeClient * nativeClientSocket = (RNS2_NativeClient*) r2; + ncbp.eventHandler=eventHandler; + ncbp.forceHostAddress=(char*) bindAddr; + ncbp.is_ipv6=false; + ncbp.nativeClientInstance=chromeInstance; + ncbp.port=0; + nativeClientSocket->Bind(&ncbp, _FILE_AND_LINE_); +#elif defined(WINDOWS_STORE_RT) + RakAssert("TODO" && 0); +#else + if (r2->IsBerkleySocket()) + { + RNS2_BerkleyBindParameters bbp; + bbp.port=0; + bbp.hostAddress=(char*)bindAddr; + bbp.addressFamily=AF_INET; + bbp.type=SOCK_DGRAM; + bbp.protocol=0; + bbp.nonBlockingSocket=true; + bbp.setBroadcast=true; + bbp.setIPHdrIncl=false; + bbp.doNotFragment=false; + bbp.pollingThreadPriority=0; + bbp.eventHandler=eventHandler; + bbp.remotePortRakNetWasStartedOn_PS3_PS4_PSP2=0; + RNS2BindResult br = ((RNS2_Berkley*) r2)->Bind(&bbp, _FILE_AND_LINE_); + + if (br==BR_FAILED_TO_BIND_SOCKET) + { + RakNetSocket2Allocator::DeallocRNS2(r2); + return 0; + } + else if (br==BR_FAILED_SEND_TEST) + { + RakNetSocket2Allocator::DeallocRNS2(r2); + return 0; + } + else + { + RakAssert(br==BR_SUCCESS); + } + + ((RNS2_Berkley*) r2)->CreateRecvPollingThread(0); + } + else + { + RakAssert("TODO" && 0); + } +#endif + + return r2; + + /* + #ifdef __native_client__ + RakNetSocket2 *s = SocketLayer::CreateBoundSocket( 0, 0, false, bindAddr, true, 0, AF_INET, chromeInstance ); + #else + RakNetSocket2 *s = SocketLayer::CreateBoundSocket( 0, 0, false, bindAddr, true, 0, AF_INET, 0 ); + #endif + + #ifdef _WIN32 + unsigned long nonblocking = 1; + s->IOCTLSocket( FIONBIO, &nonblocking ); + #elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) || defined(SN_TARGET_PSP2) + int sock_opt=1; + s->SetSockOpt(SOL_SOCKET, SO_NBIO, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + #elif defined(__native_client__) + // Nop + #else + s->Fcntl( F_SETFL, O_NONBLOCK ); + #endif + return s; + */ +} + +/* +int RakNet::NatTypeRecvFrom(char *data, RakNetSocket2* socket, SystemAddress &sender, RNS2EventHandler *eventHandler) +{ +#if defined(__native_client__) + RakAssert("TODO" && 0); +#elif defined(WINDOWS_STORE_RT) + RakAssert("TODO" && 0); +#else + if (socket->IsBerkleySocket()) + { + RNS2RecvStruct *recvFromStruct; + recvFromStruct=AllocRNS2RecvStruct(_FILE_AND_LINE_); + if (recvFromStruct != NULL) + { + recvFromStruct->socket=this; + socket->RecvFromBlocking(recvFromStruct); + } + if (recvFromStruct->bytesRead>0) + { + sender = recvFromStruct->systemAddress; + } + return recvFromStruct->bytesRead; + } + return 0; +#endif +} +*/ + +#endif // #if _RAKNET_SUPPORT_NatTypeDetectionServer==1 || _RAKNET_SUPPORT_NatTypeDetectionClient==1 diff --git a/src/raknet/NatTypeDetectionServer.cpp b/src/raknet/NatTypeDetectionServer.cpp new file mode 100644 index 0000000..4927de2 --- /dev/null +++ b/src/raknet/NatTypeDetectionServer.cpp @@ -0,0 +1,438 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_NatTypeDetectionServer==1 + +#include "include/raknet/NatTypeDetectionServer.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/RakNetSmartPtr.hpp" +#include "include/raknet/SocketIncludes.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/SocketDefines.hpp" + +// #define NTDS_VERBOSE + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(NatTypeDetectionServer,NatTypeDetectionServer); + +NatTypeDetectionServer::NatTypeDetectionServer() +{ + s1p2=s2p3=s3p4=s4p5=0; +} +NatTypeDetectionServer::~NatTypeDetectionServer() +{ + Shutdown(); +} +void NatTypeDetectionServer::Startup( + const char *nonRakNetIP2, + const char *nonRakNetIP3, + const char *nonRakNetIP4 +#ifdef __native_client__ + ,_PP_Instance_ chromeInstance +#endif + ) +{ + DataStructures::List sockets; + rakPeerInterface->GetSockets(sockets); + char str[64]; + sockets[0]->GetBoundAddress().ToString(false,str); + s1p2= + CreateNonblockingBoundSocket(str, +#ifdef __native_client__ + chromeInstance, +#endif + this); + + s2p3= + CreateNonblockingBoundSocket(nonRakNetIP2, +#ifdef __native_client__ + chromeInstance, +#endif + this); + + + s3p4= + CreateNonblockingBoundSocket(nonRakNetIP3, +#ifdef __native_client__ + chromeInstance, +#endif + this); + + s4p5= + CreateNonblockingBoundSocket(nonRakNetIP4, +#ifdef __native_client__ + chromeInstance, +#endif + this); + + strcpy(s3p4Address, nonRakNetIP3); + + + #if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + if (s3p4->IsBerkleySocket()) + ((RNS2_Berkley*) s3p4)->CreateRecvPollingThread(0); + #endif +} +void NatTypeDetectionServer::Shutdown() +{ + if (s1p2!=0) + { + RakNet::OP_DELETE(s1p2,_FILE_AND_LINE_); + s1p2=0; + } + if (s2p3!=0) + { + RakNet::OP_DELETE(s2p3,_FILE_AND_LINE_); + s2p3=0; + } + if (s3p4!=0) + { +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + if (s3p4->IsBerkleySocket()) + ((RNS2_Berkley *)s3p4)->BlockOnStopRecvPollingThread(); +#endif + + RakNet::OP_DELETE(s3p4,_FILE_AND_LINE_); + s3p4=0; + } + if (s4p5!=0) + { + RakNet::OP_DELETE(s4p5,_FILE_AND_LINE_); + s4p5=0; + } + bufferedPacketsMutex.Lock(); + while (bufferedPackets.Size()) + RakNet::OP_DELETE(bufferedPackets.Pop(), _FILE_AND_LINE_); + bufferedPacketsMutex.Unlock(); +} +void NatTypeDetectionServer::Update(void) +{ + int i=0; + RakNet::TimeMS time = RakNet::GetTimeMS(); + RakNet::BitStream bs; + SystemAddress boundAddress; + + RNS2RecvStruct *recvStruct; + bufferedPacketsMutex.Lock(); + if (bufferedPackets.Size()>0) + recvStruct=bufferedPackets.Pop(); + else + recvStruct=0; + bufferedPacketsMutex.Unlock(); + while (recvStruct) + { + SystemAddress senderAddr = recvStruct->systemAddress; + char *data = recvStruct->data; + if (data[0]==NAT_TYPE_PORT_RESTRICTED && recvStruct->socket==s3p4) + { + RakNet::BitStream bsIn((unsigned char*) data,recvStruct->bytesRead,false); + RakNetGUID senderGuid; + bsIn.IgnoreBytes(sizeof(MessageID)); + bool readSuccess = bsIn.Read(senderGuid); + RakAssert(readSuccess); + if (readSuccess) + { + unsigned int i = GetDetectionAttemptIndex(senderGuid); + if (i!=(unsigned int)-1) + { + bs.Reset(); + bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_RESULT); + // If different, then symmetric + if (senderAddr!=natDetectionAttempts[i].systemAddress) + { + +#ifdef NTDS_VERBOSE + printf("Determined client is symmetric\n"); +#endif + bs.Write((unsigned char) NAT_TYPE_SYMMETRIC); + } + else + { + // else port restricted +#ifdef NTDS_VERBOSE + + printf("Determined client is port restricted\n"); +#endif + bs.Write((unsigned char) NAT_TYPE_PORT_RESTRICTED); + } + + rakPeerInterface->Send(&bs,HIGH_PRIORITY,RELIABLE,0,natDetectionAttempts[i].systemAddress,false); + + // Done + natDetectionAttempts.RemoveAtIndexFast(i); + } + else + { + // RakAssert("i==0 in Update when looking up GUID in NatTypeDetectionServer.cpp. Either a bug or a late resend" && 0); + } + } + else + { + // RakAssert("Didn't read GUID in Update in NatTypeDetectionServer.cpp. Message format error" && 0); + } + } + + DeallocRNS2RecvStruct(recvStruct, _FILE_AND_LINE_); + bufferedPacketsMutex.Lock(); + if (bufferedPackets.Size()>0) + recvStruct=bufferedPackets.Pop(); + else + recvStruct=0; + bufferedPacketsMutex.Unlock(); + } + + /* + + // Only socket that receives messages is s3p4, to see if the external address is different than that of the connection to rakPeerInterface + char data[ MAXIMUM_MTU_SIZE ]; + int len; + SystemAddress senderAddr; + len=NatTypeRecvFrom(data, s3p4, senderAddr); + // Client is asking us if this is port restricted. Only client requests of this type come in on s3p4 + while (len>0 && data[0]==NAT_TYPE_PORT_RESTRICTED) + { + RakNet::BitStream bsIn((unsigned char*) data,len,false); + RakNetGUID senderGuid; + bsIn.IgnoreBytes(sizeof(MessageID)); + bool readSuccess = bsIn.Read(senderGuid); + RakAssert(readSuccess); + if (readSuccess) + { + unsigned int i = GetDetectionAttemptIndex(senderGuid); + if (i!=(unsigned int)-1) + { + bs.Reset(); + bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_RESULT); + // If different, then symmetric + if (senderAddr!=natDetectionAttempts[i].systemAddress) + { + + #ifdef NTDS_VERBOSE + printf("Determined client is symmetric\n"); + #endif + bs.Write((unsigned char) NAT_TYPE_SYMMETRIC); + } + else + { + // else port restricted + + #ifdef NTDS_VERBOSE + printf("Determined client is port restricted\n"); + #endif + bs.Write((unsigned char) NAT_TYPE_PORT_RESTRICTED); + } + + rakPeerInterface->Send(&bs,HIGH_PRIORITY,RELIABLE,0,natDetectionAttempts[i].systemAddress,false); + + // Done + natDetectionAttempts.RemoveAtIndexFast(i); + } + else + { + // RakAssert("i==0 in Update when looking up GUID in NatTypeDetectionServer.cpp. Either a bug or a late resend" && 0); + } + } + else + { + // RakAssert("Didn't read GUID in Update in NatTypeDetectionServer.cpp. Message format error" && 0); + } + + len=NatTypeRecvFrom(data, s3p4, senderAddr); + } + */ + + + while (i < (int) natDetectionAttempts.Size()) + { + if (time > natDetectionAttempts[i].nextStateTime) + { + RNS2_SendParameters bsp; + natDetectionAttempts[i].detectionState=(NATDetectionState)((int)natDetectionAttempts[i].detectionState+1); + natDetectionAttempts[i].nextStateTime=time+natDetectionAttempts[i].timeBetweenAttempts; + SystemAddress saOut; + unsigned char c; + bs.Reset(); + switch (natDetectionAttempts[i].detectionState) + { + case STATE_TESTING_NONE_1: + case STATE_TESTING_NONE_2: + c = NAT_TYPE_NONE; + +#ifdef NTDS_VERBOSE + printf("Testing NAT_TYPE_NONE\n"); +#endif + // S4P5 sends to C2. If arrived, no NAT. Done. (Else S4P5 potentially banned, do not use again). + saOut=natDetectionAttempts[i].systemAddress; + saOut.SetPortHostOrder(natDetectionAttempts[i].c2Port); + // SocketLayer::SendTo_PC( s4p5, (const char*) &c, 1, saOut, __FILE__, __LINE__ ); + bsp.data = (char*) &c; + bsp.length = 1; + bsp.systemAddress = saOut; + s4p5->Send(&bsp, _FILE_AND_LINE_); + break; + case STATE_TESTING_FULL_CONE_1: + case STATE_TESTING_FULL_CONE_2: + +#ifdef NTDS_VERBOSE + printf("Testing NAT_TYPE_FULL_CONE\n"); +#endif + rakPeerInterface->WriteOutOfBandHeader(&bs); + bs.Write((unsigned char) ID_NAT_TYPE_DETECT); + bs.Write((unsigned char) NAT_TYPE_FULL_CONE); + // S2P3 sends to C1 (Different address, different port, to previously used port on client). If received, Full-cone nat. Done. (Else S2P3 potentially banned, do not use again). + saOut=natDetectionAttempts[i].systemAddress; + saOut.SetPortHostOrder(natDetectionAttempts[i].systemAddress.GetPort()); + // SocketLayer::SendTo_PC( s2p3, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), saOut, __FILE__, __LINE__ ); + bsp.data = (char*) bs.GetData(); + bsp.length = bs.GetNumberOfBytesUsed(); + bsp.systemAddress = saOut; + s2p3->Send(&bsp, _FILE_AND_LINE_); + break; + case STATE_TESTING_ADDRESS_RESTRICTED_1: + case STATE_TESTING_ADDRESS_RESTRICTED_2: + +#ifdef NTDS_VERBOSE + printf("Testing NAT_TYPE_ADDRESS_RESTRICTED\n"); +#endif + rakPeerInterface->WriteOutOfBandHeader(&bs); + bs.Write((unsigned char) ID_NAT_TYPE_DETECT); + bs.Write((unsigned char) NAT_TYPE_ADDRESS_RESTRICTED); + // S1P2 sends to C1 (Same address, different port, to previously used port on client). If received, address-restricted cone nat. Done. + saOut=natDetectionAttempts[i].systemAddress; + saOut.SetPortHostOrder(natDetectionAttempts[i].systemAddress.GetPort()); + //SocketLayer::SendTo_PC( s1p2, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), saOut, __FILE__, __LINE__ ); + bsp.data = (char*) bs.GetData(); + bsp.length = bs.GetNumberOfBytesUsed(); + bsp.systemAddress = saOut; + s1p2->Send(&bsp, _FILE_AND_LINE_); + break; + case STATE_TESTING_PORT_RESTRICTED_1: + case STATE_TESTING_PORT_RESTRICTED_2: + // C1 sends to S3P4. If address of C1 as seen by S3P4 is the same as the address of C1 as seen by S1P1, then port-restricted cone nat. Done + +#ifdef NTDS_VERBOSE + printf("Testing NAT_TYPE_PORT_RESTRICTED\n"); +#endif + bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_REQUEST); + bs.Write(RakString::NonVariadic(s3p4Address)); + bs.Write(s3p4->GetBoundAddress().GetPort()); + rakPeerInterface->Send(&bs,HIGH_PRIORITY,RELIABLE,0,natDetectionAttempts[i].systemAddress,false); + break; + default: + +#ifdef NTDS_VERBOSE + printf("Warning, exceeded final check STATE_TESTING_PORT_RESTRICTED_2.\nExpected that client would have sent NAT_TYPE_PORT_RESTRICTED on s3p4.\nDefaulting to Symmetric\n"); +#endif + bs.Write((unsigned char) ID_NAT_TYPE_DETECTION_RESULT); + bs.Write((unsigned char) NAT_TYPE_SYMMETRIC); + rakPeerInterface->Send(&bs,HIGH_PRIORITY,RELIABLE,0,natDetectionAttempts[i].systemAddress,false); + natDetectionAttempts.RemoveAtIndexFast(i); + i--; + break; + } + + } + i++; + } +} +PluginReceiveResult NatTypeDetectionServer::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_NAT_TYPE_DETECTION_REQUEST: + OnDetectionRequest(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + return RR_CONTINUE_PROCESSING; +} +void NatTypeDetectionServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) rakNetGUID; + + unsigned int i = GetDetectionAttemptIndex(systemAddress); + if (i==(unsigned int)-1) + return; + natDetectionAttempts.RemoveAtIndexFast(i); +} +void NatTypeDetectionServer::OnDetectionRequest(Packet *packet) +{ + unsigned int i = GetDetectionAttemptIndex(packet->systemAddress); + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(1); + bool isRequest=false; + bsIn.Read(isRequest); + if (isRequest) + { + if (i!=(unsigned int)-1) + return; // Already in progress + + NATDetectionAttempt nda; + nda.detectionState=STATE_NONE; + nda.systemAddress=packet->systemAddress; + nda.guid=packet->guid; + bsIn.Read(nda.c2Port); + nda.nextStateTime=0; + nda.timeBetweenAttempts=rakPeerInterface->GetLastPing(nda.systemAddress)*3+50; + natDetectionAttempts.Push(nda, _FILE_AND_LINE_); + } + else + { + if (i==(unsigned int)-1) + return; // Unknown + // They are done + natDetectionAttempts.RemoveAtIndexFast(i); + } + +} +unsigned int NatTypeDetectionServer::GetDetectionAttemptIndex(const SystemAddress &sa) +{ + for (unsigned int i=0; i < natDetectionAttempts.Size(); i++) + { + if (natDetectionAttempts[i].systemAddress==sa) + return i; + } + return (unsigned int) -1; +} +unsigned int NatTypeDetectionServer::GetDetectionAttemptIndex(RakNetGUID guid) +{ + for (unsigned int i=0; i < natDetectionAttempts.Size(); i++) + { + if (natDetectionAttempts[i].guid==guid) + return i; + } + return (unsigned int) -1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void NatTypeDetectionServer::DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line) +{ + RakNet::OP_DELETE(s, file, line); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RNS2RecvStruct *NatTypeDetectionServer::AllocRNS2RecvStruct(const char *file, unsigned int line) +{ + return RakNet::OP_NEW(file,line); +} + +void NatTypeDetectionServer::OnRNS2Recv(RNS2RecvStruct *recvStruct) +{ + bufferedPacketsMutex.Lock(); + bufferedPackets.Push(recvStruct,_FILE_AND_LINE_); + bufferedPacketsMutex.Unlock(); +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/NetworkIDManager.cpp b/src/raknet/NetworkIDManager.cpp new file mode 100644 index 0000000..06dc37e --- /dev/null +++ b/src/raknet/NetworkIDManager.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#include "include/raknet/NetworkIDManager.hpp" +#include "include/raknet/NetworkIDObject.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/RakSleep.hpp" +#include "include/raknet/SuperFastHash.hpp" +#include "include/raknet/RakPeerInterface.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(NetworkIDManager,NetworkIDManager) + +NetworkIDManager::NetworkIDManager() +{ + startingOffset = RakPeerInterface::Get64BitUniqueRandomNumber(); + Clear(); +} +NetworkIDManager::~NetworkIDManager(void) +{ + +} +void NetworkIDManager::Clear(void) +{ + memset(networkIdHash,0,sizeof(networkIdHash)); +} +NetworkIDObject *NetworkIDManager::GET_BASE_OBJECT_FROM_ID(NetworkID x) +{ + unsigned int hashIndex=NetworkIDToHashIndex(x); + NetworkIDObject *nio=networkIdHash[hashIndex]; + while (nio) + { + if (nio->GetNetworkID()==x) + return nio; + nio=nio->nextInstanceForNetworkIDManager; + } + return 0; +} +NetworkID NetworkIDManager::GetNewNetworkID(void) +{ + while (GET_BASE_OBJECT_FROM_ID(++startingOffset)) + ; + if (startingOffset==UNASSIGNED_NETWORK_ID) + { + while (GET_BASE_OBJECT_FROM_ID(++startingOffset)) + ; + } + return startingOffset; +} +unsigned int NetworkIDManager::NetworkIDToHashIndex(NetworkID networkId) +{ +// return SuperFastHash((const char*) &networkId.guid.g,sizeof(networkId.guid.g)) % NETWORK_ID_MANAGER_HASH_LENGTH; + return (unsigned int) (networkId % NETWORK_ID_MANAGER_HASH_LENGTH); +} +void NetworkIDManager::TrackNetworkIDObject(NetworkIDObject *networkIdObject) +{ + RakAssert(networkIdObject->GetNetworkIDManager()==this); + NetworkID rawId = networkIdObject->GetNetworkID(); + RakAssert(rawId!=UNASSIGNED_NETWORK_ID); + + networkIdObject->nextInstanceForNetworkIDManager=0; + + unsigned int hashIndex=NetworkIDToHashIndex(rawId); +// printf("TrackNetworkIDObject hashIndex=%i guid=%s\n",hashIndex, networkIdObject->GetNetworkID().guid.ToString()); // removeme + if (networkIdHash[hashIndex]==0) + { + networkIdHash[hashIndex]=networkIdObject; + return; + } + NetworkIDObject *nio=networkIdHash[hashIndex]; + // Duplicate insertion? + RakAssert(nio!=networkIdObject); + // Random GUID conflict? + RakAssert(nio->GetNetworkID()!=rawId); + + while (nio->nextInstanceForNetworkIDManager!=0) + { + nio=nio->nextInstanceForNetworkIDManager; + + // Duplicate insertion? + RakAssert(nio!=networkIdObject); + // Random GUID conflict? + RakAssert(nio->GetNetworkID()!=rawId); + } + + nio->nextInstanceForNetworkIDManager=networkIdObject; +} +void NetworkIDManager::StopTrackingNetworkIDObject(NetworkIDObject *networkIdObject) +{ + RakAssert(networkIdObject->GetNetworkIDManager()==this); + NetworkID rawId = networkIdObject->GetNetworkID(); + RakAssert(rawId!=UNASSIGNED_NETWORK_ID); + + // RakAssert(networkIdObject->GetNetworkID()!=UNASSIGNED_NETWORK_ID); + unsigned int hashIndex=NetworkIDToHashIndex(rawId); +// printf("hashIndex=%i\n",hashIndex); // removeme + NetworkIDObject *nio=networkIdHash[hashIndex]; + if (nio==0) + { + RakAssert("NetworkIDManager::StopTrackingNetworkIDObject didn't find object" && 0); + return; + } + if (nio==networkIdObject) + { + networkIdHash[hashIndex]=nio->nextInstanceForNetworkIDManager; + return; + } + + while (nio) + { + if (nio->nextInstanceForNetworkIDManager==networkIdObject) + { + nio->nextInstanceForNetworkIDManager=networkIdObject->nextInstanceForNetworkIDManager; + return; + } + nio=nio->nextInstanceForNetworkIDManager; + } + + RakAssert("NetworkIDManager::StopTrackingNetworkIDObject didn't find object" && 0); +} diff --git a/src/raknet/NetworkIDObject.cpp b/src/raknet/NetworkIDObject.cpp new file mode 100644 index 0000000..79352dd --- /dev/null +++ b/src/raknet/NetworkIDObject.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#include "include/raknet/NetworkIDObject.hpp" +#include "include/raknet/NetworkIDManager.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakAlloca.hpp" + +using namespace RakNet; + +NetworkIDObject::NetworkIDObject() +{ + networkID=UNASSIGNED_NETWORK_ID; + parent=0; + networkIDManager=0; + nextInstanceForNetworkIDManager=0; +} +NetworkIDObject::~NetworkIDObject() +{ + if (networkIDManager) + networkIDManager->StopTrackingNetworkIDObject(this); +} +void NetworkIDObject::SetNetworkIDManager( NetworkIDManager *manager) +{ + if (manager==networkIDManager) + return; + + if (networkIDManager) + networkIDManager->StopTrackingNetworkIDObject(this); + + networkIDManager=manager; + if (networkIDManager==0) + { + networkID = UNASSIGNED_NETWORK_ID; + return; + } + + if (networkID == UNASSIGNED_NETWORK_ID) + { + // Prior ID not set + networkID = networkIDManager->GetNewNetworkID(); + } + + networkIDManager->TrackNetworkIDObject(this); +} +NetworkIDManager * NetworkIDObject::GetNetworkIDManager( void ) const +{ + return networkIDManager; +} +NetworkID NetworkIDObject::GetNetworkID( void ) +{ + return networkID; +} +void NetworkIDObject::SetNetworkID( NetworkID id ) +{ + if (networkID==id) + return; + + if ( id == UNASSIGNED_NETWORK_ID ) + { + SetNetworkIDManager(0); + return; + } + + if ( networkIDManager ) + networkIDManager->StopTrackingNetworkIDObject(this); + + networkID = id; + + if (networkIDManager) + networkIDManager->TrackNetworkIDObject(this); +} +void NetworkIDObject::SetParent( void *_parent ) +{ + parent=_parent; +} +void* NetworkIDObject::GetParent( void ) const +{ + return parent; +} diff --git a/src/raknet/PS4Includes.cpp b/src/raknet/PS4Includes.cpp new file mode 100644 index 0000000..ad3f39d --- /dev/null +++ b/src/raknet/PS4Includes.cpp @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/raknet/PacketConsoleLogger.cpp b/src/raknet/PacketConsoleLogger.cpp new file mode 100644 index 0000000..e23f29f --- /dev/null +++ b/src/raknet/PacketConsoleLogger.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_LogCommandParser==1 && _RAKNET_SUPPORT_PacketLogger==1 +#include "include/raknet/PacketConsoleLogger.hpp" +#include "include/raknet/LogCommandParser.hpp" +#include + +using namespace RakNet; + +PacketConsoleLogger::PacketConsoleLogger() +{ + logCommandParser=0; +} + +void PacketConsoleLogger::SetLogCommandParser(LogCommandParser *lcp) +{ + logCommandParser=lcp; + if (logCommandParser) + logCommandParser->AddChannel("PacketConsoleLogger"); +} +void PacketConsoleLogger::WriteLog(const char *str) +{ + if (logCommandParser) + logCommandParser->WriteLog("PacketConsoleLogger", str); +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/PacketFileLogger.cpp b/src/raknet/PacketFileLogger.cpp new file mode 100644 index 0000000..68ecde9 --- /dev/null +++ b/src/raknet/PacketFileLogger.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 +#include "include/raknet/PacketFileLogger.hpp" +#include "include/raknet/GetTime.hpp" + +using namespace RakNet; + +PacketFileLogger::PacketFileLogger() +{ + packetLogFile=0; +} +PacketFileLogger::~PacketFileLogger() +{ + if (packetLogFile) + { + fflush(packetLogFile); + fclose(packetLogFile); + } +} +void PacketFileLogger::StartLog(const char *filenamePrefix) +{ + // Open file for writing + char filename[256]; + if (filenamePrefix) + sprintf(filename, "%s_%i.csv", filenamePrefix, (int) RakNet::GetTimeMS()); + else + sprintf(filename, "PacketLog_%i.csv", (int) RakNet::GetTimeMS()); + packetLogFile = fopen(filename, "wt"); + LogHeader(); + if (packetLogFile) + { + fflush(packetLogFile); + } +} + +void PacketFileLogger::WriteLog(const char *str) +{ + if (packetLogFile) + { + fprintf(packetLogFile, "%s\n", str); + fflush(packetLogFile); + } +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/PacketLogger.cpp b/src/raknet/PacketLogger.cpp new file mode 100644 index 0000000..348e9d5 --- /dev/null +++ b/src/raknet/PacketLogger.cpp @@ -0,0 +1,477 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 + +#include "include/raknet/PacketLogger.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/DS_List.hpp" +#include "include/raknet/InternalPacket.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/GetTime.hpp" +#include +#include +#include +#include "include/raknet/Itoa.hpp" +#include +#include "include/raknet/SocketIncludes.hpp" +#include "include/raknet/gettimeofday.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(PacketLogger,PacketLogger); + +PacketLogger::PacketLogger() +{ + printId=true; + printAcks=true; + prefix[0]=0; + suffix[0]=0; + logDirectMessages=true; +} +PacketLogger::~PacketLogger() +{ +} +void PacketLogger::FormatLine( +char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame, unsigned char id +, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, +unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex) +{ + char numericID[16]; + const char* idToPrint = NULL; + if(printId) + { + if (splitPacketCount>0 && splitPacketCount!=(unsigned int)-1) + idToPrint="(SPLIT PACKET)"; + else + idToPrint = IDTOString(id); + } + // If printId is false, idToPrint will be NULL, as it will + // in the case of an unrecognized id. Testing printId for false + // would just be redundant. + if(idToPrint == NULL) + { + sprintf(numericID, "%5u", id); + idToPrint = numericID; + } + + FormatLine(into, dir, type, reliableMessageNumber, frame, idToPrint, bitLen, time, local, remote,splitPacketId,splitPacketIndex,splitPacketCount, orderingIndex); +} + +void PacketLogger::FormatLine( +char* into, const char* dir, const char* type, unsigned int reliableMessageNumber, unsigned int frame, const char* idToPrint +, const BitSize_t bitLen, unsigned long long time, const SystemAddress& local, const SystemAddress& remote, +unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex) +{ + char str1[64], str2[62]; + local.ToString(true, str1); + remote.ToString(true, str2); + char localtime[128]; + GetLocalTime(localtime); + char str3[64]; + if (reliableMessageNumber==(unsigned int)-1) + { + str3[0]='N'; + str3[1]='/'; + str3[2]='A'; + str3[3]=0; + } + else + { + sprintf(str3,"%5u",reliableMessageNumber); + } + + sprintf(into, "%s,%s%s,%s,%s,%5u,%s,%u,%" PRINTF_64_BIT_MODIFIER "u,%s,%s,%i,%i,%i,%i,%s," + , localtime + , prefix + , dir + , type + , str3 + , frame + , idToPrint + , bitLen + , time + , str1 + , str2 + , splitPacketId + , splitPacketIndex + , splitPacketCount + , orderingIndex + , suffix + ); +} +void PacketLogger::OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) +{ + if (logDirectMessages==false) + return; + + char str[256]; + FormatLine(str, "Snd", "Raw", 0, 0, data[0], bitsUsed, RakNet::GetTimeMS(), rakPeerInterface->GetExternalID(remoteSystemAddress), remoteSystemAddress, (unsigned int)-1,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1); + AddToLog(str); +} + +void PacketLogger::LogHeader(void) +{ + // Last 5 are splitpacket id, split packet index, split packet count, ordering index, suffix + AddToLog("Clock,S|R,Typ,Reliable#,Frm #,PktID,BitLn,Time ,Local IP:Port ,RemoteIP:Port,SPID,SPIN,SPCO,OI,Suffix,Miscellaneous\n"); +} +void PacketLogger::OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) +{ + if (logDirectMessages==false) + return; + + char str[256]; + FormatLine(str, "Rcv", "Raw", 0, 0, data[0], bitsUsed, RakNet::GetTime(), rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS), remoteSystemAddress,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1); + AddToLog(str); +} +void PacketLogger::OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError) +{ + char str[1024]; + char *type; + if (isError) + type=(char*) "RcvErr"; + else + type=(char*) "RcvWrn"; + FormatLine(str, type, errorMessage, 0, 0, "", bitsUsed, RakNet::GetTime(), rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS), remoteSystemAddress,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1,(unsigned int)-1); + AddToLog(str); + RakAssert(isError==false); +} +void PacketLogger::OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, RakNet::TimeMS time) +{ + char str[256]; + char str1[64], str2[62]; + SystemAddress localSystemAddress = rakPeerInterface->GetExternalID(remoteSystemAddress); + localSystemAddress.ToString(true, str1); + remoteSystemAddress.ToString(true, str2); + char localtime[128]; + GetLocalTime(localtime); + + sprintf(str, "%s,Rcv,Ack,%i,,,,%" PRINTF_64_BIT_MODIFIER "u,%s,%s,,,,,," + , localtime + , messageNumber + , (unsigned long long) time + , str1 + , str2 + ); + AddToLog(str); +} +void PacketLogger::OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) +{ + char str[256]; + char str1[64], str2[62]; + SystemAddress localSystemAddress = rakPeerInterface->GetExternalID(remoteSystemAddress); + localSystemAddress.ToString(true, str1); + remoteSystemAddress.ToString(true, str2); + RakNet::TimeMS time = RakNet::GetTimeMS(); + char localtime[128]; + GetLocalTime(localtime); + + sprintf(str, "%s,Lcl,PBP,,,%s,%i,%" PRINTF_64_BIT_MODIFIER "u,%s,%s,,,,,," + , localtime + , BaseIDTOString(data[0]) + , bitsUsed + , (unsigned long long) time + , str1 + , str2 + ); + AddToLog(str); +} +void PacketLogger::OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, RakNet::TimeMS time, int isSend) +{ + char str[256]; + const char *sendTypes[] = + { + "Rcv", + "Snd", + "Err1", + "Err2", + "Err3", + "Err4", + "Err5", + "Err6", + }; + const char *sendType = sendTypes[isSend]; + SystemAddress localSystemAddress = rakPeerInterface->GetExternalID(remoteSystemAddress); + + unsigned int reliableMessageNumber; + if (internalPacket->reliability==UNRELIABLE || internalPacket->reliability==UNRELIABLE_SEQUENCED || internalPacket->reliability==UNRELIABLE_WITH_ACK_RECEIPT) + reliableMessageNumber=(unsigned int)-1; + else + reliableMessageNumber=internalPacket->reliableMessageNumber; + + if (internalPacket->data[0]==ID_TIMESTAMP) + { + FormatLine(str, sendType, "Tms", reliableMessageNumber, frameNumber, internalPacket->data[1+sizeof(RakNet::Time)], internalPacket->dataBitLength, (unsigned long long)time, localSystemAddress, remoteSystemAddress, internalPacket->splitPacketId, internalPacket->splitPacketIndex, internalPacket->splitPacketCount, internalPacket->orderingIndex); + } + else + { + FormatLine(str, sendType, "Nrm", reliableMessageNumber, frameNumber, internalPacket->data[0], internalPacket->dataBitLength, (unsigned long long)time, localSystemAddress, remoteSystemAddress, internalPacket->splitPacketId, internalPacket->splitPacketIndex, internalPacket->splitPacketCount, internalPacket->orderingIndex); + } + + AddToLog(str); +} +void PacketLogger::AddToLog(const char *str) +{ + WriteLog(str); +} +void PacketLogger::WriteLog(const char *str) +{ + RAKNET_DEBUG_PRINTF("%s\n", str); +} +void PacketLogger::WriteMiscellaneous(const char *type, const char *msg) +{ + char str[1024]; + char str1[64]; + SystemAddress localSystemAddress = rakPeerInterface->GetInternalID(); + localSystemAddress.ToString(true, str1); + RakNet::TimeMS time = RakNet::GetTimeMS(); + char localtime[128]; + GetLocalTime(localtime); + + sprintf(str, "%s,Lcl,%s,,,,,%" PRINTF_64_BIT_MODIFIER "u,%s,,,,,,,%s" + , localtime + , type + , (unsigned long long) time + , str1 + , msg + ); + + AddToLog(msg); +} +void PacketLogger::SetPrintID(bool print) +{ + printId=print; +} +void PacketLogger::SetPrintAcks(bool print) +{ + printAcks=print; +} +const char* PacketLogger::BaseIDTOString(unsigned char Id) +{ + if (Id >= ID_USER_PACKET_ENUM) + return 0; + + const char *IDTable[((int)ID_USER_PACKET_ENUM)+1]= + { + "ID_CONNECTED_PING", + "ID_UNCONNECTED_PING", + "ID_UNCONNECTED_PING_OPEN_CONNECTIONS", + "ID_CONNECTED_PONG", + "ID_DETECT_LOST_CONNECTIONS", + "ID_OPEN_CONNECTION_REQUEST_1", + "ID_OPEN_CONNECTION_REPLY_1", + "ID_OPEN_CONNECTION_REQUEST_2", + "ID_OPEN_CONNECTION_REPLY_2", + "ID_CONNECTION_REQUEST", + "ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY", + "ID_OUR_SYSTEM_REQUIRES_SECURITY", + "ID_PUBLIC_KEY_MISMATCH", + "ID_OUT_OF_BAND_INTERNAL", + "ID_SND_RECEIPT_ACKED", + "ID_SND_RECEIPT_LOSS", + "ID_CONNECTION_REQUEST_ACCEPTED", + "ID_CONNECTION_ATTEMPT_FAILED", + "ID_ALREADY_CONNECTED", + "ID_NEW_INCOMING_CONNECTION", + "ID_NO_FREE_INCOMING_CONNECTIONS", + "ID_DISCONNECTION_NOTIFICATION", + "ID_CONNECTION_LOST", + "ID_CONNECTION_BANNED", + "ID_INVALID_PASSWORD", + "ID_INCOMPATIBLE_PROTOCOL_VERSION", + "ID_IP_RECENTLY_CONNECTED", + "ID_TIMESTAMP", + "ID_UNCONNECTED_PONG", + "ID_ADVERTISE_SYSTEM", + "ID_DOWNLOAD_PROGRESS", + "ID_REMOTE_DISCONNECTION_NOTIFICATION", + "ID_REMOTE_CONNECTION_LOST", + "ID_REMOTE_NEW_INCOMING_CONNECTION", + "ID_FILE_LIST_TRANSFER_HEADER", + "ID_FILE_LIST_TRANSFER_FILE", + "ID_FILE_LIST_REFERENCE_PUSH_ACK", + "ID_DDT_DOWNLOAD_REQUEST", + "ID_TRANSPORT_STRING", + "ID_REPLICA_MANAGER_CONSTRUCTION", + "ID_REPLICA_MANAGER_SCOPE_CHANGE", + "ID_REPLICA_MANAGER_SERIALIZE", + "ID_REPLICA_MANAGER_DOWNLOAD_STARTED", + "ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE", + "ID_RAKVOICE_OPEN_CHANNEL_REQUEST", + "ID_RAKVOICE_OPEN_CHANNEL_REPLY", + "ID_RAKVOICE_CLOSE_CHANNEL", + "ID_RAKVOICE_DATA", + "ID_AUTOPATCHER_GET_CHANGELIST_SINCE_DATE", + "ID_AUTOPATCHER_CREATION_LIST", + "ID_AUTOPATCHER_DELETION_LIST", + "ID_AUTOPATCHER_GET_PATCH", + "ID_AUTOPATCHER_PATCH_LIST", + "ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR", + "ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES", + "ID_AUTOPATCHER_FINISHED_INTERNAL", + "ID_AUTOPATCHER_FINISHED", + "ID_AUTOPATCHER_RESTART_APPLICATION", + "ID_NAT_PUNCHTHROUGH_REQUEST", + "ID_NAT_CONNECT_AT_TIME", + "ID_NAT_GET_MOST_RECENT_PORT", + "ID_NAT_CLIENT_READY", + "ID_NAT_TARGET_NOT_CONNECTED", + "ID_NAT_TARGET_UNRESPONSIVE", + "ID_NAT_CONNECTION_TO_TARGET_LOST", + "ID_NAT_ALREADY_IN_PROGRESS", + "ID_NAT_PUNCHTHROUGH_FAILED", + "ID_NAT_PUNCHTHROUGH_SUCCEEDED", + "ID_READY_EVENT_SET", + "ID_READY_EVENT_UNSET", + "ID_READY_EVENT_ALL_SET", + "ID_READY_EVENT_QUERY", + "ID_LOBBY_GENERAL", + "ID_RPC_REMOTE_ERROR", + "ID_RPC_PLUGIN", + "ID_FILE_LIST_REFERENCE_PUSH", + "ID_READY_EVENT_FORCE_ALL_SET", + "ID_ROOMS_EXECUTE_FUNC", + "ID_ROOMS_LOGON_STATUS", + "ID_ROOMS_HANDLE_CHANGE", + "ID_LOBBY2_SEND_MESSAGE", + "ID_LOBBY2_SERVER_ERROR", + "ID_FCM2_NEW_HOST", + "ID_FCM2_REQUEST_FCMGUID", + "ID_FCM2_RESPOND_CONNECTION_COUNT", + "ID_FCM2_INFORM_FCMGUID", + "ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT", + "ID_FCM2_VERIFIED_JOIN_START", + "ID_FCM2_VERIFIED_JOIN_CAPABLE", + "ID_FCM2_VERIFIED_JOIN_FAILED", + "ID_FCM2_VERIFIED_JOIN_ACCEPTED", + "ID_FCM2_VERIFIED_JOIN_REJECTED", + "ID_UDP_PROXY_GENERAL", + "ID_SQLite3_EXEC", + "ID_SQLite3_UNKNOWN_DB", + "ID_SQLLITE_LOGGER", + "ID_NAT_TYPE_DETECTION_REQUEST", + "ID_NAT_TYPE_DETECTION_RESULT", + "ID_ROUTER_2_INTERNAL", + "ID_ROUTER_2_FORWARDING_NO_PATH", + "ID_ROUTER_2_FORWARDING_ESTABLISHED", + "ID_ROUTER_2_REROUTED", + "ID_TEAM_BALANCER_INTERNAL", + "ID_TEAM_BALANCER_REQUESTED_TEAM_FULL", + "ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED", + "ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED", + "ID_TEAM_BALANCER_TEAM_ASSIGNED", + "ID_LIGHTSPEED_INTEGRATION", + "ID_XBOX_LOBBY", + "ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS", + "ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS", + "ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE", + "ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE", + "ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT", + "ID_TWO_WAY_AUTHENTICATION_NEGOTIATION", + "ID_CLOUD_POST_REQUEST", + "ID_CLOUD_RELEASE_REQUEST", + "ID_CLOUD_GET_REQUEST", + "ID_CLOUD_GET_RESPONSE", + "ID_CLOUD_UNSUBSCRIBE_REQUEST", + "ID_CLOUD_SERVER_TO_SERVER_COMMAND", + "ID_CLOUD_SUBSCRIPTION_NOTIFICATION", + "ID_LIB_VOICE", + "ID_RELAY_PLUGIN", + "ID_NAT_REQUEST_BOUND_ADDRESSES", + "ID_NAT_RESPOND_BOUND_ADDRESSES", + "ID_FCM2_UPDATE_USER_CONTEXT", + "ID_RESERVED_3", + "ID_RESERVED_4", + "ID_RESERVED_5", + "ID_RESERVED_6", + "ID_RESERVED_7", + "ID_RESERVED_8", + "ID_RESERVED_9", + "ID_USER_PACKET_ENUM" + }; + + return (char*)IDTable[Id]; +} +const char* PacketLogger::UserIDTOString(unsigned char Id) +{ + // Users should override this + static char str[256]; + Itoa(Id, str, 10); + return (const char*) str; +} +const char* PacketLogger::IDTOString(unsigned char Id) +{ + const char *out; + out=BaseIDTOString(Id); + if (out) + return out; + return UserIDTOString(Id); +} +void PacketLogger::SetPrefix(const char *_prefix) +{ + strncpy(prefix, _prefix, 255); + prefix[255]=0; +} +void PacketLogger::SetSuffix(const char *_suffix) +{ + strncpy(suffix, _suffix, 255); + suffix[255]=0; +} +void PacketLogger::GetLocalTime(char buffer[128]) +{ +#if defined(_WIN32) && !defined(__GNUC__) && !defined(__GCCXML__) + time_t rawtime; + struct timeval tv; + // If you get an arror about an incomplete type, just delete this file + struct timezone tz; + gettimeofday(&tv, &tz); + // time ( &rawtime ); + rawtime=tv.tv_sec; + + struct tm * timeinfo; + timeinfo = localtime ( &rawtime ); + strftime (buffer,128,"%x %X",timeinfo); + char buff[32]; + sprintf(buff, ".%i", tv.tv_usec); + strcat(buffer,buff); + + // Commented version puts the time first + /* + struct tm * timeinfo; + timeinfo = localtime ( &rawtime ); + strftime (buffer,128,"%X",timeinfo); + char buff[32]; + sprintf(buff, ".%i ", tv.tv_usec); + strcat(buffer,buff); + char buff2[32]; + strftime (buff2,32,"%x",timeinfo); + strcat(buffer,buff2); + */ +#else + buffer[0]=0; +#endif +} +void PacketLogger::SetLogDirectMessages(bool send) +{ + logDirectMessages=send; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/PacketOutputWindowLogger.cpp b/src/raknet/PacketOutputWindowLogger.cpp new file mode 100644 index 0000000..11f40e1 --- /dev/null +++ b/src/raknet/PacketOutputWindowLogger.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 + +#if defined(UNICODE) +#include "include/raknet/RakWString.hpp" +#endif + +#include "include/raknet/PacketOutputWindowLogger.hpp" +#include "include/raknet/RakString.hpp" +#if defined(_WIN32) +#include "include/raknet/WindowsIncludes.hpp" +#endif + +using namespace RakNet; + +PacketOutputWindowLogger::PacketOutputWindowLogger() +{ +} +PacketOutputWindowLogger::~PacketOutputWindowLogger() +{ +} +void PacketOutputWindowLogger::WriteLog(const char *str) +{ +#if defined(_WIN32) + + #if defined(UNICODE) + RakNet::RakWString str2 = str; + str2+="\n"; + OutputDebugString(str2.C_String()); + #else + RakNet::RakString str2 = str; + str2+="\n"; + OutputDebugString(str2.C_String()); + #endif +// DS_APR +#elif defined(__native_client__) + fprintf(stderr, "%s\n", str); +// /DS_APR +#endif +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/PacketizedTCP.cpp b/src/raknet/PacketizedTCP.cpp new file mode 100644 index 0000000..380897c --- /dev/null +++ b/src/raknet/PacketizedTCP.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#include "include/raknet/PacketizedTCP.hpp" +#include "include/raknet/NativeTypes.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakAlloca.hpp" + +using namespace RakNet; + +typedef uint32_t PTCPHeader; + +STATIC_FACTORY_DEFINITIONS(PacketizedTCP,PacketizedTCP); + +PacketizedTCP::PacketizedTCP() +{ + +} +PacketizedTCP::~PacketizedTCP() +{ + ClearAllConnections(); +} + +void PacketizedTCP::Stop(void) +{ + unsigned int i; + TCPInterface::Stop(); + for (i=0; i < waitingPackets.Size(); i++) + DeallocatePacket(waitingPackets[i]); + ClearAllConnections(); +} + +void PacketizedTCP::Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast ) +{ + PTCPHeader dataLength; + dataLength=length; +#ifndef __BITSTREAM_NATIVE_END + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytes((unsigned char*) &length,(unsigned char*) &dataLength,sizeof(dataLength)); +#else + dataLength=length; +#endif + + unsigned int lengthsArray[2]; + const char *dataArray[2]; + dataArray[0]=(char*) &dataLength; + dataArray[1]=data; + lengthsArray[0]=sizeof(dataLength); + lengthsArray[1]=length; + TCPInterface::SendList(dataArray,lengthsArray,2,systemAddress,broadcast); +} +bool PacketizedTCP::SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ) +{ + if (isStarted.GetValue()==0) + return false; + if (data==0) + return false; + if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS && broadcast==false) + return false; + PTCPHeader totalLengthOfUserData=0; + int i; + for (i=0; i < numParameters; i++) + { + if (lengths[i]>0) + totalLengthOfUserData+=lengths[i]; + } + if (totalLengthOfUserData==0) + return false; + + PTCPHeader dataLength; +#ifndef __BITSTREAM_NATIVE_END + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytes((unsigned char*) &totalLengthOfUserData,(unsigned char*) &dataLength,sizeof(dataLength)); +#else + dataLength=totalLengthOfUserData; +#endif + + + unsigned int lengthsArray[512]; + const char *dataArray[512]; + dataArray[0]=(char*) &dataLength; + lengthsArray[0]=sizeof(dataLength); + for (int i=0; i < 512 && i < numParameters; i++) + { + dataArray[i+1]=data[i]; + lengthsArray[i+1]=lengths[i]; + } + return TCPInterface::SendList(dataArray,lengthsArray,numParameters+1,systemAddress,broadcast); +} +void PacketizedTCP::PushNotificationsToQueues(void) +{ + SystemAddress sa; + sa = TCPInterface::HasNewIncomingConnection(); + if (sa!=UNASSIGNED_SYSTEM_ADDRESS) + { + _newIncomingConnections.Push(sa, _FILE_AND_LINE_ ); + AddToConnectionList(sa); + } + + sa = TCPInterface::HasFailedConnectionAttempt(); + if (sa!=UNASSIGNED_SYSTEM_ADDRESS) + { + _failedConnectionAttempts.Push(sa, _FILE_AND_LINE_ ); + } + + sa = TCPInterface::HasLostConnection(); + if (sa!=UNASSIGNED_SYSTEM_ADDRESS) + { + _lostConnections.Push(sa, _FILE_AND_LINE_ ); + RemoveFromConnectionList(sa); + } + + sa = TCPInterface::HasCompletedConnectionAttempt(); + if (sa!=UNASSIGNED_SYSTEM_ADDRESS) + { + _completedConnectionAttempts.Push(sa, _FILE_AND_LINE_ ); + AddToConnectionList(sa); + } +} +Packet* PacketizedTCP::Receive( void ) +{ + PushNotificationsToQueues(); + + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + messageHandlerList[i]->Update(); + + Packet *outgoingPacket=ReturnOutgoingPacket(); + if (outgoingPacket) + return outgoingPacket; + + Packet *incomingPacket; + incomingPacket = TCPInterface::ReceiveInt(); + unsigned int index; + + while (incomingPacket) + { + if (connections.Has(incomingPacket->systemAddress)) + index = connections.GetIndexAtKey(incomingPacket->systemAddress); + else + index=(unsigned int) -1; + if ((unsigned int)index==(unsigned int)-1) + { + DeallocatePacket(incomingPacket); + incomingPacket = TCPInterface::ReceiveInt(); + continue; + } + + + if (incomingPacket->deleteData==true) + { + // Came from network + SystemAddress systemAddressFromPacket; + if (index < connections.Size()) + { + DataStructures::ByteQueue *bq = connections[index]; + // Buffer data + bq->WriteBytes((const char*) incomingPacket->data,incomingPacket->length, _FILE_AND_LINE_); + systemAddressFromPacket=incomingPacket->systemAddress; + PTCPHeader dataLength; + + // Peek the header to see if a full message is waiting + bq->ReadBytes((char*) &dataLength,sizeof(PTCPHeader),true); + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &dataLength,sizeof(dataLength)); + // Header indicates packet length. If enough data is available, read out and return one packet + if (bq->GetBytesWritten()>=dataLength+sizeof(PTCPHeader)) + { + do + { + bq->IncrementReadOffset(sizeof(PTCPHeader)); + outgoingPacket = RakNet::OP_NEW(_FILE_AND_LINE_); + outgoingPacket->length=dataLength; + outgoingPacket->bitSize=BYTES_TO_BITS(dataLength); + outgoingPacket->guid=UNASSIGNED_RAKNET_GUID; + outgoingPacket->systemAddress=systemAddressFromPacket; + outgoingPacket->deleteData=false; // Did not come from the network + outgoingPacket->data=(unsigned char*) rakMalloc_Ex(dataLength, _FILE_AND_LINE_); + if (outgoingPacket->data==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + RakNet::OP_DELETE(outgoingPacket,_FILE_AND_LINE_); + return 0; + } + bq->ReadBytes((char*) outgoingPacket->data,dataLength,false); + + waitingPackets.Push(outgoingPacket, _FILE_AND_LINE_ ); + + // Peek the header to see if a full message is waiting + if (bq->ReadBytes((char*) &dataLength,sizeof(PTCPHeader),true)) + { + if (RakNet::BitStream::DoEndianSwap()) + RakNet::BitStream::ReverseBytesInPlace((unsigned char*) &dataLength,sizeof(dataLength)); + } + else + break; + } while (bq->GetBytesWritten()>=dataLength+sizeof(PTCPHeader)); + } + else + { + + unsigned int oldWritten = bq->GetBytesWritten()-incomingPacket->length; + unsigned int newWritten = bq->GetBytesWritten(); + + // Return ID_DOWNLOAD_PROGRESS + if (newWritten/65536!=oldWritten/65536) + { + outgoingPacket = RakNet::OP_NEW(_FILE_AND_LINE_); + outgoingPacket->length=sizeof(MessageID) + + sizeof(unsigned int)*2 + + sizeof(unsigned int) + + 65536; + outgoingPacket->bitSize=BYTES_TO_BITS(incomingPacket->length); + outgoingPacket->guid=UNASSIGNED_RAKNET_GUID; + outgoingPacket->systemAddress=incomingPacket->systemAddress; + outgoingPacket->deleteData=false; + outgoingPacket->data=(unsigned char*) rakMalloc_Ex(outgoingPacket->length, _FILE_AND_LINE_); + if (outgoingPacket->data==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + RakNet::OP_DELETE(outgoingPacket,_FILE_AND_LINE_); + return 0; + } + + outgoingPacket->data[0]=(MessageID)ID_DOWNLOAD_PROGRESS; + unsigned int totalParts=dataLength/65536; + unsigned int partIndex=newWritten/65536; + unsigned int oneChunkSize=65536; + memcpy(outgoingPacket->data+sizeof(MessageID), &partIndex, sizeof(unsigned int)); + memcpy(outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*1, &totalParts, sizeof(unsigned int)); + memcpy(outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*2, &oneChunkSize, sizeof(unsigned int)); + bq->IncrementReadOffset(sizeof(PTCPHeader)); + bq->ReadBytes((char*) outgoingPacket->data+sizeof(MessageID)+sizeof(unsigned int)*3,oneChunkSize,true); + bq->DecrementReadOffset(sizeof(PTCPHeader)); + + waitingPackets.Push(outgoingPacket, _FILE_AND_LINE_ ); + } + } + + } + + DeallocatePacket(incomingPacket); + incomingPacket=0; + } + else + waitingPackets.Push(incomingPacket, _FILE_AND_LINE_ ); + + incomingPacket = TCPInterface::ReceiveInt(); + } + + return ReturnOutgoingPacket(); +} +Packet *PacketizedTCP::ReturnOutgoingPacket(void) +{ + Packet *outgoingPacket=0; + unsigned int i; + while (outgoingPacket==0 && waitingPackets.IsEmpty()==false) + { + outgoingPacket=waitingPackets.Pop(); + PluginReceiveResult pluginResult; + for (i=0; i < messageHandlerList.Size(); i++) + { + pluginResult=messageHandlerList[i]->OnReceive(outgoingPacket); + if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) + { + DeallocatePacket( outgoingPacket ); + outgoingPacket=0; // Will do the loop again and get another packet + break; // break out of the enclosing for + } + else if (pluginResult==RR_STOP_PROCESSING) + { + outgoingPacket=0; + break; + } + } + } + + return outgoingPacket; +} +void PacketizedTCP::CloseConnection( SystemAddress systemAddress ) +{ + RemoveFromConnectionList(systemAddress); + TCPInterface::CloseConnection(systemAddress); +} +void PacketizedTCP::RemoveFromConnectionList(const SystemAddress &sa) +{ + if (sa==UNASSIGNED_SYSTEM_ADDRESS) + return; + if (connections.Has(sa)) + { + unsigned int index = connections.GetIndexAtKey(sa); + if (index!=(unsigned int)-1) + { + RakNet::OP_DELETE(connections[index],_FILE_AND_LINE_); + connections.RemoveAtIndex(index); + } + } +} +void PacketizedTCP::AddToConnectionList(const SystemAddress &sa) +{ + if (sa==UNASSIGNED_SYSTEM_ADDRESS) + return; + connections.SetNew(sa, RakNet::OP_NEW(_FILE_AND_LINE_)); +} +void PacketizedTCP::ClearAllConnections(void) +{ + unsigned int i; + for (i=0; i < connections.Size(); i++) + RakNet::OP_DELETE(connections[i],_FILE_AND_LINE_); + connections.Clear(); +} +SystemAddress PacketizedTCP::HasCompletedConnectionAttempt(void) +{ + PushNotificationsToQueues(); + + if (_completedConnectionAttempts.IsEmpty()==false) + return _completedConnectionAttempts.Pop(); + return UNASSIGNED_SYSTEM_ADDRESS; +} +SystemAddress PacketizedTCP::HasFailedConnectionAttempt(void) +{ + PushNotificationsToQueues(); + + if (_failedConnectionAttempts.IsEmpty()==false) + return _failedConnectionAttempts.Pop(); + return UNASSIGNED_SYSTEM_ADDRESS; +} +SystemAddress PacketizedTCP::HasNewIncomingConnection(void) +{ + PushNotificationsToQueues(); + + if (_newIncomingConnections.IsEmpty()==false) + return _newIncomingConnections.Pop(); + return UNASSIGNED_SYSTEM_ADDRESS; +} +SystemAddress PacketizedTCP::HasLostConnection(void) +{ + PushNotificationsToQueues(); + + if (_lostConnections.IsEmpty()==false) + return _lostConnections.Pop(); + return UNASSIGNED_SYSTEM_ADDRESS; +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/PluginInterface2.cpp b/src/raknet/PluginInterface2.cpp new file mode 100644 index 0000000..b73d1df --- /dev/null +++ b/src/raknet/PluginInterface2.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + + +#include "include/raknet/PluginInterface2.hpp" +#include "include/raknet/PacketizedTCP.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/BitStream.hpp" + +using namespace RakNet; + +PluginInterface2::PluginInterface2() +{ + rakPeerInterface=0; +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + tcpInterface=0; +#endif +} +PluginInterface2::~PluginInterface2() +{ + +} +void PluginInterface2::SendUnified( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) +{ + if (rakPeerInterface) + { + rakPeerInterface->Send(bitStream,priority,reliability,orderingChannel,systemIdentifier,broadcast); + return; + } +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else if (tcpInterface) + { + tcpInterface->Send((const char*) bitStream->GetData(), bitStream->GetNumberOfBytesUsed(), systemIdentifier.systemAddress, broadcast); + return; + } +#endif + + // Offline mode + if (broadcast==false && systemIdentifier.rakNetGuid==GetMyGUIDUnified()) + { +// Packet *packet = AllocatePacketUnified(bitStream->GetNumberOfBytesUsed()); +// memcpy(packet->data, bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); + Packet packet; + packet.bitSize=bitStream->GetNumberOfBitsUsed(); + packet.data=bitStream->GetData(); + packet.deleteData=false; + packet.guid=UNASSIGNED_RAKNET_GUID; + packet.length=bitStream->GetNumberOfBytesUsed(); + packet.systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + packet.wasGeneratedLocally=false; + OnReceive(&packet); +// DeallocPacketUnified(packet); + + Update(); + } +} +void PluginInterface2::SendUnified( const char * data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) +{ + if (rakPeerInterface) + { + rakPeerInterface->Send(data, length, priority,reliability,orderingChannel,systemIdentifier,broadcast); + return; + } +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else if (tcpInterface) + { + tcpInterface->Send(data, length, systemIdentifier.systemAddress, broadcast); + return; + } +#endif + + // Offline mode + if (broadcast==false && systemIdentifier.rakNetGuid==GetMyGUIDUnified()) + { + // Packet *packet = AllocatePacketUnified(bitStream->GetNumberOfBytesUsed()); + // memcpy(packet->data, bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); + Packet packet; + packet.bitSize=BYTES_TO_BITS(length); + packet.data=(unsigned char*) data; + packet.deleteData=false; + packet.guid=UNASSIGNED_RAKNET_GUID; + packet.length=length; + packet.systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + packet.wasGeneratedLocally=false; + OnReceive(&packet); + // DeallocPacketUnified(packet); + + Update(); + } +} +Packet *PluginInterface2::AllocatePacketUnified(unsigned dataSize) +{ + if (rakPeerInterface) + { + return rakPeerInterface->AllocatePacket(dataSize); + } +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else if (tcpInterface) + { + return tcpInterface->AllocatePacket(dataSize); + } +#endif + + Packet *packet = RakNet::OP_NEW(_FILE_AND_LINE_); + packet->data = (unsigned char*) rakMalloc_Ex(dataSize, _FILE_AND_LINE_); + packet->bitSize=BYTES_TO_BITS(dataSize); + packet->deleteData=true; + packet->guid=UNASSIGNED_RAKNET_GUID; + packet->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + packet->wasGeneratedLocally=false; + return packet; +} +void PluginInterface2::PushBackPacketUnified(Packet *packet, bool pushAtHead) +{ + if (rakPeerInterface) + { + rakPeerInterface->PushBackPacket(packet,pushAtHead); + return; + } +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else if (tcpInterface) + { + tcpInterface->PushBackPacket(packet,pushAtHead); + return; + } +#endif + + OnReceive(packet); + Update(); +} +void PluginInterface2::DeallocPacketUnified(Packet *packet) +{ + if (rakPeerInterface) + { + rakPeerInterface->DeallocatePacket(packet); + return; + } +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else if (tcpInterface) + { + tcpInterface->DeallocatePacket(packet); + return; + } +#endif + + rakFree_Ex(packet->data, _FILE_AND_LINE_); + RakNet::OP_DELETE(packet, _FILE_AND_LINE_); +} +bool PluginInterface2::SendListUnified( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) +{ + if (rakPeerInterface) + { + return rakPeerInterface->SendList(data,lengths,numParameters,priority,reliability,orderingChannel,systemIdentifier,broadcast)!=0; + } +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else if (tcpInterface) + { + return tcpInterface->SendList(data,(const unsigned int *) lengths,numParameters,systemIdentifier.systemAddress,broadcast ); + } +#endif + + if (broadcast==false && systemIdentifier.rakNetGuid==GetMyGUIDUnified()) + { + + unsigned int totalLength=0; + unsigned int lengthOffset; + int i; + for (i=0; i < numParameters; i++) + { + if (lengths[i]>0) + totalLength+=lengths[i]; + } + if (totalLength==0) + return false; + + char *dataAggregate; + dataAggregate = (char*) rakMalloc_Ex( (size_t) totalLength, _FILE_AND_LINE_ ); + if (dataAggregate==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + return false; + } + for (i=0, lengthOffset=0; i < numParameters; i++) + { + if (lengths[i]>0) + { + memcpy(dataAggregate+lengthOffset, data[i], lengths[i]); + lengthOffset+=lengths[i]; + } + } + + SendUnified(dataAggregate, totalLength, priority, reliability,orderingChannel, systemIdentifier, broadcast); + rakFree_Ex(dataAggregate, _FILE_AND_LINE_); + return true; + } + + return false; +} +void PluginInterface2::SetRakPeerInterface( RakPeerInterface *ptr ) +{ + rakPeerInterface=ptr; +} +#if _RAKNET_SUPPORT_TCPInterface==1 +void PluginInterface2::SetTCPInterface( TCPInterface *ptr ) +{ + tcpInterface=ptr; +} +#endif +RakNetGUID PluginInterface2::GetMyGUIDUnified(void) const +{ + if (rakPeerInterface) + return rakPeerInterface->GetMyGUID(); + return UNASSIGNED_RAKNET_GUID; +} \ No newline at end of file diff --git a/src/raknet/RPC4Plugin.cpp b/src/raknet/RPC4Plugin.cpp new file mode 100644 index 0000000..0621727 --- /dev/null +++ b/src/raknet/RPC4Plugin.cpp @@ -0,0 +1,629 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_RPC4Plugin==1 + +#include "include/raknet/RPC4Plugin.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/PacketizedTCP.hpp" +#include "include/raknet/RakSleep.hpp" +#include "include/raknet/RakNetDefines.hpp" +#include "include/raknet/DS_Queue.hpp" +//#include "include/raknet/GetTime.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(RPC4,RPC4); + +struct GlobalRegistration +{ + void ( *registerFunctionPointer ) ( RakNet::BitStream *userData, Packet *packet ); + void ( *registerBlockingFunctionPointer ) ( RakNet::BitStream *userData, RakNet::BitStream *returnData, Packet *packet ); + char functionName[RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH]; + MessageID messageId; + int callPriority; +}; +static GlobalRegistration globalRegistrationBuffer[RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS]; +static unsigned int globalRegistrationIndex=0; + +RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet )) +{ + RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); + unsigned int i; + for (i=0; uniqueID[i]; i++) + { + RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); + globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; + } + globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=functionPointer; + globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=0; + globalRegistrationBuffer[globalRegistrationIndex].callPriority=0xFFFFFFFF; + globalRegistrationIndex++; +} +RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet ), int callPriority) +{ + RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); + unsigned int i; + for (i=0; uniqueID[i]; i++) + { + RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); + globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; + } + globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=functionPointer; + globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=0; + RakAssert(callPriority!=(int) 0xFFFFFFFF); + globalRegistrationBuffer[globalRegistrationIndex].callPriority=callPriority; + globalRegistrationIndex++; +} +RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, RakNet::BitStream *returnData, Packet *packet )) +{ + RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); + unsigned int i; + for (i=0; uniqueID[i]; i++) + { + RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); + globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; + } + globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=0; + globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=functionPointer; + globalRegistrationIndex++; +} +RPC4GlobalRegistration::RPC4GlobalRegistration(const char* uniqueID, MessageID messageId) +{ + RakAssert(globalRegistrationIndex!=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS); + unsigned int i; + for (i=0; uniqueID[i]; i++) + { + RakAssert(i<=RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH-1); + globalRegistrationBuffer[globalRegistrationIndex].functionName[i]=uniqueID[i]; + } + globalRegistrationBuffer[globalRegistrationIndex].registerFunctionPointer=0; + globalRegistrationBuffer[globalRegistrationIndex].registerBlockingFunctionPointer=0; + globalRegistrationBuffer[globalRegistrationIndex].messageId=messageId; + globalRegistrationIndex++; +} + +enum RPC4Identifiers +{ + ID_RPC4_CALL, + ID_RPC4_RETURN, + ID_RPC4_SIGNAL, +}; +int RPC4::LocalSlotObjectComp( const LocalSlotObject &key, const LocalSlotObject &data ) +{ + if (key.callPriority>data.callPriority) + return -1; + if (key.callPriority==data.callPriority) + { + if (key.registrationCountmessageId) + return -1; + if (key > data->messageId) + return 1; + return 0; +} + +RPC4::RPC4() +{ + gotBlockingReturnValue=false; + nextSlotRegistrationCount=0; + interruptSignal=false; +} +RPC4::~RPC4() +{ + unsigned int i; + for (i=0; i < localCallbacks.Size(); i++) + { + RakNet::OP_DELETE(localCallbacks[i],_FILE_AND_LINE_); + } + + DataStructures::List keyList; + DataStructures::List outputList; + localSlots.GetAsList(outputList,keyList,_FILE_AND_LINE_); + unsigned int j; + for (j=0; j < outputList.Size(); j++) + { + RakNet::OP_DELETE(outputList[j],_FILE_AND_LINE_); + } + localSlots.Clear(_FILE_AND_LINE_); +} +bool RPC4::RegisterFunction(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet )) +{ + DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(uniqueID); + if (skhi.IsInvalid()==false) + return false; + + registeredNonblockingFunctions.Push(uniqueID,functionPointer,_FILE_AND_LINE_); + return true; +} +void RPC4::RegisterSlot(const char *sharedIdentifier, void ( *functionPointer ) ( RakNet::BitStream *userData, Packet *packet ), int callPriority) +{ + LocalSlotObject lso(nextSlotRegistrationCount++, callPriority, functionPointer); + DataStructures::HashIndex idx = GetLocalSlotIndex(sharedIdentifier); + LocalSlot *localSlot; + if (idx.IsInvalid()) + { + localSlot = RakNet::OP_NEW(_FILE_AND_LINE_); + localSlots.Push(sharedIdentifier, localSlot,_FILE_AND_LINE_); + } + else + { + localSlot=localSlots.ItemAtIndex(idx); + } + localSlot->slotObjects.Insert(lso,lso,true,_FILE_AND_LINE_); +} +bool RPC4::RegisterBlockingFunction(const char* uniqueID, void ( *functionPointer ) ( RakNet::BitStream *userData, RakNet::BitStream *returnData, Packet *packet )) +{ + DataStructures::HashIndex skhi = registeredBlockingFunctions.GetIndexOf(uniqueID); + if (skhi.IsInvalid()==false) + return false; + + registeredBlockingFunctions.Push(uniqueID,functionPointer,_FILE_AND_LINE_); + return true; +} +void RPC4::RegisterLocalCallback(const char* uniqueID, MessageID messageId) +{ + bool objectExists; + unsigned int index; + LocalCallback *lc; + RakNet::RakString str; + str=uniqueID; + index = localCallbacks.GetIndexFromKey(messageId,&objectExists); + if (objectExists) + { + lc = localCallbacks[index]; + index = lc->functions.GetIndexFromKey(str,&objectExists); + if (objectExists==false) + lc->functions.InsertAtIndex(str,index,_FILE_AND_LINE_); + } + else + { + lc = RakNet::OP_NEW(_FILE_AND_LINE_); + lc->messageId=messageId; + lc->functions.Insert(str,str,false,_FILE_AND_LINE_); + localCallbacks.InsertAtIndex(lc,index,_FILE_AND_LINE_); + } +} +bool RPC4::UnregisterFunction(const char* uniqueID) +{ + void ( *f ) ( RakNet::BitStream *, Packet * ); + return registeredNonblockingFunctions.Pop(f,uniqueID,_FILE_AND_LINE_); +} +bool RPC4::UnregisterBlockingFunction(const char* uniqueID) +{ + void ( *f ) ( RakNet::BitStream *, RakNet::BitStream *,Packet * ); + return registeredBlockingFunctions.Pop(f,uniqueID,_FILE_AND_LINE_); +} +bool RPC4::UnregisterLocalCallback(const char* uniqueID, MessageID messageId) +{ + bool objectExists; + unsigned int index, index2; + LocalCallback *lc; + RakNet::RakString str; + str=uniqueID; + index = localCallbacks.GetIndexFromKey(messageId,&objectExists); + if (objectExists) + { + lc = localCallbacks[index]; + index2 = lc->functions.GetIndexFromKey(str,&objectExists); + if (objectExists) + { + lc->functions.RemoveAtIndex(index2); + if (lc->functions.Size()==0) + { + RakNet::OP_DELETE(lc,_FILE_AND_LINE_); + localCallbacks.RemoveAtIndex(index); + return true; + } + } + } + return false; +} +bool RPC4::UnregisterSlot(const char* sharedIdentifier) +{ + DataStructures::HashIndex hi = localSlots.GetIndexOf(sharedIdentifier); + if (hi.IsInvalid()==false) + { + LocalSlot *ls = localSlots.ItemAtIndex(hi); + RakNet::OP_DELETE(ls, _FILE_AND_LINE_); + localSlots.RemoveAtIndex(hi, _FILE_AND_LINE_); + return true; + } + + return false; +} +void RPC4::CallLoopback( const char* uniqueID, RakNet::BitStream * bitStream ) +{ + Packet *p=0; + + DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(uniqueID); + + if (skhi.IsInvalid()==true) + { + if (rakPeerInterface) + p=AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)+(unsigned int) strlen(uniqueID)+1); +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else + p=tcpInterface->AllocatePacket(sizeof(MessageID)+sizeof(unsigned char)+(unsigned int) strlen(uniqueID)+1); +#endif + + if (rakPeerInterface) + p->guid=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else + p->guid=UNASSIGNED_RAKNET_GUID; +#endif + + p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->data[0]=ID_RPC_REMOTE_ERROR; + p->data[1]=RPC_ERROR_FUNCTION_NOT_REGISTERED; + strcpy((char*) p->data+2, uniqueID); + + PushBackPacketUnified(p,false); + + return; + } + + RakNet::BitStream out; + out.Write((MessageID) ID_RPC_PLUGIN); + out.Write((MessageID) ID_RPC4_CALL); + out.WriteCompressed(uniqueID); + out.Write(false); // nonblocking + if (bitStream) + { + bitStream->ResetReadPointer(); + out.AlignWriteToByteBoundary(); + out.Write(bitStream); + } + if (rakPeerInterface) + p=AllocatePacketUnified(out.GetNumberOfBytesUsed()); +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else + p=tcpInterface->AllocatePacket(out.GetNumberOfBytesUsed()); +#endif + + if (rakPeerInterface) + p->guid=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); +#if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 + else + p->guid=UNASSIGNED_RAKNET_GUID; +#endif + p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + p->systemAddress.systemIndex=(SystemIndex)-1; + memcpy(p->data,out.GetData(),out.GetNumberOfBytesUsed()); + PushBackPacketUnified(p,false); + return; +} +void RPC4::Call( const char* uniqueID, RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast ) +{ + RakNet::BitStream out; + out.Write((MessageID) ID_RPC_PLUGIN); + out.Write((MessageID) ID_RPC4_CALL); + out.WriteCompressed(uniqueID); + out.Write(false); // Nonblocking + if (bitStream) + { + bitStream->ResetReadPointer(); + out.AlignWriteToByteBoundary(); + out.Write(bitStream); + } + SendUnified(&out,priority,reliability,orderingChannel,systemIdentifier,broadcast); +} +bool RPC4::CallBlocking( const char* uniqueID, RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, RakNet::BitStream *returnData ) +{ + RakNet::BitStream out; + out.Write((MessageID) ID_RPC_PLUGIN); + out.Write((MessageID) ID_RPC4_CALL); + out.WriteCompressed(uniqueID); + out.Write(true); // Blocking + if (bitStream) + { + bitStream->ResetReadPointer(); + out.AlignWriteToByteBoundary(); + out.Write(bitStream); + } + RakAssert(returnData); + RakAssert(rakPeerInterface); + ConnectionState cs; + cs = rakPeerInterface->GetConnectionState(systemIdentifier); + if (cs!=IS_CONNECTED) + return false; + + SendUnified(&out,priority,reliability,orderingChannel,systemIdentifier,false); + + returnData->Reset(); + blockingReturnValue.Reset(); + gotBlockingReturnValue=false; + Packet *packet; + DataStructures::Queue packetQueue; + while (gotBlockingReturnValue==false) + { + // TODO - block, filter until gotBlockingReturnValue==true or ID_CONNECTION_LOST or ID_DISCONNECTION_NOTIFICXATION or ID_RPC_REMOTE_ERROR/RPC_ERROR_FUNCTION_NOT_REGISTERED + RakSleep(30); + + packet=rakPeerInterface->Receive(); + + if (packet) + { + if ( + (packet->data[0]==ID_CONNECTION_LOST || packet->data[0]==ID_DISCONNECTION_NOTIFICATION) && + ((systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID && packet->guid==systemIdentifier.rakNetGuid) || + (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && packet->systemAddress==systemIdentifier.systemAddress)) + ) + { + // Push back to head in reverse order + rakPeerInterface->PushBackPacket(packet,true); + while (packetQueue.Size()) + rakPeerInterface->PushBackPacket(packetQueue.Pop(),true); + return false; + } + else if (packet->data[0]==ID_RPC_REMOTE_ERROR && packet->data[1]==RPC_ERROR_FUNCTION_NOT_REGISTERED) + { + RakNet::RakString functionName; + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + bsIn.Read(functionName); + if (functionName==uniqueID) + { + // Push back to head in reverse order + rakPeerInterface->PushBackPacket(packet,true); + while (packetQueue.Size()) + rakPeerInterface->PushBackPacket(packetQueue.Pop(),true); + return false; + } + else + { + packetQueue.PushAtHead(packet,0,_FILE_AND_LINE_); + } + } + else + { + packetQueue.PushAtHead(packet,0,_FILE_AND_LINE_); + } + } + } + + returnData->Write(blockingReturnValue); + returnData->ResetReadPointer(); + return true; +} +void RPC4::Signal(const char *sharedIdentifier, RakNet::BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool invokeLocal) +{ + RakNet::BitStream out; + out.Write((MessageID) ID_RPC_PLUGIN); + out.Write((MessageID) ID_RPC4_SIGNAL); + out.WriteCompressed(sharedIdentifier); + if (bitStream) + { + bitStream->ResetReadPointer(); + out.AlignWriteToByteBoundary(); + out.Write(bitStream); + } + SendUnified(&out,priority,reliability,orderingChannel,systemIdentifier,broadcast); + + if (invokeLocal) + { + //TimeUS t1 = GetTimeUS(); + + DataStructures::HashIndex functionIndex; + functionIndex = localSlots.GetIndexOf(sharedIdentifier); + //TimeUS t2 = GetTimeUS(); + if (functionIndex.IsInvalid()) + return; + + Packet p; + p.guid=rakPeerInterface->GetMyGUID(); + p.systemAddress=rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS); + p.wasGeneratedLocally=true; + RakNet::BitStream *bsptr, bstemp; + if (bitStream) + { + bitStream->ResetReadPointer(); + p.length=bitStream->GetNumberOfBytesUsed(); + p.bitSize=bitStream->GetNumberOfBitsUsed(); + bsptr=bitStream; + } + else + { + p.length=0; + p.bitSize=0; + bsptr=&bstemp; + } + + //TimeUS t3 = GetTimeUS(); + InvokeSignal(functionIndex, bsptr, &p); + //TimeUS t4 = GetTimeUS(); + //printf("b1: %I64d\n", t2-t1); + //printf("b2: %I64d\n", t3-t2); + //printf("b3: %I64d\n", t4-t3); + } +} +void RPC4::InvokeSignal(DataStructures::HashIndex functionIndex, RakNet::BitStream *serializedParameters, Packet *packet) +{ + if (functionIndex.IsInvalid()) + return; + + //TimeUS t1 = GetTimeUS(); + //TimeUS t2=0; + //TimeUS t3=0; + + interruptSignal=false; + LocalSlot *localSlot = localSlots.ItemAtIndex(functionIndex); + unsigned int i; + i=0; + while (i < localSlot->slotObjects.Size()) + { + //t2 = GetTimeUS(); + + localSlot->slotObjects[i].functionPointer(serializedParameters, packet); + + //t3 = GetTimeUS(); + + // Not threadsafe + if (interruptSignal==true) + break; + + serializedParameters->ResetReadPointer(); + + i++; + } + + //TimeUS t4 = GetTimeUS(); + + //printf("b1: %I64d\n", t2-t1); + //printf("b2: %I64d\n", t3-t2); + //printf("b3: %I64d\n", t4-t3); +} +void RPC4::InterruptSignal(void) +{ + interruptSignal=true; +} +void RPC4::OnAttach(void) +{ + unsigned int i; + for (i=0; i < globalRegistrationIndex; i++) + { + if (globalRegistrationBuffer[i].registerFunctionPointer) + { + if (globalRegistrationBuffer[i].callPriority==(int)0xFFFFFFFF) + RegisterFunction(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].registerFunctionPointer); + else + RegisterSlot(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].registerFunctionPointer, globalRegistrationBuffer[i].callPriority); + } + else if (globalRegistrationBuffer[i].registerBlockingFunctionPointer) + RegisterBlockingFunction(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].registerBlockingFunctionPointer); + else + RegisterLocalCallback(globalRegistrationBuffer[i].functionName, globalRegistrationBuffer[i].messageId); + } +} +PluginReceiveResult RPC4::OnReceive(Packet *packet) +{ + if (packet->data[0]==ID_RPC_PLUGIN) + { + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + + if (packet->data[1]==ID_RPC4_CALL) + { + RakNet::RakString functionName; + bsIn.ReadCompressed(functionName); + bool isBlocking=false; + bsIn.Read(isBlocking); + if (isBlocking==false) + { + DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(functionName.C_String()); + if (skhi.IsInvalid()) + { + RakNet::BitStream bsOut; + bsOut.Write((unsigned char) ID_RPC_REMOTE_ERROR); + bsOut.Write((unsigned char) RPC_ERROR_FUNCTION_NOT_REGISTERED); + bsOut.Write(functionName.C_String(),(unsigned int) functionName.GetLength()+1); + SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + void ( *fp ) ( RakNet::BitStream *, Packet * ); + fp = registeredNonblockingFunctions.ItemAtIndex(skhi); + bsIn.AlignReadToByteBoundary(); + fp(&bsIn,packet); + } + else + { + DataStructures::HashIndex skhi = registeredBlockingFunctions.GetIndexOf(functionName.C_String()); + if (skhi.IsInvalid()) + { + RakNet::BitStream bsOut; + bsOut.Write((unsigned char) ID_RPC_REMOTE_ERROR); + bsOut.Write((unsigned char) RPC_ERROR_FUNCTION_NOT_REGISTERED); + bsOut.Write(functionName.C_String(),(unsigned int) functionName.GetLength()+1); + SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + void ( *fp ) ( RakNet::BitStream *, RakNet::BitStream *, Packet * ); + fp = registeredBlockingFunctions.ItemAtIndex(skhi); + RakNet::BitStream returnData; + bsIn.AlignReadToByteBoundary(); + fp(&bsIn, &returnData, packet); + + RakNet::BitStream out; + out.Write((MessageID) ID_RPC_PLUGIN); + out.Write((MessageID) ID_RPC4_RETURN); + returnData.ResetReadPointer(); + out.AlignWriteToByteBoundary(); + out.Write(returnData); + SendUnified(&out,IMMEDIATE_PRIORITY,RELIABLE_ORDERED,0,packet->systemAddress,false); + } + } + else if (packet->data[1]==ID_RPC4_SIGNAL) + { + RakNet::RakString sharedIdentifier; + bsIn.ReadCompressed(sharedIdentifier); + DataStructures::HashIndex functionIndex; + functionIndex = localSlots.GetIndexOf(sharedIdentifier); + RakNet::BitStream serializedParameters; + bsIn.AlignReadToByteBoundary(); + bsIn.Read(&serializedParameters); + InvokeSignal(functionIndex, &serializedParameters, packet); + } + else + { + RakAssert(packet->data[1]==ID_RPC4_RETURN); + blockingReturnValue.Reset(); + blockingReturnValue.Write(bsIn); + gotBlockingReturnValue=true; + } + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + bool objectExists; + unsigned int index, index2; + index = localCallbacks.GetIndexFromKey(packet->data[0],&objectExists); + if (objectExists) + { + LocalCallback *lc; + lc = localCallbacks[index]; + for (index2=0; index2 < lc->functions.Size(); index2++) + { + RakNet::BitStream bsIn(packet->data, packet->length, false); + + DataStructures::HashIndex skhi = registeredNonblockingFunctions.GetIndexOf(lc->functions[index2].C_String()); + if (skhi.IsInvalid()==false) + { + void ( *fp ) ( RakNet::BitStream *, Packet * ); + fp = registeredNonblockingFunctions.ItemAtIndex(skhi); + bsIn.AlignReadToByteBoundary(); + fp(&bsIn,packet); + } + } + } + + return RR_CONTINUE_PROCESSING; +} +DataStructures::HashIndex RPC4::GetLocalSlotIndex(const char *sharedIdentifier) +{ + return localSlots.GetIndexOf(sharedIdentifier); +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/Rackspace.cpp b/src/raknet/Rackspace.cpp new file mode 100644 index 0000000..7f5b1fb --- /dev/null +++ b/src/raknet/Rackspace.cpp @@ -0,0 +1,671 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_Rackspace==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#include "include/raknet/Rackspace.hpp" +#include "include/raknet/RakString.hpp" +#include "include/raknet/TCPInterface.hpp" + +using namespace RakNet; + +Rackspace::Rackspace() +{ + tcpInterface=0; +} + +Rackspace::~Rackspace() +{ + +} + +void Rackspace::AddEventCallback(Rackspace2EventCallback *callback) +{ + unsigned int idx = eventCallbacks.GetIndexOf(callback); + if (idx == (unsigned int)-1) + eventCallbacks.Push(callback,_FILE_AND_LINE_); +} +void Rackspace::RemoveEventCallback(Rackspace2EventCallback *callback) +{ + unsigned int idx = eventCallbacks.GetIndexOf(callback); + if (idx != (unsigned int)-1) + eventCallbacks.RemoveAtIndex(idx); +} +void Rackspace::ClearEventCallbacks(void) +{ + eventCallbacks.Clear(true, _FILE_AND_LINE_); +} +SystemAddress Rackspace::Authenticate(TCPInterface *_tcpInterface, const char *_authenticationURL, const char *_rackspaceCloudUsername, const char *_apiAccessKey) +{ + unsigned int index = GetOperationOfTypeIndex(RO_CONNECT_AND_AUTHENTICATE); + if (index!=(unsigned int)-1) + { + // In progress + return operations[index].connectionAddress; + } + + tcpInterface=_tcpInterface; + + rackspaceCloudUsername=_rackspaceCloudUsername; + apiAccessKey=_apiAccessKey; + + unsigned int i; + + RackspaceOperation ro; + ro.type=RO_CONNECT_AND_AUTHENTICATE; + ro.isPendingAuthentication=false; + + RakAssert(tcpInterface->WasStarted()); + ro.connectionAddress=tcpInterface->Connect(_authenticationURL,443,true); + if (ro.connectionAddress==UNASSIGNED_SYSTEM_ADDRESS) + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnConnectionAttemptFailure(RO_CONNECT_AND_AUTHENTICATE, _authenticationURL); + + return UNASSIGNED_SYSTEM_ADDRESS; + } + +#if OPEN_SSL_CLIENT_SUPPORT==1 + tcpInterface->StartSSLClient(ro.connectionAddress); +#endif + + RakNet::RakString command( + "GET /v1.0 HTTP/1.1\n" + "Host: %s\n" + "X-Auth-User: %s\n" + "X-Auth-Key: %s\n\n" + ,_authenticationURL, _rackspaceCloudUsername, _apiAccessKey); + tcpInterface->Send(command.C_String(), (unsigned int) command.GetLength(), ro.connectionAddress, false); + + operations.Insert(ro,_FILE_AND_LINE_); + return ro.connectionAddress; +} + +const char * Rackspace::EventTypeToString(RackspaceEventType eventType) +{ + switch (eventType) + { + case RET_Success_200: + return "Success_200"; + case RET_Success_201: + return "Success_201"; + case RET_Success_202: + return "Success_202"; + case RET_Success_203: + return "Success_203"; + case RET_Success_204: + return "Success_204"; + case RET_Cloud_Servers_Fault_500: + return "Cloud_Servers_Fault_500"; + case RET_Service_Unavailable_503: + return "Service_Unavailable_503"; + case RET_Unauthorized_401: + return "Unauthorized_401"; + case RET_Bad_Request_400: + return "Bad_Request_400"; + case RET_Over_Limit_413: + return "Over_Limit_413"; + case RET_Bad_Media_Type_415: + return "Bad_Media_Type_415"; + case RET_Item_Not_Found_404: + return "Item_Not_Found_404"; + case RET_Build_In_Progress_409: + return "Build_In_Progress_409"; + case RET_Resize_Not_Allowed_403: + return "Resize_Not_Allowed_403"; + case RET_Connection_Closed_Without_Reponse: + return "Connection_Closed_Without_Reponse"; + case RET_Unknown_Failure: + return "Unknown_Failure"; + } + return "Unknown event type (bug)"; +} +void Rackspace::AddOperation(RackspaceOperationType type, RakNet::RakString httpCommand, RakNet::RakString operation, RakNet::RakString xml) +{ + RackspaceOperation ro; + ro.type=type; + ro.httpCommand=httpCommand; + ro.operation=operation; + ro.xml=xml; + ro.isPendingAuthentication=HasOperationOfType(RO_CONNECT_AND_AUTHENTICATE); + if (ro.isPendingAuthentication==false) + { + if (ExecuteOperation(ro)) + operations.Insert(ro,_FILE_AND_LINE_); + } + else + operations.Insert(ro,_FILE_AND_LINE_); +} +void Rackspace::ListServers(void) +{ + AddOperation(RO_LIST_SERVERS, "GET", "servers", ""); +} +void Rackspace::ListServersWithDetails(void) +{ + AddOperation(RO_LIST_SERVERS_WITH_DETAILS, "GET", "servers/detail", ""); +} +void Rackspace::CreateServer(RakNet::RakString name, RakNet::RakString imageId, RakNet::RakString flavorId) +{ + RakNet::RakString xml( + "" + "" + "" + ,name.C_String() ,imageId.C_String(), flavorId.C_String()); + AddOperation(RO_CREATE_SERVER, "POST", "servers", xml); +} +void Rackspace::GetServerDetails(RakNet::RakString serverId) +{ + AddOperation(RO_GET_SERVER_DETAILS, "GET", RakNet::RakString("servers/%s", serverId.C_String()), ""); +} +void Rackspace::UpdateServerNameOrPassword(RakNet::RakString serverId, RakNet::RakString newName, RakNet::RakString newPassword) +{ + if (newName.IsEmpty() && newPassword.IsEmpty()) + return; + RakNet::RakString xml( + "" + "" + "", + rebootType.C_String()); + + AddOperation(RO_REBOOT_SERVER, "POST", RakNet::RakString("servers/%s/action", serverId.C_String()), xml); +} +void Rackspace::RebuildServer(RakNet::RakString serverId, RakNet::RakString imageId) +{ + RakNet::RakString xml( + "" + "", + imageId.C_String()); + + AddOperation(RO_REBUILD_SERVER, "POST", RakNet::RakString("servers/%s/action", serverId.C_String()), xml); +} +void Rackspace::ResizeServer(RakNet::RakString serverId, RakNet::RakString flavorId) +{ + RakNet::RakString xml( + "" + "", + flavorId.C_String()); + + AddOperation(RO_RESIZE_SERVER, "POST", RakNet::RakString("servers/%s/action", serverId.C_String()), xml); +} +void Rackspace::ConfirmResizedServer(RakNet::RakString serverId) +{ + RakNet::RakString xml( + "" + ""); + AddOperation(RO_CONFIRM_RESIZED_SERVER, "POST", RakNet::RakString("servers/%s/action", serverId.C_String()), xml); +} +void Rackspace::RevertResizedServer(RakNet::RakString serverId) +{ + RakNet::RakString xml( + "" + ""); + AddOperation(RO_REVERT_RESIZED_SERVER, "POST", RakNet::RakString("servers/%s/action", serverId.C_String()), xml); +} +void Rackspace::ListFlavors(void) +{ + AddOperation(RO_LIST_FLAVORS, "GET", "flavors", ""); +} +void Rackspace::GetFlavorDetails(RakNet::RakString flavorId) +{ + AddOperation(RO_GET_FLAVOR_DETAILS, "GET", RakNet::RakString("flavors/%s", flavorId.C_String()), ""); +} +void Rackspace::ListImages(void) +{ + AddOperation(RO_LIST_IMAGES, "GET", "images", ""); +} +void Rackspace::CreateImage(RakNet::RakString serverId, RakNet::RakString imageName) +{ + RakNet::RakString xml( + "" + "", + imageName.C_String(),serverId.C_String()); + + AddOperation(RO_CREATE_IMAGE, "POST", "images", xml); +} +void Rackspace::GetImageDetails(RakNet::RakString imageId) +{ + AddOperation(RO_GET_IMAGE_DETAILS, "GET", RakNet::RakString("images/%s", imageId.C_String()), ""); +} +void Rackspace::DeleteImage(RakNet::RakString imageId) +{ + AddOperation(RO_DELETE_IMAGE, "DELETE", RakNet::RakString("images/%s", imageId.C_String()), ""); +} +void Rackspace::ListSharedIPGroups(void) +{ + AddOperation(RO_LIST_SHARED_IP_GROUPS, "GET", "shared_ip_groups", ""); +} +void Rackspace::ListSharedIPGroupsWithDetails(void) +{ + AddOperation(RO_LIST_SHARED_IP_GROUPS_WITH_DETAILS, "GET", "shared_ip_groups/detail", ""); +} +void Rackspace::CreateSharedIPGroup(RakNet::RakString name, RakNet::RakString optionalServerId) +{ + RakNet::RakString xml( + "" + "", name.C_String()); + if (optionalServerId.IsEmpty()==false) + xml+=RakNet::RakString("", optionalServerId.C_String()); + xml+=""; + + AddOperation(RO_CREATE_SHARED_IP_GROUP, "POST", "shared_ip_groups", xml); +} +void Rackspace::GetSharedIPGroupDetails(RakNet::RakString groupId) +{ + AddOperation(RO_GET_SHARED_IP_GROUP_DETAILS, "GET", RakNet::RakString("shared_ip_groups/%s", groupId.C_String()), ""); +} +void Rackspace::DeleteSharedIPGroup(RakNet::RakString groupId) +{ + AddOperation(RO_DELETE_SHARED_IP_GROUP, "DELETE", RakNet::RakString("shared_ip_groups/%s", groupId.C_String()), ""); +} +void Rackspace::OnClosedConnection(SystemAddress systemAddress) +{ + if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) + return; + + unsigned int i, operationsIndex; + operationsIndex=0; + while (operationsIndex < operations.Size()) + { + if (operations[operationsIndex].isPendingAuthentication==false && operations[operationsIndex].connectionAddress==systemAddress) + { + RackspaceOperation ro = operations[operationsIndex]; + operations.RemoveAtIndex(operationsIndex); + + RakNet::RakString packetDataString = ro.incomingStream; + const char *packetData = packetDataString.C_String(); + + char resultCodeStr[32]; + int resultCodeInt; + + RackspaceEventType rackspaceEventType; + char *result; + result=strstr((char*) packetData, "HTTP/1.1 "); + if (result!=0) + { + result+=strlen("HTTP/1.1 "); + for (i=0; i < sizeof(resultCodeStr)-1 && result[i] && result[i]>='0' && result[i]<='9'; i++) + resultCodeStr[i]=result[i]; + resultCodeStr[i]=0; + resultCodeInt=atoi(resultCodeStr); + + switch (resultCodeInt) + { + case 200: rackspaceEventType=RET_Success_200; break; + case 201: rackspaceEventType=RET_Success_201; break; + case 202: rackspaceEventType=RET_Success_202; break; + case 203: rackspaceEventType=RET_Success_203; break; + case 204: rackspaceEventType=RET_Success_204; break; + case 500: rackspaceEventType=RET_Cloud_Servers_Fault_500; break; + case 503: rackspaceEventType=RET_Service_Unavailable_503; break; + case 401: rackspaceEventType=RET_Unauthorized_401; break; + case 400: rackspaceEventType=RET_Bad_Request_400; break; + case 413: rackspaceEventType=RET_Over_Limit_413; break; + case 415: rackspaceEventType=RET_Bad_Media_Type_415; break; + case 404: rackspaceEventType=RET_Item_Not_Found_404; break; + case 409: rackspaceEventType=RET_Build_In_Progress_409; break; + case 403: rackspaceEventType=RET_Resize_Not_Allowed_403; break; + default: rackspaceEventType=RET_Unknown_Failure; break; + } + } + else + { + rackspaceEventType=RET_Connection_Closed_Without_Reponse; + } + + switch (ro.type) + { + case RO_CONNECT_AND_AUTHENTICATE: + { + if (rackspaceEventType==RET_Success_204) + { + RakNet::RakString header; + ReadLine(packetData, "X-Server-Management-Url: ", serverManagementURL); + serverManagementURL.SplitURI(header, serverManagementDomain, serverManagementPath); + ReadLine(packetData, "X-Storage-Url: ", storageURL); + storageURL.SplitURI(header, storageDomain, storagePath); + ReadLine(packetData, "X-CDN-Management-Url: ", cdnManagementURL); + cdnManagementURL.SplitURI(header, cdnManagementDomain, cdnManagementPath); + ReadLine(packetData, "X-Auth-Token: ", authToken); + ReadLine(packetData, "X-Storage-Token: ", storageToken); + + operationsIndex=0; + while (operationsIndex < operations.Size()) + { + if (operations[operationsIndex].isPendingAuthentication==true) + { + operations[operationsIndex].isPendingAuthentication=false; + if (ExecuteOperation(operations[operationsIndex])==false) + { + operations.RemoveAtIndex(operationsIndex); + } + else + operationsIndex++; + } + else + operationsIndex++; + } + + // Restart in list + operationsIndex=0; + } + + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnAuthenticationResult(rackspaceEventType, (const char*) packetData); + + break; + } + case RO_LIST_SERVERS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnListServersResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_LIST_SERVERS_WITH_DETAILS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnListServersWithDetailsResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_CREATE_SERVER: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnCreateServerResult(rackspaceEventType, (const char*) packetData); + break; + } + + case RO_GET_SERVER_DETAILS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnGetServerDetails(rackspaceEventType, (const char*) packetData); + break; + } + case RO_UPDATE_SERVER_NAME_OR_PASSWORD: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnUpdateServerNameOrPassword(rackspaceEventType, (const char*) packetData); + break; + } + case RO_DELETE_SERVER: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnDeleteServer(rackspaceEventType, (const char*) packetData); + break; + } + case RO_LIST_SERVER_ADDRESSES: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnListServerAddresses(rackspaceEventType, (const char*) packetData); + break; + } + case RO_SHARE_SERVER_ADDRESS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnShareServerAddress(rackspaceEventType, (const char*) packetData); + break; + } + case RO_DELETE_SERVER_ADDRESS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnDeleteServerAddress(rackspaceEventType, (const char*) packetData); + break; + } + case RO_REBOOT_SERVER: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnRebootServer(rackspaceEventType, (const char*) packetData); + break; + } + case RO_REBUILD_SERVER: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnRebuildServer(rackspaceEventType, (const char*) packetData); + break; + } + case RO_RESIZE_SERVER: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnResizeServer(rackspaceEventType, (const char*) packetData); + break; + } + case RO_CONFIRM_RESIZED_SERVER: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnConfirmResizedServer(rackspaceEventType, (const char*) packetData); + break; + } + case RO_REVERT_RESIZED_SERVER: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnRevertResizedServer(rackspaceEventType, (const char*) packetData); + break; + } + + + case RO_LIST_FLAVORS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnListFlavorsResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_GET_FLAVOR_DETAILS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnGetFlavorDetailsResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_LIST_IMAGES: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnListImagesResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_CREATE_IMAGE: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnCreateImageResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_GET_IMAGE_DETAILS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnGetImageDetailsResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_DELETE_IMAGE: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnDeleteImageResult(rackspaceEventType, (const char*) packetData); + break; + } + case RO_LIST_SHARED_IP_GROUPS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnListSharedIPGroups(rackspaceEventType, (const char*) packetData); + break; + } + case RO_LIST_SHARED_IP_GROUPS_WITH_DETAILS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnListSharedIPGroupsWithDetails(rackspaceEventType, (const char*) packetData); + break; + } + case RO_CREATE_SHARED_IP_GROUP: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnCreateSharedIPGroup(rackspaceEventType, (const char*) packetData); + break; + } + case RO_GET_SHARED_IP_GROUP_DETAILS: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnGetSharedIPGroupDetails(rackspaceEventType, (const char*) packetData); + break; + } + case RO_DELETE_SHARED_IP_GROUP: + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnDeleteSharedIPGroup(rackspaceEventType, (const char*) packetData); + break; + } + default: + break; + + } + } + else + { + operationsIndex++; + } + } +} +void Rackspace::OnReceive(Packet *packet) +{ + unsigned int operationsIndex; + for (operationsIndex=0; operationsIndex < operations.Size(); operationsIndex++) + { + if (operations[operationsIndex].isPendingAuthentication==false && operations[operationsIndex].connectionAddress==packet->systemAddress) + { + operations[operationsIndex].incomingStream+=packet->data; + } + } +} +bool Rackspace::ExecuteOperation(RackspaceOperation &ro) +{ + if (ConnectToServerManagementDomain(ro)==false) + return false; + + RakNet::RakString command( + "%s %s/%s HTTP/1.1\n" + "Host: %s\n" + "Content-Type: application/xml\n" + "Content-Length: %i\n" + "Accept: application/xml\n" + "X-Auth-Token: %s\n", + ro.httpCommand.C_String(), serverManagementPath.C_String(), ro.operation.C_String(), serverManagementDomain.C_String(), + ro.xml.GetLength(), + authToken.C_String()); + + if (ro.xml.IsEmpty()==false) + { + command+="\n"; + command+=ro.xml; + command+="\n"; + } + + command+="\n"; + + //printf(command.C_String()); + + tcpInterface->Send(command.C_String(), (unsigned int) command.GetLength(), ro.connectionAddress, false); + return true; +} +void Rackspace::ReadLine(const char *data, const char *stringStart, RakNet::RakString &output) +{ + output.Clear(); + + char *result, *resultEnd; + + result=strstr((char*) data, stringStart); + if (result==0) + { + RakAssert(0); + return; + } + + result+=strlen(stringStart); + if (result==0) + { + RakAssert(0); + return; + } + + output=result; + resultEnd=result; + while (*resultEnd && (*resultEnd!='\r') && (*resultEnd!='\n') ) + resultEnd++; + output.Truncate((unsigned int) (resultEnd-result)); +} + + +bool Rackspace::ConnectToServerManagementDomain(RackspaceOperation &ro) +{ + unsigned int i; + + ro.connectionAddress=tcpInterface->Connect(serverManagementDomain.C_String(),443,true); + if (ro.connectionAddress==UNASSIGNED_SYSTEM_ADDRESS) + { + for (i=0; i < eventCallbacks.Size(); i++) + eventCallbacks[i]->OnConnectionAttemptFailure(ro.type, serverManagementURL); + return false; + } + +#if OPEN_SSL_CLIENT_SUPPORT==1 + tcpInterface->StartSSLClient(ro.connectionAddress); +#endif + + return true; +} +bool Rackspace::HasOperationOfType(RackspaceOperationType t) +{ + unsigned int i; + for (i=0; i < operations.Size(); i++) + { + if (operations[i].type==t) + return true; + } + return false; +} +unsigned int Rackspace::GetOperationOfTypeIndex(RackspaceOperationType t) +{ + unsigned int i; + for (i=0; i < operations.Size(); i++) + { + if (operations[i].type==t) + return i; + } + return (unsigned int) -1; +} + +#endif diff --git a/src/raknet/RakMemoryOverride.cpp b/src/raknet/RakMemoryOverride.cpp new file mode 100644 index 0000000..b250912 --- /dev/null +++ b/src/raknet/RakMemoryOverride.cpp @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/RakMemoryOverride.hpp" +#include "include/raknet/RakAssert.hpp" +#include + +#ifdef _RAKNET_SUPPORT_DL_MALLOC +#include "include/raknet/rdlmalloc.h" +#endif + + + + + + + +using namespace RakNet; + +#if _USE_RAK_MEMORY_OVERRIDE==1 + #if defined(malloc) + #pragma push_macro("malloc") + #undef malloc + #define RMO_MALLOC_UNDEF + #endif + + #if defined(realloc) + #pragma push_macro("realloc") + #undef realloc + #define RMO_REALLOC_UNDEF + #endif + + #if defined(free) + #pragma push_macro("free") + #undef free + #define RMO_FREE_UNDEF + #endif +#endif + +void DefaultOutOfMemoryHandler(const char *file, const long line) +{ + (void) file; + (void) line; + RakAssert(0); +} + +void * (*rakMalloc) (size_t size) = RakNet::_RakMalloc; +void* (*rakRealloc) (void *p, size_t size) = RakNet::_RakRealloc; +void (*rakFree) (void *p) = RakNet::_RakFree; +void* (*rakMalloc_Ex) (size_t size, const char *file, unsigned int line) = RakNet::_RakMalloc_Ex; +void* (*rakRealloc_Ex) (void *p, size_t size, const char *file, unsigned int line) = RakNet::_RakRealloc_Ex; +void (*rakFree_Ex) (void *p, const char *file, unsigned int line) = RakNet::_RakFree_Ex; +void (*notifyOutOfMemory) (const char *file, const long line)=DefaultOutOfMemoryHandler; +void * (*dlMallocMMap) (size_t size) = RakNet::_DLMallocMMap; +void * (*dlMallocDirectMMap) (size_t size) = RakNet::_DLMallocDirectMMap; +int (*dlMallocMUnmap) (void* ptr, size_t size) = RakNet::_DLMallocMUnmap; + +void SetMalloc( void* (*userFunction)(size_t size) ) +{ + rakMalloc=userFunction; +} +void SetRealloc( void* (*userFunction)(void *p, size_t size) ) +{ + rakRealloc=userFunction; +} +void SetFree( void (*userFunction)(void *p) ) +{ + rakFree=userFunction; +} +void SetMalloc_Ex( void* (*userFunction)(size_t size, const char *file, unsigned int line) ) +{ + rakMalloc_Ex=userFunction; +} +void SetRealloc_Ex( void* (*userFunction)(void *p, size_t size, const char *file, unsigned int line) ) +{ + rakRealloc_Ex=userFunction; +} +void SetFree_Ex( void (*userFunction)(void *p, const char *file, unsigned int line) ) +{ + rakFree_Ex=userFunction; +} +void SetNotifyOutOfMemory( void (*userFunction)(const char *file, const long line) ) +{ + notifyOutOfMemory=userFunction; +} +void SetDLMallocMMap( void* (*userFunction)(size_t size) ) +{ + dlMallocMMap=userFunction; +} +void SetDLMallocDirectMMap( void* (*userFunction)(size_t size) ) +{ + dlMallocDirectMMap=userFunction; +} +void SetDLMallocMUnmap( int (*userFunction)(void* ptr, size_t size) ) +{ + dlMallocMUnmap=userFunction; +} +void * (*GetMalloc()) (size_t size) +{ + return rakMalloc; +} +void * (*GetRealloc()) (void *p, size_t size) +{ + return rakRealloc; +} +void (*GetFree()) (void *p) +{ + return rakFree; +} +void * (*GetMalloc_Ex()) (size_t size, const char *file, unsigned int line) +{ + return rakMalloc_Ex; +} +void * (*GetRealloc_Ex()) (void *p, size_t size, const char *file, unsigned int line) +{ + return rakRealloc_Ex; +} +void (*GetFree_Ex()) (void *p, const char *file, unsigned int line) +{ + return rakFree_Ex; +} +void *(*GetDLMallocMMap())(size_t size) +{ + return dlMallocMMap; +} +void *(*GetDLMallocDirectMMap())(size_t size) +{ + return dlMallocDirectMMap; +} +int (*GetDLMallocMUnmap())(void* ptr, size_t size) +{ + return dlMallocMUnmap; +} +void* RakNet::_RakMalloc (size_t size) +{ + return malloc(size); +} + +void* RakNet::_RakRealloc (void *p, size_t size) +{ + return realloc(p,size); +} + +void RakNet::_RakFree (void *p) +{ + free(p); +} + +void* RakNet::_RakMalloc_Ex (size_t size, const char *file, unsigned int line) +{ + (void) file; + (void) line; + + return malloc(size); +} + +void* RakNet::_RakRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) +{ + (void) file; + (void) line; + + return realloc(p,size); +} + +void RakNet::_RakFree_Ex (void *p, const char *file, unsigned int line) +{ + (void) file; + (void) line; + + free(p); +} +#ifdef _RAKNET_SUPPORT_DL_MALLOC +void * RakNet::_DLMallocMMap (size_t size) +{ + return RAK_MMAP_DEFAULT(size); +} +void * RakNet::_DLMallocDirectMMap (size_t size) +{ + return RAK_DIRECT_MMAP_DEFAULT(size); +} +int RakNet::_DLMallocMUnmap (void *p, size_t size) +{ + return RAK_MUNMAP_DEFAULT(p,size); +} + +static mspace rakNetFixedHeapMSpace=0; + +void* _DLMalloc(size_t size) +{ + return rak_mspace_malloc(rakNetFixedHeapMSpace,size); +} + +void* _DLRealloc(void *p, size_t size) +{ + return rak_mspace_realloc(rakNetFixedHeapMSpace,p,size); +} + +void _DLFree(void *p) +{ + if (p) + rak_mspace_free(rakNetFixedHeapMSpace,p); +} +void* _DLMalloc_Ex (size_t size, const char *file, unsigned int line) +{ + (void) file; + (void) line; + + return rak_mspace_malloc(rakNetFixedHeapMSpace,size); +} + +void* _DLRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) +{ + (void) file; + (void) line; + + return rak_mspace_realloc(rakNetFixedHeapMSpace,p,size); +} + +void _DLFree_Ex (void *p, const char *file, unsigned int line) +{ + (void) file; + (void) line; + + if (p) + rak_mspace_free(rakNetFixedHeapMSpace,p); +} + +void UseRaknetFixedHeap(size_t initialCapacity, + void * (*yourMMapFunction) (size_t size), + void * (*yourDirectMMapFunction) (size_t size), + int (*yourMUnmapFunction) (void *p, size_t size)) +{ + SetDLMallocMMap(yourMMapFunction); + SetDLMallocDirectMMap(yourDirectMMapFunction); + SetDLMallocMUnmap(yourMUnmapFunction); + SetMalloc(_DLMalloc); + SetRealloc(_DLRealloc); + SetFree(_DLFree); + SetMalloc_Ex(_DLMalloc_Ex); + SetRealloc_Ex(_DLRealloc_Ex); + SetFree_Ex(_DLFree_Ex); + + rakNetFixedHeapMSpace=rak_create_mspace(initialCapacity, 0); +} +void FreeRakNetFixedHeap(void) +{ + if (rakNetFixedHeapMSpace) + { + rak_destroy_mspace(rakNetFixedHeapMSpace); + rakNetFixedHeapMSpace=0; + } + + SetMalloc(_RakMalloc); + SetRealloc(_RakRealloc); + SetFree(_RakFree); + SetMalloc_Ex(_RakMalloc_Ex); + SetRealloc_Ex(_RakRealloc_Ex); + SetFree_Ex(_RakFree_Ex); +} +#else +void * RakNet::_DLMallocMMap (size_t size) {(void) size; return 0;} +void * RakNet::_DLMallocDirectMMap (size_t size) {(void) size; return 0;} +int RakNet::_DLMallocMUnmap (void *p, size_t size) {(void) size; (void) p; return 0;} +void* _DLMalloc(size_t size) {(void) size; return 0;} +void* _DLRealloc(void *p, size_t size) {(void) p; (void) size; return 0;} +void _DLFree(void *p) {(void) p;} +void* _DLMalloc_Ex (size_t size, const char *file, unsigned int line) {(void) size; (void) file; (void) line; return 0;} +void* _DLRealloc_Ex (void *p, size_t size, const char *file, unsigned int line) {(void) p; (void) size; (void) file; (void) line; return 0;} +void _DLFree_Ex (void *p, const char *file, unsigned int line) {(void) p; (void) file; (void) line;} + +void UseRaknetFixedHeap(size_t initialCapacity, + void * (*yourMMapFunction) (size_t size), + void * (*yourDirectMMapFunction) (size_t size), + int (*yourMUnmapFunction) (void *p, size_t size)) +{ + (void) initialCapacity; + (void) yourMMapFunction; + (void) yourDirectMMapFunction; + (void) yourMUnmapFunction; +} +void FreeRakNetFixedHeap(void) {} +#endif + +#if _USE_RAK_MEMORY_OVERRIDE==1 + #if defined(RMO_MALLOC_UNDEF) + #pragma pop_macro("malloc") + #undef RMO_MALLOC_UNDEF + #endif + + #if defined(RMO_REALLOC_UNDEF) + #pragma pop_macro("realloc") + #undef RMO_REALLOC_UNDEF + #endif + + #if defined(RMO_FREE_UNDEF) + #pragma pop_macro("free") + #undef RMO_FREE_UNDEF + #endif +#endif diff --git a/src/raknet/RakNetCommandParser.cpp b/src/raknet/RakNetCommandParser.cpp new file mode 100644 index 0000000..1fb7faf --- /dev/null +++ b/src/raknet/RakNetCommandParser.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_RakNetCommandParser==1 + +#include "include/raknet/RakNetCommandParser.hpp" +#include "include/raknet/TransportInterface.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/RakAssert.hpp" +#include +#include +#include + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(RakNetCommandParser,RakNetCommandParser); + +RakNetCommandParser::RakNetCommandParser() +{ + RegisterCommand(4, "Startup","( unsigned int maxConnections, unsigned short localPort, const char *forceHostAddress );"); + RegisterCommand(0,"InitializeSecurity","();"); + RegisterCommand(0,"DisableSecurity","( void );"); + RegisterCommand(1,"AddToSecurityExceptionList","( const char *ip );"); + RegisterCommand(1,"RemoveFromSecurityExceptionList","( const char *ip );"); + RegisterCommand(1,"IsInSecurityExceptionList","( const char *ip );"); + RegisterCommand(1,"SetMaximumIncomingConnections","( unsigned short numberAllowed );"); + RegisterCommand(0,"GetMaximumIncomingConnections","( void ) const;"); + RegisterCommand(4,"Connect","( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength );"); + RegisterCommand(2,"Disconnect","( unsigned int blockDuration, unsigned char orderingChannel=0 );"); + RegisterCommand(0,"IsActive","( void ) const;"); + RegisterCommand(0,"GetConnectionList","() const;"); + RegisterCommand(3,"CloseConnection","( const SystemAddress target, bool sendDisconnectionNotification, unsigned char orderingChannel=0 );"); + RegisterCommand(2,"IsConnected","( );"); + RegisterCommand(1,"GetIndexFromSystemAddress","( const SystemAddress systemAddress );"); + RegisterCommand(1,"GetSystemAddressFromIndex","( unsigned int index );"); + RegisterCommand(2,"AddToBanList","( const char *IP, RakNet::TimeMS milliseconds=0 );"); + RegisterCommand(1,"RemoveFromBanList","( const char *IP );"); + RegisterCommand(0,"ClearBanList","( void );"); + RegisterCommand(1,"IsBanned","( const char *IP );"); + RegisterCommand(1,"Ping1","( const SystemAddress target );"); + RegisterCommand(3,"Ping2","( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections );"); + RegisterCommand(1,"GetAveragePing","( const SystemAddress systemAddress );"); + RegisterCommand(1,"GetLastPing","( const SystemAddress systemAddress ) const;"); + RegisterCommand(1,"GetLowestPing","( const SystemAddress systemAddress ) const;"); + RegisterCommand(1,"SetOccasionalPing","( bool doPing );"); + RegisterCommand(2,"SetOfflinePingResponse","( const char *data, const unsigned int length );"); + RegisterCommand(0,"GetInternalID","( void ) const;"); + RegisterCommand(1,"GetExternalID","( const SystemAddress target ) const;"); + RegisterCommand(2,"SetTimeoutTime","( RakNet::TimeMS timeMS, const SystemAddress target );"); +// RegisterCommand(1,"SetMTUSize","( int size );"); + RegisterCommand(0,"GetMTUSize","( void ) const;"); + RegisterCommand(0,"GetNumberOfAddresses","( void );"); + RegisterCommand(1,"GetLocalIP","( unsigned int index );"); + RegisterCommand(1,"AllowConnectionResponseIPMigration","( bool allow );"); + RegisterCommand(4,"AdvertiseSystem","( const char *host, unsigned short remotePort, const char *data, int dataLength );"); + RegisterCommand(2,"SetIncomingPassword","( const char* passwordData, int passwordDataLength );"); + RegisterCommand(0,"GetIncomingPassword","( void );"); + RegisterCommand(0,"IsNetworkSimulatorActive","( void );"); +} +RakNetCommandParser::~RakNetCommandParser() +{ +} +void RakNetCommandParser::SetRakPeerInterface(RakNet::RakPeerInterface *rakPeer) +{ + peer=rakPeer; +} +bool RakNetCommandParser::OnCommand(const char *command, unsigned numParameters, char **parameterList, TransportInterface *transport, const SystemAddress &systemAddress, const char *originalString) +{ + (void) originalString; + (void) numParameters; + + if (peer==0) + return false; + + if (strcmp(command, "Startup")==0) + { + RakNet::SocketDescriptor socketDescriptor((unsigned short)atoi(parameterList[1]), parameterList[2]); + ReturnResult(peer->Startup((unsigned short)atoi(parameterList[0]), &socketDescriptor, 1), command, transport, systemAddress); + } + else if (strcmp(command, "InitializeSecurity")==0) + { + ReturnResult(peer->InitializeSecurity(parameterList[0],parameterList[1]), command, transport, systemAddress); + } + else if (strcmp(command, "DisableSecurity")==0) + { + peer->DisableSecurity(); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "AddToSecurityExceptionList")==0) + { + peer->AddToSecurityExceptionList(parameterList[1]); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "RemoveFromSecurityExceptionList")==0) + { + peer->RemoveFromSecurityExceptionList(parameterList[1]); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "IsInSecurityExceptionList")==0) + { + ReturnResult(peer->IsInSecurityExceptionList(parameterList[1]),command, transport, systemAddress); + } + else if (strcmp(command, "SetMaximumIncomingConnections")==0) + { + peer->SetMaximumIncomingConnections((unsigned short)atoi(parameterList[0])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "GetMaximumIncomingConnections")==0) + { + ReturnResult((int) peer->GetMaximumIncomingConnections(), command, transport, systemAddress); + } + else if (strcmp(command, "Connect")==0) + { + ReturnResult(peer->Connect(parameterList[0], (unsigned short)atoi(parameterList[1]),parameterList[2],atoi(parameterList[3]))==RakNet::CONNECTION_ATTEMPT_STARTED, command, transport, systemAddress); + } + else if (strcmp(command, "Disconnect")==0) + { + peer->Shutdown(atoi(parameterList[0]), (unsigned char)atoi(parameterList[1])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "IsActive")==0) + { + ReturnResult(peer->IsActive(), command, transport, systemAddress); + } + else if (strcmp(command, "GetConnectionList")==0) + { + SystemAddress remoteSystems[32]; + unsigned short count=32; + unsigned i; + if (peer->GetConnectionList(remoteSystems, &count)) + { + if (count==0) + { + transport->Send(systemAddress, "GetConnectionList() returned no systems connected.\r\n"); + } + else + { + transport->Send(systemAddress, "GetConnectionList() returned:\r\n"); + for (i=0; i < count; i++) + { + char str1[64]; + remoteSystems[i].ToString(true, str1); + transport->Send(systemAddress, "%i %s\r\n", i, str1); + } + } + } + else + transport->Send(systemAddress, "GetConnectionList() returned false.\r\n"); + } + else if (strcmp(command, "CloseConnection")==0) + { + peer->CloseConnection(SystemAddress(parameterList[0]), atoi(parameterList[1])!=0,(unsigned char)atoi(parameterList[2])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "GetConnectionState")==0) + { + ReturnResult((int) peer->GetConnectionState(SystemAddress(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "GetIndexFromSystemAddress")==0) + { + ReturnResult(peer->GetIndexFromSystemAddress(SystemAddress(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "GetSystemAddressFromIndex")==0) + { + ReturnResult(peer->GetSystemAddressFromIndex(atoi(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "AddToBanList")==0) + { + peer->AddToBanList(parameterList[0], atoi(parameterList[1])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "RemoveFromBanList")==0) + { + peer->RemoveFromBanList(parameterList[0]); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "ClearBanList")==0) + { + peer->ClearBanList(); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "IsBanned")==0) + { + ReturnResult(peer->IsBanned(parameterList[0]), command, transport, systemAddress); + } + else if (strcmp(command, "Ping1")==0) + { + peer->Ping(SystemAddress(parameterList[0])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "Ping2")==0) + { + peer->Ping(parameterList[0], (unsigned short) atoi(parameterList[1]), atoi(parameterList[2])!=0); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "GetAveragePing")==0) + { + ReturnResult(peer->GetAveragePing(SystemAddress(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "GetLastPing")==0) + { + ReturnResult(peer->GetLastPing(SystemAddress(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "GetLowestPing")==0) + { + ReturnResult(peer->GetLowestPing(SystemAddress(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "SetOccasionalPing")==0) + { + peer->SetOccasionalPing(atoi(parameterList[0])!=0); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "SetOfflinePingResponse")==0) + { + peer->SetOfflinePingResponse(parameterList[0], atoi(parameterList[1])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "GetInternalID")==0) + { + ReturnResult(peer->GetInternalID(), command, transport, systemAddress); + } + else if (strcmp(command, "GetExternalID")==0) + { + ReturnResult(peer->GetExternalID(SystemAddress(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "SetTimeoutTime")==0) + { + peer->SetTimeoutTime(atoi(parameterList[0]), SystemAddress(parameterList[1])); + ReturnResult(command, transport, systemAddress); + } + /* + else if (strcmp(command, "SetMTUSize")==0) + { + ReturnResult(peer->SetMTUSize(atoi(parameterList[0]), UNASSIGNED_SYSTEM_ADDRESS), command, transport, systemAddress); + } + */ + else if (strcmp(command, "GetMTUSize")==0) + { + ReturnResult(peer->GetMTUSize(UNASSIGNED_SYSTEM_ADDRESS), command, transport, systemAddress); + } + else if (strcmp(command, "GetNumberOfAddresses")==0) + { + ReturnResult((int)peer->GetNumberOfAddresses(), command, transport, systemAddress); + } + else if (strcmp(command, "GetLocalIP")==0) + { + ReturnResult((char*) peer->GetLocalIP(atoi(parameterList[0])), command, transport, systemAddress); + } + else if (strcmp(command, "AllowConnectionResponseIPMigration")==0) + { + peer->AllowConnectionResponseIPMigration(atoi(parameterList[0])!=0); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "AdvertiseSystem")==0) + { + peer->AdvertiseSystem(parameterList[0], (unsigned short) atoi(parameterList[1]),parameterList[2],atoi(parameterList[3])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "SetIncomingPassword")==0) + { + peer->SetIncomingPassword(parameterList[0], atoi(parameterList[1])); + ReturnResult(command, transport, systemAddress); + } + else if (strcmp(command, "GetIncomingPassword")==0) + { + char password[256]; + int passwordLength; + peer->GetIncomingPassword(password, &passwordLength); + if (passwordLength) + ReturnResult((char*)password, command, transport, systemAddress); + else + ReturnResult(0, command, transport, systemAddress); + } + + return true; +} +const char *RakNetCommandParser::GetName(void) const +{ + return "RakNet"; +} +void RakNetCommandParser::SendHelp(TransportInterface *transport, const SystemAddress &systemAddress) +{ + if (peer) + { + transport->Send(systemAddress, "The RakNet parser provides mirror functions to RakPeer\r\n"); + transport->Send(systemAddress, "SystemAddresss take two parameters: send .\r\n"); + transport->Send(systemAddress, "For bool, send 1 or 0.\r\n"); + } + else + { + transport->Send(systemAddress, "Parser not active. Call SetRakPeerInterface.\r\n"); + } +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/RakNetSocket.cpp b/src/raknet/RakNetSocket.cpp new file mode 100644 index 0000000..07fc8b0 --- /dev/null +++ b/src/raknet/RakNetSocket.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/* +#include "include/raknet/RakNetSocket.hpp" +#include "include/raknet/RakMemoryOverride.hpp" + +using namespace RakNet; + +#if defined(__native_client__) +using namespace pp; +#endif + +RakNetSocket::RakNetSocket() { + #if !defined(WINDOWS_STORE_RT) + s = 0; + #endif + remotePortRakNetWasStartedOn_PS3_PSP2 = 0; + userConnectionSocketIndex = (unsigned int) -1; + socketFamily = 0; + blockingSocket = 0; + extraSocketOptions = 0; + chromeInstance = 0; + +#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) + recvEvent=INVALID_HANDLE_VALUE; +#endif + + #ifdef __native_client__ + s = 0; + sendInProgress = false; + nextSendSize = 0; + #endif +} +RakNetSocket::~RakNetSocket() +{ + #ifdef __native_client__ + if(s != 0) + ((PPB_UDPSocket_Private_0_4*) pp::Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->Close(s); +#elif defined(WINDOWS_STORE_RT) + WinRTClose(s); + #else + if ((__UDPSOCKET__)s != 0) + closesocket__(s); + #endif + + +#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) + if (recvEvent!=INVALID_HANDLE_VALUE) + { + CloseHandle( recvEvent ); + recvEvent = INVALID_HANDLE_VALUE; + } +#endif +} +// +// void RakNetSocket::Accept( +// struct sockaddr *addr, +// int *addrlen) +// { +// accept__(s, addr, addrlen); +// } + +// +// void RakNetSocket::Close( void ) +// { +// closesocket__(s); +// } + +RakNetSocket* RakNetSocket::Create +#ifdef __native_client__ + (_PP_Instance_ _chromeInstance) +#else + (int af, + int type, + int protocol) +#endif +{ + __UDPSOCKET__ sock; + + #ifndef __native_client__ + RakAssert(type==SOCK_DGRAM); + #endif + + #ifdef __native_client__ + sock = ((PPB_UDPSocket_Private_0_4*) Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->Create(_chromeInstance); + #elif defined(SN_TARGET_PSP2) + sock = sceNetSocket( "RakNetSocket::Create", SCE_NET_AF_INET, SCE_NET_SOCK_DGRAM_P2P, 0 ); + #elif defined(WINDOWS_STORE_RT) + sock = WinRTCreateDatagramSocket(af,type,protocol); + #elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3) || defined(_PS4) + sock = socket__( AF_INET, SOCK_DGRAM_P2P, 0 ); + #else + sock = socket__(af, type, protocol); + #endif + + #if !defined(WINDOWS_STORE_RT) + if (sock<0) + return 0; + #endif + RakNetSocket *rns = RakNet::OP_NEW(_FILE_AND_LINE_); + rns->s = sock; + #ifdef __native_client__ + rns->chromeInstance = _chromeInstance; + #endif + return rns; +} + +int RakNetSocket::Bind( + const struct sockaddr *addr, + int namelen) +{ + return bind__(s,addr,namelen); +} + +int RakNetSocket::IOCTLSocket( + long cmd, + unsigned long *argp) +{ + #if defined(_WIN32) + return ioctlsocket__(s,cmd,argp); + #else + return 0; + #endif +} + +int RakNetSocket::Listen ( + int backlog) +{ + return listen__(s,backlog); +} + +int RakNetSocket::SetSockOpt( + int level, + int optname, + const char * optval, + int optlen) +{ + return setsockopt__(s,level,optname,optval,optlen); +} + +int RakNetSocket::Shutdown( + int how) +{ + #ifndef SN_TARGET_PSP2 + return shutdown__(s,how); + #else + return 0; + #endif +} +*/ diff --git a/src/raknet/RakNetSocket2.cpp b/src/raknet/RakNetSocket2.cpp new file mode 100644 index 0000000..0749c64 --- /dev/null +++ b/src/raknet/RakNetSocket2.cpp @@ -0,0 +1,513 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/RakNetSocket2.hpp" +#include "include/raknet/RakMemoryOverride.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakSleep.hpp" +#include "include/raknet/SocketDefines.hpp" +#include "include/raknet/GetTime.hpp" +#include +#include // memcpy + +using namespace RakNet; + +#ifdef _WIN32 +#else +#include +#include +#include +#include // error numbers +#if !defined(ANDROID) +#include +#endif +#include +#include +#include +#include +#include +#endif + +#ifdef TEST_NATIVE_CLIENT_ON_WINDOWS +#else +#define RAKNET_SOCKET_2_INLINE_FUNCTIONS +#include "RakNetSocket2_360_720.cpp" +#include "RakNetSocket2_PS3_PS4.cpp" +#include "RakNetSocket2_PS4.cpp" +#include "RakNetSocket2_Windows_Linux.cpp" +#include "RakNetSocket2_Windows_Linux_360.cpp" +#include "RakNetSocket2_Vita.cpp" +#include "RakNetSocket2_NativeClient.cpp" +#include "RakNetSocket2_Berkley.cpp" +#include "RakNetSocket2_Berkley_NativeClient.cpp" +#include "RakNetSocket2_WindowsStore8.cpp" +#undef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#endif + +#ifndef INVALID_SOCKET +#define INVALID_SOCKET -1 +#endif + +void RakNetSocket2Allocator::DeallocRNS2(RakNetSocket2 *s) {RakNet::OP_DELETE(s,_FILE_AND_LINE_);} +RakNetSocket2::RakNetSocket2() {eventHandler=0;} +RakNetSocket2::~RakNetSocket2() {} +void RakNetSocket2::SetRecvEventHandler(RNS2EventHandler *_eventHandler) {eventHandler=_eventHandler;} +RNS2Type RakNetSocket2::GetSocketType(void) const {return socketType;} +void RakNetSocket2::SetSocketType(RNS2Type t) {socketType=t;} +bool RakNetSocket2::IsBerkleySocket(void) const { + return socketType!=RNS2T_CHROME && socketType!=RNS2T_WINDOWS_STORE_8; +} +SystemAddress RakNetSocket2::GetBoundAddress(void) const {return boundAddress;} + +RakNetSocket2* RakNetSocket2Allocator::AllocRNS2(void) +{ + RakNetSocket2* s2; +#if defined(WINDOWS_STORE_RT) + s2 = RakNet::OP_NEW(_FILE_AND_LINE_); + s2->SetSocketType(RNS2T_WINDOWS_STORE_8); + + + + + + +#elif defined(__native_client__) + s2 = RakNet::OP_NEW(_FILE_AND_LINE_); + s2->SetSocketType(RNS2T_CHROME); + + + + + + + + + +#elif defined(_WIN32) + s2 = RakNet::OP_NEW(_FILE_AND_LINE_); + s2->SetSocketType(RNS2T_WINDOWS); +#else + s2 = RakNet::OP_NEW(_FILE_AND_LINE_); + s2->SetSocketType(RNS2T_LINUX); +#endif + return s2; +} +void RakNetSocket2::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) +{ +#if defined(WINDOWS_STORE_RT) + RNS2_WindowsStore8::GetMyIP( addresses ); + + + + +#elif defined(__native_client__) + RNS2_NativeClient::GetMyIP( addresses ); + + + + + + +#elif defined(_WIN32) + RNS2_Windows::GetMyIP( addresses ); +#else + RNS2_Linux::GetMyIP( addresses ); +#endif +} + +unsigned int RakNetSocket2::GetUserConnectionSocketIndex(void) const {return userConnectionSocketIndex;} +void RakNetSocket2::SetUserConnectionSocketIndex(unsigned int i) {userConnectionSocketIndex=i;} +RNS2EventHandler * RakNetSocket2::GetEventHandler(void) const {return eventHandler;} + +void RakNetSocket2::DomainNameToIP( const char *domainName, char ip[65] ) { +#if defined(WINDOWS_STORE_RT) + return RNS2_WindowsStore8::DomainNameToIP( domainName, ip ); +#elif defined(__native_client__) + return DomainNameToIP_Berkley( domainName, ip ); + + + + + + + + + + +#elif defined(_WIN32) + return DomainNameToIP_Berkley( domainName, ip ); +#else + return DomainNameToIP_Berkley( domainName, ip ); +#endif +} + +#if defined(WINDOWS_STORE_RT) +#elif defined(__native_client__) +RNS2_NativeClient::RNS2_NativeClient() {bindState = BS_UNBOUND; sendInProgress=false;} +RNS2_NativeClient::~RNS2_NativeClient() +{ + bufferedSendsMutex.Lock(); + while (bufferedSends.Size()) + RakNet::OP_DELETE(bufferedSends.Pop(), _FILE_AND_LINE_); + bufferedSendsMutex.Unlock(); +} +void RNS2_NativeClient::onSocketBound(void* pData, int32_t dataSize) +{ + RAKNET_DEBUG_PRINTF("onSocketBound ==> %d\n", dataSize); + RNS2_NativeClient *csc = (RNS2_NativeClient *)pData; + + //any error codes will be given to us in the dataSize value + if(dataSize < 0) + { + csc->bindState=BS_FAILED; + fprintf(stderr,"onSocketBound exiting, dataSize = %d\n", dataSize); + return; + } + + csc->bindState=BS_BOUND; + + csc->ProcessBufferedSend(); + csc->IssueReceiveCall(); +} +void RNS2_NativeClient::ProcessBufferedSend(void) +{ + // Don't send until bound + if (bindState!=BS_BOUND) + return; + // Fast non-threadsafe check + if (bufferedSends.IsEmpty()==true) + return; + + sendInProgressMutex.Lock(); + if (sendInProgress==true) {sendInProgressMutex.Unlock(); return;} + else {sendInProgress=true;} + sendInProgressMutex.Unlock(); + + RNS2_SendParameters_NativeClient *sp; + bufferedSendsMutex.Lock(); + if (bufferedSends.IsEmpty()==false) + sp=bufferedSends.Pop(); + else + sp=0; + bufferedSendsMutex.Unlock(); + if (sp==0) + { + sendInProgressMutex.Lock(); + sendInProgress=false; + sendInProgressMutex.Unlock(); + return; // Nothing to send after all + } + + SendImmediate(sp); + // sp remains in memory until the callback completes + // DeallocSP(sp); +} +void RNS2_NativeClient::DeallocSP(RNS2_SendParameters_NativeClient *sp) +{ + rakFree_Ex(sp->data, _FILE_AND_LINE_); + RakNet::OP_DELETE(sp, _FILE_AND_LINE_); +} +RNS2_SendParameters_NativeClient* RNS2_NativeClient::CloneSP(RNS2_SendParameters *sp, RNS2_NativeClient *socket2, const char *file, unsigned int line) +{ + RNS2_SendParameters_NativeClient *spNew = RakNet::OP_NEW(file, line); + spNew->data=(char*) rakMalloc(sp->length); + memcpy(spNew->data,sp->data,sp->length); + spNew->length = sp->length; + spNew->socket2=socket2; + spNew->systemAddress=sp->systemAddress; + spNew->ttl=0; // Unused + return spNew; +} +void RNS2_NativeClient::onSendTo(void* pData, int32_t dataSize) +{ + if(dataSize <= 0) + RAKNET_DEBUG_PRINTF("onSendTo: send failed with error %d\n", dataSize); + + RNS2_SendParameters_NativeClient *sp = (RNS2_SendParameters_NativeClient*) pData; + + // Caller will check sendInProgress to send again if needed + sp->socket2->sendInProgressMutex.Lock(); + sp->socket2->sendInProgress=false; + sp->socket2->sendInProgressMutex.Unlock(); + + DeallocSP(sp); + +// if(dataSize == PP_ERROR_ABORTED) +// return; +} +RNS2SendResult RNS2_NativeClient::Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ) +{ + if (bindState==BS_FAILED) + return -1; + + // This is called from multiple threads. Always buffer the send, until native client is threadsafe + BufferSend(sendParameters, file, line); + return sendParameters->length; +} +void RNS2_NativeClient::BufferSend( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ) +{ + if (bindState==BS_FAILED) + return; + + RNS2_SendParameters_NativeClient* sp = CloneSP(sendParameters, this, file, line); + bufferedSendsMutex.Lock(); + bufferedSends.Push(sp, file, line); + bufferedSendsMutex.Unlock(); + + // Do not check to send immediately, because this was probably invoked from a thread and native client is not threadsafe +} +void RNS2_NativeClient::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) {addresses[0]=UNASSIGNED_SYSTEM_ADDRESS; RakAssert("GetMyIP Unsupported?" && 0);} +const NativeClientBindParameters *RNS2_NativeClient::GetBindings(void) const {return &binding;} +void RNS2_NativeClient::Update(void) +{ + // Don't send until bound + if (bindState==BS_BOUND) + { + do + { + ProcessBufferedSend(); + } while (sendInProgress==false && bufferedSends.Size()>1); + } +} + +#else // defined(__native_client__) +bool IRNS2_Berkley::IsPortInUse(unsigned short port, const char *hostAddress, unsigned short addressFamily, int type ) { + RNS2_BerkleyBindParameters bbp; + bbp.remotePortRakNetWasStartedOn_PS3_PS4_PSP2=0; + bbp.port=port; bbp.hostAddress=(char*) hostAddress; bbp.addressFamily=addressFamily; + bbp.type=type; bbp.protocol=0; bbp.nonBlockingSocket=false; + bbp.setBroadcast=false; bbp.doNotFragment=false; bbp.protocol=0; + bbp.setIPHdrIncl=false; + SystemAddress boundAddress; + RNS2_Berkley *rns2 = (RNS2_Berkley*) RakNetSocket2Allocator::AllocRNS2(); + RNS2BindResult bindResult = rns2->Bind(&bbp, _FILE_AND_LINE_); + RakNetSocket2Allocator::DeallocRNS2(rns2); + return bindResult==BR_FAILED_TO_BIND_SOCKET; +} + +#if defined(__APPLE__) +void SocketReadCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) +// This C routine is called by CFSocket when there's data waiting on our +// UDP socket. It just redirects the call to Objective-C code. +{ } +#endif + +RNS2BindResult RNS2_Berkley::BindShared( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { + RNS2BindResult br; +#if RAKNET_SUPPORT_IPV6==1 + br=BindSharedIPV4And6(bindParameters, file, line); +#else + br=BindSharedIPV4(bindParameters, file, line); +#endif + + if (br!=BR_SUCCESS) + return br; + + unsigned long zero=0; + RNS2_SendParameters bsp; + bsp.data=(char*) &zero; + bsp.length=4; + bsp.systemAddress=boundAddress; + bsp.ttl=0; + RNS2SendResult sr = Send(&bsp, _FILE_AND_LINE_); + if (sr<0) + return BR_FAILED_SEND_TEST; + + memcpy(&binding, bindParameters, sizeof(RNS2_BerkleyBindParameters)); + + /* +#if defined(__APPLE__) + const CFSocketContext context = { 0, this, NULL, NULL, NULL }; + _cfSocket = CFSocketCreateWithNative(NULL, rns2Socket, kCFSocketReadCallBack, SocketReadCallback, &context); +#endif + */ + + return br; +} + +RAK_THREAD_DECLARATION(RNS2_Berkley::RecvFromLoop) +{ + + + + RNS2_Berkley *b = ( RNS2_Berkley * ) arguments; + + b->RecvFromLoopInt(); + return 0; +} +unsigned RNS2_Berkley::RecvFromLoopInt(void) +{ + isRecvFromLoopThreadActive.Increment(); + + while ( endThreads == false ) + { + RNS2RecvStruct *recvFromStruct; + recvFromStruct=binding.eventHandler->AllocRNS2RecvStruct(_FILE_AND_LINE_); + if (recvFromStruct != NULL) + { + recvFromStruct->socket=this; + RecvFromBlocking(recvFromStruct); + + if (recvFromStruct->bytesRead>0) + { + RakAssert(recvFromStruct->systemAddress.GetPort()); + binding.eventHandler->OnRNS2Recv(recvFromStruct); + } + else + { + RakSleep(0); + binding.eventHandler->DeallocRNS2RecvStruct(recvFromStruct, _FILE_AND_LINE_); + } + } + } + isRecvFromLoopThreadActive.Decrement(); + + + + + return 0; + +} +RNS2_Berkley::RNS2_Berkley() +{ + rns2Socket=(RNS2Socket)INVALID_SOCKET; +} +RNS2_Berkley::~RNS2_Berkley() +{ + if (rns2Socket!=INVALID_SOCKET) + { + /* +#if defined(__APPLE__) + CFSocketInvalidate(_cfSocket); +#endif + */ + + closesocket__(rns2Socket); + } + +} +int RNS2_Berkley::CreateRecvPollingThread(int threadPriority) +{ + endThreads=false; + + + + + + + int errorCode = RakNet::RakThread::Create(RecvFromLoop, this, threadPriority); + + return errorCode; +} +void RNS2_Berkley::SignalStopRecvPollingThread(void) +{ + endThreads=true; +} +void RNS2_Berkley::BlockOnStopRecvPollingThread(void) +{ + endThreads=true; + + // Get recvfrom to unblock + RNS2_SendParameters bsp; + unsigned long zero=0; + bsp.data=(char*) &zero; + bsp.length=4; + bsp.systemAddress=boundAddress; + bsp.ttl=0; + Send(&bsp, _FILE_AND_LINE_); + + RakNet::TimeMS timeout = RakNet::GetTimeMS()+1000; + while ( isRecvFromLoopThreadActive.GetValue()>0 && RakNet::GetTimeMS()RakNetSendTo(sendParameters->data, sendParameters->length,sendParameters->systemAddress); + if (len>=0) + return len; + } + return Send_Windows_Linux_360NoVDP(rns2Socket,sendParameters, file, line); +} +void RNS2_Windows::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) {return GetMyIP_Windows_Linux(addresses);} +void RNS2_Windows::SetSocketLayerOverride(SocketLayerOverride *_slo) {slo = _slo;} +SocketLayerOverride* RNS2_Windows::GetSocketLayerOverride(void) {return slo;} +#else +RNS2BindResult RNS2_Linux::Bind( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) {return BindShared(bindParameters, file, line);} +RNS2SendResult RNS2_Linux::Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ) {return Send_Windows_Linux_360NoVDP(rns2Socket,sendParameters, file, line);} +void RNS2_Linux::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) {return GetMyIP_Windows_Linux(addresses);} +#endif // Linux + +#endif // defined(__native_client__) diff --git a/src/raknet/RakNetSocket2_360_720.cpp b/src/raknet/RakNetSocket2_360_720.cpp new file mode 100644 index 0000000..fed08c5 --- /dev/null +++ b/src/raknet/RakNetSocket2_360_720.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_360_720_CPP +#define RAKNETSOCKET2_360_720_CPP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_Berkley.cpp b/src/raknet/RakNetSocket2_Berkley.cpp new file mode 100644 index 0000000..a24617e --- /dev/null +++ b/src/raknet/RakNetSocket2_Berkley.cpp @@ -0,0 +1,554 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_BERKLEY_CPP +#define RAKNETSOCKET2_BERKLEY_CPP + +// Every platform except windows store 8 and native client supports Berkley sockets +#if !defined(WINDOWS_STORE_RT) && !defined(__native_client__) + +#include "include/raknet/Itoa.hpp" + +void RNS2_Berkley::SetSocketOptions(void) +{ + int r; + // This doubles the max throughput rate + int sock_opt=1024*256; + r = setsockopt__( rns2Socket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + RakAssert(r==0); + + // Immediate hard close. Don't linger the socket, or recreating the socket quickly on Vista fails. + // Fail with voice and xbox + + sock_opt=0; + r = setsockopt__( rns2Socket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + // Do not assert, ignore failure + + + + // This doesn't make much difference: 10% maybe + // Not supported on console 2 + sock_opt=1024*16; + r = setsockopt__( rns2Socket, SOL_SOCKET, SO_SNDBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + RakAssert(r==0); + +} + +void RNS2_Berkley::SetNonBlockingSocket(unsigned long nonblocking) +{ +#ifdef _WIN32 + int res = ioctlsocket__( rns2Socket, FIONBIO, &nonblocking ); + RakAssert(res==0); + + + +#else + if (nonblocking) + fcntl( rns2Socket, F_SETFL, O_NONBLOCK ); +#endif +} +void RNS2_Berkley::SetBroadcastSocket(int broadcast) +{ + setsockopt__( rns2Socket, SOL_SOCKET, SO_BROADCAST, ( char * ) & broadcast, sizeof( broadcast ) ); +} +void RNS2_Berkley::SetIPHdrIncl(int ipHdrIncl) +{ + + setsockopt__( rns2Socket, IPPROTO_IP, IP_HDRINCL, ( char * ) & ipHdrIncl, sizeof( ipHdrIncl ) ); + +} +void RNS2_Berkley::SetDoNotFragment( int opt ) +{ + #if defined( IP_DONTFRAGMENT ) + #if defined(_WIN32) && !defined(_DEBUG) + // If this assert hit you improperly linked against WSock32.h + RakAssert(IP_DONTFRAGMENT==14); + #endif + setsockopt__( rns2Socket, boundAddress.GetIPPROTO(), IP_DONTFRAGMENT, ( char * ) & opt, sizeof ( opt ) ); + #endif +} + +void RNS2_Berkley::GetSystemAddressIPV4 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ) +{ + sockaddr_in sa; + memset(&sa,0,sizeof(sockaddr_in)); + socklen_t len = sizeof(sa); + //int r = + getsockname__(rns2Socket, (sockaddr*)&sa, &len); + systemAddressOut->SetPortNetworkOrder(sa.sin_port); + systemAddressOut->address.addr4.sin_addr.s_addr=sa.sin_addr.s_addr; + + if (systemAddressOut->address.addr4.sin_addr.s_addr == INADDR_ANY) + { + + + + + + systemAddressOut->address.addr4.sin_addr.s_addr=inet_addr__("127.0.0.1"); + + } +} +void RNS2_Berkley::GetSystemAddressIPV4And6 ( RNS2Socket rns2Socket, SystemAddress *systemAddressOut ) +{ +#if RAKNET_SUPPORT_IPV6==1 + + socklen_t slen; + sockaddr_storage ss; + slen = sizeof(ss); + + if ( getsockname__(rns2Socket, (struct sockaddr *)&ss, &slen)!=0) + { +#if defined(_WIN32) && defined(_DEBUG) + DWORD dwIOError = GetLastError(); + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "getsockname failed:Error code - %d\n%s", dwIOError, messageBuffer ); + + //Free the buffer. + LocalFree( messageBuffer ); +#endif + systemAddressOut->FromString(0); + return; + } + + if (ss.ss_family==AF_INET) + { + memcpy(&systemAddressOut->address.addr4,(sockaddr_in *)&ss,sizeof(sockaddr_in)); + systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr4.sin_port); + + uint32_t zero = 0; + if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) + systemAddressOut->SetToLoopback(4); + // systemAddressOut->address.addr4.sin_port=ntohs(systemAddressOut->address.addr4.sin_port); + } + else + { + memcpy(&systemAddressOut->address.addr6,(sockaddr_in6 *)&ss,sizeof(sockaddr_in6)); + systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr6.sin6_port); + + char zero[16]; + memset(zero,0,sizeof(zero)); + if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) + systemAddressOut->SetToLoopback(6); + + // systemAddressOut->address.addr6.sin6_port=ntohs(systemAddressOut->address.addr6.sin6_port); + } + +#else + (void) rns2Socket; + (void) systemAddressOut; + return; +#endif +} + +#ifdef _MSC_VER +#pragma warning( disable : 4702 ) // warning C4702: unreachable code +#endif +RNS2BindResult RNS2_Berkley::BindSharedIPV4( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { + + (void) file; + (void) line; + + int ret; + memset(&boundAddress.address.addr4,0,sizeof(sockaddr_in)); + boundAddress.address.addr4.sin_port = htons( bindParameters->port ); + rns2Socket = (int) socket__( bindParameters->addressFamily, bindParameters->type, bindParameters->protocol ); + if (rns2Socket == -1) + return BR_FAILED_TO_BIND_SOCKET; + + SetSocketOptions(); + SetNonBlockingSocket(bindParameters->nonBlockingSocket); + SetBroadcastSocket(bindParameters->setBroadcast); + SetIPHdrIncl(bindParameters->setIPHdrIncl); + + // Fill in the rest of the address structure + boundAddress.address.addr4.sin_family = AF_INET; + + + + + + if (bindParameters->hostAddress && bindParameters->hostAddress[0]) + { + + + + + + boundAddress.address.addr4.sin_addr.s_addr = inet_addr__( bindParameters->hostAddress ); + + } + else + { + // RAKNET_DEBUG_PRINTF("Binding any on port %i\n", port); + boundAddress.address.addr4.sin_addr.s_addr = INADDR_ANY; + } + + + + + + // bind our name to the socket + ret = bind__( rns2Socket, ( struct sockaddr * ) &boundAddress.address.addr4, sizeof( boundAddress.address.addr4 ) ); + + if ( ret <= -1 ) + { + + + + + + + + +#if defined(_WIN32) + closesocket__(rns2Socket); + return BR_FAILED_TO_BIND_SOCKET; +#elif (defined(__GNUC__) || defined(__GCCXML__) ) && !defined(_WIN32) + closesocket__(rns2Socket); + switch (ret) + { + case EBADF: + RAKNET_DEBUG_PRINTF("bind__(): sockfd is not a valid descriptor.\n"); break; + + case ENOTSOCK: + RAKNET_DEBUG_PRINTF("bind__(): Argument is a descriptor for a file, not a socket.\n"); break; + + case EINVAL: + RAKNET_DEBUG_PRINTF("bind__(): The addrlen is wrong, or the socket was not in the AF_UNIX family.\n"); break; + case EROFS: + RAKNET_DEBUG_PRINTF("bind__(): The socket inode would reside on a read-only file system.\n"); break; + case EFAULT: + RAKNET_DEBUG_PRINTF("bind__(): my_addr points outside the user's accessible address space.\n"); break; + case ENAMETOOLONG: + RAKNET_DEBUG_PRINTF("bind__(): my_addr is too long.\n"); break; + case ENOENT: + RAKNET_DEBUG_PRINTF("bind__(): The file does not exist.\n"); break; + case ENOMEM: + RAKNET_DEBUG_PRINTF("bind__(): Insufficient kernel memory was available.\n"); break; + case ENOTDIR: + RAKNET_DEBUG_PRINTF("bind__(): A component of the path prefix is not a directory.\n"); break; + case EACCES: + // Port reserved on PS4 + RAKNET_DEBUG_PRINTF("bind__(): Search permission is denied on a component of the path prefix.\n"); break; + + case ELOOP: + RAKNET_DEBUG_PRINTF("bind__(): Too many symbolic links were encountered in resolving my_addr.\n"); break; + + default: + RAKNET_DEBUG_PRINTF("Unknown bind__() error %i.\n", ret); break; + } +#endif + + return BR_FAILED_TO_BIND_SOCKET; + } + + GetSystemAddressIPV4(rns2Socket, &boundAddress ); + + return BR_SUCCESS; + +} +RNS2BindResult RNS2_Berkley::BindSharedIPV4And6( RNS2_BerkleyBindParameters *bindParameters, const char *file, unsigned int line ) { + + (void) file; + (void) line; + (void) bindParameters; + +#if RAKNET_SUPPORT_IPV6==1 + + int ret=0; + struct addrinfo hints; + struct addrinfo *servinfo=0, *aip; // will point to the results + PrepareAddrInfoHints2(&hints); + hints.ai_family=bindParameters->addressFamily; + char portStr[32]; + Itoa(bindParameters->port,portStr,10); + + + // On Ubuntu, "" returns "No address associated with hostname" while 0 works. + if (bindParameters->hostAddress && + (_stricmp(bindParameters->hostAddress,"UNASSIGNED_SYSTEM_ADDRESS")==0 || bindParameters->hostAddress[0]==0)) + { + getaddrinfo(0, portStr, &hints, &servinfo); + } + else + { + getaddrinfo(bindParameters->hostAddress, portStr, &hints, &servinfo); + } + + // Try all returned addresses until one works + for (aip = servinfo; aip != NULL; aip = aip->ai_next) + { + // Open socket. The address type depends on what + // getaddrinfo() gave us. + rns2Socket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol); + + if (rns2Socket == -1) + return BR_FAILED_TO_BIND_SOCKET; + + + + + + + + + + + + + + + + + + + + ret = bind__(rns2Socket, aip->ai_addr, (int) aip->ai_addrlen ); + if (ret>=0) + { + // Is this valid? + memcpy(&boundAddress.address.addr6, aip->ai_addr, sizeof(boundAddress.address.addr6)); + + freeaddrinfo(servinfo); // free the linked-list + + SetSocketOptions(); + SetNonBlockingSocket(bindParameters->nonBlockingSocket); + SetBroadcastSocket(bindParameters->setBroadcast); + SetIPHdrIncl(bindParameters->setIPHdrIncl); + + GetSystemAddressIPV4And6( rns2Socket, &boundAddress ); + + return BR_SUCCESS; + } + else + { + closesocket__(rns2Socket); + } + } + + return BR_FAILED_TO_BIND_SOCKET; + +#else +return BR_REQUIRES_RAKNET_SUPPORT_IPV6_DEFINE; +#endif +} + +void RNS2_Berkley::RecvFromBlockingIPV4And6(RNS2RecvStruct *recvFromStruct) +{ +#if RAKNET_SUPPORT_IPV6==1 + + sockaddr_storage their_addr; + sockaddr* sockAddrPtr; + socklen_t sockLen; + socklen_t* socketlenPtr=(socklen_t*) &sockLen; + memset(&their_addr,0,sizeof(their_addr)); + int dataOutSize; + const int flag=0; + + + + + + + + + + + + { + sockLen=sizeof(their_addr); + sockAddrPtr=(sockaddr*) &their_addr; + } + + + + + dataOutSize=MAXIMUM_MTU_SIZE; + + + recvFromStruct->bytesRead = recvfrom__(rns2Socket, recvFromStruct->data, dataOutSize, flag, sockAddrPtr, socketlenPtr ); + +#if defined(_WIN32) && defined(_DEBUG) && !defined(WINDOWS_PHONE_8) + if (recvFromStruct->bytesRead==-1) + { + DWORD dwIOError = GetLastError(); + if (dwIoError != 10035) + { + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // I see this hit on XP with IPV6 for some reason + RAKNET_DEBUG_PRINTF( "Warning: recvfrom failed:Error code - %d\n%s", dwIOError, messageBuffer ); + LocalFree( messageBuffer ); + } + } +#endif + + + + + + + + + + + if (recvFromStruct->bytesRead<=0) + return; + recvFromStruct->timeRead=RakNet::GetTimeUS(); + + + + + + + + + + { + if (their_addr.ss_family==AF_INET) + { + memcpy(&recvFromStruct->systemAddress.address.addr4,(sockaddr_in *)&their_addr,sizeof(sockaddr_in)); + recvFromStruct->systemAddress.debugPort=ntohs(recvFromStruct->systemAddress.address.addr4.sin_port); + // systemAddressOut->address.addr4.sin_port=ntohs( systemAddressOut->address.addr4.sin_port ); + } + else + { + memcpy(&recvFromStruct->systemAddress.address.addr6,(sockaddr_in6 *)&their_addr,sizeof(sockaddr_in6)); + recvFromStruct->systemAddress.debugPort=ntohs(recvFromStruct->systemAddress.address.addr6.sin6_port); + // systemAddressOut->address.addr6.sin6_port=ntohs( systemAddressOut->address.addr6.sin6_port ); + } + } + + +#else + (void) recvFromStruct; +#endif +} + +void RNS2_Berkley::RecvFromBlockingIPV4(RNS2RecvStruct *recvFromStruct) +{ + sockaddr* sockAddrPtr; + socklen_t sockLen; + socklen_t* socketlenPtr=(socklen_t*) &sockLen; + sockaddr_in sa; + memset(&sa,0,sizeof(sockaddr_in)); + const int flag=0; + + + + + + + + + + + + + + + + + + + + + + { + sockLen=sizeof(sa); + sa.sin_family = AF_INET; + sa.sin_port=0; + sockAddrPtr=(sockaddr*) &sa; + } + + recvFromStruct->bytesRead = recvfrom__( GetSocket(), recvFromStruct->data, sizeof(recvFromStruct->data), flag, sockAddrPtr, socketlenPtr ); + + + + + + + + + + if (recvFromStruct->bytesRead<=0) + { + /* + DWORD dwIOError = WSAGetLastError(); + + if ( dwIOError == WSAECONNRESET ) + { +#if defined(_DEBUG) + RAKNET_DEBUG_PRINTF( "A previous send operation resulted in an ICMP Port Unreachable message.\n" ); +#endif + + } + else if ( dwIOError != WSAEWOULDBLOCK && dwIOError != WSAEADDRNOTAVAIL) + { +#if defined(_WIN32) && !defined(_XBOX) && !defined(_XBOX_720_COMPILE_AS_WINDOWS) && !defined(X360) && defined(_DEBUG) && !defined(_XBOX_720_COMPILE_AS_WINDOWS) && !defined(WINDOWS_PHONE_8) + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "sendto failed:Error code - %d\n%s", dwIOError, messageBuffer ); + + //Free the buffer. + LocalFree( messageBuffer ); +#endif + } + */ + + return; + } + recvFromStruct->timeRead=RakNet::GetTimeUS(); + + + + + + + + + + { + + recvFromStruct->systemAddress.SetPortNetworkOrder( sa.sin_port ); + recvFromStruct->systemAddress.address.addr4.sin_addr.s_addr=sa.sin_addr.s_addr; + } + + // printf("--- Got %i bytes from %s\n", recvFromStruct->bytesRead, recvFromStruct->systemAddress.ToString()); +} + +void RNS2_Berkley::RecvFromBlocking(RNS2RecvStruct *recvFromStruct) +{ +#if RAKNET_SUPPORT_IPV6==1 + return RecvFromBlockingIPV4And6(recvFromStruct); +#else + return RecvFromBlockingIPV4(recvFromStruct); +#endif +} + +#endif // !defined(WINDOWS_STORE_RT) && !defined(__native_client__) + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_Berkley_NativeClient.cpp b/src/raknet/RakNetSocket2_Berkley_NativeClient.cpp new file mode 100644 index 0000000..1b31c3f --- /dev/null +++ b/src/raknet/RakNetSocket2_Berkley_NativeClient.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_BERKLEY_NATIVE_CLIENT_CPP +#define RAKNETSOCKET2_BERKLEY_NATIVE_CLIENT_CPP + +// Every platform except windows store 8 and native client supports Berkley sockets +#if !defined(WINDOWS_STORE_RT) + +#include "include/raknet/Itoa.hpp" + +// Shared on most platforms, but excluded from the listed + + +void DomainNameToIP_Berkley_IPV4And6( const char *domainName, char ip[65] ) +{ +#if RAKNET_SUPPORT_IPV6==1 + struct addrinfo hints, *res, *p; + int status; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version + hints.ai_socktype = SOCK_DGRAM; + + if ((status = getaddrinfo(domainName, NULL, &hints, &res)) != 0) { + memset(ip, 0, sizeof(ip)); + return; + } + + p=res; +// for(p = res;p != NULL; p = p->ai_next) { + void *addr; +// char *ipver; + + // get the pointer to the address itself, + // different fields in IPv4 and IPv6: + if (p->ai_family == AF_INET) + { + struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr; + addr = &(ipv4->sin_addr); + strcpy(ip, inet_ntoa( ipv4->sin_addr )); + } + else + { + // TODO - test + struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr; + addr = &(ipv6->sin6_addr); + // inet_ntop function does not exist on windows + // http://www.mail-archive.com/users@ipv6.org/msg02107.html + getnameinfo((struct sockaddr *)ipv6, sizeof(struct sockaddr_in6), ip, 1, NULL, 0, NI_NUMERICHOST); + } + freeaddrinfo(res); // free the linked list +// } +#else + (void) domainName; + (void) ip; +#endif // #if RAKNET_SUPPORT_IPV6==1 +} + + +void DomainNameToIP_Berkley_IPV4( const char *domainName, char ip[65] ) +{ + static struct in_addr addr; + memset(&addr,0,sizeof(in_addr)); + + // Use inet_addr instead? What is the difference? + struct hostent * phe = gethostbyname( domainName ); + + if ( phe == 0 || phe->h_addr_list[ 0 ] == 0 ) + { + //cerr << "Yow! Bad host lookup." << endl; + memset(ip,0,65*sizeof(char)); + return; + } + + if (phe->h_addr_list[ 0 ]==0) + { + memset(ip,0,65*sizeof(char)); + return; + } + + memcpy( &addr, phe->h_addr_list[ 0 ], sizeof( struct in_addr ) ); + strcpy(ip, inet_ntoa( addr )); +} + + + +void DomainNameToIP_Berkley( const char *domainName, char ip[65] ) +{ +#if RAKNET_SUPPORT_IPV6==1 + return DomainNameToIP_Berkley_IPV4And6(domainName, ip); +#else + return DomainNameToIP_Berkley_IPV4(domainName, ip); +#endif +} + + + + +#endif // !defined(WINDOWS_STORE_RT) && !defined(__native_client__) + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_NativeClient.cpp b/src/raknet/RakNetSocket2_NativeClient.cpp new file mode 100644 index 0000000..b8af77c --- /dev/null +++ b/src/raknet/RakNetSocket2_NativeClient.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_NATIVE_CLIENT_CPP +#define RAKNETSOCKET2_NATIVE_CLIENT_CPP + +#if defined(__native_client__) + +using namespace pp; + +RNS2BindResult RNS2_NativeClient::Bind( NativeClientBindParameters *bindParameters, const char *file, unsigned int line ) +{ + memcpy(&binding, bindParameters, sizeof(NativeClientBindParameters)); + + if(Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4)) + { + rns2Socket = ((PPB_UDPSocket_Private_0_4*) Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->Create(bindParameters->nativeClientInstance); + RAKNET_DEBUG_PRINTF("CreateChromeSocket(%d,%s,0x%08x,%d) ==> 0x%08x\n", bindParameters->port, bindParameters->forceHostAddress?bindParameters->forceHostAddress:"(null)",bindParameters->nativeClientInstance,bindParameters->is_ipv6, rns2Socket); + + // Enable the broadcast feature on the socket (must happen before the + // bind call) + ((PPB_UDPSocket_Private_0_4*) pp::Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->SetSocketFeature(rns2Socket, PP_UDPSOCKETFEATURE_BROADCAST, PP_MakeBool(PP_TRUE)); + + PP_NetAddress_Private client_addr; + uint8_t ipv6[16], ipv4[4]; + if (bindParameters->forceHostAddress) + { + unsigned int ipIdx=0; + char * pch; + pch = strtok ((char*) bindParameters->forceHostAddress,"."); + if (bindParameters->is_ipv6) + { + while (pch != NULL && ipIdx<16) + { + ipv6[ipIdx++]=atoi(pch); + pch = strtok (NULL, "."); + } + NetAddressPrivate::CreateFromIPv6Address(ipv6,0,bindParameters->port,&client_addr); + } + else + { + while (pch != NULL && ipIdx<4) + { + ipv4[ipIdx++]=atoi(pch); + pch = strtok (NULL, "."); + } + NetAddressPrivate::CreateFromIPv4Address(ipv4,bindParameters->port,&client_addr); + } + } + else + { + NetAddressPrivate::GetAnyAddress(bindParameters->is_ipv6, &client_addr); + NetAddressPrivate::ReplacePort(client_addr, bindParameters->port, &client_addr); + } + + bindState = BS_IN_PROGRESS; + + RAKNET_DEBUG_PRINTF("attempting to bind to %s\n", NetAddressPrivate::Describe(client_addr, true).c_str()); + PP_CompletionCallback cc = PP_MakeCompletionCallback(RNS2_NativeClient::onSocketBound, this); + ((PPB_UDPSocket_Private_0_4*) Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->Bind(rns2Socket, &client_addr, cc); + return BR_SUCCESS; + } + return BR_FAILED_TO_BIND_SOCKET; +} + +void RNS2_NativeClient::SendImmediate(RNS2_SendParameters_NativeClient *sp) +{ + // Assuming data does not have to remain valid until callback called + PP_NetAddress_Private client_addr; +#if RAKNET_SUPPORT_IPV6==1 + NetAddressPrivate::CreateFromIPv6Address(sp->systemAddress.address.addr6.sin6_addr.u.Byte,0,sp->systemAddress.GetPort(),&client_addr); +#else + NetAddressPrivate::CreateFromIPv4Address((const uint8_t*) &sp->systemAddress.address.addr4.sin_addr,sp->systemAddress.GetPort(),&client_addr); +#endif + + // sp remains in memory until the callback completes + PP_CompletionCallback cc = PP_MakeCompletionCallback(onSendTo, sp); + ((PPB_UDPSocket_Private_0_4*) Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->SendTo(sp->socket2->rns2Socket, sp->data, sp->length, &client_addr, cc); +} + +void RNS2_NativeClient::onRecvFrom(void* pData, int32_t dataSize) +{ + RNS2RecvStruct *recvStruct = (RNS2RecvStruct *) pData; + RNS2_NativeClient *socket2 = (RNS2_NativeClient *) recvStruct->socket; + + //any error codes will be given to us in the dataSize value; see pp_errors.h for a list of errors + if(dataSize <=0 || !pData ) + { + // Free data + socket2->eventHandler->DeallocRNS2RecvStruct(recvStruct, _FILE_AND_LINE_); + + // This value indicates failure due to an asynchronous operation being + // interrupted. The most common cause of this error code is destroying + // a resource that still has a callback pending. All callbacks are + // guaranteed to execute, so any callbacks pending on a destroyed + // resource will be issued with PP_ERROR_ABORTED. + if(dataSize==PP_ERROR_ABORTED) + { + RAKNET_DEBUG_PRINTF("onRecvFrom error PP_ERROR_ABORTED, killing recvfrom loop\n"); + } + else + { + RAKNET_DEBUG_PRINTF("onRecvFrom error %d\n", dataSize); + + // Reissue call + socket2->IssueReceiveCall(); + } + + return; + } + + recvStruct->bytesRead=dataSize; + recvStruct->timeRead=RakNet::GetTimeUS(); + + + PP_NetAddress_Private addr; + bool ok=false; + if(((PPB_UDPSocket_Private_0_4*) Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->GetRecvFromAddress(socket2->rns2Socket, &addr) == PP_TRUE) + { + PP_NetAddressFamily_Private family = NetAddressPrivate::GetFamily(addr); + if (family == PP_NETADDRESSFAMILY_IPV4) + { + ok = NetAddressPrivate::GetAddress(addr, &recvStruct->systemAddress.address.addr4.sin_addr, sizeof(in_addr)); + } +#if RAKNET_SUPPORT_IPV6==1 + else + { + ok = NetAddressPrivate::GetAddress(addr, &recvStruct->systemAddress.address.addr6.sin6_addr, sizeof(in6_addr)); + } +#endif + } + + if(ok) + { + recvStruct->systemAddress.SetPortHostOrder(pp::NetAddressPrivate::GetPort(addr)); + socket2->binding.eventHandler->OnRNS2Recv(recvStruct); + } + + // Reissue call + socket2->IssueReceiveCall(); +} +void RNS2_NativeClient::IssueReceiveCall(void) +{ + RNS2RecvStruct *recvFromStruct; + recvFromStruct=binding.eventHandler->AllocRNS2RecvStruct(_FILE_AND_LINE_); + if (recvFromStruct != NULL) + { + recvFromStruct->socket=this; + PP_CompletionCallback cc = PP_MakeCompletionCallback(onRecvFrom, recvFromStruct); + ((PPB_UDPSocket_Private_0_4*) Module::Get()->GetBrowserInterface(PPB_UDPSOCKET_PRIVATE_INTERFACE_0_4))->RecvFrom(rns2Socket, recvFromStruct->data, MAXIMUM_MTU_SIZE, cc); + } +} + +#endif // defined(__native_client__) + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_PS3_PS4.cpp b/src/raknet/RakNetSocket2_PS3_PS4.cpp new file mode 100644 index 0000000..fc92cb0 --- /dev/null +++ b/src/raknet/RakNetSocket2_PS3_PS4.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_PS3_PS4_CPP +#define RAKNETSOCKET2_PS3_PS4_CPP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_PS4.cpp b/src/raknet/RakNetSocket2_PS4.cpp new file mode 100644 index 0000000..8898687 --- /dev/null +++ b/src/raknet/RakNetSocket2_PS4.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_PS4_CPP +#define RAKNETSOCKET2_PS4_CPP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_Vita.cpp b/src/raknet/RakNetSocket2_Vita.cpp new file mode 100644 index 0000000..19b08ad --- /dev/null +++ b/src/raknet/RakNetSocket2_Vita.cpp @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_VITA +#define RAKNETSOCKET2_VITA + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_WindowsStore8.cpp b/src/raknet/RakNetSocket2_WindowsStore8.cpp new file mode 100644 index 0000000..2e3e06c --- /dev/null +++ b/src/raknet/RakNetSocket2_WindowsStore8.cpp @@ -0,0 +1,467 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_WINDOWS_STORE_8 +#define RAKNETSOCKET2_WINDOWS_STORE_8 + +#if defined(WINDOWS_STORE_RT) + +#include +#include +#include "include/raknet/RakString.hpp" + +using namespace Concurrency; +using namespace Platform; +using namespace Windows::ApplicationModel::Core; +using namespace Windows::Foundation; +using namespace Windows::Networking; +using namespace Windows::Networking::Sockets; +using namespace Windows::UI::Core; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::UI::Xaml::Navigation; +using namespace Windows::Storage::Streams; +//using namespace Platform::Collections; +//using namespace Windows::Foundation::Collections; + +namespace RakNet +{ + +public ref class OutputStreamAndDataWriter sealed +{ +public: + // http://msdn.microsoft.com/en-us/library/windows/apps/hh755807.aspx + property IOutputStream ^outputStream; + /* + { + IOutputStream ^ get() {return outputStream;} + void set(IOutputStream ^ value) {outputStream = value;} + } + */ + property DataWriter ^dataWriter; + /* + { + DataWriter ^ get() {return dataWriter;} + void set(DataWriter ^ value) {dataWriter = value;} + } + */ +private: +}; + +public ref class ListenerContext sealed +{ +public: + ListenerContext(Windows::Networking::Sockets::DatagramSocket^ listener); + void OnMessage(Windows::Networking::Sockets::DatagramSocket^ socket, Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^ eventArguments); + OutputStreamAndDataWriter ^GetOutputStreamAndDataWriter(uint64_t s_addr); + +private: + ~ListenerContext(); + // CRITICAL_SECTION lock; + SimpleMutex outputStreamMapMutex; + Windows::Networking::Sockets::DatagramSocket^ listener; + //Windows::Storage::Streams::IOutputStream^ outputStream; + //Windows::Networking::HostName^ hostName; + //Platform::String^ port; + // http://msdn.microsoft.com/en-us/library/windows/apps/hh700103.aspx + Platform::Collections::Map^ outputStreamMap; + + void EchoMessage(Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^ eventArguments); +}; +} + +using namespace RakNet; + +ListenerContext::ListenerContext(Windows::Networking::Sockets::DatagramSocket^ listener) +{ + this->listener = listener; +// InitializeCriticalSectionEx(&lock, 0, 0); + outputStreamMap = ref new Platform::Collections::Map(); +} + +ListenerContext::~ListenerContext() +{ + // The listener can be closed in two ways: + // - explicit: by using delete operator (the listener is closed even if there are outstanding references to it). + // - implicit: by removing last reference to it (i.e. falling out-of-scope). + // In this case this is the last reference to the listener so both will yield the same result. + delete listener; + listener = nullptr; + +// DeleteCriticalSection(&lock); +} + +OutputStreamAndDataWriter ^ListenerContext::GetOutputStreamAndDataWriter(uint64_t s_addr) +{ + outputStreamMapMutex.Lock(); + if (outputStreamMap->HasKey(s_addr)) + { + OutputStreamAndDataWriter ^o = outputStreamMap->Lookup(s_addr); + outputStreamMapMutex.Unlock(); + return o; + } + outputStreamMapMutex.Unlock(); + uint16_t port = s_addr & 0xFFFF; + uint32_t addr = (uint32_t) (s_addr >> 32); + //addr = ntohl(addr); + char buf[64]; + unsigned char *ucp = (unsigned char *)&addr; + sprintf(buf, "%d.%d.%d.%d", + ucp[0] & 0xff, + ucp[1] & 0xff, + ucp[2] & 0xff, + ucp[3] & 0xff); + char portStr[32]; + _itoa(port, portStr, 10); + + RakNet::RakString rs1(buf); + WCHAR *w_char1 = rs1.ToWideChar(); + HostName ^hostName = ref new HostName(ref new Platform::String(w_char1)); + RakNet::RakString rs2(portStr); + WCHAR *w_char2 = rs2.ToWideChar(); + task< IOutputStream^ > op(listener->GetOutputStreamAsync(hostName, ref new Platform::String(w_char2))); + op.wait(); + OutputStreamAndDataWriter ^outputStreamAndDataWriter = ref new OutputStreamAndDataWriter; + outputStreamAndDataWriter->outputStream = op.get(); + outputStreamAndDataWriter->dataWriter = ref new DataWriter(outputStreamAndDataWriter->outputStream); + + rs1.DeallocWideChar(w_char1); + rs2.DeallocWideChar(w_char2); + + outputStreamMapMutex.Lock(); + if (outputStreamMap->HasKey(s_addr)==false) + { + outputStreamMap->Insert(s_addr, outputStreamAndDataWriter); + outputStreamMapMutex.Unlock(); + return outputStreamAndDataWriter; + } + else + { + // Just use the one that was inserted from another thread + OutputStreamAndDataWriter ^o = outputStreamMap->Lookup(s_addr); + outputStreamMapMutex.Unlock(); + return o; + } +} + +void ListenerContext::OnMessage(Windows::Networking::Sockets::DatagramSocket^ socket, Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^ eventArguments) +{ + HostName ^remoteHost=eventArguments->RemoteAddress; + eventArguments->RemoteAddress->DisplayName; + eventArguments->RemotePort; + + RNS2_WindowsStore8 *rns2 = RNS2_WindowsStore8::GetRNS2FromDatagramSocket(socket); + if (rns2==0) + return; + + //auto platformBuffer = ref new Platform::Array((unsigned char*) sendParameters->data, (UINT)sendParameters->length); + RNS2EventHandler *eventHandler = rns2->GetEventHandler(); + RNS2RecvStruct *recvFromStruct = eventHandler->AllocRNS2RecvStruct(_FILE_AND_LINE_); + + // http://stackoverflow.com/questions/11853838/getting-an-array-of-bytes-out-of-windowsstoragestreamsibuffer + IBuffer ^uselessBuffer = eventArguments->GetDataReader()->DetachBuffer(); + Windows::Storage::Streams::DataReader^ uselessReader = Windows::Storage::Streams::DataReader::FromBuffer(uselessBuffer); + Platform::Array^ managedBytes = ref new Platform::Array(uselessBuffer->Length); + uselessReader->ReadBytes( managedBytes ); + for(unsigned int i = 0; i < uselessBuffer->Length; i++) + recvFromStruct->data[i] = managedBytes[i]; + recvFromStruct->bytesRead = uselessBuffer->Length; + char ip[64]; + RakString rs2; + rs2.FromWideChar(eventArguments->RemoteAddress->DisplayName->Data()); + strcpy(ip, rs2.C_String()); + recvFromStruct->systemAddress.address.addr4.sin_addr.s_addr = RNS2_WindowsStore8::WinRTInet_Addr(ip); + char portStr[64]; + rs2.FromWideChar(eventArguments->RemotePort->Data()); + strcpy(portStr, rs2.C_String()); + recvFromStruct->systemAddress.SetPortHostOrder(atoi(portStr)); + recvFromStruct->timeRead=RakNet::GetTimeUS(); + recvFromStruct->socket = rns2; + eventHandler->OnRNS2Recv(recvFromStruct); + + /* + if (outputStream != nullptr) + { + EchoMessage(eventArguments); + return; + } + + + // We do not have an output stream yet so create one. + task(socket->GetOutputStreamAsync(eventArguments->RemoteAddress, eventArguments->RemotePort)).then([this, socket, eventArguments] (IOutputStream^ stream) + { + // It might happen that the OnMessage was invoked more than once before the GetOutputStreamAsync completed. + // In this case we will end up with multiple streams - make sure we have just one of it. + EnterCriticalSection(&lock); + + if (outputStream == nullptr) + { + outputStream = stream; + hostName = eventArguments->RemoteAddress; + port = eventArguments->RemotePort; + } + + LeaveCriticalSection(&lock); + + EchoMessage(eventArguments); + }).then([this, socket, eventArguments] (task previousTask) + { + try + { + // Try getting all exceptions from the continuation chain above this point. + previousTask.get(); + } + catch (Exception^ exception) + { + // NotifyUserFromAsyncThread("Getting an output stream failed with error: " + exception->Message, NotifyType::ErrorMessage); + } + }); + */ +} +void ListenerContext::EchoMessage(DatagramSocketMessageReceivedEventArgs^ eventArguments) +{ +} +RakNet::DataStructures::List RNS2_WindowsStore8::rns2List; +SimpleMutex RNS2_WindowsStore8::rns2ListMutex; +RNS2_WindowsStore8::RNS2_WindowsStore8() +{ + rns2ListMutex.Lock(); + rns2List.Insert(this, _FILE_AND_LINE_); + rns2ListMutex.Unlock(); +} +RNS2_WindowsStore8::~RNS2_WindowsStore8() +{ + unsigned int i; + rns2ListMutex.Lock(); + for (i=0; i < rns2List.Size(); i++) + { + if (rns2List[i]==this) + { + rns2List.RemoveAtIndexFast(i); + break; + } + } + rns2ListMutex.Unlock(); +} +RNS2_WindowsStore8 *RNS2_WindowsStore8::GetRNS2FromDatagramSocket(Windows::Networking::Sockets::DatagramSocket^ s) +{ + RNS2_WindowsStore8 *out=0; + unsigned int i; + rns2ListMutex.Lock(); + for (i=0; i < rns2List.Size(); i++) + { + if (rns2List[i]->listener==s) + { + out=rns2List[i]; + break; + } + } + rns2ListMutex.Unlock(); + return out; +} +RNS2BindResult RNS2_WindowsStore8::Bind( Platform::String ^localServiceName ) { + + listener = ref new DatagramSocket(); + listenerContext = ref new ListenerContext(listener); + listener->MessageReceived += ref new TypedEventHandler(listenerContext, &ListenerContext::OnMessage); + // http://msdn.microsoft.com/en-us/library/dd492427.aspx + task bindOp(listener->BindServiceNameAsync(localServiceName)); + try + { + bindOp.wait(); + } + catch (Exception^ exception) + { + return BR_FAILED_TO_BIND_SOCKET; + } + + return BR_SUCCESS; +} +void RNS2_WindowsStore8::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) {RakAssert("GetMyIP Unsupported" && 0);} +RNS2SendResult RNS2_WindowsStore8::Send( RNS2_SendParameters *sendParameters, const char *file, unsigned int line ) { + uint64_t s_addr = sendParameters->systemAddress.address.addr4.sin_addr.s_addr; + s_addr <<=32; + s_addr |= sendParameters->systemAddress.debugPort; + OutputStreamAndDataWriter ^outputStreamAndDataWriter = listenerContext->GetOutputStreamAndDataWriter(s_addr); + // DataWriter ^dataWriter = ref new DataWriter(outputStream); + + auto platformBuffer = ref new Platform::Array((unsigned char*) sendParameters->data, (UINT)sendParameters->length); + outputStreamAndDataWriter->dataWriter->WriteBytes(platformBuffer); + + + // Write the locally buffered data to the network. Please note that write operation will succeed + // even if the server is not listening. + task(outputStreamAndDataWriter->dataWriter->StoreAsync()).then([&] (task writeTask) + { + try + { + // Try getting an excpetion. + // writeTask.get(); + // SendOutput->Style = dynamic_cast(rootPage->Resources->Lookup("StatusStyle")); + // SendOutput->Text = "\"" + stringToSend + "\" sent successfully"; + } + catch (Exception^ exception) + { + // rootPage->NotifyUser("Send failed with error: " + exception->Message, NotifyType::ErrorMessage); + OutputDebugStringW(exception->Message->Data()); + } + }); + + return 0; +} +void RNS2_WindowsStore8::DomainNameToIP( const char *domainName, char ip[65] ) { + ip[0]=0; + +// RakAssert("DomainNameToIP Unsupported" && 0); + +// std::string s_str = std::string(domainName); +// std::wstring wid_str = std::wstring(s_str.begin(), s_str.end()); +// const wchar_t* w_char = wid_str.c_str(); + + RakNet::RakString rs(domainName); + WCHAR *w_char = rs.ToWideChar(); + +// DatagramSocket ^listener = ref new DatagramSocket(); + + +// task bindOp(listener->BindServiceNameAsync(ref new Platform::String())); + //bindOp.wait(); + + HostName ^hostName = ref new HostName(ref new Platform::String(w_char)); + //HostName ^hostName = ref new HostName(ref new Platform::String(L"microsoft.com")); + //HostName ^hostName = ref new HostName(ref new Platform::String(L"127.0.0.1")); + //task< Windows::Foundation::Collections::IVectorView^ > op(listener->GetEndpointPairsAsync(hostName, L"42")); + //listener->GetEndpointPairsAsync(hostName, L"42"); + // task< Windows::Foundation::Collections::IVectorView^ > op(DatagramSocket::GetEndpointPairsAsync(hostName, L"42")); + + IAsyncOperation^>^ op = DatagramSocket::GetEndpointPairsAsync(hostName, L"0"); + + bool completed=false; + op->Completed = ref new AsyncOperationCompletedHandler< Windows::Foundation::Collections::IVectorView^ >( + [&] ( + IAsyncOperation< Windows::Foundation::Collections::IVectorView^>^ result, + AsyncStatus status + ) { + Windows::Foundation::Collections::IVectorView^ result2 = result->GetResults(); + if (result2->Size>0) + { + Platform::String ^name = result2->GetAt(0)->RemoteHostName->DisplayName; + RakString rs2; + rs2.FromWideChar(name->Data()); + strcpy(ip, rs2.C_String()); + } + else + { + ip[0]=0; + } + + result->Close(); + completed=true; + } + ) ; + + while (!completed) + RakSleep(0); + /* + op->Completed = ref new AsyncOperationCompletedHandler< Windows::Foundation::Collections::IVectorView^ >( + [](IAsyncOperation< Windows::Foundation::Collections::IVectorView^ >^ operation) + { + operation->GetResults(); + + }); + */ + + +// RakSleep(10000); + /* + try + { + op.wait(); + } + catch (Exception^ exception) + { + int a=5; + } + Windows::Foundation::Collections::IVectorView^view = op.get(); + if (view->Size>0) + { + Platform::String ^name = view->GetAt(0)->RemoteHostName->DisplayName; + RakString rs2; + rs2.FromWideChar(name->Data()); + strcpy(ip, rs2.C_String()); + } + else + { + ip[0]=0; + } + */ + + rs.DeallocWideChar(w_char); + +} + + +int RNS2_WindowsStore8::WinRTInet_Addr(const char *str) { + int parts[4]; + unsigned char curVal; + + const char *strIndex=str; + int partsIndex; + + for (partsIndex=0; partsIndex < 4; partsIndex++) + parts[partsIndex]=0; + + partsIndex=0; + curVal=0; + while (partsIndex < 4) + { + if (*strIndex < '0' || *strIndex > '9') + { + parts[partsIndex]=curVal; + partsIndex++; + curVal=0; + + if (*strIndex==0) + break; + } + else + { + curVal*=10; + curVal+=*strIndex-'0'; + } + strIndex++; + } + + return htonl((parts[0]<<24) | (parts[1]<<16) | (parts[2]<<8) | (parts[3]<<0) ); +} + +int RNS2_WindowsStore8::WinRTSetSockOpt(Windows::Networking::Sockets::DatagramSocket ^s, + int level, + int optname, + const char * optval, + socklen_t optlen) {RakAssert("WinRTSetSockOpt Unsupported" && 0); return 0;} + +int RNS2_WindowsStore8::WinRTIOCTLSocket(Windows::Networking::Sockets::DatagramSocket ^s, + long cmd, + unsigned long *argp) {RakAssert("WinRTIOCTLSocket Unsupported" && 0); return 0;} + +int RNS2_WindowsStore8::WinRTGetSockName(Windows::Networking::Sockets::DatagramSocket ^s, + struct sockaddr *name, + socklen_t* namelen) {RakAssert("WinRTGetSockName Unsupported" && 0); return 0;} + +#endif // WINDOWS_STORE_RT + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_Windows_Linux.cpp b/src/raknet/RakNetSocket2_Windows_Linux.cpp new file mode 100644 index 0000000..ea94999 --- /dev/null +++ b/src/raknet/RakNetSocket2_Windows_Linux.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_WINDOWS_LINUX_CPP +#define RAKNETSOCKET2_WINDOWS_LINUX_CPP + +#if !defined(WINDOWS_STORE_RT) && !defined(__native_client__) + +#if RAKNET_SUPPORT_IPV6==1 + +void PrepareAddrInfoHints2(addrinfo *hints) +{ + memset(hints, 0, sizeof (addrinfo)); // make sure the struct is empty + hints->ai_socktype = SOCK_DGRAM; // UDP sockets + hints->ai_flags = AI_PASSIVE; // fill in my IP for me +} + +void GetMyIP_Windows_Linux_IPV4And6( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) +{ + int idx=0; + char ac[ 80 ]; + int err = gethostname( ac, sizeof( ac ) ); + RakAssert(err != -1); + + struct addrinfo hints; + struct addrinfo *servinfo=0, *aip; // will point to the results + PrepareAddrInfoHints2(&hints); + getaddrinfo(ac, "", &hints, &servinfo); + + for (idx=0, aip = servinfo; aip != NULL && idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS; aip = aip->ai_next, idx++) + { + if (aip->ai_family == AF_INET) + { + struct sockaddr_in *ipv4 = (struct sockaddr_in *)aip->ai_addr; + memcpy(&addresses[idx].address.addr4,ipv4,sizeof(sockaddr_in)); + } + else + { + struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)aip->ai_addr; + memcpy(&addresses[idx].address.addr4,ipv6,sizeof(sockaddr_in6)); + } + + } + + freeaddrinfo(servinfo); // free the linked-list + + while (idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS) + { + addresses[idx]=UNASSIGNED_SYSTEM_ADDRESS; + idx++; + } +} + +#else + +#if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(__WIN32__) +#include +#endif +void GetMyIP_Windows_Linux_IPV4( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) +{ + + + + int idx=0; + char ac[ 80 ]; + int err = gethostname( ac, sizeof( ac ) ); + (void) err; + RakAssert(err != -1); + + struct hostent *phe = gethostbyname( ac ); + + if ( phe == 0 ) + { + RakAssert(phe!=0); + return ; + } + for ( idx = 0; idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS; ++idx ) + { + if (phe->h_addr_list[ idx ] == 0) + break; + + memcpy(&addresses[idx].address.addr4.sin_addr,phe->h_addr_list[ idx ],sizeof(struct in_addr)); + } + + while (idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS) + { + addresses[idx]=UNASSIGNED_SYSTEM_ADDRESS; + idx++; + } + +} + +#endif // RAKNET_SUPPORT_IPV6==1 + + +void GetMyIP_Windows_Linux( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) +{ + #if RAKNET_SUPPORT_IPV6==1 + GetMyIP_Windows_Linux_IPV4And6(addresses); + #else + GetMyIP_Windows_Linux_IPV4(addresses); + #endif +} + + +#endif // Windows and Linux + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetSocket2_Windows_Linux_360.cpp b/src/raknet/RakNetSocket2_Windows_Linux_360.cpp new file mode 100644 index 0000000..34f37b0 --- /dev/null +++ b/src/raknet/RakNetSocket2_Windows_Linux_360.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/EmptyHeader.hpp" + +#ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS + +#ifndef RAKNETSOCKET2_WINDOWS_LINUX_360_CPP +#define RAKNETSOCKET2_WINDOWS_LINUX_360_CPP + +#if (defined(_WIN32) || defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__) ) && !defined(WINDOWS_STORE_RT) && !defined(__native_client__) + +RNS2SendResult RNS2_Windows_Linux_360::Send_Windows_Linux_360NoVDP( RNS2Socket rns2Socket, RNS2_SendParameters *sendParameters, const char *file, unsigned int line ) { + + int len=0; + do + { + (void) file; + (void) line; + + + int oldTTL=-1; + if (sendParameters->ttl>0) + { + socklen_t opLen=sizeof(oldTTL); + // Get the current TTL + if (getsockopt__(rns2Socket, sendParameters->systemAddress.GetIPPROTO(), IP_TTL, ( char * ) & oldTTL, &opLen ) != -1) + { + int newTTL=sendParameters->ttl; + setsockopt__(rns2Socket, sendParameters->systemAddress.GetIPPROTO(), IP_TTL, ( char * ) & newTTL, sizeof ( newTTL ) ); + } + } + + + if (sendParameters->systemAddress.address.addr4.sin_family==AF_INET) + { + len = sendto__( rns2Socket, sendParameters->data, sendParameters->length, 0, ( const sockaddr* ) & sendParameters->systemAddress.address.addr4, sizeof( sockaddr_in ) ); + } + else + { +#if RAKNET_SUPPORT_IPV6==1 + len = sendto__( rns2Socket, sendParameters->data, sendParameters->length, 0, ( const sockaddr* ) & sendParameters->systemAddress.address.addr6, sizeof( sockaddr_in6 ) ); +#endif + } + + if (len<0) + { + RAKNET_DEBUG_PRINTF("sendto failed with code %i for char %i and length %i.\n", len, sendParameters->data[0], sendParameters->length); + } + + + if (oldTTL!=-1) + { + setsockopt__(rns2Socket, sendParameters->systemAddress.GetIPPROTO(), IP_TTL, ( char * ) & oldTTL, sizeof ( oldTTL ) ); + } + + } + while ( len == 0 ); + return len; +} + +#endif // Windows, Linux, 360 + +#endif // file header + +#endif // #ifdef RAKNET_SOCKET_2_INLINE_FUNCTIONS diff --git a/src/raknet/RakNetStatistics.cpp b/src/raknet/RakNetStatistics.cpp new file mode 100644 index 0000000..f550f68 --- /dev/null +++ b/src/raknet/RakNetStatistics.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + + +#include "include/raknet/RakNetStatistics.hpp" +#include // sprintf +#include "include/raknet/GetTime.hpp" +#include "include/raknet/RakString.hpp" + +using namespace RakNet; + +// Verbosity level currently supports 0 (low), 1 (medium), 2 (high) +// Buffer must be hold enough to hold the output string. See the source to get an idea of how many bytes will be output +void RAK_DLL_EXPORT RakNet::StatisticsToString( RakNetStatistics *s, char *buffer, int verbosityLevel ) +{ + if ( s == 0 ) + { + sprintf( buffer, "stats is a NULL pointer in statsToString\n" ); + return ; + } + + if (verbosityLevel==0) + { + sprintf(buffer, + "Bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" + "Bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" + "Current packetloss %.1f%%\n", + (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], + (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], + s->packetlossLastSecond*100.0f + ); + } + else if (verbosityLevel==1) + { + sprintf(buffer, + "Actual bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" + "Actual bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" + "Message bytes per second pushed %" PRINTF_64_BIT_MODIFIER "u\n" + "Total actual bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" + "Total actual bytes received %" PRINTF_64_BIT_MODIFIER "u\n" + "Total message bytes pushed %" PRINTF_64_BIT_MODIFIER "u\n" + "Current packetloss %.1f%%\n" + "Average packetloss %.1f%%\n" + "Elapsed connection time in seconds %" PRINTF_64_BIT_MODIFIER "u\n", + (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], + (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], + (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], + (long long unsigned int) s->runningTotal[ACTUAL_BYTES_SENT], + (long long unsigned int) s->runningTotal[ACTUAL_BYTES_RECEIVED], + (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_PUSHED], + s->packetlossLastSecond*100.0f, + s->packetlossTotal*100.0f, + (long long unsigned int) (uint64_t)((RakNet::GetTimeUS()-s->connectionStartTime)/1000000) + ); + + if (s->BPSLimitByCongestionControl!=0) + { + char buff2[128]; + sprintf(buff2, + "Send capacity %" PRINTF_64_BIT_MODIFIER "u bytes per second (%.0f%%)\n", + (long long unsigned int) s->BPSLimitByCongestionControl, + 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl + ); + strcat(buffer,buff2); + } + if (s->BPSLimitByOutgoingBandwidthLimit!=0) + { + char buff2[128]; + sprintf(buff2, + "Send limit %" PRINTF_64_BIT_MODIFIER "u (%.0f%%)\n", + (long long unsigned int) s->BPSLimitByOutgoingBandwidthLimit, + 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit + ); + strcat(buffer,buff2); + } + } + else + { + sprintf(buffer, + "Actual bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" + "Actual bytes per second received %" PRINTF_64_BIT_MODIFIER "u\n" + "Message bytes per second sent %" PRINTF_64_BIT_MODIFIER "u\n" + "Message bytes per second resent %" PRINTF_64_BIT_MODIFIER "u\n" + "Message bytes per second pushed %" PRINTF_64_BIT_MODIFIER "u\n" + "Message bytes per second returned %" PRINTF_64_BIT_MODIFIER "u\n" + "Message bytes per second ignored %" PRINTF_64_BIT_MODIFIER "u\n" + "Total bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" + "Total bytes received %" PRINTF_64_BIT_MODIFIER "u\n" + "Total message bytes sent %" PRINTF_64_BIT_MODIFIER "u\n" + "Total message bytes resent %" PRINTF_64_BIT_MODIFIER "u\n" + "Total message bytes pushed %" PRINTF_64_BIT_MODIFIER "u\n" + "Total message bytes returned %" PRINTF_64_BIT_MODIFIER "u\n" + "Total message bytes ignored %" PRINTF_64_BIT_MODIFIER "u\n" + "Messages in send buffer, by priority %i,%i,%i,%i\n" + "Bytes in send buffer, by priority %i,%i,%i,%i\n" + "Messages in resend buffer %i\n" + "Bytes in resend buffer %" PRINTF_64_BIT_MODIFIER "u\n" + "Current packetloss %.1f%%\n" + "Average packetloss %.1f%%\n" + "Elapsed connection time in seconds %" PRINTF_64_BIT_MODIFIER "u\n", + (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_SENT], + (long long unsigned int) s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], + (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_SENT], + (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT], + (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], + (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], + (long long unsigned int) s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_IGNORED], + (long long unsigned int) s->runningTotal[ACTUAL_BYTES_SENT], + (long long unsigned int) s->runningTotal[ACTUAL_BYTES_RECEIVED], + (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_SENT], + (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RESENT], + (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_PUSHED], + (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], + (long long unsigned int) s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_IGNORED], + s->messageInSendBuffer[IMMEDIATE_PRIORITY],s->messageInSendBuffer[HIGH_PRIORITY],s->messageInSendBuffer[MEDIUM_PRIORITY],s->messageInSendBuffer[LOW_PRIORITY], + (unsigned int) s->bytesInSendBuffer[IMMEDIATE_PRIORITY],(unsigned int) s->bytesInSendBuffer[HIGH_PRIORITY],(unsigned int) s->bytesInSendBuffer[MEDIUM_PRIORITY],(unsigned int) s->bytesInSendBuffer[LOW_PRIORITY], + s->messagesInResendBuffer, + (long long unsigned int) s->bytesInResendBuffer, + s->packetlossLastSecond*100.0f, + s->packetlossTotal*100.0f, + (long long unsigned int) (uint64_t)((RakNet::GetTimeUS()-s->connectionStartTime)/1000000) + ); + + if (s->BPSLimitByCongestionControl!=0) + { + char buff2[128]; + sprintf(buff2, + "Send capacity %" PRINTF_64_BIT_MODIFIER "u bytes per second (%.0f%%)\n", + (long long unsigned int) s->BPSLimitByCongestionControl, + 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl + ); + strcat(buffer,buff2); + } + if (s->BPSLimitByOutgoingBandwidthLimit!=0) + { + char buff2[128]; + sprintf(buff2, + "Send limit %" PRINTF_64_BIT_MODIFIER "u (%.0f%%)\n", + (long long unsigned int) s->BPSLimitByOutgoingBandwidthLimit, + 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit + ); + strcat(buffer,buff2); + } + } +} diff --git a/src/raknet/RakNetTransport2.cpp b/src/raknet/RakNetTransport2.cpp new file mode 100644 index 0000000..70efd66 --- /dev/null +++ b/src/raknet/RakNetTransport2.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TelnetTransport==1 + +#include "include/raknet/RakNetTransport2.hpp" + +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include +#include +#include +#include "include/raknet/LinuxStrings.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(RakNetTransport2,RakNetTransport2); + +RakNetTransport2::RakNetTransport2() +{ +} +RakNetTransport2::~RakNetTransport2() +{ + Stop(); +} +bool RakNetTransport2::Start(unsigned short port, bool serverMode) +{ + (void) port; + (void) serverMode; + return true; +} +void RakNetTransport2::Stop(void) +{ + newConnections.Clear(_FILE_AND_LINE_); + lostConnections.Clear(_FILE_AND_LINE_); + for (unsigned int i=0; i < packetQueue.Size(); i++) + { + rakFree_Ex(packetQueue[i]->data,_FILE_AND_LINE_); + RakNet::OP_DELETE(packetQueue[i],_FILE_AND_LINE_); + } + packetQueue.Clear(_FILE_AND_LINE_); +} +void RakNetTransport2::Send( SystemAddress systemAddress, const char *data, ... ) +{ + if (data==0 || data[0]==0) return; + + char text[REMOTE_MAX_TEXT_INPUT]; + va_list ap; + va_start(ap, data); + _vsnprintf(text, REMOTE_MAX_TEXT_INPUT, data, ap); + va_end(ap); + text[REMOTE_MAX_TEXT_INPUT-1]=0; + + RakNet::BitStream str; + str.Write((MessageID)ID_TRANSPORT_STRING); + str.Write(text, (int) strlen(text)); + str.Write((unsigned char) 0); // Null terminate the string + rakPeerInterface->Send(&str, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, systemAddress, (systemAddress==UNASSIGNED_SYSTEM_ADDRESS)!=0); +} +void RakNetTransport2::CloseConnection( SystemAddress systemAddress ) +{ + rakPeerInterface->CloseConnection(systemAddress, true, 0); +} +Packet* RakNetTransport2::Receive( void ) +{ + if (packetQueue.Size()==0) + return 0; + return packetQueue.Pop(); +} +SystemAddress RakNetTransport2::HasNewIncomingConnection(void) +{ + if (newConnections.Size()) + return newConnections.Pop(); + return UNASSIGNED_SYSTEM_ADDRESS; +} +SystemAddress RakNetTransport2::HasLostConnection(void) +{ + if (lostConnections.Size()) + return lostConnections.Pop(); + return UNASSIGNED_SYSTEM_ADDRESS; +} +void RakNetTransport2::DeallocatePacket( Packet *packet ) +{ + rakFree_Ex(packet->data, _FILE_AND_LINE_ ); + RakNet::OP_DELETE(packet, _FILE_AND_LINE_ ); +} +PluginReceiveResult RakNetTransport2::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_TRANSPORT_STRING: + { + if (packet->length==sizeof(MessageID)) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + + Packet *p = RakNet::OP_NEW(_FILE_AND_LINE_); + *p=*packet; + p->bitSize-=8; + p->length--; + p->data=(unsigned char*) rakMalloc_Ex(p->length,_FILE_AND_LINE_); + memcpy(p->data, packet->data+1, p->length); + packetQueue.Push(p, _FILE_AND_LINE_ ); + + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + return RR_CONTINUE_PROCESSING; +} +void RakNetTransport2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) rakNetGUID; + (void) lostConnectionReason; + lostConnections.Push(systemAddress, _FILE_AND_LINE_ ); +} +void RakNetTransport2::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) rakNetGUID; + (void) isIncoming; + newConnections.Push(systemAddress, _FILE_AND_LINE_ ); +} +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/RakNetTypes.cpp b/src/raknet/RakNetTypes.cpp new file mode 100644 index 0000000..122106d --- /dev/null +++ b/src/raknet/RakNetTypes.cpp @@ -0,0 +1,812 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#include "include/raknet/RakNetTypes.hpp" +#include "include/raknet/RakAssert.hpp" +#include +#include +#include "include/raknet/WindowsIncludes.hpp" +#include "include/raknet/WSAStartupSingleton.hpp" +#include "include/raknet/SocketDefines.hpp" +#include "include/raknet/RakNetSocket2.hpp" + + +#if defined(_WIN32) +// extern __int64 _strtoui64(const char*, char**, int); // needed for Code::Blocks. Does not compile on Visual Studio 2010 +// IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib +// winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly +#include "include/raknet/WindowsIncludes.hpp" + +#else +#include +#include +#include +#endif + +#include // strncasecmp +#include "include/raknet/Itoa.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/SuperFastHash.hpp" +#include + +using namespace RakNet; + +const char *IPV6_LOOPBACK="::1"; +const char *IPV4_LOOPBACK="127.0.0.1"; + +AddressOrGUID::AddressOrGUID( Packet *packet ) +{ + rakNetGuid=packet->guid; + systemAddress=packet->systemAddress; +} + +unsigned long AddressOrGUID::ToInteger( const AddressOrGUID &aog ) +{ + if (aog.rakNetGuid!=UNASSIGNED_RAKNET_GUID) + return RakNetGUID::ToUint32(aog.rakNetGuid); + return SystemAddress::ToInteger(aog.systemAddress); +} +const char *AddressOrGUID::ToString(bool writePort) const +{ + if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) + return rakNetGuid.ToString(); + return systemAddress.ToString(writePort); +} +void AddressOrGUID::ToString(bool writePort, char *dest) const +{ + if (rakNetGuid!=UNASSIGNED_RAKNET_GUID) + return rakNetGuid.ToString(dest); + return systemAddress.ToString(writePort,dest); +} +bool RakNet::NonNumericHostString( const char *host ) +{ + // Return false if IP address. Return true if domain + unsigned int i=0; + while (host[i]) + { + // IPV4: natpunch.jenkinssoftware.com + // IPV6: fe80::7c:31f7:fec4:27de%14 + if ((host[i]>='g' && host[i]<='z') || + (host[i]>='A' && host[i]<='Z')) + return true; + ++i; + } + return false; +} + +SocketDescriptor::SocketDescriptor() { +#ifdef __native_client__ + blockingSocket=false; +#else + blockingSocket=true; +#endif + port=0; hostAddress[0]=0; remotePortRakNetWasStartedOn_PS3_PSP2=0; extraSocketOptions=0; socketFamily=AF_INET;} +SocketDescriptor::SocketDescriptor(unsigned short _port, const char *_hostAddress) +{ + #ifdef __native_client__ + blockingSocket=false; + #else + blockingSocket=true; + #endif + remotePortRakNetWasStartedOn_PS3_PSP2=0; + port=_port; + if (_hostAddress) + strcpy(hostAddress, _hostAddress); + else + hostAddress[0]=0; + extraSocketOptions=0; + socketFamily=AF_INET; +} + +// Defaults to not in peer to peer mode for NetworkIDs. This only sends the localSystemAddress portion in the BitStream class +// This is what you want for client/server, where the server assigns all NetworkIDs and it is unnecessary to transmit the full structure. +// For peer to peer, this will transmit the systemAddress of the system that created the object in addition to localSystemAddress. This allows +// Any system to create unique ids locally. +// All systems must use the same value for this variable. +//bool RAK_DLL_EXPORT NetworkID::peerToPeerMode=false; + +SystemAddress& SystemAddress::operator = ( const SystemAddress& input ) +{ + memcpy(&address, &input.address, sizeof(address)); + systemIndex = input.systemIndex; + debugPort = input.debugPort; + return *this; +} +bool SystemAddress::EqualsExcludingPort( const SystemAddress& right ) const +{ + return (address.addr4.sin_family==AF_INET && address.addr4.sin_addr.s_addr==right.address.addr4.sin_addr.s_addr) +#if RAKNET_SUPPORT_IPV6==1 + || (address.addr4.sin_family==AF_INET6 && memcmp(address.addr6.sin6_addr.s6_addr, right.address.addr6.sin6_addr.s6_addr, sizeof(address.addr6.sin6_addr.s6_addr))==0) +#endif + ; +} +unsigned short SystemAddress::GetPort(void) const +{ + return ntohs(address.addr4.sin_port); +} +unsigned short SystemAddress::GetPortNetworkOrder(void) const +{ + return address.addr4.sin_port; +} +void SystemAddress::SetPortHostOrder(unsigned short s) +{ + address.addr4.sin_port=htons(s); + debugPort=s; +} +void SystemAddress::SetPortNetworkOrder(unsigned short s) +{ + address.addr4.sin_port=s; + debugPort=ntohs(s); +} +bool SystemAddress::operator==( const SystemAddress& right ) const +{ + return address.addr4.sin_port == right.address.addr4.sin_port && EqualsExcludingPort(right); +} + +bool SystemAddress::operator!=( const SystemAddress& right ) const +{ + return (*this==right)==false; +} + +bool SystemAddress::operator>( const SystemAddress& right ) const +{ + if (address.addr4.sin_port == right.address.addr4.sin_port) + { +#if RAKNET_SUPPORT_IPV6==1 + if (address.addr4.sin_family==AF_INET) + return address.addr4.sin_addr.s_addr>right.address.addr4.sin_addr.s_addr; + return memcmp(address.addr6.sin6_addr.s6_addr, right.address.addr6.sin6_addr.s6_addr, sizeof(address.addr6.sin6_addr.s6_addr))>0; +#else + return address.addr4.sin_addr.s_addr>right.address.addr4.sin_addr.s_addr; +#endif + } + return address.addr4.sin_port>right.address.addr4.sin_port; +} + +bool SystemAddress::operator<( const SystemAddress& right ) const +{ + if (address.addr4.sin_port == right.address.addr4.sin_port) + { +#if RAKNET_SUPPORT_IPV6==1 + if (address.addr4.sin_family==AF_INET) + return address.addr4.sin_addr.s_addr0; +#else + return address.addr4.sin_addr.s_addr> 24) == 10 || (address.addr4.sin_addr.s_addr >> 24) == 192; +#endif +} +bool SystemAddress::SetBinaryAddress(const char *str, char portDelineator) +{ + if ( NonNumericHostString( str ) ) + { + +#if defined(_WIN32) + if (_strnicmp(str,"localhost", 9)==0) +#else + if (strncasecmp(str,"localhost", 9)==0) +#endif + { + + + + + + address.addr4.sin_addr.s_addr=inet_addr__("127.0.0.1"); + + if (str[9]) + { + SetPortHostOrder((unsigned short) atoi(str+9)); + } + return true; + } + + //const char *ip = ( char* ) SocketLayer::DomainNameToIP( str ); + char ip[65]; + ip[0]=0; + RakNetSocket2::DomainNameToIP(str, ip); + if (ip[0]) + { + + + + + + address.addr4.sin_addr.s_addr=inet_addr__(ip); + + } + else + { + *this = UNASSIGNED_SYSTEM_ADDRESS; + return false; + } + } + else + { + //#ifdef _XBOX + // binaryAddress=UNASSIGNED_SYSTEM_ADDRESS.binaryAddress; + //#else + // Split the string into the first part, and the : part + int index, portIndex; + char IPPart[22]; + char portPart[10]; + // Only write the valid parts, don't change existing if invalid + // binaryAddress=UNASSIGNED_SYSTEM_ADDRESS.binaryAddress; + // port=UNASSIGNED_SYSTEM_ADDRESS.port; + for (index=0; str[index] && str[index]!=portDelineator && index<22; index++) + { + if (str[index]!='.' && (str[index]<'0' || str[index]>'9')) + break; + IPPart[index]=str[index]; + } + IPPart[index]=0; + portPart[0]=0; + if (str[index] && str[index+1]) + { + index++; + for (portIndex=0; portIndex<10 && str[index] && index < 22+10; index++, portIndex++) + { + if (str[index]<'0' || str[index]>'9') + break; + + portPart[portIndex]=str[index]; + } + portPart[portIndex]=0; + } + + + + + + + + + + + + + + if (IPPart[0]) + { + + + + + + address.addr4.sin_addr.s_addr=inet_addr__(IPPart); + + } + + + if (portPart[0]) + { + address.addr4.sin_port=htons((unsigned short) atoi(portPart)); + debugPort=ntohs(address.addr4.sin_port); + } + //#endif + } + return true; +} + +#ifdef _MSC_VER +#pragma warning( disable : 4702 ) // warning C4702: unreachable code +#endif +bool SystemAddress::FromString(const char *str, char portDelineator, int ipVersion) +{ +#if RAKNET_SUPPORT_IPV6!=1 + (void) ipVersion; + return SetBinaryAddress(str,portDelineator); +#else + if (str==0) + { + memset(&address,0,sizeof(address)); + address.addr4.sin_family=AF_INET; + return true; + } +#if RAKNET_SUPPORT_IPV6==1 + char ipPart[INET6_ADDRSTRLEN]; +#else + char ipPart[INET_ADDRSTRLEN]; +#endif + char portPart[32]; + int i=0,j; + + // TODO - what about 255.255.255.255? + if (ipVersion==4 && strcmp(str, IPV6_LOOPBACK)==0) + { + strcpy(ipPart,IPV4_LOOPBACK); + } + else if (ipVersion==6 && strcmp(str, IPV4_LOOPBACK)==0) + { + address.addr4.sin_family=AF_INET6; + strcpy(ipPart,IPV6_LOOPBACK); + } + else if (NonNumericHostString(str)==false) + { + for (; i < sizeof(ipPart) && str[i]!=0 && str[i]!=portDelineator; i++) + { + if ((str[i]<'0' || str[i]>'9') && (str[i]<'a' || str[i]>'f') && (str[i]<'A' || str[i]>'F') && str[i]!='.' && str[i]!=':' && str[i]!='%' && str[i]!='-' && str[i]!='/') + break; + + ipPart[i]=str[i]; + } + ipPart[i]=0; + } + else + { + strncpy(ipPart,str,sizeof(ipPart)); + ipPart[sizeof(ipPart)-1]=0; + } + + j=0; + if (str[i]==portDelineator && portDelineator!=0) + { + i++; + for (; j < sizeof(portPart) && str[i]!=0; i++, j++) + { + portPart[j]=str[i]; + } + } + portPart[j]=0; + + + + + + + + + + + // needed for getaddrinfo + WSAStartupSingleton::AddRef(); + + // This could be a domain, or a printable address such as "192.0.2.1" or "2001:db8:63b3:1::3490" + // I want to convert it to its binary representation + addrinfo hints, *servinfo=0; + memset(&hints, 0, sizeof hints); + hints.ai_socktype = SOCK_DGRAM; + if (ipVersion==6) + hints.ai_family = AF_INET6; + else if (ipVersion==4) + hints.ai_family = AF_INET; + else + hints.ai_family = AF_UNSPEC; + getaddrinfo(ipPart, "", &hints, &servinfo); + if (servinfo==0) + { + if (ipVersion==6) + { + ipVersion=4; + hints.ai_family = AF_UNSPEC; + getaddrinfo(ipPart, "", &hints, &servinfo); + if (servinfo==0) + return false; + } + else + return false; + } + RakAssert(servinfo); + + unsigned short oldPort = address.addr4.sin_port; +#if RAKNET_SUPPORT_IPV6==1 + if (servinfo->ai_family == AF_INET) + { +// if (ipVersion==6) +// { +// address.addr4.sin_family=AF_INET6; +// memset(&address.addr6,0,sizeof(address.addr6)); +// memcpy(address.addr6.sin6_addr.s6_addr+12,&((struct sockaddr_in *)servinfo->ai_addr)->sin_addr.s_addr,sizeof(unsigned long)); +// } +// else +// { + address.addr4.sin_family=AF_INET; + memcpy(&address.addr4, (struct sockaddr_in *)servinfo->ai_addr,sizeof(struct sockaddr_in)); +// } + } + else + { + address.addr4.sin_family=AF_INET6; + memcpy(&address.addr6, (struct sockaddr_in6 *)servinfo->ai_addr,sizeof(struct sockaddr_in6)); + } +#else + address.addr4.sin_family=AF_INET4; + memcpy(&address.addr4, (struct sockaddr_in *)servinfo->ai_addr,sizeof(struct sockaddr_in)); +#endif + + freeaddrinfo(servinfo); // free the linked list + + // needed for getaddrinfo + WSAStartupSingleton::Deref(); + + // PORT + if (portPart[0]) + { + address.addr4.sin_port=htons((unsigned short) atoi(portPart)); + debugPort=ntohs(address.addr4.sin_port); + } + else + { + address.addr4.sin_port=oldPort; + } +#endif // #if RAKNET_SUPPORT_IPV6!=1 + + return true; +} +bool SystemAddress::FromStringExplicitPort(const char *str, unsigned short port, int ipVersion) +{ + bool b = FromString(str,(char) 0,ipVersion); + if (b==false) + { + *this=UNASSIGNED_SYSTEM_ADDRESS; + return false; + } + address.addr4.sin_port=htons(port); + debugPort=ntohs(address.addr4.sin_port); + return true; +} +void SystemAddress::CopyPort( const SystemAddress& right ) +{ + address.addr4.sin_port=right.address.addr4.sin_port; + debugPort=right.debugPort; +} +RakNetGUID::RakNetGUID() +{ + systemIndex=(SystemIndex)-1; + *this=UNASSIGNED_RAKNET_GUID; +} +bool RakNetGUID::operator==( const RakNetGUID& right ) const +{ + return g==right.g; +} +bool RakNetGUID::operator!=( const RakNetGUID& right ) const +{ + return g!=right.g; +} +bool RakNetGUID::operator > ( const RakNetGUID& right ) const +{ + return g > right.g; +} +bool RakNetGUID::operator < ( const RakNetGUID& right ) const +{ + return g < right.g; +} +const char *RakNetGUID::ToString(void) const +{ + static unsigned char strIndex=0; + static char str[8][64]; + + unsigned char lastStrIndex=strIndex; + strIndex++; + ToString(str[lastStrIndex&7]); + return (char*) str[lastStrIndex&7]; +} +void RakNetGUID::ToString(char *dest) const +{ + if (*this==UNASSIGNED_RAKNET_GUID) + strcpy(dest, "UNASSIGNED_RAKNET_GUID"); + else + //sprintf(dest, "%u.%u.%u.%u.%u.%u", g[0], g[1], g[2], g[3], g[4], g[5]); + sprintf(dest, "%" PRINTF_64_BIT_MODIFIER "u", (long long unsigned int) g); + // sprintf(dest, "%u.%u.%u.%u.%u.%u", g[0], g[1], g[2], g[3], g[4], g[5]); +} +bool RakNetGUID::FromString(const char *source) +{ + if (source==0) + return false; + + + +#if defined(WIN32) + g=_strtoui64(source, NULL, 10); + + +#else + // Changed from g=strtoull(source,0,10); for android + g=strtoull(source, (char **)NULL, 10); +#endif + return true; + +} +unsigned long RakNetGUID::ToUint32( const RakNetGUID &g ) +{ + return ((unsigned long) (g.g >> 32)) ^ ((unsigned long) (g.g & 0xFFFFFFFF)); +} diff --git a/src/raknet/RakPeer.cpp b/src/raknet/RakPeer.cpp new file mode 100644 index 0000000..8cc6add --- /dev/null +++ b/src/raknet/RakPeer.cpp @@ -0,0 +1,6504 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +// \file +// + + + +#define CAT_NEUTER_EXPORT /* Neuter dllimport for libcat */ + +#include "include/raknet/RakNetDefines.hpp" +#include "include/raknet/RakPeer.hpp" +#include "include/raknet/RakNetTypes.hpp" + +#ifdef _WIN32 + +#else +#include +#endif + +// #if defined(new) +// #pragma push_macro("new") +// #undef new +// #define RMO_NEW_UNDEF_ALLOCATING_QUEUE +// #endif + +#include +#include // toupper +#include +#include "include/raknet/GetTime.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/DS_HuffmanEncodingTree.hpp" +#include "include/raknet/Rand.hpp" +#include "include/raknet/PluginInterface2.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/StringTable.hpp" +#include "include/raknet/NetworkIDObject.hpp" +#include "include/raknet/RakNetTypes.hpp" +#include "include/raknet/DR_SHA1.hpp" +#include "include/raknet/RakSleep.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakNetVersion.hpp" +#include "include/raknet/NetworkIDManager.hpp" +#include "include/raknet/gettimeofday.hpp" +#include "include/raknet/SignaledEvent.hpp" +#include "include/raknet/SuperFastHash.hpp" +#include "include/raknet/RakAlloca.hpp" +#include "include/raknet/WSAStartupSingleton.hpp" + +#ifdef USE_THREADED_SEND +#include "include/raknet/SendToThread.hpp" +#endif + +#ifdef CAT_AUDIT +#define CAT_AUDIT_PRINTF(...) printf(__VA_ARGS__) +#else +#define CAT_AUDIT_PRINTF(...) +#endif + +namespace RakNet +{ +RAK_THREAD_DECLARATION(UpdateNetworkLoop); +RAK_THREAD_DECLARATION(RecvFromLoop); +RAK_THREAD_DECLARATION(UDTConnect); +} +#define REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE 8 + +#if !defined ( __APPLE__ ) && !defined ( __APPLE_CC__ ) +#include // malloc +#endif + + + +#if defined(_WIN32) +// +#else +/* +#include // Console 2 +#include +extern bool _extern_Console2LoadModules(void); +extern int _extern_Console2GetConnectionStatus(void); +extern int _extern_Console2GetLobbyStatus(void); +//extern bool Console2StartupFluff(unsigned int *); +extern void Console2ShutdownFluff(void); +//extern unsigned int Console2ActivateConnection(unsigned int, void *); +//extern bool Console2BlockOnEstablished(void); +extern void Console2GetIPAndPort(unsigned int, char *, unsigned short *, unsigned int ); +//extern void Console2DeactivateConnection(unsigned int, unsigned int); +*/ +#endif + + +static const int NUM_MTU_SIZES=3; + + + +static const int mtuSizes[NUM_MTU_SIZES]={MAXIMUM_MTU_SIZE, 1200, 576}; + + +// Note to self - if I change this it might affect RECIPIENT_OFFLINE_MESSAGE_INTERVAL in Natpunchthrough.cpp +//static const int MAX_OPEN_CONNECTION_REQUESTS=8; +//static const int TIME_BETWEEN_OPEN_CONNECTION_REQUESTS=500; + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +static RakNetRandom rnr; + +/* +struct RakPeerAndIndex +{ + RakNetSocket2 *s; + RakPeer *rakPeer; +}; +*/ + +static const unsigned int MAX_OFFLINE_DATA_LENGTH=400; // I set this because I limit ID_CONNECTION_REQUEST to 512 bytes, and the password is appended to that packet. + +// Used to distinguish between offline messages with data, and messages from the reliability layer +// Should be different than any message that could result from messages from the reliability layer +#if !defined(__GNUC__) +#pragma warning(disable:4309) // 'initializing' : truncation of constant value +#endif +// Make sure highest bit is 0, so isValid in DatagramHeaderFormat is false +static const unsigned char OFFLINE_MESSAGE_DATA_ID[16]={0x00,0xFF,0xFF,0x00,0xFE,0xFE,0xFE,0xFE,0xFD,0xFD,0xFD,0xFD,0x12,0x34,0x56,0x78}; + +struct PacketFollowedByData +{ + Packet p; + unsigned char data[1]; +}; + +Packet *RakPeer::AllocPacket(unsigned dataSize, const char *file, unsigned int line) +{ + // Crashes when dataSize is 4 bytes - not sure why +// unsigned char *data = (unsigned char *) rakMalloc_Ex(sizeof(PacketFollowedByData)+dataSize, file, line); +// Packet *p = &((PacketFollowedByData *)data)->p; +// p->data=((PacketFollowedByData *)data)->data; +// p->length=dataSize; +// p->bitSize=BYTES_TO_BITS(dataSize); +// p->deleteData=false; +// p->guid=UNASSIGNED_RAKNET_GUID; +// return p; + + RakNet::Packet *p; + packetAllocationPoolMutex.Lock(); + p = packetAllocationPool.Allocate(file,line); + packetAllocationPoolMutex.Unlock(); + p = new ((void*)p) Packet; + p->data=(unsigned char*) rakMalloc_Ex(dataSize,file,line); + p->length=dataSize; + p->bitSize=BYTES_TO_BITS(dataSize); + p->deleteData=true; + p->guid=UNASSIGNED_RAKNET_GUID; + p->wasGeneratedLocally=false; + return p; +} + +Packet *RakPeer::AllocPacket(unsigned dataSize, unsigned char *data, const char *file, unsigned int line) +{ + // Packet *p = (Packet *)rakMalloc_Ex(sizeof(Packet), file, line); + RakNet::Packet *p; + packetAllocationPoolMutex.Lock(); + p = packetAllocationPool.Allocate(file,line); + packetAllocationPoolMutex.Unlock(); + p = new ((void*)p) Packet; + RakAssert(p); + p->data=data; + p->length=dataSize; + p->bitSize=BYTES_TO_BITS(dataSize); + p->deleteData=true; + p->guid=UNASSIGNED_RAKNET_GUID; + p->wasGeneratedLocally=false; + return p; +} + +STATIC_FACTORY_DEFINITIONS(RakPeerInterface,RakPeer) + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Constructor +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakPeer::RakPeer() +{ +#if LIBCAT_SECURITY==1 + // Encryption and security + CAT_AUDIT_PRINTF("AUDIT: Initializing RakPeer security flags: using_security = false, server_handshake = null, cookie_jar = null\n"); + _using_security = false; + _server_handshake = 0; + _cookie_jar = 0; +#endif + + StringCompressor::AddReference(); + RakNet::StringTable::AddReference(); + WSAStartupSingleton::AddRef(); + + defaultMTUSize = mtuSizes[NUM_MTU_SIZES-1]; + trackFrequencyTable = false; + maximumIncomingConnections = 0; + maximumNumberOfPeers = 0; + //remoteSystemListSize=0; + remoteSystemList = 0; + activeSystemList = 0; + activeSystemListSize=0; + remoteSystemLookup=0; + bytesSentPerSecond = bytesReceivedPerSecond = 0; + endThreads = true; + isMainLoopThreadActive = false; + incomingDatagramEventHandler=0; + + + + + + // isRecvfromThreadActive=false; +#if defined(GET_TIME_SPIKE_LIMIT) && GET_TIME_SPIKE_LIMIT>0 + occasionalPing = true; +#else + occasionalPing = false; +#endif + allowInternalRouting=false; + for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + ipList[i]=UNASSIGNED_SYSTEM_ADDRESS; + allowConnectionResponseIPMigration = false; + //incomingPasswordLength=outgoingPasswordLength=0; + incomingPasswordLength=0; + splitMessageProgressInterval=0; + //unreliableTimeout=0; + unreliableTimeout=1000; + maxOutgoingBPS=0; + firstExternalID=UNASSIGNED_SYSTEM_ADDRESS; + myGuid=UNASSIGNED_RAKNET_GUID; + userUpdateThreadPtr=0; + userUpdateThreadData=0; + +#ifdef _DEBUG + // Wait longer to disconnect in debug so I don't get disconnected while tracing + defaultTimeoutTime=30000; +#else + defaultTimeoutTime=10000; +#endif + +#ifdef _DEBUG + _packetloss=0.0; + _minExtraPing=0; + _extraPingVariance=0; +#endif + + bufferedCommands.SetPageSize(sizeof(BufferedCommandStruct)*16); + socketQueryOutput.SetPageSize(sizeof(SocketQueryOutput)*8); + + packetAllocationPoolMutex.Lock(); + packetAllocationPool.SetPageSize(sizeof(DataStructures::MemoryPool::MemoryWithPage)*32); + packetAllocationPoolMutex.Unlock(); + + remoteSystemIndexPool.SetPageSize(sizeof(DataStructures::MemoryPool::MemoryWithPage)*32); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + GenerateGUID(); + + quitAndDataEvents.InitEvent(); + limitConnectionFrequencyFromTheSameIP=false; + ResetSendReceipt(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Destructor +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakPeer::~RakPeer() +{ + Shutdown( 0, 0 ); + + // Free the ban list. + ClearBanList(); + + StringCompressor::RemoveReference(); + RakNet::StringTable::RemoveReference(); + WSAStartupSingleton::Deref(); + + quitAndDataEvents.CloseEvent(); + +#if LIBCAT_SECURITY==1 + // Encryption and security + CAT_AUDIT_PRINTF("AUDIT: Deleting RakPeer security objects, handshake = %x, cookie jar = %x\n", _server_handshake, _cookie_jar); + if (_server_handshake) RakNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); + if (_cookie_jar) RakNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); +#endif + + + + + + + + + + + + + + + + +// for (unsigned int i=0; i < pluginListTS.Size(); i++) +// pluginListTS[i]->SetRakPeerInterface(0); +// for (unsigned int i=0; i < pluginListNTS.Size(); i++) +// pluginListNTS[i]->SetRakPeerInterface(0); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// \brief Starts the network threads, opens the listen port. +// You must call this before calling Connect(). +// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown(). +// \note Call SetMaximumIncomingConnections if you want to accept incoming connections +// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections +// \param[in] localPort The port to listen for connections on. +// \param[in] _threadSleepTimer How many ms to Sleep each internal update cycle. With new congestion control, the best results will be obtained by passing 10. +// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass &socketDescriptor, 1SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor(); +// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass. +// \return False on failure (can't create socket or thread), true on success. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +StartupResult RakPeer::Startup( unsigned int maxConnections, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount, int threadPriority ) +{ + if (IsActive()) + return RAKNET_ALREADY_STARTED; + + // If getting the guid failed in the constructor, try again + if (myGuid.g==0) + { + GenerateGUID(); + if (myGuid.g==0) + return COULD_NOT_GENERATE_GUID; + } + + if (threadPriority==-99999) + { + + +#if defined(_WIN32) + threadPriority=0; + + + + +#else + threadPriority=1000; +#endif + } + + + FillIPList(); + + if (myGuid==UNASSIGNED_RAKNET_GUID) + { + rnr.SeedMT( GenerateSeedFromGuid() ); + } + + //RakPeerAndIndex rpai[32]; + //RakAssert(socketDescriptorCount<32); + + RakAssert(socketDescriptors && socketDescriptorCount>=1); + + if (socketDescriptors==0 || socketDescriptorCount<1) + return INVALID_SOCKET_DESCRIPTORS; + + //unsigned short localPort; + //localPort=socketDescriptors[0].port; + + RakAssert( maxConnections > 0 ); + + if ( maxConnections <= 0 ) + return INVALID_MAX_CONNECTIONS; + + DerefAllSockets(); + + + unsigned int i; + // Go through all socket descriptors and precreate sockets on the specified addresses + for (i=0; iSetUserConnectionSocketIndex(i); + #if defined(__native_client__) + NativeClientBindParameters ncbp; + RNS2_NativeClient * nativeClientSocket = (RNS2_NativeClient*) r2; + ncbp.eventHandler=this; + ncbp.forceHostAddress=(char*) socketDescriptors[i].hostAddress; + ncbp.is_ipv6=socketDescriptors[i].socketFamily==AF_INET6; + ncbp.nativeClientInstance=socketDescriptors[i].chromeInstance; + ncbp.port=socketDescriptors[i].port; + nativeClientSocket->Bind(&ncbp, _FILE_AND_LINE_); + #elif defined(WINDOWS_STORE_RT) + RNS2BindResult br; + ((RNS2_WindowsStore8*) r2)->SetRecvEventHandler(this); + br = ((RNS2_WindowsStore8*) r2)->Bind(ref new Platform::String()); + if (br!=BR_SUCCESS) + { + RakNetSocket2Allocator::DeallocRNS2(r2); + DerefAllSockets(); + return SOCKET_FAILED_TO_BIND; + } + #else + if (r2->IsBerkleySocket()) + { + RNS2_BerkleyBindParameters bbp; + bbp.port=socketDescriptors[i].port; + bbp.hostAddress=(char*) socketDescriptors[i].hostAddress; + bbp.addressFamily=socketDescriptors[i].socketFamily; + bbp.type=SOCK_DGRAM; + bbp.protocol=socketDescriptors[i].extraSocketOptions; + bbp.nonBlockingSocket=false; + bbp.setBroadcast=true; + bbp.setIPHdrIncl=false; + bbp.doNotFragment=false; + bbp.pollingThreadPriority=threadPriority; + bbp.eventHandler=this; + bbp.remotePortRakNetWasStartedOn_PS3_PS4_PSP2=socketDescriptors[i].remotePortRakNetWasStartedOn_PS3_PSP2; + RNS2BindResult br = ((RNS2_Berkley*) r2)->Bind(&bbp, _FILE_AND_LINE_); + + if ( + #if RAKNET_SUPPORT_IPV6==0 + socketDescriptors[i].socketFamily!=AF_INET || + #endif + br==BR_REQUIRES_RAKNET_SUPPORT_IPV6_DEFINE) + { + RakNetSocket2Allocator::DeallocRNS2(r2); + DerefAllSockets(); + return SOCKET_FAMILY_NOT_SUPPORTED; + } + else if (br==BR_FAILED_TO_BIND_SOCKET) + { + RakNetSocket2Allocator::DeallocRNS2(r2); + DerefAllSockets(); + return SOCKET_PORT_ALREADY_IN_USE; + } + else if (br==BR_FAILED_SEND_TEST) + { + RakNetSocket2Allocator::DeallocRNS2(r2); + DerefAllSockets(); + return SOCKET_FAILED_TEST_SEND; + } + else + { + RakAssert(br==BR_SUCCESS); + } + } + else + { + RakAssert("TODO" && 0); + } + #endif +/* + + SystemAddress saOut; + SocketLayer::GetSystemAddress( rns, &saOut ); + rns->SetBoundAddress(saOut); + rns->SetRemotePortRakNetWasStartedOn(socketDescriptors[i].remotePortRakNetWasStartedOn_PS3_PSP2); + rns->SetChromeInstance(socketDescriptors[i].chromeInstance); + rns->SetExtraSocketOptions(socketDescriptors[i].extraSocketOptions); + rns->SetUserConnectionSocketIndex(i); + rns->SetBlockingSocket(socketDescriptors[i].blockingSocket); + +#if RAKNET_SUPPORT_IPV6==0 + if (addrToBind==0) + rns->SetBoundAddressToLoopback(4); +#endif + + // GetBoundAddress is asynch, which isn't supported by this architecture +#if !defined(__native_client__) + int zero=0; + if (SocketLayer::SendTo(rns, (const char*) &zero,4, rns->GetBoundAddress(), _FILE_AND_LINE_)!=0) + { + DerefAllSockets(); + return SOCKET_FAILED_TEST_SEND; + } +#endif + */ + + socketList.Push(r2, _FILE_AND_LINE_ ); + + } + +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + for (i=0; iIsBerkleySocket()) + ((RNS2_Berkley*) socketList[i])->CreateRecvPollingThread(threadPriority); + } +#endif + +// #if !defined(_XBOX) && !defined(_XBOX_720_COMPILE_AS_WINDOWS) && !defined(X360) + for (i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + { + if (ipList[i]==UNASSIGNED_SYSTEM_ADDRESS) + break; +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + if (socketList[0]->IsBerkleySocket()) + { + unsigned short port = ((RNS2_Berkley*)socketList[0])->GetBoundAddress().GetPort(); + ipList[i].SetPortHostOrder(port); + + } +#endif +// ipList[i].SetPort(((RNS2_360_720*)socketList[0])->GetBoundAddress().GetPort()); + } +// #endif + + + if ( maximumNumberOfPeers == 0 ) + { + // Don't allow more incoming connections than we have peers. + if ( maximumIncomingConnections > maxConnections ) + maximumIncomingConnections = maxConnections; + + maximumNumberOfPeers = maxConnections; + // 04/19/2006 - Don't overallocate because I'm no longer allowing connected pings. + // The disconnects are not consistently processed and the process was sloppy and complicated. + // Allocate 10% extra to handle new connections from players trying to connect when the server is full + //remoteSystemListSize = maxConnections;// * 11 / 10 + 1; + + // remoteSystemList in Single thread + //remoteSystemList = RakNet::OP_NEW( _FILE_AND_LINE_ ); + remoteSystemList = RakNet::OP_NEW_ARRAY(maximumNumberOfPeers, _FILE_AND_LINE_ ); + + remoteSystemLookup = RakNet::OP_NEW_ARRAY((unsigned int) maximumNumberOfPeers * REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE, _FILE_AND_LINE_ ); + + activeSystemList = RakNet::OP_NEW_ARRAY(maximumNumberOfPeers, _FILE_AND_LINE_ ); + + for ( i = 0; i < maximumNumberOfPeers; i++ ) + //for ( i = 0; i < remoteSystemListSize; i++ ) + { + // remoteSystemList in Single thread + remoteSystemList[ i ].isActive = false; + remoteSystemList[ i ].systemAddress = UNASSIGNED_SYSTEM_ADDRESS; + remoteSystemList[ i ].guid = UNASSIGNED_RAKNET_GUID; + remoteSystemList[ i ].myExternalSystemAddress = UNASSIGNED_SYSTEM_ADDRESS; + remoteSystemList[ i ].connectMode=RemoteSystemStruct::NO_ACTION; + remoteSystemList[ i ].MTUSize = defaultMTUSize; + remoteSystemList[ i ].remoteSystemIndex = (SystemIndex) i; +#ifdef _DEBUG + remoteSystemList[ i ].reliabilityLayer.ApplyNetworkSimulator(_packetloss, _minExtraPing, _extraPingVariance); +#endif + + // All entries in activeSystemList have valid pointers all the time. + activeSystemList[ i ] = &remoteSystemList[ i ]; + } + + for (unsigned int i=0; i < (unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE; i++) + { + remoteSystemLookup[i]=0; + } + } + + // For histogram statistics + // nextReadBytesTime=0; + // lastSentBytes=lastReceivedBytes=0; + + if ( endThreads ) + { + updateCycleIsRunning = false; + endThreads = false; + firstExternalID=UNASSIGNED_SYSTEM_ADDRESS; + + ClearBufferedCommands(); + ClearBufferedPackets(); + ClearSocketQueryOutput(); + + if ( isMainLoopThreadActive == false ) + { +#if RAKPEER_USER_THREADED!=1 + + int errorCode; + + + + + + + + errorCode = RakNet::RakThread::Create(UpdateNetworkLoop, this, threadPriority); + + + if ( errorCode != 0 ) + { + Shutdown( 0, 0 ); + return FAILED_TO_CREATE_NETWORK_THREAD; + } +// RakAssert(isRecvFromLoopThreadActive.GetValue()==0); +#endif // RAKPEER_USER_THREADED!=1 + + /* + for (i=0; i(_FILE_AND_LINE_); + rpai->s=socketList[i]; + rpai->rakPeer=this; + +#if RAKPEER_USER_THREADED!=1 + + #if defined(SN_TARGET_PSP2) + sprintf(threadName, "RecvFromLoop_%p", this); + //errorCode = RakNet::RakThread::Create(RecvFromLoop, rpai, threadPriority, threadName, 1+i, runtime); + errorCode = RakNet::RakThread::Create(RecvFromLoop, rpai, threadPriority, threadName, 1024*1); + #else + errorCode = RakNet::RakThread::Create(RecvFromLoop, rpai, threadPriority); + #endif + + if ( errorCode != 0 ) + { + Shutdown( 0, 0 ); + return FAILED_TO_CREATE_NETWORK_THREAD; + } +#endif // RAKPEER_USER_THREADED!=1 + } + */ + + + /* +#if RAKPEER_USER_THREADED!=1 + + while ( isRecvFromLoopThreadActive.GetValue() < (uint32_t) socketDescriptorCount ) + RakSleep(10); + #endif // RAKPEER_USER_THREADED!=1 + */ + + } + +#if RAKPEER_USER_THREADED!=1 + // Wait for the threads to activate. When they are active they will set these variables to true + while ( isMainLoopThreadActive == false ) + RakSleep(10); +#endif // RAKPEER_USER_THREADED!=1 + } + + for (i=0; i < pluginListTS.Size(); i++) + { + pluginListTS[i]->OnRakPeerStartup(); + } + + for (i=0; i < pluginListNTS.Size(); i++) + { + pluginListNTS[i]->OnRakPeerStartup(); + } + +#ifdef USE_THREADED_SEND + RakNet::SendToThread::AddRef(); +#endif + + return RAKNET_STARTED; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Must be called while offline +// +// If you accept connections, you must call this or else security will not be enabled for incoming connections. +// +// This feature requires more round trips, bandwidth, and CPU time for the connection handshake +// x64 builds require under 25% of the CPU time of other builds +// +// See the Encryption sample for example usage +// +// Parameters: +// publicKey = A pointer to the public key for accepting new connections +// privateKey = A pointer to the private key for accepting new connections +// If the private keys are 0, then a new key will be generated when this function is called +// bRequireClientKey: Should be set to false for most servers. Allows the server to accept a public key from connecting clients as a proof of identity but eats twice as much CPU time as a normal connection +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::InitializeSecurity(const char *public_key, const char *private_key, bool bRequireClientKey) +{ +#if LIBCAT_SECURITY==1 + if ( endThreads == false ) + return false; + + // Copy client public key requirement flag + _require_client_public_key = bRequireClientKey; + + if (_server_handshake) + { + CAT_AUDIT_PRINTF("AUDIT: Deleting old server_handshake %x\n", _server_handshake); + RakNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); + } + if (_cookie_jar) + { + CAT_AUDIT_PRINTF("AUDIT: Deleting old cookie jar %x\n", _cookie_jar); + RakNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); + } + + _server_handshake = RakNet::OP_NEW(_FILE_AND_LINE_); + _cookie_jar = RakNet::OP_NEW(_FILE_AND_LINE_); + + CAT_AUDIT_PRINTF("AUDIT: Created new server_handshake %x\n", _server_handshake); + CAT_AUDIT_PRINTF("AUDIT: Created new cookie jar %x\n", _cookie_jar); + CAT_AUDIT_PRINTF("AUDIT: Running _server_handshake->Initialize()\n"); + + if (_server_handshake->Initialize(public_key, private_key)) + { + CAT_AUDIT_PRINTF("AUDIT: Successfully initialized, filling cookie jar with goodies, storing public key and setting using security flag to true\n"); + + _server_handshake->FillCookieJar(_cookie_jar); + + memcpy(my_public_key, public_key, sizeof(my_public_key)); + + _using_security = true; + return true; + } + + CAT_AUDIT_PRINTF("AUDIT: Failure to initialize so deleting server handshake and cookie jar; also setting using_security flag = false\n"); + + RakNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); + _server_handshake=0; + RakNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); + _cookie_jar=0; + _using_security = false; + return false; +#else + (void) public_key; + (void) private_key; + (void) bRequireClientKey; + + return false; +#endif +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description +// Must be called while offline +// Disables security for incoming connections. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::DisableSecurity( void ) +{ +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: DisableSecurity() called, so deleting _server_handshake %x and cookie_jar %x\n", _server_handshake, _cookie_jar); + RakNet::OP_DELETE(_server_handshake,_FILE_AND_LINE_); + _server_handshake=0; + RakNet::OP_DELETE(_cookie_jar,_FILE_AND_LINE_); + _cookie_jar=0; + + _using_security = false; +#endif +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::AddToSecurityExceptionList(const char *ip) +{ + securityExceptionMutex.Lock(); + securityExceptionList.Insert(RakString(ip), _FILE_AND_LINE_); + securityExceptionMutex.Unlock(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::RemoveFromSecurityExceptionList(const char *ip) +{ + if (securityExceptionList.Size()==0) + return; + + if (ip==0) + { + securityExceptionMutex.Lock(); + securityExceptionList.Clear(false, _FILE_AND_LINE_); + securityExceptionMutex.Unlock(); + } + else + { + unsigned i=0; + securityExceptionMutex.Lock(); + while (i < securityExceptionList.Size()) + { + if (securityExceptionList[i].IPAddressMatch(ip)) + { + securityExceptionList[i]=securityExceptionList[securityExceptionList.Size()-1]; + securityExceptionList.RemoveAtIndex(securityExceptionList.Size()-1); + } + else + i++; + } + securityExceptionMutex.Unlock(); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::IsInSecurityExceptionList(const char *ip) +{ + if (securityExceptionList.Size()==0) + return false; + + unsigned i=0; + securityExceptionMutex.Lock(); + for (; i < securityExceptionList.Size(); i++) + { + if (securityExceptionList[i].IPAddressMatch(ip)) + { + securityExceptionMutex.Unlock(); + return true; + } + } + securityExceptionMutex.Unlock(); + return false; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Sets how many incoming connections are allowed. If this is less than the number of players currently connected, no +// more players will be allowed to connect. If this is greater than the maximum number of peers allowed, it will be reduced +// to the maximum number of peers allowed. Defaults to 0. +// +// Parameters: +// numberAllowed - Maximum number of incoming connections allowed. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetMaximumIncomingConnections( unsigned short numberAllowed ) +{ + maximumIncomingConnections = numberAllowed; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Returns the maximum number of incoming connections, which is always <= maxConnections +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GetMaximumIncomingConnections( void ) const +{ + return maximumIncomingConnections; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Returns how many open connections there are at this time +// \return the number of open connections +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned short RakPeer::NumberOfConnections(void) const +{ + DataStructures::List addresses; + DataStructures::List guids; + GetSystemList(addresses, guids); + return (unsigned short) addresses.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Sets the password incoming connections must match in the call to Connect (defaults to none) +// Pass 0 to passwordData to specify no password +// +// Parameters: +// passwordData: A data block that incoming connections must match. This can be just a password, or can be a stream of data. +// - Specify 0 for no password data +// passwordDataLength: The length in bytes of passwordData +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetIncomingPassword( const char* passwordData, int passwordDataLength ) +{ + //if (passwordDataLength > MAX_OFFLINE_DATA_LENGTH) + // passwordDataLength=MAX_OFFLINE_DATA_LENGTH; + + if (passwordDataLength > 255) + passwordDataLength=255; + + if (passwordData==0) + passwordDataLength=0; + + // Not threadsafe but it's not important enough to lock. Who is going to change the password a lot during runtime? + // It won't overflow at least because incomingPasswordLength is an unsigned char + if (passwordDataLength>0) + memcpy(incomingPassword, passwordData, passwordDataLength); + incomingPasswordLength=(unsigned char)passwordDataLength; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::GetIncomingPassword( char* passwordData, int *passwordDataLength ) +{ + if (passwordData==0) + { + *passwordDataLength=incomingPasswordLength; + return; + } + + if (*passwordDataLength > incomingPasswordLength) + *passwordDataLength=incomingPasswordLength; + + if (*passwordDataLength>0) + memcpy(passwordData, incomingPassword, *passwordDataLength); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Call this to connect to the specified host (ip or domain name) and server port. +// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client. Calling both acts as a true peer. +// This is a non-blocking connection. You know the connection is successful when IsConnected() returns true +// or receive gets a packet with the type identifier ID_CONNECTION_REQUEST_ACCEPTED. If the connection is not +// successful, such as rejected connection or no response then neither of these things will happen. +// Requires that you first call Initialize +// +// Parameters: +// host: Either a dotted IP address or a domain name +// remotePort: Which port to connect to on the remote machine. +// passwordData: A data block that must match the data block on the server. This can be just a password, or can be a stream of data +// passwordDataLength: The length in bytes of passwordData +// +// Returns: +// True on successful initiation. False on incorrect parameters, internal error, or too many existing peers +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +ConnectionAttemptResult RakPeer::Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNet::TimeMS timeoutTime ) +{ + // If endThreads is true here you didn't call Startup() first. + if ( host == 0 || endThreads || connectionSocketIndex>=socketList.Size() ) + return INVALID_PARAMETER; + + RakAssert(remotePort!=0); + + connectionSocketIndex=GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); + + if (passwordDataLength>255) + passwordDataLength=255; + + if (passwordData==0) + passwordDataLength=0; + + // Not threadsafe but it's not important enough to lock. Who is going to change the password a lot during runtime? + // It won't overflow at least because outgoingPasswordLength is an unsigned char +// if (passwordDataLength>0) +// memcpy(outgoingPassword, passwordData, passwordDataLength); +// outgoingPasswordLength=(unsigned char) passwordDataLength; + + // 04/02/09 - Can't remember why I disabled connecting to self, but it seems to work + // Connecting to ourselves in the same instance of the program? +// if ( ( strcmp( host, "127.0.0.1" ) == 0 || strcmp( host, "0.0.0.0" ) == 0 ) && remotePort == mySystemAddress[0].port ) +// return false; + + return SendConnectionRequest( host, remotePort, passwordData, passwordDataLength, publicKey, connectionSocketIndex, 0, sendConnectionAttemptCount, timeBetweenSendConnectionAttemptsMS, timeoutTime); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ConnectionAttemptResult RakPeer::ConnectWithSocket(const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, RakNetSocket2* socket, PublicKey *publicKey, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNet::TimeMS timeoutTime) +{ + if ( host == 0 || endThreads || socket == 0 ) + return INVALID_PARAMETER; + + if (passwordDataLength>255) + passwordDataLength=255; + + if (passwordData==0) + passwordDataLength=0; + + return SendConnectionRequest( host, remotePort, passwordData, passwordDataLength, publicKey, 0, 0, sendConnectionAttemptCount, timeBetweenSendConnectionAttemptsMS, timeoutTime, socket ); + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Stops the network threads and close all connections. Multiple calls are ok. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::Shutdown( unsigned int blockDuration, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority ) +{ + unsigned i,j; + bool anyActive; + RakNet::TimeMS startWaitingTime; +// SystemAddress systemAddress; + RakNet::TimeMS time; + //unsigned short systemListSize = remoteSystemListSize; // This is done for threading reasons + unsigned int systemListSize = maximumNumberOfPeers; + + if ( blockDuration > 0 ) + { + for ( i = 0; i < systemListSize; i++ ) + { + // remoteSystemList in user thread + if (remoteSystemList[i].isActive) + NotifyAndFlagForShutdown(remoteSystemList[i].systemAddress, false, orderingChannel, disconnectionNotificationPriority); + } + + time = RakNet::GetTimeMS(); + startWaitingTime = time; + while ( time - startWaitingTime < blockDuration ) + { + anyActive=false; + for (j=0; j < systemListSize; j++) + { + // remoteSystemList in user thread + if (remoteSystemList[j].isActive) + { + anyActive=true; + break; + } + } + + // If this system is out of packets to send, then stop waiting + if ( anyActive==false ) + break; + + // This will probably cause the update thread to run which will probably + // send the disconnection notification + + RakSleep(15); + time = RakNet::GetTimeMS(); + } + } + for (i=0; i < pluginListTS.Size(); i++) + { + pluginListTS[i]->OnRakPeerShutdown(); + } + for (i=0; i < pluginListNTS.Size(); i++) + { + pluginListNTS[i]->OnRakPeerShutdown(); + } + + activeSystemListSize=0; + + quitAndDataEvents.SetEvent(); + + endThreads = true; + +// RakNet::TimeMS timeout; +#if RAKPEER_USER_THREADED!=1 + +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + for (i=0; i < socketList.Size(); i++) + { + if (socketList[i]->IsBerkleySocket()) + { + ((RNS2_Berkley *)socketList[i])->SignalStopRecvPollingThread(); + } + } +#endif + + /* + // Get recvfrom to unblock + for (i=0; i < socketList.Size(); i++) + { + if (SocketLayer::SendTo(socketList[i], (const char*) &i,1,socketList[i]->GetBoundAddress(), _FILE_AND_LINE_)!=0) + break; + } + */ + + while ( isMainLoopThreadActive ) + { + endThreads = true; + RakSleep(15); + } + + /* + timeout = RakNet::GetTimeMS()+1000; + while ( isRecvFromLoopThreadActive.GetValue()>0 && RakNet::GetTimeMS()GetBoundAddress(), _FILE_AND_LINE_); + } + + RakSleep(30); + } + */ + +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + for (i=0; i < socketList.Size(); i++) + { + if (socketList[i]->IsBerkleySocket()) + { + ((RNS2_Berkley *)socketList[i])->BlockOnStopRecvPollingThread(); + } + } +#endif + + +#endif // RAKPEER_USER_THREADED!=1 + +// char c=0; +// unsigned int socketIndex; + // remoteSystemList in Single thread + for ( i = 0; i < systemListSize; i++ ) + { + // Reserve this reliability layer for ourselves + remoteSystemList[ i ].isActive = false; + + // Remove any remaining packets + RakAssert(remoteSystemList[ i ].MTUSize <= MAXIMUM_MTU_SIZE); + remoteSystemList[ i ].reliabilityLayer.Reset(false, remoteSystemList[ i ].MTUSize, false); + remoteSystemList[ i ].rakNetSocket = 0; + } + + + // Setting maximumNumberOfPeers to 0 allows remoteSystemList to be reallocated in Initialize. + // Setting remoteSystemListSize prevents threads from accessing the reliability layer + maximumNumberOfPeers = 0; + //remoteSystemListSize = 0; + + // Free any packets the user didn't deallocate + packetReturnMutex.Lock(); + for (i=0; i < packetReturnQueue.Size(); i++) + DeallocatePacket(packetReturnQueue[i]); + packetReturnQueue.Clear(_FILE_AND_LINE_); + packetReturnMutex.Unlock(); + packetAllocationPoolMutex.Lock(); + packetAllocationPool.Clear(_FILE_AND_LINE_); + packetAllocationPoolMutex.Unlock(); + + /* + if (isRecvFromLoopThreadActive.GetValue()>0) + { + timeout = RakNet::GetTimeMS()+1000; + while ( isRecvFromLoopThreadActive.GetValue()>0 && RakNet::GetTimeMS() addresses; + DataStructures::List guids; + GetSystemList(addresses, guids); + if (remoteSystems) + { + unsigned short i; + for (i=0; i < *numberOfSystems && i < addresses.Size(); i++) + remoteSystems[i]=addresses[i]; + *numberOfSystems=i; + } + else + { + *numberOfSystems=(unsigned short) addresses.Size(); + } + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +uint32_t RakPeer::GetNextSendReceipt(void) +{ + sendReceiptSerialMutex.Lock(); + uint32_t retVal = sendReceiptSerial; + sendReceiptSerialMutex.Unlock(); + return retVal; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +uint32_t RakPeer::IncrementNextSendReceipt(void) +{ + sendReceiptSerialMutex.Lock(); + uint32_t returned = sendReceiptSerial; + if (++sendReceiptSerial==0) + sendReceiptSerial=1; + sendReceiptSerialMutex.Unlock(); + return returned; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Sends a block of data to the specified system that you are connected to. +// This function only works while the client is connected (Use the Connect function). +// The first byte should be a message identifier starting at ID_USER_PACKET_ENUM +// +// Parameters: +// data: The block of data to send +// length: The size in bytes of the data to send +// bitStream: The bitstream to send +// priority: What priority level to send on. +// reliability: How reliability to send this data +// orderingChannel: When using ordered or sequenced packets, what channel to order these on. +// - Packets are only ordered relative to other packets on the same stream +// systemAddress: Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none +// broadcast: True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. +// Returns: +// \return 0 on bad input. Otherwise a number that identifies this message. If \a reliability is a type that returns a receipt, on a later call to Receive() you will get ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS with bytes 1-4 inclusive containing this number +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +uint32_t RakPeer::Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber ) +{ +#ifdef _DEBUG + RakAssert( data && length > 0 ); +#endif + RakAssert( !( reliability >= NUMBER_OF_RELIABILITIES || reliability < 0 ) ); + RakAssert( !( priority > NUMBER_OF_PRIORITIES || priority < 0 ) ); + RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); + + if ( data == 0 || length < 0 ) + return 0; + + if ( remoteSystemList == 0 || endThreads == true ) + return 0; + + if ( broadcast == false && systemIdentifier.IsUndefined()) + return 0; + + uint32_t usedSendReceipt; + if (forceReceiptNumber!=0) + usedSendReceipt=forceReceiptNumber; + else + usedSendReceipt=IncrementNextSendReceipt(); + + if (broadcast==false && IsLoopbackAddress(systemIdentifier,true)) + { + SendLoopback(data,length); + + if (reliability>=UNRELIABLE_WITH_ACK_RECEIPT) + { + char buff[5]; + buff[0]=ID_SND_RECEIPT_ACKED; + sendReceiptSerialMutex.Lock(); + memcpy(buff+1, &sendReceiptSerial, 4); + sendReceiptSerialMutex.Unlock(); + SendLoopback( buff, 5 ); + } + + return usedSendReceipt; + } + + SendBuffered(data, length*8, priority, reliability, orderingChannel, systemIdentifier, broadcast, RemoteSystemStruct::NO_ACTION, usedSendReceipt); + + return usedSendReceipt; +} + +void RakPeer::SendLoopback( const char *data, const int length ) +{ + if ( data == 0 || length < 0 ) + return; + + Packet *packet = AllocPacket(length, _FILE_AND_LINE_); + memcpy(packet->data, data, length); + packet->systemAddress = GetLoopbackAddress(); + packet->guid=myGuid; + PushBackPacket(packet, false); +} + +uint32_t RakPeer::Send( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber ) +{ +#ifdef _DEBUG + RakAssert( bitStream->GetNumberOfBytesUsed() > 0 ); +#endif + + RakAssert( !( reliability >= NUMBER_OF_RELIABILITIES || reliability < 0 ) ); + RakAssert( !( priority > NUMBER_OF_PRIORITIES || priority < 0 ) ); + RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); + + if ( bitStream->GetNumberOfBytesUsed() == 0 ) + return 0; + + if ( remoteSystemList == 0 || endThreads == true ) + return 0; + + if ( broadcast == false && systemIdentifier.IsUndefined() ) + return 0; + + uint32_t usedSendReceipt; + if (forceReceiptNumber!=0) + usedSendReceipt=forceReceiptNumber; + else + usedSendReceipt=IncrementNextSendReceipt(); + + if (broadcast==false && IsLoopbackAddress(systemIdentifier,true)) + { + SendLoopback((const char*) bitStream->GetData(),bitStream->GetNumberOfBytesUsed()); + if (reliability>=UNRELIABLE_WITH_ACK_RECEIPT) + { + char buff[5]; + buff[0]=ID_SND_RECEIPT_ACKED; + sendReceiptSerialMutex.Lock(); + memcpy(buff+1, &sendReceiptSerial,4); + sendReceiptSerialMutex.Unlock(); + SendLoopback( buff, 5 ); + } + return usedSendReceipt; + } + + // Sends need to be buffered and processed in the update thread because the systemAddress associated with the reliability layer can change, + // from that thread, resulting in a send to the wrong player! While I could mutex the systemAddress, that is much slower than doing this + SendBuffered((const char*)bitStream->GetData(), bitStream->GetNumberOfBitsUsed(), priority, reliability, orderingChannel, systemIdentifier, broadcast, RemoteSystemStruct::NO_ACTION, usedSendReceipt); + + + return usedSendReceipt; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Sends multiple blocks of data, concatenating them automatically. +// +// This is equivalent to: +// RakNet::BitStream bs; +// bs.WriteAlignedBytes(block1, blockLength1); +// bs.WriteAlignedBytes(block2, blockLength2); +// bs.WriteAlignedBytes(block3, blockLength3); +// Send(&bs, ...) +// +// This function only works while connected +// \param[in] data An array of pointers to blocks of data +// \param[in] lengths An array of integers indicating the length of each block of data +// \param[in] numParameters Length of the arrays data and lengths +// \param[in] priority What priority level to send on. See PacketPriority.h +// \param[in] reliability How reliability to send this data. See PacketPriority.h +// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream +// \param[in] systemIdentifier Who to send this packet to, or in the case of broadcasting who not to send it to. Pass either a SystemAddress structure or a RakNetGUID structure. Use UNASSIGNED_SYSTEM_ADDRESS or to specify none +// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to. +// \return False if we are not connected to the specified recipient. True otherwise +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +uint32_t RakPeer::SendList( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, uint32_t forceReceiptNumber ) +{ +#ifdef _DEBUG + RakAssert( data ); +#endif + + if ( data == 0 || lengths == 0 ) + return 0; + + if ( remoteSystemList == 0 || endThreads == true ) + return 0; + + if (numParameters==0) + return 0; + + if (lengths==0) + return 0; + + if ( broadcast == false && systemIdentifier.IsUndefined() ) + return 0; + + uint32_t usedSendReceipt; + if (forceReceiptNumber!=0) + usedSendReceipt=forceReceiptNumber; + else + usedSendReceipt=IncrementNextSendReceipt(); + + SendBufferedList(data, lengths, numParameters, priority, reliability, orderingChannel, systemIdentifier, broadcast, RemoteSystemStruct::NO_ACTION, usedSendReceipt); + + return usedSendReceipt; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Gets a packet from the incoming packet queue. Use DeallocatePacket to deallocate the packet after you are done with it. +// Check the Packet struct at the top of CoreNetworkStructures.h for the format of the struct +// +// Returns: +// 0 if no packets are waiting to be handled, otherwise an allocated packet +// If the client is not active this will also return 0, as all waiting packets are flushed when the client is Disconnected +// This also updates all memory blocks associated with synchronized memory and distributed objects +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +#ifdef _MSC_VER +#pragma warning( disable : 4701 ) // warning C4701: local variable may be used without having been initialized +#endif +Packet* RakPeer::Receive( void ) +{ + if ( !( IsActive() ) ) + return 0; + + RakNet::Packet *packet; +// Packet **threadPacket; + PluginReceiveResult pluginResult; + + int offset; + unsigned int i; + + // User should call RunUpdateCycle and RunRecvFromOnce to do this commented code + /* +#if RAKPEER_SINGLE_THREADED==1 + RakPeer::RecvFromStruct *recvFromStruct; + for (i=0; i < socketList.Size(); i++) + { + while (1) + { + recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); + recvFromStruct->s=socketList[i]->s; + recvFromStruct->remotePortRakNetWasStartedOn_PS3=socketList[i]->remotePortRakNetWasStartedOn_PS3_PSP2; + recvFromStruct->extraSocketOptions=socketList[i]->extraSocketOptions; + SocketLayer::RecvFromBlocking( + recvFromStruct->s, this, recvFromStruct->remotePortRakNetWasStartedOn_PS3, + recvFromStruct->extraSocketOptions, recvFromStruct->data, &recvFromStruct->bytesRead, &recvFromStruct->systemAddress, &recvFromStruct->timeRead); + if (recvFromStruct->bytesRead<=0) + { + bufferedPackets.Deallocate(recvFromStruct, _FILE_AND_LINE_); + break; + } + else + { + RakAssert(recvFromStruct->systemAddress.GetPort()); + bufferedPackets.Push(recvFromStruct); + } + } + } + + BitStream updateBitStream( MAXIMUM_MTU_SIZE +#if LIBCAT_SECURITY==1 + + cat::AuthenticatedEncryption::OVERHEAD_BYTES +#endif + ); + RunUpdateCycle(0, 0, updateBitStream); +#endif + */ + + for (i=0; i < pluginListTS.Size(); i++) + { + pluginListTS[i]->Update(); + } + for (i=0; i < pluginListNTS.Size(); i++) + { + pluginListNTS[i]->Update(); + } + + do + { + packetReturnMutex.Lock(); + if (packetReturnQueue.IsEmpty()) + packet=0; + else + packet = packetReturnQueue.Pop(); + packetReturnMutex.Unlock(); + if (packet==0) + return 0; + +// unsigned char msgId; + if ( ( packet->length >= sizeof(unsigned char) + sizeof( RakNet::Time ) ) && + ( (unsigned char) packet->data[ 0 ] == ID_TIMESTAMP ) ) + { + offset = sizeof(unsigned char); + ShiftIncomingTimestamp( packet->data + offset, packet->systemAddress ); +// msgId=packet->data[sizeof(unsigned char) + sizeof( RakNet::Time )]; + } +// else + // msgId=packet->data[0]; + + // Some locally generated packets need to be processed by plugins, for example ID_FCM2_NEW_HOST + // The plugin itself should intercept these messages generated remotely +// if (packet->wasGeneratedLocally) +// return packet; + + + CallPluginCallbacks(pluginListTS, packet); + CallPluginCallbacks(pluginListNTS, packet); + + for (i=0; i < pluginListTS.Size(); i++) + { + pluginResult=pluginListTS[i]->OnReceive(packet); + if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) + { + DeallocatePacket( packet ); + packet=0; // Will do the loop again and get another packet + break; // break out of the enclosing for + } + else if (pluginResult==RR_STOP_PROCESSING) + { + packet=0; + break; + } + } + + for (i=0; i < pluginListNTS.Size(); i++) + { + pluginResult=pluginListNTS[i]->OnReceive(packet); + if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) + { + DeallocatePacket( packet ); + packet=0; // Will do the loop again and get another packet + break; // break out of the enclosing for + } + else if (pluginResult==RR_STOP_PROCESSING) + { + packet=0; + break; + } + } + + } while(packet==0); + +#ifdef _DEBUG + RakAssert( packet->data ); +#endif + + return packet; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Call this to deallocate a packet returned by Receive +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::DeallocatePacket( Packet *packet ) +{ + if ( packet == 0 ) + return; + + if (packet->deleteData) + { + rakFree_Ex(packet->data, _FILE_AND_LINE_ ); + packet->~Packet(); + packetAllocationPoolMutex.Lock(); + packetAllocationPool.Release(packet,_FILE_AND_LINE_); + packetAllocationPoolMutex.Unlock(); + } + else + { + rakFree_Ex(packet, _FILE_AND_LINE_ ); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Return the total number of connections we are allowed +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GetMaximumNumberOfPeers( void ) const +{ + return maximumNumberOfPeers; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out). +// +// Parameters: +// target: Which connection to close +// sendDisconnectionNotification: True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently. +// channel: If blockDuration > 0, the disconnect packet will be sent on this channel +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::CloseConnection( const AddressOrGUID target, bool sendDisconnectionNotification, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority ) +{ + /* + // This only be called from the user thread, for the user shutting down. + // From the network thread, this should occur because of ID_DISCONNECTION_NOTIFICATION and ID_CONNECTION_LOST + unsigned j; + for (j=0; j < messageHandlerList.Size(); j++) + { + messageHandlerList[j]->OnClosedConnection( + target.systemAddress==UNASSIGNED_SYSTEM_ADDRESS ? GetSystemAddressFromGuid(target.rakNetGuid) : target.systemAddress, + target.rakNetGuid==UNASSIGNED_RAKNET_GUID ? GetGuidFromSystemAddress(target.systemAddress) : target.rakNetGuid, + LCR_CLOSED_BY_USER); + } + */ + + CloseConnectionInternal(target, sendDisconnectionNotification, false, orderingChannel, disconnectionNotificationPriority); + + // 12/14/09 Return ID_CONNECTION_LOST when calling CloseConnection with sendDisconnectionNotification==false, elsewise it is never returned + if (sendDisconnectionNotification==false && GetConnectionState(target)==IS_CONNECTED) + { + Packet *packet=AllocPacket(sizeof( char ), _FILE_AND_LINE_); + packet->data[ 0 ] = ID_CONNECTION_LOST; // DeadConnection + packet->guid = target.rakNetGuid==UNASSIGNED_RAKNET_GUID ? GetGuidFromSystemAddress(target.systemAddress) : target.rakNetGuid; + packet->systemAddress = target.systemAddress==UNASSIGNED_SYSTEM_ADDRESS ? GetSystemAddressFromGuid(target.rakNetGuid) : target.systemAddress; + packet->systemAddress.systemIndex = (SystemIndex) GetIndexFromSystemAddress(packet->systemAddress); + packet->guid.systemIndex=packet->systemAddress.systemIndex; + packet->wasGeneratedLocally=true; // else processed twice + AddPacketToProducer(packet); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Cancel a pending connection attempt +// If we are already connected, the connection stays open +// \param[in] target Which system to cancel +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::CancelConnectionAttempt( const SystemAddress target ) +{ + unsigned int i; + + // Cancel pending connection attempt, if there is one + i=0; + requestedConnectionQueueMutex.Lock(); + while (i < requestedConnectionQueue.Size()) + { + if (requestedConnectionQueue[i]->systemAddress==target) + { +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: Deleting requestedConnectionQueue %i client_handshake %x\n", i, requestedConnectionQueue[ i ]->client_handshake); + RakNet::OP_DELETE(requestedConnectionQueue[i]->client_handshake, _FILE_AND_LINE_ ); +#endif + RakNet::OP_DELETE(requestedConnectionQueue[i], _FILE_AND_LINE_ ); + requestedConnectionQueue.RemoveAtIndex(i); + break; + } + else + i++; + } + requestedConnectionQueueMutex.Unlock(); + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +#ifdef _MSC_VER +#pragma warning( disable : 4702 ) // warning C4702: unreachable code +#endif +ConnectionState RakPeer::GetConnectionState(const AddressOrGUID systemIdentifier) +{ + if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + unsigned int i=0; + requestedConnectionQueueMutex.Lock(); + for (; i < requestedConnectionQueue.Size(); i++) + { + if (requestedConnectionQueue[i]->systemAddress==systemIdentifier.systemAddress) + { + requestedConnectionQueueMutex.Unlock(); + return IS_PENDING; + } + } + requestedConnectionQueueMutex.Unlock(); + } + + int index; + if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + index = GetIndexFromSystemAddress(systemIdentifier.systemAddress, false); + } + else + { + index = GetIndexFromGuid(systemIdentifier.rakNetGuid); + } + + if (index==-1) + return IS_NOT_CONNECTED; + + if (remoteSystemList[index].isActive==false) + return IS_DISCONNECTED; + + switch (remoteSystemList[index].connectMode) + { + case RemoteSystemStruct::DISCONNECT_ASAP: + return IS_DISCONNECTING; + case RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY: + return IS_SILENTLY_DISCONNECTING; + case RemoteSystemStruct::DISCONNECT_ON_NO_ACK: + return IS_DISCONNECTING; + case RemoteSystemStruct::REQUESTED_CONNECTION: + return IS_CONNECTING; + case RemoteSystemStruct::HANDLING_CONNECTION_REQUEST: + return IS_CONNECTING; + case RemoteSystemStruct::UNVERIFIED_SENDER: + return IS_CONNECTING; + case RemoteSystemStruct::CONNECTED: + return IS_CONNECTED; + default: + return IS_NOT_CONNECTED; + } + + return IS_NOT_CONNECTED; +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1. +// +// Parameters +// systemAddress - The systemAddress to search for +// +// Returns +// An integer from 0 to the maximum number of peers -1, or -1 if that player is not found +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetIndexFromSystemAddress( const SystemAddress systemAddress ) const +{ + return GetIndexFromSystemAddress(systemAddress, false); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// This function is only useful for looping through all players. +// +// Parameters +// index - an integer between 0 and the maximum number of players allowed - 1. +// +// Returns +// A valid systemAddress or UNASSIGNED_SYSTEM_ADDRESS if no such player at that index +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +SystemAddress RakPeer::GetSystemAddressFromIndex( unsigned int index ) +{ + // remoteSystemList in user thread + //if ( index >= 0 && index < remoteSystemListSize ) + if ( index < maximumNumberOfPeers ) + if (remoteSystemList[index].isActive && remoteSystemList[ index ].connectMode==RakPeer::RemoteSystemStruct::CONNECTED) // Don't give the user players that aren't fully connected, since sends will fail + return remoteSystemList[ index ].systemAddress; + + return UNASSIGNED_SYSTEM_ADDRESS; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Same as GetSystemAddressFromIndex but returns RakNetGUID +// \param[in] index Index should range between 0 and the maximum number of players allowed - 1. +// \return The RakNetGUID +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakNetGUID RakPeer::GetGUIDFromIndex( unsigned int index ) +{ + // remoteSystemList in user thread + //if ( index >= 0 && index < remoteSystemListSize ) + if ( index < maximumNumberOfPeers ) + if (remoteSystemList[index].isActive && remoteSystemList[ index ].connectMode==RakPeer::RemoteSystemStruct::CONNECTED) // Don't give the user players that aren't fully connected, since sends will fail + return remoteSystemList[ index ].guid; + + return UNASSIGNED_RAKNET_GUID; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Same as calling GetSystemAddressFromIndex and GetGUIDFromIndex for all systems, but more efficient +// Indices match each other, so \a addresses[0] and \a guids[0] refer to the same system +// \param[out] addresses All system addresses. Size of the list is the number of connections. Size of the list will match the size of the \a guids list. +// \param[out] guids All guids. Size of the list is the number of connections. Size of the list will match the size of the \a addresses list. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::GetSystemList(DataStructures::List &addresses, DataStructures::List &guids) const +{ + addresses.Clear(false, _FILE_AND_LINE_); + guids.Clear(false, _FILE_AND_LINE_); + + if ( remoteSystemList == 0 || endThreads == true ) + return; + + unsigned int i; + for (i=0; i < activeSystemListSize; i++) + { + if ((activeSystemList[i])->isActive && + (activeSystemList[i])->connectMode==RakPeer::RemoteSystemStruct::CONNECTED) + { + addresses.Push((activeSystemList[i])->systemAddress, _FILE_AND_LINE_ ); + guids.Push((activeSystemList[i])->guid, _FILE_AND_LINE_ ); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Bans an IP from connecting. Banned IPs persist between connections. +// +// Parameters +// IP - Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban +// All IP addresses starting with 128.0.0 +// milliseconds - how many ms for a temporary ban. Use 0 for a permanent ban +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::AddToBanList( const char *IP, RakNet::TimeMS milliseconds ) +{ + unsigned index; + RakNet::TimeMS time = RakNet::GetTimeMS(); + + if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) + return ; + + // If this guy is already in the ban list, do nothing + index = 0; + + banListMutex.Lock(); + + for ( ; index < banList.Size(); index++ ) + { + if ( strcmp( IP, banList[ index ]->IP ) == 0 ) + { + // Already in the ban list. Just update the time + if (milliseconds==0) + banList[ index ]->timeout=0; // Infinite + else + banList[ index ]->timeout=time+milliseconds; + banListMutex.Unlock(); + return; + } + } + + banListMutex.Unlock(); + + BanStruct *banStruct = RakNet::OP_NEW( _FILE_AND_LINE_ ); + banStruct->IP = (char*) rakMalloc_Ex( 16, _FILE_AND_LINE_ ); + if (milliseconds==0) + banStruct->timeout=0; // Infinite + else + banStruct->timeout=time+milliseconds; + strcpy( banStruct->IP, IP ); + banListMutex.Lock(); + banList.Insert( banStruct, _FILE_AND_LINE_ ); + banListMutex.Unlock(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Allows a previously banned IP to connect. +// +// Parameters +// IP - Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban +// All IP addresses starting with 128.0.0 +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::RemoveFromBanList( const char *IP ) +{ + unsigned index; + BanStruct *temp; + + if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) + return ; + + index = 0; + temp=0; + + banListMutex.Lock(); + + for ( ; index < banList.Size(); index++ ) + { + if ( strcmp( IP, banList[ index ]->IP ) == 0 ) + { + temp = banList[ index ]; + banList[ index ] = banList[ banList.Size() - 1 ]; + banList.RemoveAtIndex( banList.Size() - 1 ); + break; + } + } + + banListMutex.Unlock(); + + if (temp) + { + rakFree_Ex(temp->IP, _FILE_AND_LINE_ ); + RakNet::OP_DELETE(temp, _FILE_AND_LINE_); + } + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Allows all previously banned IPs to connect. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ClearBanList( void ) +{ + unsigned index; + index = 0; + banListMutex.Lock(); + + for ( ; index < banList.Size(); index++ ) + { + rakFree_Ex(banList[ index ]->IP, _FILE_AND_LINE_ ); + RakNet::OP_DELETE(banList[ index ], _FILE_AND_LINE_); + } + + banList.Clear(false, _FILE_AND_LINE_); + + banListMutex.Unlock(); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetLimitIPConnectionFrequency(bool b) +{ + limitConnectionFrequencyFromTheSameIP=b; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Determines if a particular IP is banned. +// +// Parameters +// IP - Complete dotted IP address +// +// Returns +// True if IP matches any IPs in the ban list, accounting for any wildcards. +// False otherwise. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::IsBanned( const char *IP ) +{ + unsigned banListIndex, characterIndex; + RakNet::TimeMS time; + BanStruct *temp; + + if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) + return false; + + banListIndex = 0; + + if ( banList.Size() == 0 ) + return false; // Skip the mutex if possible + + time = RakNet::GetTimeMS(); + + banListMutex.Lock(); + + while ( banListIndex < banList.Size() ) + { + if (banList[ banListIndex ]->timeout>0 && banList[ banListIndex ]->timeoutIP, _FILE_AND_LINE_ ); + RakNet::OP_DELETE(temp, _FILE_AND_LINE_); + } + else + { + characterIndex = 0; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while ( true ) + { + if ( banList[ banListIndex ]->IP[ characterIndex ] == IP[ characterIndex ] ) + { + // Equal characters + + if ( IP[ characterIndex ] == 0 ) + { + banListMutex.Unlock(); + // End of the string and the strings match + + return true; + } + + characterIndex++; + } + + else + { + if ( banList[ banListIndex ]->IP[ characterIndex ] == 0 || IP[ characterIndex ] == 0 ) + { + // End of one of the strings + break; + } + + // Characters do not match + if ( banList[ banListIndex ]->IP[ characterIndex ] == '*' ) + { + banListMutex.Unlock(); + + // Domain is banned. + return true; + } + + // Characters do not match and it is not a * + break; + } + } + + banListIndex++; + } + } + + banListMutex.Unlock(); + + // No match found. + return false; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Send a ping to the specified connected system. +// +// Parameters: +// target - who to ping +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::Ping( const SystemAddress target ) +{ + PingInternal(target, false, UNRELIABLE); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Send a ping to the specified unconnected system. +// The remote system, if it is Initialized, will respond with ID_UNCONNECTED_PONG. +// The final ping time will be encoded in the following sizeof(RakNet::TimeMS) bytes. (Default is 4 bytes - See __GET_TIME_64BIT in RakNetTypes.h +// +// Parameters: +// host: Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast. +// remotePort: Which port to connect to on the remote machine. +// onlyReplyOnAcceptingConnections: Only request a reply if the remote system has open connections +// connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex ) +{ + if ( host == 0 ) + return false; + + // If this assert hits then Startup wasn't called or the call failed. + RakAssert(connectionSocketIndex < socketList.Size()); + +// if ( IsActive() == false ) +// return; + + RakNet::BitStream bitStream( sizeof(unsigned char) + sizeof(RakNet::Time) ); + if ( onlyReplyOnAcceptingConnections ) + bitStream.Write((MessageID)ID_UNCONNECTED_PING_OPEN_CONNECTIONS); + else + bitStream.Write((MessageID)ID_UNCONNECTED_PING); + + bitStream.Write(RakNet::GetTime()); + + bitStream.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + + bitStream.Write(GetMyGUID()); + + // No timestamp for 255.255.255.255 + unsigned int realIndex = GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); + /* + + SystemAddress systemAddress; + systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); + systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); + + unsigned i; + for (i=0; i < pluginListNTS.Size(); i++) + pluginListNTS[i]->OnDirectSocketSend((const char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), systemAddress); + SocketLayer::SendTo( socketList[realIndex], (const char*)bitStream.GetData(), (int) bitStream.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + */ + + RNS2_SendParameters bsp; + bsp.data = (char*) bitStream.GetData() ; + bsp.length = bitStream.GetNumberOfBytesUsed(); + bsp.systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); + if (bsp.systemAddress==UNASSIGNED_SYSTEM_ADDRESS) + return false; + bsp.systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); + unsigned i; + for (i=0; i < pluginListNTS.Size(); i++) + pluginListNTS[i]->OnDirectSocketSend((const char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), bsp.systemAddress); + socketList[realIndex]->Send(&bsp, _FILE_AND_LINE_); + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Returns the average of all ping times read for a specified target +// +// Parameters: +// target - whose time to read +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetAveragePing( const AddressOrGUID systemIdentifier ) +{ + int sum, quantity; + RemoteSystemStruct *remoteSystem = GetRemoteSystem( systemIdentifier, false, false ); + + if ( remoteSystem == 0 ) + return -1; + + for ( sum = 0, quantity = 0; quantity < PING_TIMES_ARRAY_SIZE; quantity++ ) + { + if ( remoteSystem->pingAndClockDifferential[ quantity ].pingTime == 65535 ) + break; + else + sum += remoteSystem->pingAndClockDifferential[ quantity ].pingTime; + } + + if ( quantity > 0 ) + return sum / quantity; + else + return -1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Returns the last ping time read for the specific player or -1 if none read yet +// +// Parameters: +// target - whose time to read +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetLastPing( const AddressOrGUID systemIdentifier ) const +{ + RemoteSystemStruct * remoteSystem = GetRemoteSystem( systemIdentifier, false, false ); + + if ( remoteSystem == 0 ) + return -1; + +// return (int)(remoteSystem->reliabilityLayer.GetAckPing()/(RakNet::TimeUS)1000); + + if ( remoteSystem->pingAndClockDifferentialWriteIndex == 0 ) + return remoteSystem->pingAndClockDifferential[ PING_TIMES_ARRAY_SIZE - 1 ].pingTime; + else + return remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex - 1 ].pingTime; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Returns the lowest ping time read or -1 if none read yet +// +// Parameters: +// target - whose time to read +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetLowestPing( const AddressOrGUID systemIdentifier ) const +{ + RemoteSystemStruct * remoteSystem = GetRemoteSystem( systemIdentifier, false, false ); + + if ( remoteSystem == 0 ) + return -1; + + return remoteSystem->lowestPing; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Ping the remote systems every so often. This is off by default +// This will work anytime +// +// Parameters: +// doPing - True to start occasional pings. False to stop them. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetOccasionalPing( bool doPing ) +{ + occasionalPing = doPing; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +/// Return the clock difference between your system and the specified system +/// Subtract the time from a time returned by the remote system to get that time relative to your own system +/// Returns 0 if the system is unknown +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakNet::Time RakPeer::GetClockDifferential( const AddressOrGUID systemIdentifier ) +{ + RemoteSystemStruct *remoteSystem = GetRemoteSystem(systemIdentifier, false, false); + if (remoteSystem == 0) + return 0; + return GetClockDifferentialInt(remoteSystem); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RakNet::Time RakPeer::GetClockDifferentialInt(RemoteSystemStruct *remoteSystem) const +{ + int counter, lowestPingSoFar; + RakNet::Time clockDifferential; + + lowestPingSoFar = 65535; + + clockDifferential = 0; + + for ( counter = 0; counter < PING_TIMES_ARRAY_SIZE; counter++ ) + { + if ( remoteSystem->pingAndClockDifferential[ counter ].pingTime == 65535 ) + break; + + if ( remoteSystem->pingAndClockDifferential[ counter ].pingTime < lowestPingSoFar ) + { + clockDifferential = remoteSystem->pingAndClockDifferential[ counter ].clockDifferential; + lowestPingSoFar = remoteSystem->pingAndClockDifferential[ counter ].pingTime; + } + } + + return clockDifferential; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Length should be under 400 bytes, as a security measure against flood attacks +// Sets the data to send with an (LAN server discovery) /(offline ping) response +// See the Ping sample project for how this is used. +// data: a block of data to store, or 0 for none +// length: The length of data in bytes, or 0 for none +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetOfflinePingResponse( const char *data, const unsigned int length ) +{ + RakAssert(length < 400); + + rakPeerMutexes[ offlinePingResponse_Mutex ].Lock(); + offlinePingResponse.Reset(); + + if ( data && length > 0 ) + offlinePingResponse.Write( data, length ); + + rakPeerMutexes[ offlinePingResponse_Mutex ].Unlock(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Returns pointers to a copy of the data passed to SetOfflinePingResponse +// \param[out] data A pointer to a copy of the data passed to \a SetOfflinePingResponse() +// \param[out] length A pointer filled in with the length parameter passed to SetOfflinePingResponse() +// \sa SetOfflinePingResponse +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::GetOfflinePingResponse( char **data, unsigned int *length ) +{ + rakPeerMutexes[ offlinePingResponse_Mutex ].Lock(); + *data = (char*) offlinePingResponse.GetData(); + *length = (int) offlinePingResponse.GetNumberOfBytesUsed(); + rakPeerMutexes[ offlinePingResponse_Mutex ].Unlock(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Return the unique SystemAddress that represents you on the the network +// Note that unlike in previous versions, this is a struct and is not sequential +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +SystemAddress RakPeer::GetInternalID( const SystemAddress systemAddress, const int index ) const +{ + if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) + { + return ipList[index]; + } + else + { + +// SystemAddress returnValue; + RemoteSystemStruct * remoteSystem = GetRemoteSystemFromSystemAddress( systemAddress, false, true ); + if (remoteSystem==0) + return UNASSIGNED_SYSTEM_ADDRESS; + + return remoteSystem->theirInternalSystemAddress[index]; + /* + sockaddr_in sa; + socklen_t len = sizeof(sa); + if (getsockname__(connectionSockets[remoteSystem->connectionSocketIndex], (sockaddr*)&sa, &len)!=0) + return UNASSIGNED_SYSTEM_ADDRESS; + returnValue.port=ntohs(sa.sin_port); + returnValue.binaryAddress=sa.sin_addr.s_addr; + return returnValue; +*/ + + + + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +/// \brief Sets your internal IP address, for platforms that do not support reading it, or to override a value +/// \param[in] systemAddress. The address to set. Use SystemAddress::FromString() if you want to use a dotted string +/// \param[in] index When you have multiple internal IDs, which index to set? +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetInternalID(SystemAddress systemAddress, int index) +{ + RakAssert(index >=0 && index < MAXIMUM_NUMBER_OF_INTERNAL_IDS); + ipList[index]=systemAddress; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Return the unique address identifier that represents you on the the network and is based on your external +// IP / port (the IP / port the specified player uses to communicate with you) +// Note that unlike in previous versions, this is a struct and is not sequential +// +// Parameters: +// target: Which remote system you are referring to for your external ID +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +SystemAddress RakPeer::GetExternalID( const SystemAddress target ) const +{ + unsigned i; + SystemAddress inactiveExternalId; + + inactiveExternalId=UNASSIGNED_SYSTEM_ADDRESS; + + if (target==UNASSIGNED_SYSTEM_ADDRESS) + return firstExternalID; + + // First check for active connection with this systemAddress + for ( i = 0; i < maximumNumberOfPeers; i++ ) + { + if (remoteSystemList[ i ].systemAddress == target ) + { + if ( remoteSystemList[ i ].isActive ) + return remoteSystemList[ i ].myExternalSystemAddress; + else if (remoteSystemList[ i ].myExternalSystemAddress!=UNASSIGNED_SYSTEM_ADDRESS) + inactiveExternalId=remoteSystemList[ i ].myExternalSystemAddress; + } + } + + return inactiveExternalId; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +const RakNetGUID RakPeer::GetMyGUID(void) const +{ + return myGuid; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +SystemAddress RakPeer::GetMyBoundAddress(const int socketIndex) +{ + DataStructures::List sockets; + GetSockets( sockets ); + if (sockets.Size()>0) + return sockets[socketIndex]->GetBoundAddress(); + else + return UNASSIGNED_SYSTEM_ADDRESS; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +const RakNetGUID& RakPeer::GetGuidFromSystemAddress( const SystemAddress input ) const +{ + if (input==UNASSIGNED_SYSTEM_ADDRESS) + return myGuid; + + if (input.systemIndex!=(SystemIndex)-1 && input.systemIndexreliabilityLayer.SetTimeoutTime(timeMS); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RakNet::TimeMS RakPeer::GetTimeoutTime( const SystemAddress target ) +{ + if (target==UNASSIGNED_SYSTEM_ADDRESS) + { + return defaultTimeoutTime; + } + else + { + RemoteSystemStruct * remoteSystem = GetRemoteSystemFromSystemAddress( target, false, true ); + + if ( remoteSystem != 0 ) + remoteSystem->reliabilityLayer.GetTimeoutTime(); + } + return defaultTimeoutTime; +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Returns the current MTU size +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetMTUSize( const SystemAddress target ) const +{ + if (target!=UNASSIGNED_SYSTEM_ADDRESS) + { + RemoteSystemStruct *rss=GetRemoteSystemFromSystemAddress(target, false, true); + if (rss) + return rss->MTUSize; + } + return defaultMTUSize; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Returns the number of IP addresses we have +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GetNumberOfAddresses( void ) +{ + + if (IsActive()==false) + { + FillIPList(); + } + + int i = 0; + + while ( ipList[ i ]!=UNASSIGNED_SYSTEM_ADDRESS ) + i++; + + return i; + + + + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Returns an IP address at index 0 to GetNumberOfAddresses-1 +// \param[in] index index into the list of IP addresses +// \return The local IP address at this index +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +const char* RakPeer::GetLocalIP( unsigned int index ) +{ + if (IsActive()==false) + { + // Fill out ipList structure + + FillIPList(); + + } + + + static char str[128]; + ipList[index].ToString(false,str); + return str; + + + + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Is this a local IP? +// \param[in] An IP address to check +// \return True if this is one of the IP addresses returned by GetLocalIP +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::IsLocalIP( const char *ip ) +{ + if (ip==0 || ip[0]==0) + return false; + + + if (strcmp(ip, "127.0.0.1")==0 || strcmp(ip, "localhost")==0) + return true; + + int num = GetNumberOfAddresses(); + int i; + for (i=0; i < num; i++) + { + if (strcmp(ip, GetLocalIP(i))==0) + return true; + } + + + + + return false; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary +// when connection to servers with multiple IP addresses +// +// Parameters: +// allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::AllowConnectionResponseIPMigration( bool allow ) +{ + allowConnectionResponseIPMigration = allow; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Description: +// Sends a message ID_ADVERTISE_SYSTEM to the remote unconnected system. +// This will tell the remote system our external IP outside the LAN, and can be used for NAT punch through +// +// Requires: +// The sender and recipient must already be started via a successful call to Initialize +// +// host: Either a dotted IP address or a domain name +// remotePort: Which port to connect to on the remote machine. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex ) +{ + RakNet::BitStream bs; + bs.Write((MessageID)ID_ADVERTISE_SYSTEM); + bs.WriteAlignedBytes((const unsigned char*) data,dataLength); + return SendOutOfBand(host, remotePort, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), connectionSocketIndex ); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads. +// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived +// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned. +// Defaults to 0 (never return this notification) +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetSplitMessageProgressInterval(int interval) +{ + RakAssert(interval>=0); + splitMessageProgressInterval=interval; + for ( unsigned short i = 0; i < maximumNumberOfPeers; i++ ) + remoteSystemList[ i ].reliabilityLayer.SetSplitMessageProgressInterval(splitMessageProgressInterval); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Returns what was passed to SetSplitMessageProgressInterval() +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetSplitMessageProgressInterval(void) const +{ + return splitMessageProgressInterval; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Set how long to wait before giving up on sending an unreliable message +// Useful if the network is clogged up. +// Set to 0 or less to never timeout. Defaults to 0. +// timeoutMS How many ms to wait before simply not sending an unreliable message. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetUnreliableTimeout(RakNet::TimeMS timeoutMS) +{ + unreliableTimeout=timeoutMS; + for ( unsigned short i = 0; i < maximumNumberOfPeers; i++ ) + remoteSystemList[ i ].reliabilityLayer.SetUnreliableTimeout(unreliableTimeout); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Send a message to host, with the IP socket option TTL set to 3 +// This message will not reach the host, but will open the router. +// Used for NAT-Punchthrough +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SendTTL( const char* host, unsigned short remotePort, int ttl, unsigned connectionSocketIndex ) +{ +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + char fakeData[2]; + fakeData[0]=0; + fakeData[1]=1; + unsigned int realIndex = GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); + if (socketList[realIndex]->IsBerkleySocket()) + { + RNS2_SendParameters bsp; + bsp.data = (char*) fakeData; + bsp.length = 2; + bsp.systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); + bsp.systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); + bsp.ttl=ttl; + unsigned i; + for (i=0; i < pluginListNTS.Size(); i++) + pluginListNTS[i]->OnDirectSocketSend((const char*)bsp.data, BYTES_TO_BITS(bsp.length), bsp.systemAddress); + socketList[realIndex]->Send(&bsp, _FILE_AND_LINE_); + } +#endif +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Attatches a Plugin interface to run code automatically on message receipt in the Receive call +// +// \param messageHandler Pointer to a plugin to attach +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::AttachPlugin( PluginInterface2 *plugin ) +{ + bool isNotThreadsafe = plugin->UsesReliabilityLayer(); + if (isNotThreadsafe) + { + if (pluginListNTS.GetIndexOf(plugin)==MAX_UNSIGNED_LONG) + { + plugin->SetRakPeerInterface(this); + plugin->OnAttach(); + pluginListNTS.Insert(plugin, _FILE_AND_LINE_); + } + } + else + { + if (pluginListTS.GetIndexOf(plugin)==MAX_UNSIGNED_LONG) + { + plugin->SetRakPeerInterface(this); + plugin->OnAttach(); + pluginListTS.Insert(plugin, _FILE_AND_LINE_); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Detaches a Plugin interface to run code automatically on message receipt +// +// \param messageHandler Pointer to a plugin to detach +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::DetachPlugin( PluginInterface2 *plugin ) +{ + if (plugin==0) + return; + + unsigned int index; + + bool isNotThreadsafe = plugin->UsesReliabilityLayer(); + if (isNotThreadsafe) + { + index = pluginListNTS.GetIndexOf(plugin); + if (index!=MAX_UNSIGNED_LONG) + { + // Unordered list so delete from end for speed + pluginListNTS[index]=pluginListNTS[pluginListNTS.Size()-1]; + pluginListNTS.RemoveFromEnd(); + } + } + else + { + index = pluginListTS.GetIndexOf(plugin); + if (index!=MAX_UNSIGNED_LONG) + { + // Unordered list so delete from end for speed + pluginListTS[index]=pluginListTS[pluginListTS.Size()-1]; + pluginListTS.RemoveFromEnd(); + } + } + plugin->OnDetach(); + plugin->SetRakPeerInterface(0); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Put a packet back at the end of the receive queue in case you don't want to deal with it immediately +// +// packet The packet you want to push back. +// pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order) +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::PushBackPacket( Packet *packet, bool pushAtHead) +{ + if (packet==0) + return; + + unsigned i; + for (i=0; i < pluginListTS.Size(); i++) + pluginListTS[i]->OnPushBackPacket((const char*) packet->data, packet->bitSize, packet->systemAddress); + for (i=0; i < pluginListNTS.Size(); i++) + pluginListNTS[i]->OnPushBackPacket((const char*) packet->data, packet->bitSize, packet->systemAddress); + + packetReturnMutex.Lock(); + if (pushAtHead) + packetReturnQueue.PushAtHead(packet,0,_FILE_AND_LINE_); + else + packetReturnQueue.Push(packet,_FILE_AND_LINE_); + packetReturnMutex.Unlock(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ChangeSystemAddress(RakNetGUID guid, const SystemAddress &systemAddress) +{ + BufferedCommandStruct *bcs; + + bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); + bcs->data = 0; + bcs->systemIdentifier.systemAddress=systemAddress; + bcs->systemIdentifier.rakNetGuid=guid; + bcs->command=BufferedCommandStruct::BCS_CHANGE_SYSTEM_ADDRESS; + bufferedCommands.Push(bcs); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +Packet* RakPeer::AllocatePacket(unsigned dataSize) +{ + return AllocPacket(dataSize, _FILE_AND_LINE_); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakNetSocket2* RakPeer::GetSocket( const SystemAddress target ) +{ + // Send a query to the thread to get the socket, and return when we got it + BufferedCommandStruct *bcs; + bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); + bcs->command=BufferedCommandStruct::BCS_GET_SOCKET; + bcs->systemIdentifier=target; + bcs->data=0; + bufferedCommands.Push(bcs); + + // Block up to one second to get the socket, although it should actually take virtually no time + SocketQueryOutput *sqo; + RakNet::TimeMS stopWaiting = RakNet::GetTimeMS()+1000; + DataStructures::List output; + while (RakNet::GetTimeMS() < stopWaiting) + { + if (isMainLoopThreadActive==false) + return 0; + + RakSleep(0); + + sqo = socketQueryOutput.Pop(); + if (sqo) + { + output=sqo->sockets; + sqo->sockets.Clear(false, _FILE_AND_LINE_); + socketQueryOutput.Deallocate(sqo, _FILE_AND_LINE_); + if (output.Size()) + return output[0]; + break; + } + } + return 0; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::GetSockets( DataStructures::List &sockets ) +{ + sockets.Clear(false, _FILE_AND_LINE_); + + // Send a query to the thread to get the socket, and return when we got it + BufferedCommandStruct *bcs; + + bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); + bcs->command=BufferedCommandStruct::BCS_GET_SOCKET; + bcs->systemIdentifier=UNASSIGNED_SYSTEM_ADDRESS; + bcs->data=0; + bufferedCommands.Push(bcs); + + // Block up to one second to get the socket, although it should actually take virtually no time + SocketQueryOutput *sqo; +// RakNetSocket2* output; + while (1) + { + if (isMainLoopThreadActive==false) + return; + + RakSleep(0); + + sqo = socketQueryOutput.Pop(); + if (sqo) + { + sockets=sqo->sockets; + sqo->sockets.Clear(false, _FILE_AND_LINE_); + socketQueryOutput.Deallocate(sqo, _FILE_AND_LINE_); + return; + } + } + return; +} +void RakPeer::ReleaseSockets( DataStructures::List &sockets ) +{ + sockets.Clear(false,_FILE_AND_LINE_); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Adds simulated ping and packet loss to the outgoing data flow. +// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and maxSendBPS value on each. +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ApplyNetworkSimulator( float packetloss, unsigned short minExtraPing, unsigned short extraPingVariance) +{ +#ifdef _DEBUG + if (remoteSystemList) + { + unsigned short i; + for (i=0; i < maximumNumberOfPeers; i++) + //for (i=0; i < remoteSystemListSize; i++) + remoteSystemList[i].reliabilityLayer.ApplyNetworkSimulator(packetloss, minExtraPing, extraPingVariance); + } + + _packetloss=packetloss; + _minExtraPing=minExtraPing; + _extraPingVariance=extraPingVariance; +#endif +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void RakPeer::SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond ) +{ + maxOutgoingBPS=maxBitsPerSecond; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Returns if you previously called ApplyNetworkSimulator +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::IsNetworkSimulatorActive( void ) +{ +#ifdef _DEBUG + return _packetloss>0 || _minExtraPing>0 || _extraPingVariance>0; +#else + return false; +#endif +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::WriteOutOfBandHeader(RakNet::BitStream *bitStream) +{ + bitStream->Write((MessageID)ID_OUT_OF_BAND_INTERNAL); + bitStream->Write(myGuid); + bitStream->WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetUserUpdateThread(void (*_userUpdateThreadPtr)(RakPeerInterface *, void *), void *_userUpdateThreadData) +{ + userUpdateThreadPtr=_userUpdateThreadPtr; + userUpdateThreadData=_userUpdateThreadData; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetIncomingDatagramEventHandler( bool (*_incomingDatagramEventHandler)(RNS2RecvStruct *) ) +{ + incomingDatagramEventHandler=_incomingDatagramEventHandler; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::SendOutOfBand(const char *host, unsigned short remotePort, const char *data, BitSize_t dataLength, unsigned connectionSocketIndex ) +{ + if ( IsActive() == false ) + return false; + + if (host==0 || host[0]==0) + return false; + + // If this assert hits then Startup wasn't called or the call failed. + RakAssert(connectionSocketIndex < socketList.Size()); + + // This is a security measure. Don't send data longer than this value + RakAssert(dataLength <= (MAX_OFFLINE_DATA_LENGTH + sizeof(unsigned char)+sizeof(RakNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID))); + + if (host==0) + return false; + + // 34 bytes + RakNet::BitStream bitStream; + WriteOutOfBandHeader(&bitStream); + + if (dataLength>0) + { + bitStream.Write(data, dataLength); + } + + unsigned int realIndex = GetRakNetSocketFromUserConnectionSocketIndex(connectionSocketIndex); + + /* + SystemAddress systemAddress; + systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); + systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); + + unsigned i; + for (i=0; i < pluginListNTS.Size(); i++) + pluginListNTS[i]->OnDirectSocketSend((const char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), systemAddress); + + SocketLayer::SendTo( socketList[realIndex], (const char*)bitStream.GetData(), (int) bitStream.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + */ + + RNS2_SendParameters bsp; + bsp.data = (char*) bitStream.GetData(); + bsp.length = bitStream.GetNumberOfBytesUsed(); + bsp.systemAddress.FromStringExplicitPort(host,remotePort, socketList[realIndex]->GetBoundAddress().GetIPVersion()); + bsp.systemAddress.FixForIPVersion(socketList[realIndex]->GetBoundAddress()); + unsigned i; + for (i=0; i < pluginListNTS.Size(); i++) + pluginListNTS[i]->OnDirectSocketSend((const char*)bsp.data, BYTES_TO_BITS(bsp.length), bsp.systemAddress); + socketList[realIndex]->Send(&bsp, _FILE_AND_LINE_); + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakNetStatistics * RakPeer::GetStatistics( const SystemAddress systemAddress, RakNetStatistics *rns ) +{ + static RakNetStatistics staticStatistics; + RakNetStatistics *systemStats; + if (rns==0) + systemStats=&staticStatistics; + else + systemStats=rns; + + if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) + { + bool firstWrite=false; + // Return a crude sum + for ( unsigned short i = 0; i < maximumNumberOfPeers; i++ ) + { + if (remoteSystemList[ i ].isActive) + { + RakNetStatistics rnsTemp; + remoteSystemList[ i ].reliabilityLayer.GetStatistics(&rnsTemp); + + if (firstWrite==false) + { + memcpy(systemStats, &rnsTemp, sizeof(RakNetStatistics)); + firstWrite=true; + } + else + (*systemStats)+=rnsTemp; + } + } + return systemStats; + } + else + { + RemoteSystemStruct * rss; + rss = GetRemoteSystemFromSystemAddress( systemAddress, false, false ); + if ( rss && endThreads==false ) + { + rss->reliabilityLayer.GetStatistics(systemStats); + return systemStats; + } + } + + return 0; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::GetStatisticsList(DataStructures::List &addresses, DataStructures::List &guids, DataStructures::List &statistics) +{ + addresses.Clear(false, _FILE_AND_LINE_); + guids.Clear(false, _FILE_AND_LINE_); + statistics.Clear(false, _FILE_AND_LINE_); + + if ( remoteSystemList == 0 || endThreads == true ) + return; + + unsigned int i; + for (i=0; i < activeSystemListSize; i++) + { + if ((activeSystemList[i])->isActive && + (activeSystemList[i])->connectMode==RakPeer::RemoteSystemStruct::CONNECTED) + { + addresses.Push((activeSystemList[i])->systemAddress, _FILE_AND_LINE_ ); + guids.Push((activeSystemList[i])->guid, _FILE_AND_LINE_ ); + RakNetStatistics rns; + (activeSystemList[i])->reliabilityLayer.GetStatistics(&rns); + statistics.Push(rns, _FILE_AND_LINE_); + } + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::GetStatistics( const unsigned int index, RakNetStatistics *rns ) +{ + if (index < maximumNumberOfPeers && remoteSystemList[ index ].isActive) + { + remoteSystemList[ index ].reliabilityLayer.GetStatistics(rns); + return true; + } + return false; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GetReceiveBufferSize(void) +{ + unsigned int size; + packetReturnMutex.Lock(); + size=packetReturnQueue.Size(); + packetReturnMutex.Unlock(); + return size; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetIndexFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread ) const +{ + unsigned i; + + if ( systemAddress == UNASSIGNED_SYSTEM_ADDRESS ) + return -1; + + if (systemAddress.systemIndex!=(SystemIndex)-1 && systemAddress.systemIndex < maximumNumberOfPeers && remoteSystemList[systemAddress.systemIndex].systemAddress==systemAddress && remoteSystemList[ systemAddress.systemIndex ].isActive) + return systemAddress.systemIndex; + + if (calledFromNetworkThread) + { + return GetRemoteSystemIndex(systemAddress); + } + else + { + // remoteSystemList in user and network thread + for ( i = 0; i < maximumNumberOfPeers; i++ ) + if ( remoteSystemList[ i ].isActive && remoteSystemList[ i ].systemAddress == systemAddress ) + return i; + + // If no active results found, try previously active results. + for ( i = 0; i < maximumNumberOfPeers; i++ ) + if ( remoteSystemList[ i ].systemAddress == systemAddress ) + return i; + } + + return -1; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +int RakPeer::GetIndexFromGuid( const RakNetGUID guid ) +{ + unsigned i; + + if ( guid == UNASSIGNED_RAKNET_GUID ) + return -1; + + if (guid.systemIndex!=(SystemIndex)-1 && guid.systemIndex < maximumNumberOfPeers && remoteSystemList[guid.systemIndex].guid==guid && remoteSystemList[ guid.systemIndex ].isActive) + return guid.systemIndex; + + // remoteSystemList in user and network thread + for ( i = 0; i < maximumNumberOfPeers; i++ ) + if ( remoteSystemList[ i ].isActive && remoteSystemList[ i ].guid == guid ) + return i; + + // If no active results found, try previously active results. + for ( i = 0; i < maximumNumberOfPeers; i++ ) + if ( remoteSystemList[ i ].guid == guid ) + return i; + + return -1; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +#if LIBCAT_SECURITY==1 +bool RakPeer::GenerateConnectionRequestChallenge(RequestedConnectionStruct *rcs,PublicKey *publicKey) +{ + CAT_AUDIT_PRINTF("AUDIT: In GenerateConnectionRequestChallenge()\n"); + + rcs->client_handshake = 0; + rcs->publicKeyMode = PKM_INSECURE_CONNECTION; + + if (!publicKey) return true; + + switch (publicKey->publicKeyMode) + { + default: + case PKM_INSECURE_CONNECTION: + break; + + case PKM_ACCEPT_ANY_PUBLIC_KEY: + CAT_OBJCLR(rcs->remote_public_key); + rcs->client_handshake = RakNet::OP_NEW(_FILE_AND_LINE_); + + rcs->publicKeyMode = PKM_ACCEPT_ANY_PUBLIC_KEY; + break; + + case PKM_USE_TWO_WAY_AUTHENTICATION: + if (publicKey->myPublicKey == 0 || publicKey->myPrivateKey == 0 || + publicKey->remoteServerPublicKey == 0) + { + return false; + } + + rcs->client_handshake = RakNet::OP_NEW(_FILE_AND_LINE_); + memcpy(rcs->remote_public_key, publicKey->remoteServerPublicKey, cat::EasyHandshake::PUBLIC_KEY_BYTES); + + if (!rcs->client_handshake->Initialize(publicKey->remoteServerPublicKey) || + !rcs->client_handshake->SetIdentity(publicKey->myPublicKey, publicKey->myPrivateKey) || + !rcs->client_handshake->GenerateChallenge(rcs->handshakeChallenge)) + { + CAT_AUDIT_PRINTF("AUDIT: Failure initializing new client_handshake object with identity for this RequestedConnectionStruct\n"); + RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); + rcs->client_handshake=0; + return false; + } + + CAT_AUDIT_PRINTF("AUDIT: Success initializing new client handshake object with identity for this RequestedConnectionStruct -- pre-generated challenge\n"); + + rcs->publicKeyMode = PKM_USE_TWO_WAY_AUTHENTICATION; + break; + + case PKM_USE_KNOWN_PUBLIC_KEY: + if (publicKey->remoteServerPublicKey == 0) + return false; + + rcs->client_handshake = RakNet::OP_NEW(_FILE_AND_LINE_); + memcpy(rcs->remote_public_key, publicKey->remoteServerPublicKey, cat::EasyHandshake::PUBLIC_KEY_BYTES); + + if (!rcs->client_handshake->Initialize(publicKey->remoteServerPublicKey) || + !rcs->client_handshake->GenerateChallenge(rcs->handshakeChallenge)) + { + CAT_AUDIT_PRINTF("AUDIT: Failure initializing new client_handshake object for this RequestedConnectionStruct\n"); + RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); + rcs->client_handshake=0; + return false; + } + + CAT_AUDIT_PRINTF("AUDIT: Success initializing new client handshake object for this RequestedConnectionStruct -- pre-generated challenge\n"); + + rcs->publicKeyMode = PKM_USE_KNOWN_PUBLIC_KEY; + break; + } + + return true; +} +#endif +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +ConnectionAttemptResult RakPeer::SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNet::TimeMS timeoutTime ) +{ + RakAssert(passwordDataLength <= 256); + RakAssert(remotePort!=0); + SystemAddress systemAddress; + if (!systemAddress.FromStringExplicitPort(host,remotePort,socketList[connectionSocketIndex]->GetBoundAddress().GetIPVersion())) + return CANNOT_RESOLVE_DOMAIN_NAME; + + // Already connected? + if (GetRemoteSystemFromSystemAddress(systemAddress, false, true)) + return ALREADY_CONNECTED_TO_ENDPOINT; + + //RequestedConnectionStruct *rcs = (RequestedConnectionStruct *) rakMalloc_Ex(sizeof(RequestedConnectionStruct), _FILE_AND_LINE_); + RequestedConnectionStruct *rcs = RakNet::OP_NEW(_FILE_AND_LINE_); + + rcs->systemAddress=systemAddress; + rcs->nextRequestTime=RakNet::GetTimeMS(); + rcs->requestsMade=0; + rcs->data=0; + rcs->socket=0; + rcs->extraData=extraData; + rcs->socketIndex=connectionSocketIndex; + rcs->actionToTake=RequestedConnectionStruct::CONNECT; + rcs->sendConnectionAttemptCount=sendConnectionAttemptCount; + rcs->timeBetweenSendConnectionAttemptsMS=timeBetweenSendConnectionAttemptsMS; + memcpy(rcs->outgoingPassword, passwordData, passwordDataLength); + rcs->outgoingPasswordLength=(unsigned char) passwordDataLength; + rcs->timeoutTime=timeoutTime; + +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: In SendConnectionRequest()\n"); + if (!GenerateConnectionRequestChallenge(rcs,publicKey)) + return SECURITY_INITIALIZATION_FAILED; +#else + (void) publicKey; +#endif + + // Return false if already pending, else push on queue + unsigned int i=0; + requestedConnectionQueueMutex.Lock(); + for (; i < requestedConnectionQueue.Size(); i++) + { + if (requestedConnectionQueue[i]->systemAddress==systemAddress) + { + requestedConnectionQueueMutex.Unlock(); + // Not necessary + //RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); + RakNet::OP_DELETE(rcs,_FILE_AND_LINE_); + return CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS; + } + } + requestedConnectionQueue.Push(rcs, _FILE_AND_LINE_ ); + requestedConnectionQueueMutex.Unlock(); + + return CONNECTION_ATTEMPT_STARTED; +} +ConnectionAttemptResult RakPeer::SendConnectionRequest( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, PublicKey *publicKey, unsigned connectionSocketIndex, unsigned int extraData, unsigned sendConnectionAttemptCount, unsigned timeBetweenSendConnectionAttemptsMS, RakNet::TimeMS timeoutTime, RakNetSocket2* socket ) +{ + RakAssert(passwordDataLength <= 256); + SystemAddress systemAddress; + systemAddress.FromStringExplicitPort(host,remotePort); + + // Already connected? + if (GetRemoteSystemFromSystemAddress(systemAddress, false, true)) + return ALREADY_CONNECTED_TO_ENDPOINT; + + //RequestedConnectionStruct *rcs = (RequestedConnectionStruct *) rakMalloc_Ex(sizeof(RequestedConnectionStruct), _FILE_AND_LINE_); + RequestedConnectionStruct *rcs = RakNet::OP_NEW(_FILE_AND_LINE_); + + rcs->systemAddress=systemAddress; + rcs->nextRequestTime=RakNet::GetTimeMS(); + rcs->requestsMade=0; + rcs->data=0; + rcs->socket=0; + rcs->extraData=extraData; + rcs->socketIndex=connectionSocketIndex; + rcs->actionToTake=RequestedConnectionStruct::CONNECT; + rcs->sendConnectionAttemptCount=sendConnectionAttemptCount; + rcs->timeBetweenSendConnectionAttemptsMS=timeBetweenSendConnectionAttemptsMS; + memcpy(rcs->outgoingPassword, passwordData, passwordDataLength); + rcs->outgoingPasswordLength=(unsigned char) passwordDataLength; + rcs->timeoutTime=timeoutTime; + rcs->socket=socket; + +#if LIBCAT_SECURITY==1 + if (!GenerateConnectionRequestChallenge(rcs,publicKey)) + return SECURITY_INITIALIZATION_FAILED; +#else + (void) publicKey; +#endif + + // Return false if already pending, else push on queue + unsigned int i=0; + requestedConnectionQueueMutex.Lock(); + for (; i < requestedConnectionQueue.Size(); i++) + { + if (requestedConnectionQueue[i]->systemAddress==systemAddress) + { + requestedConnectionQueueMutex.Unlock(); + // Not necessary + //RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); + RakNet::OP_DELETE(rcs,_FILE_AND_LINE_); + return CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS; + } + } + requestedConnectionQueue.Push(rcs, _FILE_AND_LINE_ ); + requestedConnectionQueueMutex.Unlock(); + + return CONNECTION_ATTEMPT_STARTED; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ValidateRemoteSystemLookup(void) const +{ +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakPeer::RemoteSystemStruct *RakPeer::GetRemoteSystem( const AddressOrGUID systemIdentifier, bool calledFromNetworkThread, bool onlyActive ) const +{ + if (systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID) + return GetRemoteSystemFromGUID(systemIdentifier.rakNetGuid, onlyActive); + else + return GetRemoteSystemFromSystemAddress(systemIdentifier.systemAddress, calledFromNetworkThread, onlyActive); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakPeer::RemoteSystemStruct *RakPeer::GetRemoteSystemFromSystemAddress( const SystemAddress systemAddress, bool calledFromNetworkThread, bool onlyActive ) const +{ + unsigned i; + + if ( systemAddress == UNASSIGNED_SYSTEM_ADDRESS ) + return 0; + + if (calledFromNetworkThread) + { + unsigned int index = GetRemoteSystemIndex(systemAddress); + if (index!=(unsigned int) -1) + { + if (onlyActive==false || remoteSystemList[ index ].isActive==true ) + { + RakAssert(remoteSystemList[index].systemAddress==systemAddress); + return remoteSystemList + index; + } + } + } + else + { + int deadConnectionIndex=-1; + + // Active connections take priority. But if there are no active connections, return the first systemAddress match found + for ( i = 0; i < maximumNumberOfPeers; i++ ) + { + if (remoteSystemList[ i ].systemAddress == systemAddress) + { + if ( remoteSystemList[ i ].isActive ) + return remoteSystemList + i; + else if (deadConnectionIndex==-1) + deadConnectionIndex=i; + } + } + + if (deadConnectionIndex!=-1 && onlyActive==false) + return remoteSystemList + deadConnectionIndex; + } + + return 0; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakPeer::RemoteSystemStruct *RakPeer::GetRemoteSystemFromGUID( const RakNetGUID guid, bool onlyActive ) const +{ + if (guid==UNASSIGNED_RAKNET_GUID) + return 0; + + unsigned i; + for ( i = 0; i < maximumNumberOfPeers; i++ ) + { + if (remoteSystemList[ i ].guid == guid && (onlyActive==false || remoteSystemList[ i ].isActive)) + { + return remoteSystemList + i; + } + } + return 0; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ParseConnectionRequestPacket( RakPeer::RemoteSystemStruct *remoteSystem, const SystemAddress &systemAddress, const char *data, int byteSize ) +{ + RakNet::BitStream bs((unsigned char*) data,byteSize,false); + bs.IgnoreBytes(sizeof(MessageID)); + RakNetGUID guid; + bs.Read(guid); + RakNet::Time incomingTimestamp; + bs.Read(incomingTimestamp); + unsigned char doSecurity; + bs.Read(doSecurity); + +#if LIBCAT_SECURITY==1 + unsigned char doClientKey; + if (_using_security) + { + // Ignore message on bad state + if (doSecurity != 1 || !remoteSystem->reliabilityLayer.GetAuthenticatedEncryption()) + return; + + // Validate client proof of key + unsigned char proof[cat::EasyHandshake::PROOF_BYTES]; + bs.ReadAlignedBytes(proof, sizeof(proof)); + if (!remoteSystem->reliabilityLayer.GetAuthenticatedEncryption()->ValidateProof(proof, sizeof(proof))) + { + remoteSystem->connectMode = RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; + return; + } + + CAT_OBJCLR(remoteSystem->client_public_key); + + bs.Read(doClientKey); + + // Check if client wants to prove identity + if (doClientKey == 1) + { + // Read identity proof + unsigned char ident[cat::EasyHandshake::IDENTITY_BYTES]; + bs.ReadAlignedBytes(ident, sizeof(ident)); + + // If we are listening to these proofs, + if (_require_client_public_key) + { + // Validate client identity + if (!_server_handshake->VerifyInitiatorIdentity(remoteSystem->answer, ident, remoteSystem->client_public_key)) + { + RakNet::BitStream bitStream; + bitStream.Write((MessageID)ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY); // Report an error since the client is not providing an identity when it is necessary to connect + bitStream.Write((unsigned char)2); // Indicate client identity is invalid + SendImmediate((char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), IMMEDIATE_PRIORITY, RELIABLE, 0, systemAddress, false, false, RakNet::GetTimeUS(), 0); + remoteSystem->connectMode = RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; + return; + } + } + + // Otherwise ignore the client public key + } + else + { + // If no client key was provided but it is required, + if (_require_client_public_key) + { + RakNet::BitStream bitStream; + bitStream.Write((MessageID)ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY); // Report an error since the client is not providing an identity when it is necessary to connect + bitStream.Write((unsigned char)1); // Indicate client identity is missing + SendImmediate((char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), IMMEDIATE_PRIORITY, RELIABLE, 0, systemAddress, false, false, RakNet::GetTimeUS(), 0); + remoteSystem->connectMode = RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; + return; + } + } + } +#endif // LIBCAT_SECURITY + + unsigned char *password = bs.GetData()+BITS_TO_BYTES(bs.GetReadOffset()); + int passwordLength = byteSize - BITS_TO_BYTES(bs.GetReadOffset()); + if ( incomingPasswordLength != passwordLength || + memcmp( password, incomingPassword, incomingPasswordLength ) != 0 ) + { + CAT_AUDIT_PRINTF("AUDIT: Invalid password\n"); + // This one we only send once since we don't care if it arrives. + RakNet::BitStream bitStream; + bitStream.Write((MessageID)ID_INVALID_PASSWORD); + bitStream.Write(GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); + SendImmediate((char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), IMMEDIATE_PRIORITY, RELIABLE, 0, systemAddress, false, false, RakNet::GetTimeUS(), 0); + remoteSystem->connectMode=RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; + return; + } + + // OK + remoteSystem->connectMode=RemoteSystemStruct::HANDLING_CONNECTION_REQUEST; + + OnConnectionRequest( remoteSystem, incomingTimestamp ); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::OnConnectionRequest( RakPeer::RemoteSystemStruct *remoteSystem, RakNet::Time incomingTimestamp ) +{ + RakNet::BitStream bitStream; + bitStream.Write((MessageID)ID_CONNECTION_REQUEST_ACCEPTED); + bitStream.Write(remoteSystem->systemAddress); + SystemIndex systemIndex = (SystemIndex) GetIndexFromSystemAddress( remoteSystem->systemAddress, true ); + RakAssert(systemIndex!=65535); + bitStream.Write(systemIndex); + for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + bitStream.Write(ipList[i]); + bitStream.Write(incomingTimestamp); + bitStream.Write(RakNet::GetTime()); + + SendImmediate((char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), IMMEDIATE_PRIORITY, RELIABLE_ORDERED, 0, remoteSystem->systemAddress, false, false, RakNet::GetTimeUS(), 0); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::NotifyAndFlagForShutdown( const SystemAddress systemAddress, bool performImmediate, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority ) +{ + RakNet::BitStream temp( sizeof(unsigned char) ); + temp.Write( (MessageID)ID_DISCONNECTION_NOTIFICATION ); + if (performImmediate) + { + SendImmediate((char*)temp.GetData(), temp.GetNumberOfBitsUsed(), disconnectionNotificationPriority, RELIABLE_ORDERED, orderingChannel, systemAddress, false, false, RakNet::GetTimeUS(), 0); + RemoteSystemStruct *rss=GetRemoteSystemFromSystemAddress(systemAddress, true, true); + rss->connectMode=RemoteSystemStruct::DISCONNECT_ASAP; + } + else + { + SendBuffered((const char*)temp.GetData(), temp.GetNumberOfBitsUsed(), disconnectionNotificationPriority, RELIABLE_ORDERED, orderingChannel, systemAddress, false, RemoteSystemStruct::DISCONNECT_ASAP, 0); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GetNumberOfRemoteInitiatedConnections( void ) const +{ + if ( remoteSystemList == 0 || endThreads == true ) + return 0; + + unsigned int numberOfIncomingConnections; + numberOfIncomingConnections = 0; + unsigned int i; + for (i=0; i < activeSystemListSize; i++) + { + if ((activeSystemList[i])->isActive && + (activeSystemList[i])->connectMode==RakPeer::RemoteSystemStruct::CONNECTED && + (activeSystemList[i])->weInitiatedTheConnection==false + ) + { + numberOfIncomingConnections++; + } + } + return numberOfIncomingConnections; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakPeer::RemoteSystemStruct * RakPeer::AssignSystemAddressToRemoteSystemList( const SystemAddress systemAddress, RemoteSystemStruct::ConnectMode connectionMode, RakNetSocket2* incomingRakNetSocket, bool *thisIPConnectedRecently, SystemAddress bindingAddress, int incomingMTU, RakNetGUID guid, bool useSecurity ) +{ + RemoteSystemStruct * remoteSystem; + unsigned i,j,assignedIndex; + RakNet::TimeMS time = RakNet::GetTimeMS(); +#ifdef _DEBUG + RakAssert(systemAddress!=UNASSIGNED_SYSTEM_ADDRESS); +#endif + + if (limitConnectionFrequencyFromTheSameIP) + { + if (IsLoopbackAddress(systemAddress,false)==false) + { + for ( i = 0; i < maximumNumberOfPeers; i++ ) + { + if ( remoteSystemList[ i ].isActive==true && + remoteSystemList[ i ].systemAddress.EqualsExcludingPort(systemAddress) && + time >= remoteSystemList[ i ].connectionTime && + time - remoteSystemList[ i ].connectionTime < 100 + ) + { + // 4/13/09 Attackers can flood ID_OPEN_CONNECTION_REQUEST and use up all available connection slots + // Ignore connection attempts if this IP address connected within the last 100 milliseconds + *thisIPConnectedRecently=true; + ValidateRemoteSystemLookup(); + return 0; + } + } + } + } + + // Don't use a different port than what we received on + bindingAddress.CopyPort(incomingRakNetSocket->GetBoundAddress()); + + *thisIPConnectedRecently=false; + for ( assignedIndex = 0; assignedIndex < maximumNumberOfPeers; assignedIndex++ ) + { + if ( remoteSystemList[ assignedIndex ].isActive==false ) + { + // printf("--- Address %s has become active\n", systemAddress.ToString()); + + remoteSystem=remoteSystemList+assignedIndex; + ReferenceRemoteSystem(systemAddress, assignedIndex); + remoteSystem->MTUSize=defaultMTUSize; + remoteSystem->guid=guid; + remoteSystem->isActive = true; // This one line causes future incoming packets to go through the reliability layer + // Reserve this reliability layer for ourselves. + if (incomingMTU > remoteSystem->MTUSize) + remoteSystem->MTUSize=incomingMTU; + RakAssert(remoteSystem->MTUSize <= MAXIMUM_MTU_SIZE); + remoteSystem->reliabilityLayer.Reset(true, remoteSystem->MTUSize, useSecurity); + remoteSystem->reliabilityLayer.SetSplitMessageProgressInterval(splitMessageProgressInterval); + remoteSystem->reliabilityLayer.SetUnreliableTimeout(unreliableTimeout); + remoteSystem->reliabilityLayer.SetTimeoutTime(defaultTimeoutTime); + AddToActiveSystemList(assignedIndex); + if (incomingRakNetSocket->GetBoundAddress()==bindingAddress) + { + remoteSystem->rakNetSocket=incomingRakNetSocket; + } + else + { + char str[256]; + bindingAddress.ToString(true,str); + // See if this is an internal IP address. + // If so, force binding on it so we reply on the same IP address as they sent to. + unsigned int ipListIndex, foundIndex=(unsigned int)-1; + + for (ipListIndex=0; ipListIndex < MAXIMUM_NUMBER_OF_INTERNAL_IDS; ipListIndex++) + { + if (ipList[ipListIndex]==UNASSIGNED_SYSTEM_ADDRESS) + break; + + if (bindingAddress.EqualsExcludingPort(ipList[ipListIndex])) + { + foundIndex=ipListIndex; + break; + } + } + + // 06/26/09 Unconfirmed report that Vista firewall blocks the reply if we force a binding + // For now use the incoming socket only + // Originally this code was to force a machine with multiple IP addresses to reply back on the IP + // that the datagram came in on + if (1 || foundIndex==(unsigned int)-1) + { + // Must not be an internal LAN address. Just use whatever socket it came in on + remoteSystem->rakNetSocket=incomingRakNetSocket; + } + else + { + /* + // Force binding + unsigned int socketListIndex; + for (socketListIndex=0; socketListIndex < socketList.Size(); socketListIndex++) + { + if (socketList[socketListIndex]->GetBoundAddress()==bindingAddress) + { + // Force binding with existing socket + remoteSystem->rakNetSocket=socketList[socketListIndex]; + break; + } + } + + if (socketListIndex==socketList.Size()) + { + char ipListFoundIndexStr[128]; + ipList[foundIndex].ToString(false,str); + + // Force binding with new socket + RakNetSocket* rns(RakNet::OP_NEW(_FILE_AND_LINE_)); + if (incomingRakNetSocket->GetRemotePortRakNetWasStartedOn()==0) + rns = SocketLayer::CreateBoundSocket( this, bindingAddress.GetPort(), incomingRakNetSocket->GetBlockingSocket(), ipListFoundIndexStr, 0, incomingRakNetSocket->GetExtraSocketOptions(), incomingRakNetSocket->GetSocketFamily(), incomingRakNetSocket->GetChromeInstance() ); + else + rns = SocketLayer::CreateBoundSocket_PS3Lobby( bindingAddress.GetPort(), incomingRakNetSocket->GetBlockingSocket(), ipListFoundIndexStr, incomingRakNetSocket->GetSocketFamily() ); + + + if (rns==0) + { + // Can't bind. Just use whatever socket it came in on + remoteSystem->rakNetSocket=incomingRakNetSocket; + } + else + { + rns->GetBoundAddress()=bindingAddress; + rns->SetUserConnectionSocketIndex((unsigned int)-1); + socketList.Push(rns, _FILE_AND_LINE_ ); + remoteSystem->rakNetSocket=rns; + + +#ifdef _WIN32 + int highPriority=THREAD_PRIORITY_ABOVE_NORMAL; +#else + int highPriority=-10; +#endif + + highPriority=0; + + + } + } + + */ + } + } + + for ( j = 0; j < (unsigned) PING_TIMES_ARRAY_SIZE; j++ ) + { + remoteSystem->pingAndClockDifferential[ j ].pingTime = 65535; + remoteSystem->pingAndClockDifferential[ j ].clockDifferential = 0; + } + + remoteSystem->connectMode=connectionMode; + remoteSystem->pingAndClockDifferentialWriteIndex = 0; + remoteSystem->lowestPing = 65535; + remoteSystem->nextPingTime = 0; // Ping immediately + remoteSystem->weInitiatedTheConnection = false; + remoteSystem->connectionTime = time; + remoteSystem->myExternalSystemAddress = UNASSIGNED_SYSTEM_ADDRESS; + remoteSystem->lastReliableSend=time; + +#ifdef _DEBUG + int indexLoopupCheck=GetIndexFromSystemAddress( systemAddress, true ); + if ((int) indexLoopupCheck!=(int) assignedIndex) + { + RakAssert((int) indexLoopupCheck==(int) assignedIndex); + } +#endif + + return remoteSystem; + } + } + + return 0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Adjust the first four bytes (treated as unsigned int) of the pointer +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ShiftIncomingTimestamp( unsigned char *data, const SystemAddress &systemAddress ) const +{ +#ifdef _DEBUG + RakAssert( IsActive() ); + RakAssert( data ); +#endif + + RakNet::BitStream timeBS( data, sizeof(RakNet::Time), false); + RakNet::Time encodedTimestamp; + timeBS.Read(encodedTimestamp); + + encodedTimestamp = encodedTimestamp - GetBestClockDifferential( systemAddress ); + timeBS.SetWriteOffset(0); + timeBS.Write(encodedTimestamp); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// Thanks to Chris Taylor (cat02e@fsu.edu) for the improved timestamping algorithm +RakNet::Time RakPeer::GetBestClockDifferential( const SystemAddress systemAddress ) const +{ + RemoteSystemStruct *remoteSystem = GetRemoteSystemFromSystemAddress( systemAddress, true, true ); + + if ( remoteSystem == 0 ) + return 0; + + return GetClockDifferentialInt(remoteSystem); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::RemoteSystemLookupHashIndex(const SystemAddress &sa) const +{ + return SystemAddress::ToInteger(sa) % ((unsigned int) maximumNumberOfPeers * REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ReferenceRemoteSystem(const SystemAddress &sa, unsigned int remoteSystemListIndex) +{ +// #ifdef _DEBUG +// for ( int remoteSystemIndex = 0; remoteSystemIndex < maximumNumberOfPeers; ++remoteSystemIndex ) +// { +// if (remoteSystemList[remoteSystemIndex].isActive ) +// { +// unsigned int hashIndex = GetRemoteSystemIndex(remoteSystemList[remoteSystemIndex].systemAddress); +// RakAssert(hashIndex==remoteSystemIndex); +// } +// } +// #endif + + + SystemAddress oldAddress = remoteSystemList[remoteSystemListIndex].systemAddress; + if (oldAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + // The system might be active if rerouting +// RakAssert(remoteSystemList[remoteSystemListIndex].isActive==false); + + // Remove the reference if the reference is pointing to this inactive system + if (GetRemoteSystem(oldAddress)==&remoteSystemList[remoteSystemListIndex]) + DereferenceRemoteSystem(oldAddress); + } + DereferenceRemoteSystem(sa); + +// #ifdef _DEBUG +// for ( int remoteSystemIndex = 0; remoteSystemIndex < maximumNumberOfPeers; ++remoteSystemIndex ) +// { +// if (remoteSystemList[remoteSystemIndex].isActive ) +// { +// unsigned int hashIndex = GetRemoteSystemIndex(remoteSystemList[remoteSystemIndex].systemAddress); +// if (hashIndex!=remoteSystemIndex) +// { +// RakAssert(hashIndex==remoteSystemIndex); +// } +// } +// } +// #endif + + + remoteSystemList[remoteSystemListIndex].systemAddress=sa; + + unsigned int hashIndex = RemoteSystemLookupHashIndex(sa); + RemoteSystemIndex *rsi; + rsi = remoteSystemIndexPool.Allocate(_FILE_AND_LINE_); + if (remoteSystemLookup[hashIndex]==0) + { + rsi->next=0; + rsi->index=remoteSystemListIndex; + remoteSystemLookup[hashIndex]=rsi; + } + else + { + RemoteSystemIndex *cur = remoteSystemLookup[hashIndex]; + while (cur->next!=0) + { + cur=cur->next; + } + + rsi = remoteSystemIndexPool.Allocate(_FILE_AND_LINE_); + rsi->next=0; + rsi->index=remoteSystemListIndex; + cur->next=rsi; + } + +// #ifdef _DEBUG +// for ( int remoteSystemIndex = 0; remoteSystemIndex < maximumNumberOfPeers; ++remoteSystemIndex ) +// { +// if (remoteSystemList[remoteSystemIndex].isActive ) +// { +// unsigned int hashIndex = GetRemoteSystemIndex(remoteSystemList[remoteSystemIndex].systemAddress); +// RakAssert(hashIndex==remoteSystemIndex); +// } +// } +// #endif + + + RakAssert(GetRemoteSystemIndex(sa)==remoteSystemListIndex); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::DereferenceRemoteSystem(const SystemAddress &sa) +{ + unsigned int hashIndex = RemoteSystemLookupHashIndex(sa); + RemoteSystemIndex *cur = remoteSystemLookup[hashIndex]; + RemoteSystemIndex *last = 0; + while (cur!=0) + { + if (remoteSystemList[cur->index].systemAddress==sa) + { + if (last==0) + { + remoteSystemLookup[hashIndex]=cur->next; + } + else + { + last->next=cur->next; + } + remoteSystemIndexPool.Release(cur,_FILE_AND_LINE_); + break; + } + last=cur; + cur=cur->next; + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GetRemoteSystemIndex(const SystemAddress &sa) const +{ + unsigned int hashIndex = RemoteSystemLookupHashIndex(sa); + RemoteSystemIndex *cur = remoteSystemLookup[hashIndex]; + while (cur!=0) + { + if (remoteSystemList[cur->index].systemAddress==sa) + return cur->index; + cur=cur->next; + } + return (unsigned int) -1; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RakPeer::RemoteSystemStruct* RakPeer::GetRemoteSystem(const SystemAddress &sa) const +{ + unsigned int remoteSystemIndex = GetRemoteSystemIndex(sa); + if (remoteSystemIndex==(unsigned int)-1) + return 0; + return remoteSystemList + remoteSystemIndex; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ClearRemoteSystemLookup(void) +{ + remoteSystemIndexPool.Clear(_FILE_AND_LINE_); + RakNet::OP_DELETE_ARRAY(remoteSystemLookup,_FILE_AND_LINE_); + remoteSystemLookup=0; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::AddToActiveSystemList(unsigned int remoteSystemListIndex) +{ + activeSystemList[activeSystemListSize++]=remoteSystemList+remoteSystemListIndex; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::RemoveFromActiveSystemList(const SystemAddress &sa) +{ + unsigned int i; + for (i=0; i < activeSystemListSize; i++) + { + RemoteSystemStruct *rss=activeSystemList[i]; + if (rss->systemAddress==sa) + { + activeSystemList[i]=activeSystemList[activeSystemListSize-1]; + activeSystemListSize--; + return; + } + } + RakAssert("activeSystemList invalid, entry not found in RemoveFromActiveSystemList. Ensure that AddToActiveSystemList and RemoveFromActiveSystemList are called by the same thread." && 0); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +/* +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::LookupIndexUsingHashIndex(const SystemAddress &sa) const +{ + unsigned int scanCount=0; + unsigned int index = RemoteSystemLookupHashIndex(sa); + if (remoteSystemLookup[index].index==(unsigned int)-1) + return (unsigned int) -1; + while (remoteSystemList[remoteSystemLookup[index].index].systemAddress!=sa) + { + if (++index==(unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE) + index=0; + if (++scanCount>(unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE) + return (unsigned int) -1; + if (remoteSystemLookup[index].index==-1) + return (unsigned int) -1; + } + return index; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::RemoteSystemListIndexUsingHashIndex(const SystemAddress &sa) const +{ + unsigned int index = LookupIndexUsingHashIndex(sa); + if (index!=(unsigned int) -1) + { + return remoteSystemLookup[index].index; + } + return (unsigned int) -1; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::FirstFreeRemoteSystemLookupIndex(const SystemAddress &sa) const +{ +// unsigned int collisionCount=0; + unsigned int index = RemoteSystemLookupHashIndex(sa); + while (remoteSystemLookup[index].index!=(unsigned int)-1) + { + if (++index==(unsigned int) maximumNumberOfPeers*REMOTE_SYSTEM_LOOKUP_HASH_MULTIPLE) + index=0; +// collisionCount++; + } +// printf("%i collisions. Using index %i\n", collisionCount, index); + return index; +} +*/ +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::IsLoopbackAddress(const AddressOrGUID &systemIdentifier, bool matchPort) const +{ + if (systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID) + return systemIdentifier.rakNetGuid==myGuid; + + for (int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS && ipList[i]!=UNASSIGNED_SYSTEM_ADDRESS; i++) + { + if (matchPort) + { + if (ipList[i]==systemIdentifier.systemAddress) + return true; + } + else + { + if (ipList[i].EqualsExcludingPort(systemIdentifier.systemAddress)) + return true; + } + } + + return (matchPort==true && systemIdentifier.systemAddress==firstExternalID) || + (matchPort==false && systemIdentifier.systemAddress.EqualsExcludingPort(firstExternalID)); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +SystemAddress RakPeer::GetLoopbackAddress(void) const +{ + + return ipList[0]; + + + +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::AllowIncomingConnections(void) const +{ + return GetNumberOfRemoteInitiatedConnections() < GetMaximumIncomingConnections(); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::DeallocRNS2RecvStruct(RNS2RecvStruct *s, const char *file, unsigned int line) +{ + bufferedPacketsFreePoolMutex.Lock(); + bufferedPacketsFreePool.Push(s, file, line); + bufferedPacketsFreePoolMutex.Unlock(); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RNS2RecvStruct *RakPeer::AllocRNS2RecvStruct(const char *file, unsigned int line) +{ + bufferedPacketsFreePoolMutex.Lock(); + if (bufferedPacketsFreePool.Size()>0) + { + RNS2RecvStruct *s = bufferedPacketsFreePool.Pop(); + bufferedPacketsFreePoolMutex.Unlock(); + return s; + } + else + { + bufferedPacketsFreePoolMutex.Unlock(); + return RakNet::OP_NEW(file,line); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ClearBufferedPackets(void) +{ + bufferedPacketsFreePoolMutex.Lock(); + while (bufferedPacketsFreePool.Size()>0) + RakNet::OP_DELETE(bufferedPacketsFreePool.Pop(), _FILE_AND_LINE_); + bufferedPacketsFreePoolMutex.Unlock(); + + bufferedPacketsQueueMutex.Lock(); + while (bufferedPacketsQueue.Size()>0) + RakNet::OP_DELETE(bufferedPacketsQueue.Pop(), _FILE_AND_LINE_); + bufferedPacketsQueueMutex.Unlock(); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SetupBufferedPackets(void) +{ +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::PushBufferedPacket(RNS2RecvStruct * p) +{ + bufferedPacketsQueueMutex.Lock(); + bufferedPacketsQueue.Push(p, _FILE_AND_LINE_); + bufferedPacketsQueueMutex.Unlock(); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RNS2RecvStruct *RakPeer::PopBufferedPacket(void) +{ + bufferedPacketsQueueMutex.Lock(); + if (bufferedPacketsQueue.Size()>0) + { + RNS2RecvStruct *s = bufferedPacketsQueue.Pop(); + bufferedPacketsQueueMutex.Unlock(); + return s; + } + bufferedPacketsQueueMutex.Unlock(); + return 0; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::PingInternal( const SystemAddress target, bool performImmediate, PacketReliability reliability ) +{ + if ( IsActive() == false ) + return ; + + RakNet::BitStream bitStream(sizeof(unsigned char)+sizeof(RakNet::Time)); + bitStream.Write((MessageID)ID_CONNECTED_PING); + bitStream.Write(RakNet::GetTime()); + if (performImmediate) + SendImmediate( (char*)bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), IMMEDIATE_PRIORITY, reliability, 0, target, false, false, RakNet::GetTimeUS(), 0 ); + else + Send( &bitStream, IMMEDIATE_PRIORITY, reliability, 0, target, false ); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::CloseConnectionInternal( const AddressOrGUID& systemIdentifier, bool sendDisconnectionNotification, bool performImmediate, unsigned char orderingChannel, PacketPriority disconnectionNotificationPriority ) +{ +#ifdef _DEBUG + RakAssert(orderingChannel < 32); +#endif + + if (systemIdentifier.IsUndefined()) + return; + + if ( remoteSystemList == 0 || endThreads == true ) + return; + + SystemAddress target; + if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + target=systemIdentifier.systemAddress; + } + else + { + target=GetSystemAddressFromGuid(systemIdentifier.rakNetGuid); + } + + if (target!=UNASSIGNED_SYSTEM_ADDRESS && performImmediate) + target.FixForIPVersion(socketList[0]->GetBoundAddress()); + + if (sendDisconnectionNotification) + { + NotifyAndFlagForShutdown(target, performImmediate, orderingChannel, disconnectionNotificationPriority); + } + else + { + if (performImmediate) + { + unsigned int index = GetRemoteSystemIndex(target); + if (index!=(unsigned int) -1) + { + if ( remoteSystemList[index].isActive ) + { + RemoveFromActiveSystemList(target); + + // Found the index to stop + // printf("--- Address %s has become inactive\n", remoteSystemList[index].systemAddress.ToString()); + remoteSystemList[index].isActive = false; + + remoteSystemList[index].guid=UNASSIGNED_RAKNET_GUID; + + // Reserve this reliability layer for ourselves + //remoteSystemList[ remoteSystemLookup[index].index ].systemAddress = UNASSIGNED_SYSTEM_ADDRESS; + + // Clear any remaining messages + RakAssert(remoteSystemList[index].MTUSize <= MAXIMUM_MTU_SIZE); + remoteSystemList[index].reliabilityLayer.Reset(false, remoteSystemList[index].MTUSize, false); + + // Not using this socket + remoteSystemList[index].rakNetSocket = 0; + } + } + } + else + { + BufferedCommandStruct *bcs; + bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); + bcs->command=BufferedCommandStruct::BCS_CLOSE_CONNECTION; + bcs->systemIdentifier=target; + bcs->data=0; + bcs->orderingChannel=orderingChannel; + bcs->priority=disconnectionNotificationPriority; + bufferedCommands.Push(bcs); + } + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SendBuffered( const char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ) +{ + BufferedCommandStruct *bcs; + + bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); + bcs->data = (char*) rakMalloc_Ex( (size_t) BITS_TO_BYTES(numberOfBitsToSend), _FILE_AND_LINE_ ); // Making a copy doesn't lose efficiency because I tell the reliability layer to use this allocation for its own copy + if (bcs->data==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + bufferedCommands.Deallocate(bcs, _FILE_AND_LINE_); + return; + } + + RakAssert( !( reliability >= NUMBER_OF_RELIABILITIES || reliability < 0 ) ); + RakAssert( !( priority > NUMBER_OF_PRIORITIES || priority < 0 ) ); + RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); + + memcpy(bcs->data, data, (size_t) BITS_TO_BYTES(numberOfBitsToSend)); + bcs->numberOfBitsToSend=numberOfBitsToSend; + bcs->priority=priority; + bcs->reliability=reliability; + bcs->orderingChannel=orderingChannel; + bcs->systemIdentifier=systemIdentifier; + bcs->broadcast=broadcast; + bcs->connectionMode=connectionMode; + bcs->receipt=receipt; + bcs->command=BufferedCommandStruct::BCS_SEND; + bufferedCommands.Push(bcs); + + if (priority==IMMEDIATE_PRIORITY) + { + // Forces pending sends to go out now, rather than waiting to the next update interval + quitAndDataEvents.SetEvent(); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::SendBufferedList( const char **data, const int *lengths, const int numParameters, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, RemoteSystemStruct::ConnectMode connectionMode, uint32_t receipt ) +{ + BufferedCommandStruct *bcs; + unsigned int totalLength=0; + unsigned int lengthOffset; + int i; + for (i=0; i < numParameters; i++) + { + if (lengths[i]>0) + totalLength+=lengths[i]; + } + if (totalLength==0) + return; + + char *dataAggregate; + dataAggregate = (char*) rakMalloc_Ex( (size_t) totalLength, _FILE_AND_LINE_ ); // Making a copy doesn't lose efficiency because I tell the reliability layer to use this allocation for its own copy + if (dataAggregate==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + return; + } + for (i=0, lengthOffset=0; i < numParameters; i++) + { + if (lengths[i]>0) + { + memcpy(dataAggregate+lengthOffset, data[i], lengths[i]); + lengthOffset+=lengths[i]; + } + } + + if (broadcast==false && IsLoopbackAddress(systemIdentifier,true)) + { + SendLoopback(dataAggregate,totalLength); + rakFree_Ex(dataAggregate,_FILE_AND_LINE_); + return; + } + + RakAssert( !( reliability >= NUMBER_OF_RELIABILITIES || reliability < 0 ) ); + RakAssert( !( priority > NUMBER_OF_PRIORITIES || priority < 0 ) ); + RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); + + bcs=bufferedCommands.Allocate( _FILE_AND_LINE_ ); + bcs->data = dataAggregate; + bcs->numberOfBitsToSend=BYTES_TO_BITS(totalLength); + bcs->priority=priority; + bcs->reliability=reliability; + bcs->orderingChannel=orderingChannel; + bcs->systemIdentifier=systemIdentifier; + bcs->broadcast=broadcast; + bcs->connectionMode=connectionMode; + bcs->receipt=receipt; + bcs->command=BufferedCommandStruct::BCS_SEND; + bufferedCommands.Push(bcs); + + if (priority==IMMEDIATE_PRIORITY) + { + // Forces pending sends to go out now, rather than waiting to the next update interval + quitAndDataEvents.SetEvent(); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::SendImmediate( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool useCallerDataAllocation, RakNet::TimeUS currentTime, uint32_t receipt ) +{ + unsigned *sendList; + unsigned sendListSize; + bool callerDataAllocationUsed; + unsigned int remoteSystemIndex, sendListIndex; // Iterates into the list of remote systems +// unsigned numberOfBytesUsed = (unsigned) BITS_TO_BYTES(numberOfBitsToSend); + callerDataAllocationUsed=false; + + sendListSize=0; + + if (systemIdentifier.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) + remoteSystemIndex=GetIndexFromSystemAddress( systemIdentifier.systemAddress, true ); + else if (systemIdentifier.rakNetGuid!=UNASSIGNED_RAKNET_GUID) + remoteSystemIndex=GetSystemIndexFromGuid(systemIdentifier.rakNetGuid); + else + remoteSystemIndex=(unsigned int) -1; + + // 03/06/06 - If broadcast is false, use the optimized version of GetIndexFromSystemAddress + if (broadcast==false) + { + if (remoteSystemIndex==(unsigned int) -1) + { +#ifdef _DEBUG +// int debugIndex = GetRemoteSystemIndex(systemIdentifier.systemAddress); +#endif + return false; + } + + #if USE_ALLOCA==1 + sendList=(unsigned *)alloca(sizeof(unsigned)); + #else + sendList = (unsigned *) rakMalloc_Ex(sizeof(unsigned), _FILE_AND_LINE_); + #endif + + if (remoteSystemList[remoteSystemIndex].isActive && + remoteSystemList[remoteSystemIndex].connectMode!=RemoteSystemStruct::DISCONNECT_ASAP && + remoteSystemList[remoteSystemIndex].connectMode!=RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY && + remoteSystemList[remoteSystemIndex].connectMode!=RemoteSystemStruct::DISCONNECT_ON_NO_ACK) + { + sendList[0]=remoteSystemIndex; + sendListSize=1; + } + } + else + { + #if USE_ALLOCA==1 + sendList=(unsigned *)alloca(sizeof(unsigned)*maximumNumberOfPeers); + #else + sendList = (unsigned *) rakMalloc_Ex(sizeof(unsigned)*maximumNumberOfPeers, _FILE_AND_LINE_); + #endif + + // remoteSystemList in network thread + unsigned int idx; + for ( idx = 0; idx < maximumNumberOfPeers; idx++ ) + { + if (remoteSystemIndex!=(unsigned int) -1 && idx==remoteSystemIndex) + continue; + + if ( remoteSystemList[ idx ].isActive && remoteSystemList[ idx ].systemAddress != UNASSIGNED_SYSTEM_ADDRESS ) + sendList[sendListSize++]=idx; + } + } + + if (sendListSize==0) + { + #if !defined(USE_ALLOCA) + rakFree_Ex(sendList, _FILE_AND_LINE_ ); + #endif + + return false; + } + + for (sendListIndex=0; sendListIndex < sendListSize; sendListIndex++) + { + // Send may split the packet and thus deallocate data. Don't assume data is valid if we use the callerAllocationData + bool useData = useCallerDataAllocation && callerDataAllocationUsed==false && sendListIndex+1==sendListSize; + remoteSystemList[sendList[sendListIndex]].reliabilityLayer.Send( data, numberOfBitsToSend, priority, reliability, orderingChannel, useData==false, remoteSystemList[sendList[sendListIndex]].MTUSize, currentTime, receipt ); + if (useData) + callerDataAllocationUsed=true; + + if (reliability==RELIABLE || + reliability==RELIABLE_ORDERED || + reliability==RELIABLE_SEQUENCED || + reliability==RELIABLE_WITH_ACK_RECEIPT || + reliability==RELIABLE_ORDERED_WITH_ACK_RECEIPT +// || +// reliability==RELIABLE_SEQUENCED_WITH_ACK_RECEIPT + ) + remoteSystemList[sendList[sendListIndex]].lastReliableSend=(RakNet::TimeMS)(currentTime/(RakNet::TimeUS)1000); + } + +#if !defined(USE_ALLOCA) + rakFree_Ex(sendList, _FILE_AND_LINE_ ); +#endif + + // Return value only meaningful if true was passed for useCallerDataAllocation. Means the reliability layer used that data copy, so the caller should not deallocate it + return callerDataAllocationUsed; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ResetSendReceipt(void) +{ + sendReceiptSerialMutex.Lock(); + sendReceiptSerial=1; + sendReceiptSerialMutex.Unlock(); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::OnConnectedPong(RakNet::Time sendPingTime, RakNet::Time sendPongTime, RemoteSystemStruct *remoteSystem) +{ + RakNet::Time ping; +// RakNet::TimeMS lastPing; + RakNet::Time time = RakNet::GetTime(); // Update the time value to be accurate + if (time > sendPingTime) + ping = time - sendPingTime; + else + ping=0; + +// lastPing = remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].pingTime; + + remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].pingTime = ( unsigned short ) ping; + // Thanks to Chris Taylor (cat02e@fsu.edu) for the improved timestamping algorithm + // Divide each integer by 2, rather than the sum by 2, to prevent overflow + remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].clockDifferential = sendPongTime - ( time/2 + sendPingTime/2 ); + + if ( remoteSystem->lowestPing == (unsigned short)-1 || remoteSystem->lowestPing > (int) ping ) + remoteSystem->lowestPing = (unsigned short) ping; + + if ( ++( remoteSystem->pingAndClockDifferentialWriteIndex ) == (RakNet::Time) PING_TIMES_ARRAY_SIZE ) + remoteSystem->pingAndClockDifferentialWriteIndex = 0; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ClearBufferedCommands(void) +{ + BufferedCommandStruct *bcs; + + while ((bcs=bufferedCommands.Pop())!=0) + { + if (bcs->data) + rakFree_Ex(bcs->data, _FILE_AND_LINE_ ); + + bufferedCommands.Deallocate(bcs, _FILE_AND_LINE_); + } + bufferedCommands.Clear(_FILE_AND_LINE_); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ClearSocketQueryOutput(void) +{ + socketQueryOutput.Clear(_FILE_AND_LINE_); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::ClearRequestedConnectionList(void) +{ + DataStructures::Queue freeQueue; + requestedConnectionQueueMutex.Lock(); + while (requestedConnectionQueue.Size()) + freeQueue.Push(requestedConnectionQueue.Pop(), _FILE_AND_LINE_ ); + requestedConnectionQueueMutex.Unlock(); + unsigned i; + for (i=0; i < freeQueue.Size(); i++) + { +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: In ClearRequestedConnectionList(), Deleting freeQueue index %i client_handshake %x\n", i, freeQueue[i]->client_handshake); + RakNet::OP_DELETE(freeQueue[i]->client_handshake,_FILE_AND_LINE_); +#endif + RakNet::OP_DELETE(freeQueue[i], _FILE_AND_LINE_ ); + } +} +inline void RakPeer::AddPacketToProducer(RakNet::Packet *p) +{ + packetReturnMutex.Lock(); + packetReturnQueue.Push(p,_FILE_AND_LINE_); + packetReturnMutex.Unlock(); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +union Buff6AndBuff8 +{ + unsigned char buff6[6]; + uint64_t buff8; +}; +uint64_t RakPeerInterface::Get64BitUniqueRandomNumber(void) +{ + // Mac address is a poor solution because you can't have multiple connections from the same system + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#if defined(_WIN32) + uint64_t g=RakNet::GetTimeUS(); + + RakNet::TimeUS lastTime, thisTime; + int j; + // Sleep a small random time, then use the last 4 bits as a source of randomness + for (j=0; j < 8; j++) + { + lastTime = RakNet::GetTimeUS(); + RakSleep(1); + RakSleep(0); + thisTime = RakNet::GetTimeUS(); + RakNet::TimeUS diff = thisTime-lastTime; + unsigned int diff4Bits = (unsigned int) (diff & 15); + diff4Bits <<= 32-4; + diff4Bits >>= j*4; + ((char*)&g)[j] ^= diff4Bits; + } + return g; + +#else + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_usec + tv.tv_sec * 1000000; +#endif +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::GenerateGUID(void) +{ + myGuid.g=Get64BitUniqueRandomNumber(); + +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +// void RakNet::ProcessPortUnreachable( SystemAddress systemAddress, RakPeer *rakPeer ) +// { +// (void) binaryAddress; +// (void) port; +// (void) rakPeer; +// +// } +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +namespace RakNet { +bool ProcessOfflineNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, bool *isOfflineMessage, RakNet::TimeUS timeRead ) +{ + (void) timeRead; + RakPeer::RemoteSystemStruct *remoteSystem; + RakNet::Packet *packet; + unsigned i; + + + char str1[64]; + systemAddress.ToString(false, str1); + if (rakPeer->IsBanned( str1 )) + { + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); + + RakNet::BitStream bs; + bs.Write((MessageID)ID_CONNECTION_BANNED); + bs.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bs.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); + + + RNS2_SendParameters bsp; + bsp.data = (char*) bs.GetData(); + bsp.length = bs.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((char*) bs.GetData(), bs.GetNumberOfBitsUsed(), systemAddress); + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + +/* + unsigned i; + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((char*) bs.GetData(), bs.GetNumberOfBitsUsed(), systemAddress); + SocketLayer::SendTo( rakNetSocket, (char*) bs.GetData(), bs.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + */ + + return true; + } + + + + // The reason for all this is that the reliability layer has no way to tell between offline messages that arrived late for a player that is now connected, + // and a regular encoding. So I insert OFFLINE_MESSAGE_DATA_ID into the stream, the encoding of which is essentially impossible to hit by chance + if (length <=2) + { + *isOfflineMessage=true; + } + else if ( + ((unsigned char)data[0] == ID_UNCONNECTED_PING || + (unsigned char)data[0] == ID_UNCONNECTED_PING_OPEN_CONNECTIONS) && + (unsigned int)length >= sizeof(unsigned char) + sizeof(RakNet::Time) + sizeof(OFFLINE_MESSAGE_DATA_ID)) + { + *isOfflineMessage=memcmp(data+sizeof(unsigned char) + sizeof(RakNet::Time), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; + } + else if ((unsigned char)data[0] == ID_UNCONNECTED_PONG && (size_t) length >= sizeof(unsigned char) + sizeof(RakNet::TimeMS) + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID)) + { + *isOfflineMessage=memcmp(data+sizeof(unsigned char) + sizeof(RakNet::Time) + RakNetGUID::size(), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; + } + else if ( + (unsigned char)data[0] == ID_OUT_OF_BAND_INTERNAL && + (size_t) length >= sizeof(MessageID) + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID)) + { + *isOfflineMessage=memcmp(data+sizeof(MessageID) + RakNetGUID::size(), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; + } + else if ( + ( + (unsigned char)data[0] == ID_OPEN_CONNECTION_REPLY_1 || + (unsigned char)data[0] == ID_OPEN_CONNECTION_REPLY_2 || + (unsigned char)data[0] == ID_OPEN_CONNECTION_REQUEST_1 || + (unsigned char)data[0] == ID_OPEN_CONNECTION_REQUEST_2 || + (unsigned char)data[0] == ID_CONNECTION_ATTEMPT_FAILED || + (unsigned char)data[0] == ID_NO_FREE_INCOMING_CONNECTIONS || + (unsigned char)data[0] == ID_CONNECTION_BANNED || + (unsigned char)data[0] == ID_ALREADY_CONNECTED || + (unsigned char)data[0] == ID_IP_RECENTLY_CONNECTED) && + (size_t) length >= sizeof(MessageID) + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID)) + { + *isOfflineMessage=memcmp(data+sizeof(MessageID), OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; + } + else if (((unsigned char)data[0] == ID_INCOMPATIBLE_PROTOCOL_VERSION&& + (size_t) length == sizeof(MessageID)*2 + RakNetGUID::size() + sizeof(OFFLINE_MESSAGE_DATA_ID))) + { + *isOfflineMessage=memcmp(data+sizeof(MessageID)*2, OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID))==0; + } + else + { + *isOfflineMessage=false; + } + + if (*isOfflineMessage) + { + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); + + // These are all messages from unconnected systems. Messages here can be any size, but are never processed from connected systems. + if ( ( (unsigned char) data[ 0 ] == ID_UNCONNECTED_PING_OPEN_CONNECTIONS + || (unsigned char)(data)[0] == ID_UNCONNECTED_PING) && (unsigned int)length >= sizeof(unsigned char)+sizeof(RakNet::Time)+sizeof(OFFLINE_MESSAGE_DATA_ID) ) + { + if ( (unsigned char)(data)[0] == ID_UNCONNECTED_PING || + rakPeer->AllowIncomingConnections() ) // Open connections with players + { + RakNet::BitStream inBitStream( (unsigned char *) data, length, false ); + inBitStream.IgnoreBits(8); + RakNet::Time sendPingTime; + inBitStream.Read(sendPingTime); + inBitStream.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); + RakNetGUID remoteGuid=UNASSIGNED_RAKNET_GUID; + inBitStream.Read(remoteGuid); + + RakNet::BitStream outBitStream; + outBitStream.Write((MessageID)ID_UNCONNECTED_PONG); // Should be named ID_UNCONNECTED_PONG eventually + outBitStream.Write(sendPingTime); + outBitStream.Write(rakPeer->myGuid); + outBitStream.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + + rakPeer->rakPeerMutexes[ RakPeer::offlinePingResponse_Mutex ].Lock(); + // They are connected, so append offline ping data + outBitStream.Write( (char*)rakPeer->offlinePingResponse.GetData(), rakPeer->offlinePingResponse.GetNumberOfBytesUsed() ); + rakPeer->rakPeerMutexes[ RakPeer::offlinePingResponse_Mutex ].Unlock(); + + unsigned i; + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*)outBitStream.GetData(), outBitStream.GetNumberOfBytesUsed(), systemAddress); + + RNS2_SendParameters bsp; + bsp.data = (char*) outBitStream.GetData(); + bsp.length = outBitStream.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + + // SocketLayer::SendTo( rakNetSocket, (const char*)outBitStream.GetData(), (unsigned int) outBitStream.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + + packet=rakPeer->AllocPacket(sizeof(MessageID), _FILE_AND_LINE_); + packet->data[0]=data[0]; + packet->systemAddress = systemAddress; + packet->guid=remoteGuid; + packet->systemAddress.systemIndex = ( SystemIndex ) rakPeer->GetIndexFromSystemAddress( systemAddress, true ); + packet->guid.systemIndex=packet->systemAddress.systemIndex; + rakPeer->AddPacketToProducer(packet); + } + } + // UNCONNECTED MESSAGE Pong with no data. + else if ((unsigned char) data[ 0 ] == ID_UNCONNECTED_PONG && (size_t) length >= sizeof(unsigned char)+sizeof(RakNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID) && (size_t) length < sizeof(unsigned char)+sizeof(RakNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID)+MAX_OFFLINE_DATA_LENGTH) + { + packet=rakPeer->AllocPacket((unsigned int) (length-sizeof(OFFLINE_MESSAGE_DATA_ID)-RakNetGUID::size()-sizeof(RakNet::Time)+sizeof(RakNet::TimeMS)), _FILE_AND_LINE_); + RakNet::BitStream bsIn((unsigned char*) data, length, false); + bsIn.IgnoreBytes(sizeof(unsigned char)); + RakNet::Time ping; + bsIn.Read(ping); + bsIn.Read(packet->guid); + + RakNet::BitStream bsOut((unsigned char*) packet->data, packet->length, false); + bsOut.ResetWritePointer(); + bsOut.Write((unsigned char)ID_UNCONNECTED_PONG); + RakNet::TimeMS pingMS=(RakNet::TimeMS)ping; + bsOut.Write(pingMS); + bsOut.WriteAlignedBytes( + (const unsigned char*)data+sizeof(unsigned char)+sizeof(RakNet::Time)+RakNetGUID::size()+sizeof(OFFLINE_MESSAGE_DATA_ID), + length-sizeof(unsigned char)-sizeof(RakNet::Time)-RakNetGUID::size()-sizeof(OFFLINE_MESSAGE_DATA_ID) + ); + + packet->systemAddress = systemAddress; + packet->systemAddress.systemIndex = ( SystemIndex ) rakPeer->GetIndexFromSystemAddress( systemAddress, true ); + packet->guid.systemIndex=packet->systemAddress.systemIndex; + rakPeer->AddPacketToProducer(packet); + } + else if ((unsigned char) data[ 0 ] == ID_OUT_OF_BAND_INTERNAL && + (size_t) length > sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID)+RakNetGUID::size() && + (size_t) length < MAX_OFFLINE_DATA_LENGTH+sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID)+RakNetGUID::size()) + { + unsigned int dataLength = (unsigned int) (length-sizeof(OFFLINE_MESSAGE_DATA_ID)-RakNetGUID::size()-sizeof(MessageID)); + RakAssert(dataLength<1024); + packet=rakPeer->AllocPacket(dataLength+1, _FILE_AND_LINE_); + RakAssert(packet->length<1024); + + RakNet::BitStream bs2((unsigned char*) data, length, false); + bs2.IgnoreBytes(sizeof(MessageID)); + bs2.Read(packet->guid); + + if (data[sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID) + RakNetGUID::size()]==ID_ADVERTISE_SYSTEM) + { + packet->length--; + packet->bitSize=BYTES_TO_BITS(packet->length); + packet->data[0]=ID_ADVERTISE_SYSTEM; + memcpy(packet->data+1, data+sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID)*2 + RakNetGUID::size(), dataLength-1); + } + else + { + packet->data[0]=ID_OUT_OF_BAND_INTERNAL; + memcpy(packet->data+1, data+sizeof(OFFLINE_MESSAGE_DATA_ID)+sizeof(MessageID) + RakNetGUID::size(), dataLength); + } + + packet->systemAddress = systemAddress; + packet->systemAddress.systemIndex = ( SystemIndex ) rakPeer->GetIndexFromSystemAddress( systemAddress, true ); + packet->guid.systemIndex=packet->systemAddress.systemIndex; + rakPeer->AddPacketToProducer(packet); + } + else if ((unsigned char)(data)[0] == (MessageID)ID_OPEN_CONNECTION_REPLY_1) + { + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); + + RakNet::BitStream bsIn((unsigned char*) data,length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + bsIn.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); + RakNetGUID serverGuid; + bsIn.Read(serverGuid); + unsigned char serverHasSecurity; + uint32_t cookie; + (void) cookie; + bsIn.Read(serverHasSecurity); + // Even if the server has security, it may not be required of us if we are in the security exception list + if (serverHasSecurity) + { + bsIn.Read(cookie); + } + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_OPEN_CONNECTION_REQUEST_2); + bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + if (serverHasSecurity) + bsOut.Write(cookie); + + unsigned i; + rakPeer->requestedConnectionQueueMutex.Lock(); + for (i=0; i < rakPeer->requestedConnectionQueue.Size(); i++) + { + RakPeer::RequestedConnectionStruct *rcs; + rcs=rakPeer->requestedConnectionQueue[i]; + if (rcs->systemAddress==systemAddress) + { + if (serverHasSecurity) + { +#if LIBCAT_SECURITY==1 + unsigned char public_key[cat::EasyHandshake::PUBLIC_KEY_BYTES]; + bsIn.ReadAlignedBytes(public_key, sizeof(public_key)); + + if (rcs->publicKeyMode==PKM_ACCEPT_ANY_PUBLIC_KEY) + { + memcpy(rcs->remote_public_key, public_key, cat::EasyHandshake::PUBLIC_KEY_BYTES); + if (!rcs->client_handshake->Initialize(public_key) || + !rcs->client_handshake->GenerateChallenge(rcs->handshakeChallenge)) + { + CAT_AUDIT_PRINTF("AUDIT: Server passed a bad public key with PKM_ACCEPT_ANY_PUBLIC_KEY"); + return true; + } + } + + if (cat::SecureEqual(public_key, + rcs->remote_public_key, + cat::EasyHandshake::PUBLIC_KEY_BYTES)==false) + { + rakPeer->requestedConnectionQueueMutex.Unlock(); + CAT_AUDIT_PRINTF("AUDIT: Expected public key does not match what was sent by server -- Reporting back ID_PUBLIC_KEY_MISMATCH to user\n"); + + packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); + packet->data[ 0 ] = ID_PUBLIC_KEY_MISMATCH; // Attempted a connection and couldn't + packet->bitSize = ( sizeof( char ) * 8); + packet->systemAddress = rcs->systemAddress; + packet->guid=serverGuid; + rakPeer->AddPacketToProducer(packet); + return true; + } + + if (rcs->client_handshake==0) + { + // Message does not contain a challenge + // We might still pass if we are in the security exception list + bsOut.Write((unsigned char)0); + } + else + { + // Message contains a challenge + bsOut.Write((unsigned char)1); + // challenge + CAT_AUDIT_PRINTF("AUDIT: Sending challenge\n"); + bsOut.WriteAlignedBytes((const unsigned char*) rcs->handshakeChallenge,cat::EasyHandshake::CHALLENGE_BYTES); + } +#else // LIBCAT_SECURITY + // Message does not contain a challenge + bsOut.Write((unsigned char)0); +#endif // LIBCAT_SECURITY + } + else + { + // Server does not need security +#if LIBCAT_SECURITY==1 + if (rcs->client_handshake!=0) + { + rakPeer->requestedConnectionQueueMutex.Unlock(); + CAT_AUDIT_PRINTF("AUDIT: Security disabled by server but we expected security (indicated by client_handshake not null) so failing!\n"); + + packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); + packet->data[ 0 ] = ID_OUR_SYSTEM_REQUIRES_SECURITY; // Attempted a connection and couldn't + packet->bitSize = ( sizeof( char ) * 8); + packet->systemAddress = rcs->systemAddress; + packet->guid=serverGuid; + rakPeer->AddPacketToProducer(packet); + return true; + } +#endif // LIBCAT_SECURITY + + } + + uint16_t mtu; + bsIn.Read(mtu); + + // Binding address + bsOut.Write(rcs->systemAddress); + rakPeer->requestedConnectionQueueMutex.Unlock(); + // MTU + bsOut.Write(mtu); + // Our guid + bsOut.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); + + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), rcs->systemAddress); + + // SocketLayer::SendTo( rakPeer->socketList[rcs->socketIndex], (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), rcs->systemAddress, _FILE_AND_LINE_ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) bsOut.GetData(); + bsp.length = bsOut.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + + return true; + } + } + rakPeer->requestedConnectionQueueMutex.Unlock(); + } + else if ((unsigned char)(data)[0] == (MessageID)ID_OPEN_CONNECTION_REPLY_2) + { + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); + + RakNet::BitStream bs((unsigned char*) data,length,false); + bs.IgnoreBytes(sizeof(MessageID)); + bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); + RakNetGUID guid; + bs.Read(guid); + SystemAddress bindingAddress; + bool b = bs.Read(bindingAddress); + RakAssert(b); + uint16_t mtu; + b=bs.Read(mtu); + RakAssert(b); + bool doSecurity=false; + b=bs.Read(doSecurity); + RakAssert(b); + +#if LIBCAT_SECURITY==1 + char answer[cat::EasyHandshake::ANSWER_BYTES]; + CAT_AUDIT_PRINTF("AUDIT: Got ID_OPEN_CONNECTION_REPLY_2 and given doSecurity=%i\n", (int)doSecurity); + if (doSecurity) + { + CAT_AUDIT_PRINTF("AUDIT: Reading cookie and public key\n"); + bs.ReadAlignedBytes((unsigned char*) answer, sizeof(answer)); + } + cat::ClientEasyHandshake *client_handshake=0; +#endif // LIBCAT_SECURITY + + RakPeer::RequestedConnectionStruct *rcs; + bool unlock=true; + unsigned i; + rakPeer->requestedConnectionQueueMutex.Lock(); + for (i=0; i < rakPeer->requestedConnectionQueue.Size(); i++) + { + rcs=rakPeer->requestedConnectionQueue[i]; + + + if (rcs->systemAddress==systemAddress) + { +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: System address matches an entry in the requestedConnectionQueue and doSecurity=%i\n", (int)doSecurity); + if (doSecurity) + { + if (rcs->client_handshake==0) + { + CAT_AUDIT_PRINTF("AUDIT: Server wants security but we didn't set a public key -- Reporting back ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY to user\n"); + rakPeer->requestedConnectionQueueMutex.Unlock(); + + packet=rakPeer->AllocPacket(2, _FILE_AND_LINE_); + packet->data[ 0 ] = ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY; // Attempted a connection and couldn't + packet->data[ 1 ] = 0; // Indicate server public key is missing + packet->bitSize = ( sizeof( char ) * 8); + packet->systemAddress = rcs->systemAddress; + packet->guid=guid; + rakPeer->AddPacketToProducer(packet); + return true; + } + + CAT_AUDIT_PRINTF("AUDIT: Looks good, preparing to send challenge to server! client_handshake = %x\n", client_handshake); + } + +#endif // LIBCAT_SECURITY + + rakPeer->requestedConnectionQueueMutex.Unlock(); + unlock=false; + + RakAssert(rcs->actionToTake==RakPeer::RequestedConnectionStruct::CONNECT); + // You might get this when already connected because of cross-connections + bool thisIPConnectedRecently=false; + remoteSystem=rakPeer->GetRemoteSystemFromSystemAddress( systemAddress, true, true ); + if (remoteSystem==0) + { + if (rcs->socket == 0) + { + remoteSystem=rakPeer->AssignSystemAddressToRemoteSystemList(systemAddress, RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER, rakNetSocket, &thisIPConnectedRecently, bindingAddress, mtu, guid, doSecurity); + } + else + { + remoteSystem=rakPeer->AssignSystemAddressToRemoteSystemList(systemAddress, RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER, rcs->socket, &thisIPConnectedRecently, bindingAddress, mtu, guid, doSecurity); + } + } + + // 4/13/09 Attackers can flood ID_OPEN_CONNECTION_REQUEST and use up all available connection slots + // Ignore connection attempts if this IP address connected within the last 100 milliseconds + if (thisIPConnectedRecently==false) + { + // Don't check GetRemoteSystemFromGUID, server will verify + if (remoteSystem) + { + // Move pointer from RequestedConnectionStruct to RemoteSystemStruct +#if LIBCAT_SECURITY==1 + cat::u8 ident[cat::EasyHandshake::IDENTITY_BYTES]; + bool doIdentity = false; + + if (rcs->client_handshake) + { + CAT_AUDIT_PRINTF("AUDIT: Processing answer\n"); + if (rcs->publicKeyMode == PKM_USE_TWO_WAY_AUTHENTICATION) + { + if (!rcs->client_handshake->ProcessAnswerWithIdentity(answer, ident, remoteSystem->reliabilityLayer.GetAuthenticatedEncryption())) + { + CAT_AUDIT_PRINTF("AUDIT: Processing answer -- Invalid Answer\n"); + rakPeer->requestedConnectionQueueMutex.Unlock(); + + return true; + } + + doIdentity = true; + } + else + { + if (!rcs->client_handshake->ProcessAnswer(answer, remoteSystem->reliabilityLayer.GetAuthenticatedEncryption())) + { + CAT_AUDIT_PRINTF("AUDIT: Processing answer -- Invalid Answer\n"); + rakPeer->requestedConnectionQueueMutex.Unlock(); + + return true; + } + } + CAT_AUDIT_PRINTF("AUDIT: Success!\n"); + + RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); + rcs->client_handshake=0; + } +#endif // LIBCAT_SECURITY + + remoteSystem->weInitiatedTheConnection=true; + remoteSystem->connectMode=RakPeer::RemoteSystemStruct::REQUESTED_CONNECTION; + if (rcs->timeoutTime!=0) + remoteSystem->reliabilityLayer.SetTimeoutTime(rcs->timeoutTime); + + RakNet::BitStream temp; + temp.Write( (MessageID)ID_CONNECTION_REQUEST); + temp.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); + temp.Write(RakNet::GetTime()); + +#if LIBCAT_SECURITY==1 + temp.Write((unsigned char)(doSecurity ? 1 : 0)); + + if (doSecurity) + { + unsigned char proof[32]; + remoteSystem->reliabilityLayer.GetAuthenticatedEncryption()->GenerateProof(proof, sizeof(proof)); + temp.WriteAlignedBytes(proof, sizeof(proof)); + + temp.Write((unsigned char)(doIdentity ? 1 : 0)); + + if (doIdentity) + { + temp.WriteAlignedBytes(ident, sizeof(ident)); + } + } +#else + temp.Write((unsigned char)0); +#endif // LIBCAT_SECURITY + + if ( rcs->outgoingPasswordLength > 0 ) + temp.Write( ( char* ) rcs->outgoingPassword, rcs->outgoingPasswordLength ); + + rakPeer->SendImmediate((char*)temp.GetData(), temp.GetNumberOfBitsUsed(), IMMEDIATE_PRIORITY, RELIABLE, 0, systemAddress, false, false, timeRead, 0 ); + } + else + { + // Failed, no connections available anymore + packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); + packet->data[ 0 ] = ID_CONNECTION_ATTEMPT_FAILED; // Attempted a connection and couldn't + packet->bitSize = ( sizeof( char ) * 8); + packet->systemAddress = rcs->systemAddress; + packet->guid=guid; + rakPeer->AddPacketToProducer(packet); + } + } + + rakPeer->requestedConnectionQueueMutex.Lock(); + for (unsigned int k=0; k < rakPeer->requestedConnectionQueue.Size(); k++) + { + if (rakPeer->requestedConnectionQueue[k]->systemAddress==systemAddress) + { + rakPeer->requestedConnectionQueue.RemoveAtIndex(k); + break; + } + } + rakPeer->requestedConnectionQueueMutex.Unlock(); + +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: Deleting client_handshake object %x and rcs->client_handshake object %x\n", client_handshake, rcs->client_handshake); + RakNet::OP_DELETE(client_handshake,_FILE_AND_LINE_); + RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); +#endif // LIBCAT_SECURITY + RakNet::OP_DELETE(rcs,_FILE_AND_LINE_); + + break; + } + } + + if (unlock) + rakPeer->requestedConnectionQueueMutex.Unlock(); + + return true; + + } + else if ((unsigned char)(data)[0] == (MessageID)ID_CONNECTION_ATTEMPT_FAILED || + (unsigned char)(data)[0] == (MessageID)ID_NO_FREE_INCOMING_CONNECTIONS || + (unsigned char)(data)[0] == (MessageID)ID_CONNECTION_BANNED || + (unsigned char)(data)[0] == (MessageID)ID_ALREADY_CONNECTED || + (unsigned char)(data)[0] == (MessageID)ID_INVALID_PASSWORD || + (unsigned char)(data)[0] == (MessageID)ID_IP_RECENTLY_CONNECTED || + (unsigned char)(data)[0] == (MessageID)ID_INCOMPATIBLE_PROTOCOL_VERSION) + { + + RakNet::BitStream bs((unsigned char*) data,length,false); + bs.IgnoreBytes(sizeof(MessageID)); + bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); + if ((unsigned char)(data)[0] == (MessageID)ID_INCOMPATIBLE_PROTOCOL_VERSION) + bs.IgnoreBytes(sizeof(unsigned char)); + + RakNetGUID guid; + bs.Read(guid); + + RakPeer::RequestedConnectionStruct *rcs; + bool connectionAttemptCancelled=false; + unsigned i; + rakPeer->requestedConnectionQueueMutex.Lock(); + for (i=0; i < rakPeer->requestedConnectionQueue.Size(); i++) + { + rcs=rakPeer->requestedConnectionQueue[i]; + if (rcs->actionToTake==RakPeer::RequestedConnectionStruct::CONNECT && rcs->systemAddress==systemAddress) + { + connectionAttemptCancelled=true; + rakPeer->requestedConnectionQueue.RemoveAtIndex(i); + +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: Connection attempt canceled so deleting rcs->client_handshake object %x\n", rcs->client_handshake); + RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); +#endif // LIBCAT_SECURITY + RakNet::OP_DELETE(rcs,_FILE_AND_LINE_); + break; + } + } + + rakPeer->requestedConnectionQueueMutex.Unlock(); + + if (connectionAttemptCancelled) + { + // Tell user of connection attempt failed + packet=rakPeer->AllocPacket(sizeof( char ), _FILE_AND_LINE_); + packet->data[ 0 ] = data[0]; // Attempted a connection and couldn't + packet->bitSize = ( sizeof( char ) * 8); + packet->systemAddress = systemAddress; + packet->guid=guid; + rakPeer->AddPacketToProducer(packet); + } + } + else if ((unsigned char)(data)[0] == ID_OPEN_CONNECTION_REQUEST_1 && length > (int) (1+sizeof(OFFLINE_MESSAGE_DATA_ID))) + {/* + static int x = 0; + ++x; + + SystemAddress *addr = (SystemAddress*)&systemAddress; + addr->binaryAddress += x;*/ + + unsigned int i; + //RAKNET_DEBUG_PRINTF("%i:IOCR, ", __LINE__); + char remoteProtocol=data[1+sizeof(OFFLINE_MESSAGE_DATA_ID)]; + if (remoteProtocol!=RAKNET_PROTOCOL_VERSION) + { + RakNet::BitStream bs; + bs.Write((MessageID)ID_INCOMPATIBLE_PROTOCOL_VERSION); + bs.Write((unsigned char)RAKNET_PROTOCOL_VERSION); + bs.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bs.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); + + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((char*)bs.GetData(), bs.GetNumberOfBitsUsed(), systemAddress); + + // SocketLayer::SendTo( rakNetSocket, (char*)bs.GetData(), bs.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) bs.GetData(); + bsp.length = bs.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + return true; + } + + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketReceive(data, length*8, systemAddress); + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_OPEN_CONNECTION_REPLY_1); + bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bsOut.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); +#if LIBCAT_SECURITY==1 + if (rakPeer->_using_security) + { + bsOut.Write((unsigned char) 1); // HasCookie Yes + // Write cookie + uint32_t cookie = rakPeer->_cookie_jar->Generate(&systemAddress.address,sizeof(systemAddress.address)); + CAT_AUDIT_PRINTF("AUDIT: Writing cookie %i to %i:%i\n", cookie, systemAddress); + bsOut.Write(cookie); + // Write my public key + bsOut.WriteAlignedBytes((const unsigned char *) rakPeer->my_public_key,sizeof(rakPeer->my_public_key)); + } + else +#endif // LIBCAT_SECURITY + bsOut.Write((unsigned char) 0); // HasCookie oN + + // MTU. Lower MTU if it is exceeds our own limit + if (length+UDP_HEADER_SIZE > MAXIMUM_MTU_SIZE) + bsOut.WriteCasted(MAXIMUM_MTU_SIZE); + else + bsOut.WriteCasted(length+UDP_HEADER_SIZE); + + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); + // SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) bsOut.GetData(); + bsp.length = bsOut.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + } + else if ((unsigned char)(data)[0] == ID_OPEN_CONNECTION_REQUEST_2) + { + SystemAddress bindingAddress; + RakNetGUID guid; + RakNet::BitStream bsOut; + RakNet::BitStream bs((unsigned char*) data, length, false); + bs.IgnoreBytes(sizeof(MessageID)); + bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); + + bool requiresSecurityOfThisClient=false; +#if LIBCAT_SECURITY==1 + char remoteHandshakeChallenge[cat::EasyHandshake::CHALLENGE_BYTES]; + + if (rakPeer->_using_security) + { + char str1[64]; + systemAddress.ToString(false, str1); + requiresSecurityOfThisClient=rakPeer->IsInSecurityExceptionList(str1)==false; + + uint32_t cookie; + bs.Read(cookie); + CAT_AUDIT_PRINTF("AUDIT: Got cookie %i from %i:%i\n", cookie, systemAddress); + if (rakPeer->_cookie_jar->Verify(&systemAddress.address,sizeof(systemAddress.address), cookie)==false) + { + return true; + } + CAT_AUDIT_PRINTF("AUDIT: Cookie good!\n"); + + unsigned char clientWroteChallenge; + bs.Read(clientWroteChallenge); + + if (requiresSecurityOfThisClient==true && clientWroteChallenge==0) + { + // Fail, client doesn't support security, and it is required + return true; + } + + if (clientWroteChallenge) + { + bs.ReadAlignedBytes((unsigned char*) remoteHandshakeChallenge, cat::EasyHandshake::CHALLENGE_BYTES); +#ifdef CAT_AUDIT + printf("AUDIT: RECV CHALLENGE "); + for (int ii = 0; ii < sizeof(remoteHandshakeChallenge); ++ii) + { + printf("%02x", (cat::u8)remoteHandshakeChallenge[ii]); + } + printf("\n"); +#endif + } + } +#endif // LIBCAT_SECURITY + + bs.Read(bindingAddress); + uint16_t mtu; + bs.Read(mtu); + bs.Read(guid); + + RakPeer::RemoteSystemStruct *rssFromSA = rakPeer->GetRemoteSystemFromSystemAddress( systemAddress, true, true ); + bool IPAddrInUse = rssFromSA != 0 && rssFromSA->isActive; + RakPeer::RemoteSystemStruct *rssFromGuid = rakPeer->GetRemoteSystemFromGUID(guid, true); + bool GUIDInUse = rssFromGuid != 0 && rssFromGuid->isActive; + + // IPAddrInUse, GuidInUse, outcome + // TRUE, , TRUE , ID_OPEN_CONNECTION_REPLY if they are the same, else ID_ALREADY_CONNECTED + // FALSE, , TRUE , ID_ALREADY_CONNECTED (someone else took this guid) + // TRUE, , FALSE , ID_ALREADY_CONNECTED (silently disconnected, restarted rakNet) + // FALSE , FALSE , Allow connection + + int outcome; + if (IPAddrInUse & GUIDInUse) + { + if (rssFromSA==rssFromGuid && rssFromSA->connectMode==RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER) + { + // ID_OPEN_CONNECTION_REPLY if they are the same + outcome=1; + + // Note to self: If REQUESTED_CONNECTION, this means two systems attempted to connect to each other at the same time, and one finished first. + // Returns ID)_CONNECTION_REQUEST_ACCEPTED to one system, and ID_ALREADY_CONNECTED followed by ID_NEW_INCOMING_CONNECTION to another + } + else + { + // ID_ALREADY_CONNECTED (restarted raknet, connected again from same ip, plus someone else took this guid) + outcome=2; + } + } + else if (IPAddrInUse==false && GUIDInUse==true) + { + // ID_ALREADY_CONNECTED (someone else took this guid) + outcome=3; + } + else if (IPAddrInUse==true && GUIDInUse==false) + { + // ID_ALREADY_CONNECTED (silently disconnected, restarted rakNet) + outcome=4; + } + else + { + // Allow connection + outcome=0; + } + + RakNet::BitStream bsAnswer; + bsAnswer.Write((MessageID)ID_OPEN_CONNECTION_REPLY_2); + bsAnswer.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bsAnswer.Write(rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)); + bsAnswer.Write(systemAddress); + bsAnswer.Write(mtu); + bsAnswer.Write(requiresSecurityOfThisClient); + + if (outcome==1) + { + // Duplicate connection request packet from packetloss + // Send back the same answer +#if LIBCAT_SECURITY==1 + if (requiresSecurityOfThisClient) + { + CAT_AUDIT_PRINTF("AUDIT: Resending public key and answer from packetloss. Sending ID_OPEN_CONNECTION_REPLY_2\n"); + bsAnswer.WriteAlignedBytes((const unsigned char *) rssFromSA->answer,sizeof(rssFromSA->answer)); + } +#endif // LIBCAT_SECURITY + + unsigned int i; + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBitsUsed(), systemAddress); + // SocketLayer::SendTo( rakNetSocket, (const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) bsAnswer.GetData(); + bsp.length = bsAnswer.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + + return true; + } + else if (outcome!=0) + { + bsOut.Write((MessageID)ID_ALREADY_CONNECTED); + bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bsOut.Write(rakPeer->myGuid); + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); + // SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + RNS2_SendParameters bsp; + bsp.data = (char*) bsOut.GetData(); + bsp.length = bsOut.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + + return true; + } + + if (rakPeer->AllowIncomingConnections()==false) + { + bsOut.Write((MessageID)ID_NO_FREE_INCOMING_CONNECTIONS); + bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bsOut.Write(rakPeer->myGuid); + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); + //SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + RNS2_SendParameters bsp; + bsp.data = (char*) bsOut.GetData(); + bsp.length = bsOut.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + + return true; + } + + bool thisIPConnectedRecently=false; + rssFromSA = rakPeer->AssignSystemAddressToRemoteSystemList(systemAddress, RakPeer::RemoteSystemStruct::UNVERIFIED_SENDER, rakNetSocket, &thisIPConnectedRecently, bindingAddress, mtu, guid, requiresSecurityOfThisClient); + + if (thisIPConnectedRecently==true) + { + bsOut.Write((MessageID)ID_IP_RECENTLY_CONNECTED); + bsOut.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bsOut.Write(rakPeer->myGuid); + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsOut.GetData(), bsOut.GetNumberOfBitsUsed(), systemAddress); + //SocketLayer::SendTo( rakNetSocket, (const char*) bsOut.GetData(), bsOut.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) bsOut.GetData(); + bsp.length = bsOut.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + + return true; + } + +#if LIBCAT_SECURITY==1 + if (requiresSecurityOfThisClient) + { + CAT_AUDIT_PRINTF("AUDIT: Writing public key. Sending ID_OPEN_CONNECTION_REPLY_2\n"); + if (rakPeer->_server_handshake->ProcessChallenge(remoteHandshakeChallenge, rssFromSA->answer, rssFromSA->reliabilityLayer.GetAuthenticatedEncryption() )) + { + CAT_AUDIT_PRINTF("AUDIT: Challenge good!\n"); + // Keep going to OK block + } + else + { + CAT_AUDIT_PRINTF("AUDIT: Challenge BAD!\n"); + + // Unassign this remote system + rakPeer->DereferenceRemoteSystem(systemAddress); + return true; + } + + bsAnswer.WriteAlignedBytes((const unsigned char *) rssFromSA->answer,sizeof(rssFromSA->answer)); + } +#endif // LIBCAT_SECURITY + + unsigned int i; + for (i=0; i < rakPeer->pluginListNTS.Size(); i++) + rakPeer->pluginListNTS[i]->OnDirectSocketSend((const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBitsUsed(), systemAddress); + // SocketLayer::SendTo( rakNetSocket, (const char*) bsAnswer.GetData(), bsAnswer.GetNumberOfBytesUsed(), systemAddress, _FILE_AND_LINE_ ); + RNS2_SendParameters bsp; + bsp.data = (char*) bsAnswer.GetData(); + bsp.length = bsAnswer.GetNumberOfBytesUsed(); + bsp.systemAddress = systemAddress; + rakNetSocket->Send(&bsp, _FILE_AND_LINE_); + } + return true; + } + + return false; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void ProcessNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNet::TimeUS timeRead, BitStream &updateBitStream ) +{ + ProcessNetworkPacket(systemAddress,data,length,rakPeer,rakPeer->socketList[0],timeRead, updateBitStream); +} +void ProcessNetworkPacket( SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket2* rakNetSocket, RakNet::TimeUS timeRead, BitStream &updateBitStream ) +{ +#if LIBCAT_SECURITY==1 +#ifdef CAT_AUDIT + printf("AUDIT: RECV "); + for (int ii = 0; ii < length; ++ii) + { + printf("%02x", (cat::u8)data[ii]); + } + printf("\n"); +#endif +#endif // LIBCAT_SECURITY + + RakAssert(systemAddress.GetPort()); + bool isOfflineMessage; + if (ProcessOfflineNetworkPacket(systemAddress, data, length, rakPeer, rakNetSocket, &isOfflineMessage, timeRead)) + { + return; + } + +// RakNet::Packet *packet; + RakPeer::RemoteSystemStruct *remoteSystem; + + // See if this datagram came from a connected system + remoteSystem = rakPeer->GetRemoteSystemFromSystemAddress( systemAddress, true, true ); + if ( remoteSystem ) + { + // Handle regular incoming data + // HandleSocketReceiveFromConnectedPlayer is only safe to be called from the same thread as Update, which is this thread + if ( isOfflineMessage==false) + { + remoteSystem->reliabilityLayer.HandleSocketReceiveFromConnectedPlayer( + data, length, systemAddress, rakPeer->pluginListNTS, remoteSystem->MTUSize, + rakNetSocket, &rnr, timeRead, updateBitStream); + } + } + else + { + // int a=5; + // printf("--- Packet from unknown system %s\n", systemAddress.ToString()); + } +} + +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GenerateSeedFromGuid(void) +{ + /* + // Construct a random seed based on the initial guid value, and the last digits of the difference to each subsequent number + // This assumes that only the last 3 bits of each guidId integer has a meaningful amount of randomness between it and the prior number + unsigned int t = guid.g[0]; + unsigned int i; + for (i=1; i < sizeof(guid.g) / sizeof(guid.g[0]); i++) + { + unsigned int diff = guid.g[i]-guid.g[i-1]; + unsigned int diff3Bits = diff & 0x0007; + diff3Bits <<= 29; + diff3Bits >>= (i-1)*3; + t ^= diff3Bits; + } + + return t; + */ + return (unsigned int) ((myGuid.g >> 32) ^ myGuid.g); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void RakPeer::DerefAllSockets(void) +{ + unsigned int i; + for (i=0; i < socketList.Size(); i++) + { + delete socketList[i]; + } + socketList.Clear(false, _FILE_AND_LINE_); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +unsigned int RakPeer::GetRakNetSocketFromUserConnectionSocketIndex(unsigned int userIndex) const +{ + unsigned int i; + for (i=0; i < socketList.Size(); i++) + { + if (socketList[i]->GetUserConnectionSocketIndex()==userIndex) + return i; + } + RakAssert("GetRakNetSocketFromUserConnectionSocketIndex failed" && 0); + return (unsigned int) -1; +} + +/* +// DS_APR +void RakPeer::ProcessChromePacket(RakNetSocket2 *s, const char *buffer, int dataSize, const SystemAddress& recvFromAddress, RakNet::TimeUS timeRead) +{ + RakAssert(buffer); + RakAssert(dataSize > 0); + RakAssert(recvFromAddress.GetPort()); + + RNS2RecvStruct *recvFromStruct; + recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); + RakAssert(dataSize <= (int)sizeof(recvFromStruct->data)); + memcpy(recvFromStruct->data, buffer, dataSize); + recvFromStruct->bytesRead=dataSize; + recvFromStruct->systemAddress=recvFromAddress; + recvFromStruct->timeRead=timeRead; + bufferedPackets.Push(recvFromStruct); +} +*/ + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +/* +bool RakPeer::RunRecvFromOnce( RakNetSocket *s ) +{ + RakPeer::RecvFromStruct *recvFromStruct; + + recvFromStruct=bufferedPackets.Allocate( _FILE_AND_LINE_ ); + if (recvFromStruct != NULL) + { + recvFromStruct->s=s; + SocketLayer::RecvFromBlocking(s, this, recvFromStruct->data, &recvFromStruct->bytesRead, &recvFromStruct->systemAddress, &recvFromStruct->timeRead); + + if (recvFromStruct->bytesRead>0) + { + RakAssert(recvFromStruct->systemAddress.GetPort()); + bufferedPackets.Push(recvFromStruct); + quitAndDataEvents.SetEvent(); + + // Got data + return true; + } + else + { + bufferedPackets.Deallocate(recvFromStruct, _FILE_AND_LINE_); + } + } + // No data + return false; +} +*/ +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +bool RakPeer::RunUpdateCycle(BitStream &updateBitStream ) +{ + RakPeer::RemoteSystemStruct * remoteSystem; + unsigned int activeSystemListIndex; + Packet *packet; + // int currentSentBytes,currentReceivedBytes; +// unsigned numberOfBytesUsed; +// BitSize_t numberOfBitsUsed; + //SystemAddress authoritativeClientSystemAddress; + BitSize_t bitSize; + unsigned int byteSize; + unsigned char *data; + SystemAddress systemAddress; + BufferedCommandStruct *bcs; + bool callerDataAllocationUsed; + RakNetStatistics *rnss; + RakNet::TimeUS timeNS=0; + RakNet::Time timeMS=0; + + // This is here so RecvFromBlocking actually gets data from the same thread + + #if defined(WINDOWS_STORE_RT) + #elif defined(_WIN32) + if (socketList[0]->GetSocketType()==RNS2T_WINDOWS && ((RNS2_Windows*)socketList[0])->GetSocketLayerOverride()) + { + int len; + SystemAddress sender; + char dataOut[ MAXIMUM_MTU_SIZE ]; + do { + len = ((RNS2_Windows*)socketList[0])->GetSocketLayerOverride()->RakNetRecvFrom(dataOut,&sender,true); + if (len>0) + ProcessNetworkPacket( sender, dataOut, len, this, socketList[0], RakNet::GetTimeUS(), updateBitStream ); + } while (len>0); + } + #endif + +// unsigned int socketListIndex; + RNS2RecvStruct *recvFromStruct; + while ((recvFromStruct=PopBufferedPacket())!=0) + { + /* + for (socketListIndex=0; socketListIndex < socketList.Size(); socketListIndex++) + { + if ((RakNetSocket*) socketList[socketListIndex]==recvFromStruct->s) + break; + } + if (socketListIndex!=socketList.Size()) + */ + ProcessNetworkPacket(recvFromStruct->systemAddress, recvFromStruct->data, recvFromStruct->bytesRead, this, recvFromStruct->socket, recvFromStruct->timeRead, updateBitStream); + DeallocRNS2RecvStruct(recvFromStruct, _FILE_AND_LINE_); + } + + while ((bcs=bufferedCommands.PopInaccurate())!=0) + { + if (bcs->command==BufferedCommandStruct::BCS_SEND) + { + // GetTime is a very slow call so do it once and as late as possible + if (timeNS==0) + { + timeNS = RakNet::GetTimeUS(); + timeMS = (RakNet::TimeMS)(timeNS/(RakNet::TimeUS)1000); + } + + callerDataAllocationUsed=SendImmediate((char*)bcs->data, bcs->numberOfBitsToSend, bcs->priority, bcs->reliability, bcs->orderingChannel, bcs->systemIdentifier, bcs->broadcast, true, timeNS, bcs->receipt); + if ( callerDataAllocationUsed==false ) + rakFree_Ex(bcs->data, _FILE_AND_LINE_ ); + + // Set the new connection state AFTER we call sendImmediate in case we are setting it to a disconnection state, which does not allow further sends + if (bcs->connectionMode!=RemoteSystemStruct::NO_ACTION ) + { + remoteSystem=GetRemoteSystem( bcs->systemIdentifier, true, true ); + if (remoteSystem) + remoteSystem->connectMode=bcs->connectionMode; + } + } + else if (bcs->command==BufferedCommandStruct::BCS_CLOSE_CONNECTION) + { + CloseConnectionInternal(bcs->systemIdentifier, false, true, bcs->orderingChannel, bcs->priority); + } + else if (bcs->command==BufferedCommandStruct::BCS_CHANGE_SYSTEM_ADDRESS) + { + // Reroute + RakPeer::RemoteSystemStruct *rssFromGuid = GetRemoteSystem(bcs->systemIdentifier.rakNetGuid,true,true); + if (rssFromGuid!=0) + { + unsigned int existingSystemIndex = GetRemoteSystemIndex(rssFromGuid->systemAddress); + ReferenceRemoteSystem(bcs->systemIdentifier.systemAddress, existingSystemIndex); + } + } + else if (bcs->command==BufferedCommandStruct::BCS_GET_SOCKET) + { + SocketQueryOutput *sqo; + if (bcs->systemIdentifier.IsUndefined()) + { + sqo = socketQueryOutput.Allocate( _FILE_AND_LINE_ ); + sqo->sockets=socketList; + socketQueryOutput.Push(sqo); + } + else + { + remoteSystem=GetRemoteSystem( bcs->systemIdentifier, true, true ); + sqo = socketQueryOutput.Allocate( _FILE_AND_LINE_ ); + + sqo->sockets.Clear(false, _FILE_AND_LINE_); + if (remoteSystem) + { + sqo->sockets.Push(remoteSystem->rakNetSocket, _FILE_AND_LINE_ ); + } + else + { + // Leave empty smart pointer + } + socketQueryOutput.Push(sqo); + } + + } + +#ifdef _DEBUG + bcs->data=0; +#endif + + bufferedCommands.Deallocate(bcs, _FILE_AND_LINE_); + } + + if (requestedConnectionQueue.IsEmpty()==false) + { + if (timeNS==0) + { + timeNS = RakNet::GetTimeUS(); + timeMS = (RakNet::TimeMS)(timeNS/(RakNet::TimeUS)1000); + } + + bool condition1, condition2; + unsigned requestedConnectionQueueIndex=0; + requestedConnectionQueueMutex.Lock(); + while (requestedConnectionQueueIndex < requestedConnectionQueue.Size()) + { + RequestedConnectionStruct *rcs; + rcs = requestedConnectionQueue[requestedConnectionQueueIndex]; + requestedConnectionQueueMutex.Unlock(); + if (rcs->nextRequestTime < timeMS) + { + condition1=rcs->requestsMade==rcs->sendConnectionAttemptCount+1; + condition2=(bool)((rcs->systemAddress==UNASSIGNED_SYSTEM_ADDRESS)==1); + // If too many requests made or a hole then remove this if possible, otherwise invalidate it + if (condition1 || condition2) + { + if (rcs->data) + { + rakFree_Ex(rcs->data, _FILE_AND_LINE_ ); + rcs->data=0; + } + + if (condition1 && !condition2 && rcs->actionToTake==RequestedConnectionStruct::CONNECT) + { + // Tell user of connection attempt failed + packet=AllocPacket(sizeof( char ), _FILE_AND_LINE_); + packet->data[ 0 ] = ID_CONNECTION_ATTEMPT_FAILED; // Attempted a connection and couldn't + packet->bitSize = ( sizeof( char ) * 8); + packet->systemAddress = rcs->systemAddress; + AddPacketToProducer(packet); + } + +#if LIBCAT_SECURITY==1 + CAT_AUDIT_PRINTF("AUDIT: Connection attempt FAILED so deleting rcs->client_handshake object %x\n", rcs->client_handshake); + RakNet::OP_DELETE(rcs->client_handshake,_FILE_AND_LINE_); +#endif + RakNet::OP_DELETE(rcs,_FILE_AND_LINE_); + + requestedConnectionQueueMutex.Lock(); + for (unsigned int k=0; k < requestedConnectionQueue.Size(); k++) + { + if (requestedConnectionQueue[k]==rcs) + { + requestedConnectionQueue.RemoveAtIndex(k); + break; + } + } + requestedConnectionQueueMutex.Unlock(); + } + else + { + + int MTUSizeIndex = rcs->requestsMade / (rcs->sendConnectionAttemptCount/NUM_MTU_SIZES); + if (MTUSizeIndex>=NUM_MTU_SIZES) + MTUSizeIndex=NUM_MTU_SIZES-1; + rcs->requestsMade++; + rcs->nextRequestTime=timeMS+rcs->timeBetweenSendConnectionAttemptsMS; + + RakNet::BitStream bitStream; + //WriteOutOfBandHeader(&bitStream, ID_USER_PACKET_ENUM); + bitStream.Write((MessageID)ID_OPEN_CONNECTION_REQUEST_1); + bitStream.WriteAlignedBytes((const unsigned char*) OFFLINE_MESSAGE_DATA_ID, sizeof(OFFLINE_MESSAGE_DATA_ID)); + bitStream.Write((MessageID)RAKNET_PROTOCOL_VERSION); + bitStream.PadWithZeroToByteLength(mtuSizes[MTUSizeIndex]-UDP_HEADER_SIZE); + + char str[256]; + rcs->systemAddress.ToString(true,str); + + //RAKNET_DEBUG_PRINTF("%i:IOCR, ", __LINE__); + + unsigned i; + for (i=0; i < pluginListNTS.Size(); i++) + pluginListNTS[i]->OnDirectSocketSend((const char*) bitStream.GetData(), bitStream.GetNumberOfBitsUsed(), rcs->systemAddress); + + RakNetSocket2 *socketToUse; + if (rcs->socket == 0) + socketToUse = socketList[rcs->socketIndex]; + else + socketToUse = rcs->socket; + + rcs->systemAddress.FixForIPVersion(socketToUse->GetBoundAddress()); +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + if (socketToUse->IsBerkleySocket()) + ((RNS2_Berkley*)socketToUse)->SetDoNotFragment(1); +#endif + +// SocketLayer::SetDoNotFragment(socketToUse, 1); + RakNet::Time sendToStart=RakNet::GetTime(); + + RNS2_SendParameters bsp; + bsp.data = (char*) bitStream.GetData(); + bsp.length = bitStream.GetNumberOfBytesUsed(); + bsp.systemAddress = rcs->systemAddress; + if (socketToUse->Send(&bsp, _FILE_AND_LINE_) == 10040) + // if (SocketLayer::SendTo( socketToUse, (const char*) bitStream.GetData(), bitStream.GetNumberOfBytesUsed(), rcs->systemAddress, _FILE_AND_LINE_ )==-10040) + { + // Don't use this MTU size again + rcs->requestsMade = (unsigned char) ((MTUSizeIndex + 1) * (rcs->sendConnectionAttemptCount/NUM_MTU_SIZES)); + rcs->nextRequestTime=timeMS; + } + else + { + RakNet::Time sendToEnd=RakNet::GetTime(); + if (sendToEnd-sendToStart>100) + { + // Drop to lowest MTU + int lowestMtuIndex = rcs->sendConnectionAttemptCount/NUM_MTU_SIZES * (NUM_MTU_SIZES - 1); + if (lowestMtuIndex > rcs->requestsMade) + { + rcs->requestsMade = (unsigned char) lowestMtuIndex; + rcs->nextRequestTime=timeMS; + } + else + rcs->requestsMade=(unsigned char)(rcs->sendConnectionAttemptCount+1); + } + } + // SocketLayer::SetDoNotFragment(socketToUse, 0); +#if !defined(__native_client__) && !defined(WINDOWS_STORE_RT) + if (socketToUse->IsBerkleySocket()) + ((RNS2_Berkley*)socketToUse)->SetDoNotFragment(0); +#endif + + requestedConnectionQueueIndex++; + } + } + else + requestedConnectionQueueIndex++; + + requestedConnectionQueueMutex.Lock(); + } + requestedConnectionQueueMutex.Unlock(); + } + + // remoteSystemList in network thread + for ( activeSystemListIndex = 0; activeSystemListIndex < activeSystemListSize; ++activeSystemListIndex ) + //for ( remoteSystemIndex = 0; remoteSystemIndex < remoteSystemListSize; ++remoteSystemIndex ) + { + // I'm using systemAddress from remoteSystemList but am not locking it because this loop is called very frequently and it doesn't + // matter if we miss or do an extra update. The reliability layers themselves never care which player they are associated with + //systemAddress = remoteSystemList[ remoteSystemIndex ].systemAddress; + // Allow the systemAddress for this remote system list to change. We don't care if it changes now. + // remoteSystemList[ remoteSystemIndex ].allowSystemAddressAssigment=true; + + + // Found an active remote system + remoteSystem = activeSystemList[ activeSystemListIndex ]; + systemAddress = remoteSystem->systemAddress; + RakAssert(systemAddress!=UNASSIGNED_SYSTEM_ADDRESS); + // Update is only safe to call from the same thread that calls HandleSocketReceiveFromConnectedPlayer, + // which is this thread + + if (timeNS==0) + { + timeNS = RakNet::GetTimeUS(); + timeMS = (RakNet::TimeMS)(timeNS/(RakNet::TimeUS)1000); + //RAKNET_DEBUG_PRINTF("timeNS = %I64i timeMS=%i\n", timeNS, timeMS); + } + + + if (timeMS > remoteSystem->lastReliableSend && timeMS-remoteSystem->lastReliableSend > remoteSystem->reliabilityLayer.GetTimeoutTime()/2 && remoteSystem->connectMode==RemoteSystemStruct::CONNECTED) + { + // If no reliable packets are waiting for an ack, do a one byte reliable send so that disconnections are noticed + RakNetStatistics rakNetStatistics; + rnss=remoteSystem->reliabilityLayer.GetStatistics(&rakNetStatistics); + if (rnss->messagesInResendBuffer==0) + { + PingInternal( systemAddress, true, RELIABLE ); + + //remoteSystem->lastReliableSend=timeMS+remoteSystem->reliabilityLayer.GetTimeoutTime(); + remoteSystem->lastReliableSend=timeMS; + } + } + + remoteSystem->reliabilityLayer.Update( remoteSystem->rakNetSocket, systemAddress, remoteSystem->MTUSize, timeNS, maxOutgoingBPS, pluginListNTS, &rnr, updateBitStream ); // systemAddress only used for the internet simulator test + + // Check for failure conditions + if ( remoteSystem->reliabilityLayer.IsDeadConnection() || + ((remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ASAP || remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY) && remoteSystem->reliabilityLayer.IsOutgoingDataWaiting()==false) || + (remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ON_NO_ACK && (remoteSystem->reliabilityLayer.AreAcksWaiting()==false || remoteSystem->reliabilityLayer.AckTimeout(timeMS)==true)) || + (( + (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION || + remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST || + remoteSystem->connectMode==RemoteSystemStruct::UNVERIFIED_SENDER) + && timeMS > remoteSystem->connectionTime && timeMS - remoteSystem->connectionTime > 10000)) + ) + { + // RAKNET_DEBUG_PRINTF("timeMS=%i remoteSystem->connectionTime=%i\n", timeMS, remoteSystem->connectionTime ); + + // Failed. Inform the user? + // TODO - RakNet 4.0 - Return a different message identifier for DISCONNECT_ASAP_SILENTLY and DISCONNECT_ASAP than for DISCONNECT_ON_NO_ACK + // The first two mean we called CloseConnection(), the last means the other system sent us ID_DISCONNECTION_NOTIFICATION + if (remoteSystem->connectMode==RemoteSystemStruct::CONNECTED || remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION + || remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ASAP || remoteSystem->connectMode==RemoteSystemStruct::DISCONNECT_ON_NO_ACK) + { + +// RakNet::BitStream undeliveredMessages; +// remoteSystem->reliabilityLayer.GetUndeliveredMessages(&undeliveredMessages,remoteSystem->MTUSize); + +// packet=AllocPacket(sizeof( char ) + undeliveredMessages.GetNumberOfBytesUsed()); + packet=AllocPacket(sizeof( char ), _FILE_AND_LINE_); + if (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION) + packet->data[ 0 ] = ID_CONNECTION_ATTEMPT_FAILED; // Attempted a connection and couldn't + else if (remoteSystem->connectMode==RemoteSystemStruct::CONNECTED) + packet->data[ 0 ] = ID_CONNECTION_LOST; // DeadConnection + else + packet->data[ 0 ] = ID_DISCONNECTION_NOTIFICATION; // DeadConnection + +// memcpy(packet->data+1, undeliveredMessages.GetData(), undeliveredMessages.GetNumberOfBytesUsed()); + + packet->guid = remoteSystem->guid; + packet->systemAddress = systemAddress; + packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; + packet->guid.systemIndex=packet->systemAddress.systemIndex; + + AddPacketToProducer(packet); + } + // else connection shutting down, don't bother telling the user + +#ifdef _DO_PRINTF + RAKNET_DEBUG_PRINTF("Connection dropped for player %i:%i\n", systemAddress); +#endif + CloseConnectionInternal( systemAddress, false, true, 0, LOW_PRIORITY ); + continue; + } + + // Ping this guy if it is time to do so + if ( remoteSystem->connectMode==RemoteSystemStruct::CONNECTED && timeMS > remoteSystem->nextPingTime && ( occasionalPing || remoteSystem->lowestPing == (unsigned short)-1 ) ) + { + remoteSystem->nextPingTime = timeMS + 5000; + PingInternal( systemAddress, true, UNRELIABLE ); + + // Update again immediately after this tick so the ping goes out right away + quitAndDataEvents.SetEvent(); + } + + // Find whoever has the lowest player ID + //if (systemAddress < authoritativeClientSystemAddress) + // authoritativeClientSystemAddress=systemAddress; + + // Does the reliability layer have any packets waiting for us? + // To be thread safe, this has to be called in the same thread as HandleSocketReceiveFromConnectedPlayer + bitSize = remoteSystem->reliabilityLayer.Receive( &data ); + + while ( bitSize > 0 ) + { + // These types are for internal use and should never arrive from a network packet + if (data[0]==ID_CONNECTION_ATTEMPT_FAILED) + { + RakAssert(0); + bitSize=0; + continue; + } + + // Fast and easy - just use the data that was returned + byteSize = (unsigned int) BITS_TO_BYTES( bitSize ); + + // For unknown senders we only accept a few specific packets + if (remoteSystem->connectMode==RemoteSystemStruct::UNVERIFIED_SENDER) + { + if ( (unsigned char)(data)[0] == ID_CONNECTION_REQUEST ) + { + ParseConnectionRequestPacket(remoteSystem, systemAddress, (const char*)data, byteSize); + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + else + { + CloseConnectionInternal( systemAddress, false, true, 0, LOW_PRIORITY ); +#ifdef _DO_PRINTF + RAKNET_DEBUG_PRINTF("Temporarily banning %i:%i for sending nonsense data\n", systemAddress); +#endif + + char str1[64]; + systemAddress.ToString(false, str1); + AddToBanList(str1, remoteSystem->reliabilityLayer.GetTimeoutTime()); + + + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + } + else + { + // However, if we are connected we still take a connection request in case both systems are trying to connect to each other + // at the same time + if ( (unsigned char)(data)[0] == ID_CONNECTION_REQUEST ) + { + // 04/27/06 This is wrong. With cross connections, we can both have initiated the connection are in state REQUESTED_CONNECTION + // 04/28/06 Downgrading connections from connected will close the connection due to security at ((remoteSystem->connectMode!=RemoteSystemStruct::CONNECTED && time > remoteSystem->connectionTime && time - remoteSystem->connectionTime > 10000)) + if (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION) + { + ParseConnectionRequestPacket(remoteSystem, systemAddress, (const char*)data, byteSize); + } + else + { + + RakNet::BitStream bs((unsigned char*) data,byteSize,false); + bs.IgnoreBytes(sizeof(MessageID)); + bs.IgnoreBytes(sizeof(OFFLINE_MESSAGE_DATA_ID)); + bs.IgnoreBytes(RakNetGUID::size()); + RakNet::Time incomingTimestamp; + bs.Read(incomingTimestamp); + + // Got a connection request message from someone we are already connected to. Just reply normally. + // This can happen due to race conditions with the fully connected mesh + OnConnectionRequest( remoteSystem, incomingTimestamp ); + } + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + else if ( (unsigned char) data[ 0 ] == ID_NEW_INCOMING_CONNECTION && byteSize > sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned short)+sizeof(RakNet::Time)*2 ) + { + if (remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST) + { + remoteSystem->connectMode=RemoteSystemStruct::CONNECTED; + PingInternal( systemAddress, true, UNRELIABLE ); + + // Update again immediately after this tick so the ping goes out right away + quitAndDataEvents.SetEvent(); + + RakNet::BitStream inBitStream((unsigned char *) data, byteSize, false); + SystemAddress bsSystemAddress; + + inBitStream.IgnoreBits(8); + inBitStream.Read(bsSystemAddress); + for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + inBitStream.Read(remoteSystem->theirInternalSystemAddress[i]); + + RakNet::Time sendPingTime, sendPongTime; + inBitStream.Read(sendPingTime); + inBitStream.Read(sendPongTime); + OnConnectedPong(sendPingTime,sendPongTime,remoteSystem); + + // Overwrite the data in the packet + // NewIncomingConnectionStruct newIncomingConnectionStruct; + // RakNet::BitStream nICS_BS( data, NewIncomingConnectionStruct_Size, false ); + // newIncomingConnectionStruct.Deserialize( nICS_BS ); + + remoteSystem->myExternalSystemAddress = bsSystemAddress; + + // Bug: If A connects to B through R, A's firstExternalID is set to R. If A tries to send to R, sends to loopback because R==firstExternalID + // Correct fix is to specify in Connect() if target is through a proxy. + // However, in practice you have to connect to something else first anyway to know about the proxy. So setting once only is good enough + if (firstExternalID==UNASSIGNED_SYSTEM_ADDRESS) + { + firstExternalID=bsSystemAddress; + firstExternalID.debugPort=ntohs(firstExternalID.address.addr4.sin_port); + } + + // Send this info down to the game + packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); + packet->bitSize = bitSize; + packet->systemAddress = systemAddress; + packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; + packet->guid = remoteSystem->guid; + packet->guid.systemIndex=packet->systemAddress.systemIndex; + AddPacketToProducer(packet); + } + else + { + // Send to game even if already connected. This could happen when connecting to 127.0.0.1 + // Ignore, already connected + // rakFree_Ex(data, _FILE_AND_LINE_ ); + } + } + else if ( (unsigned char) data[ 0 ] == ID_CONNECTED_PONG && byteSize == sizeof(unsigned char)+sizeof(RakNet::Time)*2 ) + { + RakNet::Time sendPingTime, sendPongTime; + + // Copy into the ping times array the current time - the value returned + // First extract the sent ping + RakNet::BitStream inBitStream( (unsigned char *) data, byteSize, false ); + //PingStruct ps; + //ps.Deserialize(psBS); + inBitStream.IgnoreBits(8); + inBitStream.Read(sendPingTime); + inBitStream.Read(sendPongTime); + + OnConnectedPong(sendPingTime,sendPongTime,remoteSystem); + + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + else if ( (unsigned char)data[0] == ID_CONNECTED_PING && byteSize == sizeof(unsigned char)+sizeof(RakNet::Time) ) + { + RakNet::BitStream inBitStream( (unsigned char *) data, byteSize, false ); + inBitStream.IgnoreBits(8); + RakNet::Time sendPingTime; + inBitStream.Read(sendPingTime); + + RakNet::BitStream outBitStream; + outBitStream.Write((MessageID)ID_CONNECTED_PONG); + outBitStream.Write(sendPingTime); + outBitStream.Write(RakNet::GetTime()); + SendImmediate( (char*)outBitStream.GetData(), outBitStream.GetNumberOfBitsUsed(), IMMEDIATE_PRIORITY, UNRELIABLE, 0, systemAddress, false, false, RakNet::GetTimeUS(), 0 ); + + // Update again immediately after this tick so the ping goes out right away + quitAndDataEvents.SetEvent(); + + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + else if ( (unsigned char) data[ 0 ] == ID_DISCONNECTION_NOTIFICATION ) + { + // We shouldn't close the connection immediately because we need to ack the ID_DISCONNECTION_NOTIFICATION + remoteSystem->connectMode=RemoteSystemStruct::DISCONNECT_ON_NO_ACK; + rakFree_Ex(data, _FILE_AND_LINE_ ); + + // AddPacketToProducer(packet); + } + else if ( (unsigned char)(data)[0] == ID_DETECT_LOST_CONNECTIONS && byteSize == sizeof(unsigned char) ) + { + // Do nothing + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + else if ( (unsigned char)(data)[0] == ID_INVALID_PASSWORD ) + { + if (remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION) + { + packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); + packet->bitSize = bitSize; + packet->systemAddress = systemAddress; + packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; + packet->guid = remoteSystem->guid; + packet->guid.systemIndex=packet->systemAddress.systemIndex; + AddPacketToProducer(packet); + + remoteSystem->connectMode=RemoteSystemStruct::DISCONNECT_ASAP_SILENTLY; + } + else + { + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + } + else if ( (unsigned char)(data)[0] == ID_CONNECTION_REQUEST_ACCEPTED ) + { + if (byteSize > sizeof(MessageID)+sizeof(unsigned int)+sizeof(unsigned short)+sizeof(SystemIndex)+sizeof(RakNet::Time)*2) + { + // Make sure this connection accept is from someone we wanted to connect to + bool allowConnection, alreadyConnected; + + if (remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST || + remoteSystem->connectMode==RemoteSystemStruct::REQUESTED_CONNECTION || + allowConnectionResponseIPMigration) + allowConnection=true; + else + allowConnection=false; + + if (remoteSystem->connectMode==RemoteSystemStruct::HANDLING_CONNECTION_REQUEST) + alreadyConnected=true; + else + alreadyConnected=false; + + if ( allowConnection ) + { + SystemAddress externalID; + SystemIndex systemIndex; +// SystemAddress internalID; + + RakNet::BitStream inBitStream((unsigned char *) data, byteSize, false); + inBitStream.IgnoreBits(8); + // inBitStream.Read(remotePort); + inBitStream.Read(externalID); + inBitStream.Read(systemIndex); + for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + inBitStream.Read(remoteSystem->theirInternalSystemAddress[i]); + + RakNet::Time sendPingTime, sendPongTime; + inBitStream.Read(sendPingTime); + inBitStream.Read(sendPongTime); + OnConnectedPong(sendPingTime, sendPongTime, remoteSystem); + + // Find a free remote system struct to use + // RakNet::BitStream casBitS(data, byteSize, false); + // ConnectionAcceptStruct cas; + // cas.Deserialize(casBitS); + // systemAddress.GetPort() = remotePort; + + // The remote system told us our external IP, so save it + remoteSystem->myExternalSystemAddress = externalID; + remoteSystem->connectMode=RemoteSystemStruct::CONNECTED; + + // Bug: If A connects to B through R, A's firstExternalID is set to R. If A tries to send to R, sends to loopback because R==firstExternalID + // Correct fix is to specify in Connect() if target is through a proxy. + // However, in practice you have to connect to something else first anyway to know about the proxy. So setting once only is good enough + if (firstExternalID==UNASSIGNED_SYSTEM_ADDRESS) + { + firstExternalID=externalID; + firstExternalID.debugPort=ntohs(firstExternalID.address.addr4.sin_port); + } + + // Send the connection request complete to the game + packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); + packet->bitSize = byteSize * 8; + packet->systemAddress = systemAddress; + packet->systemAddress.systemIndex = ( SystemIndex ) GetIndexFromSystemAddress( systemAddress, true ); + packet->guid = remoteSystem->guid; + packet->guid.systemIndex=packet->systemAddress.systemIndex; + AddPacketToProducer(packet); + + RakNet::BitStream outBitStream; + outBitStream.Write((MessageID)ID_NEW_INCOMING_CONNECTION); + outBitStream.Write(systemAddress); + for (unsigned int i=0; i < MAXIMUM_NUMBER_OF_INTERNAL_IDS; i++) + outBitStream.Write(ipList[i]); + outBitStream.Write(sendPongTime); + outBitStream.Write(RakNet::GetTime()); + + SendImmediate( (char*)outBitStream.GetData(), outBitStream.GetNumberOfBitsUsed(), IMMEDIATE_PRIORITY, RELIABLE_ORDERED, 0, systemAddress, false, false, RakNet::GetTimeUS(), 0 ); + + if (alreadyConnected==false) + { + PingInternal( systemAddress, true, UNRELIABLE ); + } + } + else + { + // Ignore, already connected + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + } + else + { + // Version mismatch error? + RakAssert(0); + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + } + else + { + // What do I do if I get a message from a system, before I am fully connected? + // I can either ignore it or give it to the user + // It seems like giving it to the user is a better option + if ((data[0]>=(MessageID)ID_TIMESTAMP || data[0]==ID_SND_RECEIPT_ACKED || data[0]==ID_SND_RECEIPT_LOSS) && + remoteSystem->isActive + ) + { + packet=AllocPacket(byteSize, data, _FILE_AND_LINE_); + packet->bitSize = bitSize; + packet->systemAddress = systemAddress; + packet->systemAddress.systemIndex = remoteSystem->remoteSystemIndex; + packet->guid = remoteSystem->guid; + packet->guid.systemIndex=packet->systemAddress.systemIndex; + AddPacketToProducer(packet); + } + else + { + rakFree_Ex(data, _FILE_AND_LINE_ ); + } + } + } + + // Does the reliability layer have any more packets waiting for us? + // To be thread safe, this has to be called in the same thread as HandleSocketReceiveFromConnectedPlayer + bitSize = remoteSystem->reliabilityLayer.Receive( &data ); + } + + } + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void RakPeer::OnRNS2Recv(RNS2RecvStruct *recvStruct) +{ + if (incomingDatagramEventHandler) + { + if (incomingDatagramEventHandler(recvStruct)!=true) + return; + } + + PushBufferedPacket(recvStruct); + quitAndDataEvents.SetEvent(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +/* +RAK_THREAD_DECLARATION(RakNet::RecvFromLoop) +{ +#if defined(SN_TARGET_PSP2) + RakPeerAndIndex *rpai = ( RakPeerAndIndex * ) RakThread::GetRealThreadArgument(callGetRealThreadArgument); +#else + RakPeerAndIndex *rpai = ( RakPeerAndIndex * ) arguments; +#endif + RakPeer * rakPeer = rpai->rakPeer; + RakNetSocket *s = rpai->s; + RakNet::OP_DELETE(rpai,_FILE_AND_LINE_); + + rakPeer->isRecvFromLoopThreadActive.Increment(); + + while ( rakPeer->endThreads == false ) + { + if (rakPeer->RunRecvFromOnce(s)==false && + s->GetBlockingSocket()==false) + RakSleep(0); + } + rakPeer->isRecvFromLoopThreadActive.Decrement(); + +#if defined(SN_TARGET_PSP2) + return sceKernelExitDeleteThread(0); +#else + return 0; +#endif +} +*/ + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +RAK_THREAD_DECLARATION(RakNet::UpdateNetworkLoop) +{ + + + + RakPeer * rakPeer = ( RakPeer * ) arguments; + + +/* + // 11/15/05 - this is slower than Sleep() +#ifdef _WIN32 +#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) + // Lets see if these timers give better performance than Sleep + HANDLE timerHandle; + LARGE_INTEGER dueTime; + + if ( rakPeer->threadSleepTimer <= 0 ) + rakPeer->threadSleepTimer = 1; + + // 2nd parameter of false means synchronization timer instead of manual-reset timer + timerHandle = CreateWaitableTimer( NULL, FALSE, 0 ); + + RakAssert( timerHandle ); + + dueTime.QuadPart = -10000 * rakPeer->threadSleepTimer; // 10000 is 1 ms? + + BOOL success = SetWaitableTimer( timerHandle, &dueTime, rakPeer->threadSleepTimer, NULL, NULL, FALSE ); + (void) success; + RakAssert( success ); + +#endif +#endif +*/ + + BitStream updateBitStream( MAXIMUM_MTU_SIZE +#if LIBCAT_SECURITY==1 + + cat::AuthenticatedEncryption::OVERHEAD_BYTES +#endif + ); +// + rakPeer->isMainLoopThreadActive = true; + + while ( rakPeer->endThreads == false ) + { +// #ifdef _DEBUG +// // Sanity check, make sure RunUpdateCycle does not block or not otherwise get called for a long time +// RakNetTime thisCall=RakNet::GetTime(); +// RakAssert(thisCall-lastCall<250); +// lastCall=thisCall; +// #endif + if (rakPeer->userUpdateThreadPtr) + rakPeer->userUpdateThreadPtr(rakPeer, rakPeer->userUpdateThreadData); + + rakPeer->RunUpdateCycle(updateBitStream); + + // Pending sends go out this often, unless quitAndDataEvents is set + rakPeer->quitAndDataEvents.WaitOnEvent(10); + + /* + +// #if ((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && +#if defined(USE_WAIT_FOR_MULTIPLE_EVENTS) && defined(_WIN32) + + if (rakPeer->threadSleepTimer>0) + { + WSAEVENT eventArray[256]; + unsigned int i, eventArrayIndex; + for (i=0,eventArrayIndex=0; i < rakPeer->socketList.Size(); i++) + { + if (rakPeer->socketList[i]->recvEvent!=INVALID_HANDLE_VALUE) + { + eventArray[eventArrayIndex]=rakPeer->socketList[i]->recvEvent; + eventArrayIndex++; + if (eventArrayIndex==256) + break; + } + } + WSAWaitForMultipleEvents(eventArrayIndex,(const HANDLE*) &eventArray,FALSE,rakPeer->threadSleepTimer,FALSE); + } + else + { + RakSleep(0); + } + +#else // ((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) + #pragma message("-- RakNet: Using Sleep(). Uncomment USE_WAIT_FOR_MULTIPLE_EVENTS in RakNetDefines.h if you want to use WaitForSingleObject instead. --") + + RakSleep( rakPeer->threadSleepTimer ); +#endif + */ + } + + rakPeer->isMainLoopThreadActive = false; + + /* +#ifdef _WIN32 +#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) + CloseHandle(timerHandle); +#endif +#endif + */ + + + + + return 0; + +} + +void RakPeer::CallPluginCallbacks(DataStructures::List &pluginList, Packet *packet) +{ + for (unsigned int i=0; i < pluginList.Size(); i++) + { + switch (packet->data[0]) + { + case ID_DISCONNECTION_NOTIFICATION: + pluginList[i]->OnClosedConnection(packet->systemAddress, packet->guid, LCR_DISCONNECTION_NOTIFICATION); + break; + case ID_CONNECTION_LOST: + pluginList[i]->OnClosedConnection(packet->systemAddress, packet->guid, LCR_CONNECTION_LOST); + break; + case ID_NEW_INCOMING_CONNECTION: + pluginList[i]->OnNewConnection(packet->systemAddress, packet->guid, true); + break; + case ID_CONNECTION_REQUEST_ACCEPTED: + pluginList[i]->OnNewConnection(packet->systemAddress, packet->guid, false); + break; + case ID_CONNECTION_ATTEMPT_FAILED: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_CONNECTION_ATTEMPT_FAILED); + break; + case ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY); + break; + case ID_OUR_SYSTEM_REQUIRES_SECURITY: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_OUR_SYSTEM_REQUIRES_SECURITY); + break; + case ID_PUBLIC_KEY_MISMATCH: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_PUBLIC_KEY_MISMATCH); + break; + case ID_ALREADY_CONNECTED: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_ALREADY_CONNECTED); + break; + case ID_NO_FREE_INCOMING_CONNECTIONS: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_NO_FREE_INCOMING_CONNECTIONS); + break; + case ID_CONNECTION_BANNED: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_CONNECTION_BANNED); + break; + case ID_INVALID_PASSWORD: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_INVALID_PASSWORD); + break; + case ID_INCOMPATIBLE_PROTOCOL_VERSION: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_INCOMPATIBLE_PROTOCOL); + break; + case ID_IP_RECENTLY_CONNECTED: + pluginList[i]->OnFailedConnectionAttempt(packet, FCAR_IP_RECENTLY_CONNECTED); + break; + } + } +} + +void RakPeer::FillIPList(void) +{ + if (ipList[0]!=UNASSIGNED_SYSTEM_ADDRESS) + return; + + // Fill out ipList structure +#if !defined(WINDOWS_STORE_RT) + RakNetSocket2::GetMyIP( ipList ); +#endif + + // Sort the addresses from lowest to highest + int startingIdx = 0; + while (startingIdx < MAXIMUM_NUMBER_OF_INTERNAL_IDS-1 && ipList[startingIdx] != UNASSIGNED_SYSTEM_ADDRESS) + { + int lowestIdx = startingIdx; + for (int curIdx = startingIdx + 1; curIdx < MAXIMUM_NUMBER_OF_INTERNAL_IDS-1 && ipList[curIdx] != UNASSIGNED_SYSTEM_ADDRESS; curIdx++ ) + { + if (ipList[curIdx] < ipList[startingIdx]) + { + lowestIdx = curIdx; + } + } + if (startingIdx != lowestIdx) + { + SystemAddress temp = ipList[startingIdx]; + ipList[startingIdx] = ipList[lowestIdx]; + ipList[lowestIdx] = temp; + } + ++startingIdx; + } +} + + +// #if defined(RMO_NEW_UNDEF_ALLOCATING_QUEUE) +// #pragma pop_macro("new") +// #undef RMO_NEW_UNDEF_ALLOCATING_QUEUE +// #endif + + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif diff --git a/src/raknet/RakSleep.cpp b/src/raknet/RakSleep.cpp new file mode 100644 index 0000000..f3e5d6f --- /dev/null +++ b/src/raknet/RakSleep.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#if defined(_WIN32) +#include "include/raknet/WindowsIncludes.hpp" // Sleep + + + + + + + +#else +#include +#include +#include +pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER; +pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER; +#endif + +#include "include/raknet/RakSleep.hpp" + + +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) +#include "include/raknet/ThreadEmulation.hpp" +using namespace ThreadEmulation; +#endif + +void RakSleep(unsigned int ms) +{ +#ifdef _WIN32 + Sleep(ms); + + + + + + + +#else + //Single thread sleep code thanks to Furquan Shaikh, http://somethingswhichidintknow.blogspot.com/2009/09/sleep-in-pthread.html + //Modified slightly from the original + struct timespec timeToWait; + struct timeval now; + int rt; + + gettimeofday(&now,NULL); + + long seconds = ms/1000; + long nanoseconds = (ms - seconds * 1000) * 1000000; + timeToWait.tv_sec = now.tv_sec + seconds; + timeToWait.tv_nsec = now.tv_usec*1000 + nanoseconds; + + if (timeToWait.tv_nsec >= 1000000000) + { + timeToWait.tv_nsec -= 1000000000; + timeToWait.tv_sec++; + } + + pthread_mutex_lock(&fakeMutex); + rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait); + pthread_mutex_unlock(&fakeMutex); +#endif +} diff --git a/src/raknet/RakString.cpp b/src/raknet/RakString.cpp new file mode 100644 index 0000000..4ac0ac5 --- /dev/null +++ b/src/raknet/RakString.cpp @@ -0,0 +1,1687 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/RakString.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakMemoryOverride.hpp" +#include "include/raknet/BitStream.hpp" +#include +#include +#include "include/raknet/LinuxStrings.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/SimpleMutex.hpp" +#include +#include "include/raknet/Itoa.hpp" + +using namespace RakNet; + +//DataStructures::MemoryPool RakString::pool; +RakString::SharedString RakString::emptyString={0,0,0,(char*) "",(char*) ""}; +//RakString::SharedString *RakString::sharedStringFreeList=0; +//unsigned int RakString::sharedStringFreeListAllocationCount=0; +DataStructures::List RakString::freeList; + +class RakStringCleanup +{ +public: + ~RakStringCleanup() + { + RakNet::RakString::FreeMemoryNoMutex(); + } +}; + +static RakStringCleanup cleanup; + +SimpleMutex& GetPoolMutex(void) +{ + static SimpleMutex poolMutex; + return poolMutex; +} + +int RakNet::RakString::RakStringComp( RakString const &key, RakString const &data ) +{ + return key.StrCmp(data); +} + +RakString::RakString() +{ + sharedString=&emptyString; +} +RakString::RakString( RakString::SharedString *_sharedString ) +{ + sharedString=_sharedString; +} +RakString::RakString(char input) +{ + char str[2]; + str[0]=input; + str[1]=0; + Assign(str); +} +RakString::RakString(unsigned char input) +{ + char str[2]; + str[0]=(char) input; + str[1]=0; + Assign(str); +} +RakString::RakString(const unsigned char *format, ...){ + va_list ap; + va_start(ap, format); + Assign((const char*) format,ap); +} +RakString::RakString(const char *format, ...){ + va_list ap; + va_start(ap, format); + Assign(format,ap); +} +RakString::RakString( const RakString & rhs) +{ + if (rhs.sharedString==&emptyString) + { + sharedString=&emptyString; + return; + } + + rhs.sharedString->refCountMutex->Lock(); + if (rhs.sharedString->refCount==0) + { + sharedString=&emptyString; + } + else + { + rhs.sharedString->refCount++; + sharedString=rhs.sharedString; + } + rhs.sharedString->refCountMutex->Unlock(); +} +RakString::~RakString() +{ + Free(); +} +RakString& RakString::operator = ( const RakString& rhs ) +{ + Free(); + if (rhs.sharedString==&emptyString) + return *this; + + rhs.sharedString->refCountMutex->Lock(); + if (rhs.sharedString->refCount==0) + { + sharedString=&emptyString; + } + else + { + sharedString=rhs.sharedString; + sharedString->refCount++; + } + rhs.sharedString->refCountMutex->Unlock(); + return *this; +} +RakString& RakString::operator = ( const char *str ) +{ + Free(); + Assign(str); + return *this; +} +RakString& RakString::operator = ( char *str ) +{ + return operator = ((const char*)str); +} +RakString& RakString::operator = ( const unsigned char *str ) +{ + return operator = ((const char*)str); +} +RakString& RakString::operator = ( char unsigned *str ) +{ + return operator = ((const char*)str); +} +RakString& RakString::operator = ( const char c ) +{ + char buff[2]; + buff[0]=c; + buff[1]=0; + return operator = ((const char*)buff); +} +void RakString::Realloc(SharedString *sharedString, size_t bytes) +{ + if (bytes<=sharedString->bytesUsed) + return; + + RakAssert(bytes>0); + size_t oldBytes = sharedString->bytesUsed; + size_t newBytes; + const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; + newBytes = GetSizeToAllocate(bytes); + if (oldBytes <=(size_t) smallStringSize && newBytes > (size_t) smallStringSize) + { + sharedString->bigString=(char*) rakMalloc_Ex(newBytes, _FILE_AND_LINE_); + strcpy(sharedString->bigString, sharedString->smallString); + sharedString->c_str=sharedString->bigString; + } + else if (oldBytes > smallStringSize) + { + sharedString->bigString=(char*) rakRealloc_Ex(sharedString->bigString,newBytes, _FILE_AND_LINE_); + sharedString->c_str=sharedString->bigString; + } + sharedString->bytesUsed=newBytes; +} +RakString& RakString::operator +=( const RakString& rhs) +{ + if (rhs.IsEmpty()) + return *this; + + if (IsEmpty()) + { + return operator=(rhs); + } + else + { + Clone(); + size_t strLen=rhs.GetLength()+GetLength()+1; + Realloc(sharedString, strLen+GetLength()); + strcat(sharedString->c_str,rhs.C_String()); + } + return *this; +} +RakString& RakString::operator +=( const char *str ) +{ + if (str==0 || str[0]==0) + return *this; + + if (IsEmpty()) + { + Assign(str); + } + else + { + Clone(); + size_t strLen=strlen(str)+GetLength()+1; + Realloc(sharedString, strLen); + strcat(sharedString->c_str,str); + } + return *this; +} +RakString& RakString::operator +=( char *str ) +{ + return operator += ((const char*)str); +} +RakString& RakString::operator +=( const unsigned char *str ) +{ + return operator += ((const char*)str); +} +RakString& RakString::operator +=( unsigned char *str ) +{ + return operator += ((const char*)str); +} +RakString& RakString::operator +=( const char c ) +{ + char buff[2]; + buff[0]=c; + buff[1]=0; + return operator += ((const char*)buff); +} +unsigned char RakString::operator[] ( const unsigned int position ) const +{ + RakAssert(positionc_str[position]; +} +bool RakString::operator==(const RakString &rhs) const +{ + return strcmp(sharedString->c_str,rhs.sharedString->c_str)==0; +} +bool RakString::operator==(const char *str) const +{ + return strcmp(sharedString->c_str,str)==0; +} +bool RakString::operator==(char *str) const +{ + return strcmp(sharedString->c_str,str)==0; +} +bool RakString::operator < ( const RakString& right ) const +{ + return strcmp(sharedString->c_str,right.C_String()) < 0; +} +bool RakString::operator <= ( const RakString& right ) const +{ + return strcmp(sharedString->c_str,right.C_String()) <= 0; +} +bool RakString::operator > ( const RakString& right ) const +{ + return strcmp(sharedString->c_str,right.C_String()) > 0; +} +bool RakString::operator >= ( const RakString& right ) const +{ + return strcmp(sharedString->c_str,right.C_String()) >= 0; +} +bool RakString::operator!=(const RakString &rhs) const +{ + return strcmp(sharedString->c_str,rhs.sharedString->c_str)!=0; +} +bool RakString::operator!=(const char *str) const +{ + return strcmp(sharedString->c_str,str)!=0; +} +bool RakString::operator!=(char *str) const +{ + return strcmp(sharedString->c_str,str)!=0; +} +const RakNet::RakString operator+(const RakNet::RakString &lhs, const RakNet::RakString &rhs) +{ + if (lhs.IsEmpty() && rhs.IsEmpty()) + { + return RakString(&RakString::emptyString); + } + if (lhs.IsEmpty()) + { + rhs.sharedString->refCountMutex->Lock(); + if (rhs.sharedString->refCount==0) + { + rhs.sharedString->refCountMutex->Unlock(); + lhs.sharedString->refCountMutex->Lock(); + lhs.sharedString->refCount++; + lhs.sharedString->refCountMutex->Unlock(); + return RakString(lhs.sharedString); + } + else + { + rhs.sharedString->refCount++; + rhs.sharedString->refCountMutex->Unlock(); + return RakString(rhs.sharedString); + } + // rhs.sharedString->refCountMutex->Unlock(); + } + if (rhs.IsEmpty()) + { + lhs.sharedString->refCountMutex->Lock(); + lhs.sharedString->refCount++; + lhs.sharedString->refCountMutex->Unlock(); + return RakString(lhs.sharedString); + } + + size_t len1 = lhs.GetLength(); + size_t len2 = rhs.GetLength(); + size_t allocatedBytes = len1 + len2 + 1; + allocatedBytes = RakString::GetSizeToAllocate(allocatedBytes); + RakString::SharedString *sharedString; + + RakString::LockMutex(); + // sharedString = RakString::pool.Allocate( _FILE_AND_LINE_ ); + if (RakString::freeList.Size()==0) + { + //RakString::sharedStringFreeList=(RakString::SharedString*) rakRealloc_Ex(RakString::sharedStringFreeList,(RakString::sharedStringFreeListAllocationCount+1024)*sizeof(RakString::SharedString), _FILE_AND_LINE_); + unsigned i; + for (i=0; i < 128; i++) + { + // RakString::freeList.Insert(RakString::sharedStringFreeList+i+RakString::sharedStringFreeListAllocationCount); + RakString::SharedString *ss; + ss = (RakString::SharedString*) rakMalloc_Ex(sizeof(RakString::SharedString), _FILE_AND_LINE_); + ss->refCountMutex=RakNet::OP_NEW(_FILE_AND_LINE_); + RakString::freeList.Insert(ss, _FILE_AND_LINE_); + + } + //RakString::sharedStringFreeListAllocationCount+=1024; + } + sharedString = RakString::freeList[RakString::freeList.Size()-1]; + RakString::freeList.RemoveAtIndex(RakString::freeList.Size()-1); + RakString::UnlockMutex(); + + const int smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; + sharedString->bytesUsed=allocatedBytes; + sharedString->refCount=1; + if (allocatedBytes <= (size_t) smallStringSize) + { + sharedString->c_str=sharedString->smallString; + } + else + { + sharedString->bigString=(char*)rakMalloc_Ex(sharedString->bytesUsed, _FILE_AND_LINE_); + sharedString->c_str=sharedString->bigString; + } + + strcpy(sharedString->c_str, lhs); + strcat(sharedString->c_str, rhs); + + return RakString(sharedString); +} +const char * RakString::ToLower(void) +{ + Clone(); + + size_t strLen = strlen(sharedString->c_str); + unsigned i; + for (i=0; i < strLen; i++) + sharedString->c_str[i]=ToLower(sharedString->c_str[i]); + return sharedString->c_str; +} +const char * RakString::ToUpper(void) +{ + Clone(); + + size_t strLen = strlen(sharedString->c_str); + unsigned i; + for (i=0; i < strLen; i++) + sharedString->c_str[i]=ToUpper(sharedString->c_str[i]); + return sharedString->c_str; +} +void RakString::Set(const char *format, ...) +{ + va_list ap; + va_start(ap, format); + Clear(); + Assign(format,ap); +} +bool RakString::IsEmpty(void) const +{ + return sharedString==&emptyString; +} +size_t RakString::GetLength(void) const +{ + return strlen(sharedString->c_str); +} +// http://porg.es/blog/counting-characters-in-utf-8-strings-is-faster +int porges_strlen2(char *s) +{ + int i = 0; + int iBefore = 0; + int count = 0; + + while (s[i] > 0) +ascii: i++; + + count += i-iBefore; + while (s[i]) + { + if (s[i] > 0) + { + iBefore = i; + goto ascii; + } + else + switch (0xF0 & s[i]) + { + case 0xE0: i += 3; break; + case 0xF0: i += 4; break; + default: i += 2; break; + } + ++count; + } + return count; +} +size_t RakString::GetLengthUTF8(void) const +{ + return porges_strlen2(sharedString->c_str); +} +void RakString::Replace(unsigned index, unsigned count, unsigned char c) +{ + RakAssert(index+count < GetLength()); + Clone(); + unsigned countIndex=0; + while (countIndexc_str[index]=c; + index++; + countIndex++; + } + +} +void RakString::SetChar( unsigned index, unsigned char c ) +{ + RakAssert(index < GetLength()); + Clone(); + sharedString->c_str[index]=c; +} +void RakString::SetChar( unsigned index, RakNet::RakString s ) +{ + RakAssert(index < GetLength()); + Clone(); + RakNet::RakString firstHalf = SubStr(0, index); + RakNet::RakString secondHalf = SubStr(index+1, (unsigned int)-1); + *this = firstHalf; + *this += s; + *this += secondHalf; +} + +#ifdef _WIN32 +WCHAR * RakString::ToWideChar(void) +{ + // + // Special case of NULL or empty input string + // + if ( (sharedString->c_str == NULL) || (*sharedString->c_str == '\0') ) + { + // Return empty string + return L""; + } + + // + // Get size of destination UTF-16 buffer, in WCHAR's + // + int cchUTF16 = ::MultiByteToWideChar( + CP_UTF8, // convert from UTF-8 + 0, // Flags + sharedString->c_str, // source UTF-8 string + GetLength()+1, // total length of source UTF-8 string, + // in CHAR's (= bytes), including end-of-string \0 + NULL, // unused - no conversion done in this step + 0 // request size of destination buffer, in WCHAR's + ); + + if ( cchUTF16 == 0 ) + { + RakAssert("RakString::ToWideChar exception from cchUTF16==0" && 0); + return 0; + } + + // + // Allocate destination buffer to store UTF-16 string + // + WCHAR * pszUTF16 = RakNet::OP_NEW_ARRAY(cchUTF16,__FILE__,__LINE__); + + // + // Do the conversion from UTF-8 to UTF-16 + // + int result = ::MultiByteToWideChar( + CP_UTF8, // convert from UTF-8 + 0, // Buffer + sharedString->c_str, // source UTF-8 string + GetLength()+1, // total length of source UTF-8 string, + // in CHAR's (= bytes), including end-of-string \0 + pszUTF16, // destination buffer + cchUTF16 // size of destination buffer, in WCHAR's + ); + + if ( result == 0 ) + { + RakAssert("RakString::ToWideChar exception from MultiByteToWideChar" && 0); + return 0; + } + + return pszUTF16; +} +void RakString::DeallocWideChar(WCHAR * w) +{ + RakNet::OP_DELETE_ARRAY(w,__FILE__,__LINE__); +} +void RakString::FromWideChar(const wchar_t *source) +{ + Clear(); + int bufSize = wcslen(source)*4; + Allocate(bufSize); + WideCharToMultiByte ( CP_ACP, // ANSI code page + + + + WC_COMPOSITECHECK, // Check for accented characters + + source, // Source Unicode string + -1, // -1 means string is zero-terminated + sharedString->c_str, // Destination char string + bufSize, // Size of buffer + NULL, // No default character + NULL ); // Don't care about this flag + + +} +RakNet::RakString RakString::FromWideChar_S(const wchar_t *source) +{ + RakNet::RakString rs; + rs.FromWideChar(source); + return rs; +} +#endif +size_t RakString::Find(const char *stringToFind,size_t pos) +{ + size_t len=GetLength(); + if (pos>=len || stringToFind==0 || stringToFind[0]==0) + { + return (size_t) -1; + } + size_t matchLen= strlen(stringToFind); + size_t matchPos=0; + size_t iStart=0; + + for (size_t i=pos;ic_str[i]) + { + if(matchPos==0) + { + iStart=i; + } + matchPos++; + } + else + { + matchPos=0; + } + + if (matchPos>=matchLen) + { + return iStart; + } + } + + return (size_t) -1; +} + +void RakString::TruncateUTF8(unsigned int length) +{ + int i = 0; + unsigned int count = 0; + + while (sharedString->c_str[i]!=0) + { + if (count==length) + { + sharedString->c_str[i]=0; + return; + } + else if (sharedString->c_str[i]>0) + { + i++; + } + else + { + switch (0xF0 & sharedString->c_str[i]) + { + case 0xE0: i += 3; break; + case 0xF0: i += 4; break; + default: i += 2; break; + } + } + + count++; + } +} + +void RakString::Truncate(unsigned int length) +{ + if (length < GetLength()) + { + SetChar(length, 0); + } +} + +RakString RakString::SubStr(unsigned int index, unsigned int count) const +{ + size_t length = GetLength(); + if (index >= length || count==0) + return RakString(); + RakString copy; + size_t numBytes = length-index; + if (count < numBytes) + numBytes=count; + copy.Allocate(numBytes+1); + size_t i; + for (i=0; i < numBytes; i++) + copy.sharedString->c_str[i]=sharedString->c_str[index+i]; + copy.sharedString->c_str[i]=0; + return copy; +} +void RakString::Erase(unsigned int index, unsigned int count) +{ + size_t len = GetLength(); + RakAssert(index+count <= len); + + Clone(); + unsigned i; + for (i=index; i < len-count; i++) + { + sharedString->c_str[i]=sharedString->c_str[i+count]; + } + sharedString->c_str[i]=0; +} +void RakString::TerminateAtLastCharacter(char c) +{ + int i, len=(int) GetLength(); + for (i=len-1; i >= 0; i--) + { + if (sharedString->c_str[i]==c) + { + Clone(); + sharedString->c_str[i]=0; + return; + } + } +} +void RakString::StartAfterLastCharacter(char c) +{ + int i, len=(int) GetLength(); + for (i=len-1; i >= 0; i--) + { + if (sharedString->c_str[i]==c) + { + ++i; + if (i < len) + { + *this = SubStr(i,GetLength()-i); + } + return; + } + } +} +void RakString::TerminateAtFirstCharacter(char c) +{ + unsigned int i, len=(unsigned int) GetLength(); + for (i=0; i < len; i++) + { + if (sharedString->c_str[i]==c) + { + if (i > 0) + { + Clone(); + sharedString->c_str[i]=0; + } + } + } +} +void RakString::StartAfterFirstCharacter(char c) +{ + unsigned int i, len=(unsigned int) GetLength(); + for (i=0; i < len; i++) + { + if (sharedString->c_str[i]==c) + { + ++i; + if (i < len) + { + *this = SubStr(i,GetLength()-i); + } + return; + } + } +} +int RakString::GetCharacterCount(char c) +{ + int count=0; + unsigned int i, len=(unsigned int) GetLength(); + for (i=0; i < len; i++) + { + if (sharedString->c_str[i]==c) + { + ++count; + } + } + return count; +} +void RakString::RemoveCharacter(char c) +{ + if (c==0) + return; + + unsigned int readIndex, writeIndex=0; + for (readIndex=0; sharedString->c_str[readIndex]; readIndex++) + { + if (sharedString->c_str[readIndex]!=c) + sharedString->c_str[writeIndex++]=sharedString->c_str[readIndex]; + else + Clone(); + } + sharedString->c_str[writeIndex]=0; + if (writeIndex==0) + Clear(); +} +int RakString::StrCmp(const RakString &rhs) const +{ + return strcmp(sharedString->c_str, rhs.C_String()); +} +int RakString::StrNCmp(const RakString &rhs, size_t num) const +{ + return strncmp(sharedString->c_str, rhs.C_String(), num); +} +int RakString::StrICmp(const RakString &rhs) const +{ + return _stricmp(sharedString->c_str, rhs.C_String()); +} +void RakString::Printf(void) +{ + RAKNET_DEBUG_PRINTF("%s", sharedString->c_str); +} +void RakString::FPrintf(FILE *fp) +{ + fprintf(fp,"%s", sharedString->c_str); +} +bool RakString::IPAddressMatch(const char *IP) +{ + unsigned characterIndex; + + if ( IP == 0 || IP[ 0 ] == 0 || strlen( IP ) > 15 ) + return false; + + characterIndex = 0; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while ( true ) + { + if (sharedString->c_str[ characterIndex ] == IP[ characterIndex ] ) + { + // Equal characters + if ( IP[ characterIndex ] == 0 ) + { + // End of the string and the strings match + + return true; + } + + characterIndex++; + } + + else + { + if ( sharedString->c_str[ characterIndex ] == 0 || IP[ characterIndex ] == 0 ) + { + // End of one of the strings + break; + } + + // Characters do not match + if ( sharedString->c_str[ characterIndex ] == '*' ) + { + // Domain is banned. + return true; + } + + // Characters do not match and it is not a * + break; + } + } + + + // No match found. + return false; +} +bool RakString::ContainsNonprintableExceptSpaces(void) const +{ + size_t strLen = strlen(sharedString->c_str); + unsigned i; + for (i=0; i < strLen; i++) + { + if (sharedString->c_str[i] < ' ' || sharedString->c_str[i] >126) + return true; + } + return false; +} +bool RakString::IsEmailAddress(void) const +{ + if (IsEmpty()) + return false; + size_t strLen = strlen(sharedString->c_str); + if (strLen < 6) // a@b.de + return false; + if (sharedString->c_str[strLen-4]!='.' && sharedString->c_str[strLen-3]!='.') // .com, .net., .org, .de + return false; + unsigned i; + // Has non-printable? + for (i=0; i < strLen; i++) + { + if (sharedString->c_str[i] <= ' ' || sharedString->c_str[i] >126) + return false; + } + int atCount=0; + for (i=0; i < strLen; i++) + { + if (sharedString->c_str[i]=='@') + { + atCount++; + } + } + if (atCount!=1) + return false; + int dotCount=0; + for (i=0; i < strLen; i++) + { + if (sharedString->c_str[i]=='.') + { + dotCount++; + } + } + if (dotCount==0) + return false; + + // There's more I could check, but this is good enough + return true; +} +RakNet::RakString& RakString::URLEncode(void) +{ + RakString result; + size_t strLen = strlen(sharedString->c_str); + result.Allocate(strLen*3); + char *output=result.sharedString->c_str; + unsigned int outputIndex=0; + unsigned i; + unsigned char c; + for (i=0; i < strLen; i++) + { + c=sharedString->c_str[i]; + if ( + (c<=47) || + (c>=58 && c<=64) || + (c>=91 && c<=96) || + (c>=123) + ) + { + char buff[3]; + Itoa(c, buff, 16); + output[outputIndex++]='%'; + output[outputIndex++]=buff[0]; + output[outputIndex++]=buff[1]; + } + else + { + output[outputIndex++]=c; + } + } + + output[outputIndex]=0; + + *this = result; + return *this; +} +RakNet::RakString& RakString::URLDecode(void) +{ + RakString result; + size_t strLen = strlen(sharedString->c_str); + result.Allocate(strLen); + char *output=result.sharedString->c_str; + unsigned int outputIndex=0; + char c; + char hexDigits[2]; + char hexValues[2]; + unsigned int i; + for (i=0; i < strLen; i++) + { + c=sharedString->c_str[i]; + if (c=='%') + { + hexDigits[0]=sharedString->c_str[++i]; + hexDigits[1]=sharedString->c_str[++i]; + + if (hexDigits[0]==' ') + hexValues[0]=0; + + if (hexDigits[0]>='A' && hexDigits[0]<='F') + hexValues[0]=hexDigits[0]-'A'+10; + if (hexDigits[0]>='a' && hexDigits[0]<='f') + hexValues[0]=hexDigits[0]-'a'+10; + else + hexValues[0]=hexDigits[0]-'0'; + + if (hexDigits[1]>='A' && hexDigits[1]<='F') + hexValues[1]=hexDigits[1]-'A'+10; + if (hexDigits[1]>='a' && hexDigits[1]<='f') + hexValues[1]=hexDigits[1]-'a'+10; + else + hexValues[1]=hexDigits[1]-'0'; + + output[outputIndex++]=hexValues[0]*16+hexValues[1]; + } + else + { + output[outputIndex++]=c; + } + } + + output[outputIndex]=0; + + *this = result; + return *this; +} +void RakString::SplitURI(RakNet::RakString &header, RakNet::RakString &domain, RakNet::RakString &path) +{ + header.Clear(); + domain.Clear(); + path.Clear(); + + size_t strLen = strlen(sharedString->c_str); + + char c; + unsigned int i=0; + if (strncmp(sharedString->c_str, "http://", 7)==0) + i+=(unsigned int) strlen("http://"); + else if (strncmp(sharedString->c_str, "https://", 8)==0) + i+=(unsigned int) strlen("https://"); + + if (strncmp(sharedString->c_str, "www.", 4)==0) + i+=(unsigned int) strlen("www."); + + if (i!=0) + { + header.Allocate(i+1); + strncpy(header.sharedString->c_str, sharedString->c_str, i); + header.sharedString->c_str[i]=0; + } + + + domain.Allocate(strLen-i+1); + char *domainOutput=domain.sharedString->c_str; + unsigned int outputIndex=0; + for (; i < strLen; i++) + { + c=sharedString->c_str[i]; + if (c=='/') + { + break; + } + else + { + domainOutput[outputIndex++]=sharedString->c_str[i]; + } + } + + domainOutput[outputIndex]=0; + + path.Allocate(strLen-header.GetLength()-outputIndex+1); + outputIndex=0; + char *pathOutput=path.sharedString->c_str; + for (; i < strLen; i++) + { + pathOutput[outputIndex++]=sharedString->c_str[i]; + } + pathOutput[outputIndex]=0; +} +RakNet::RakString& RakString::SQLEscape(void) +{ + int strLen=(int)GetLength(); + int escapedCharacterCount=0; + int index; + for (index=0; index < strLen; index++) + { + if (sharedString->c_str[index]=='\'' || + sharedString->c_str[index]=='"' || + sharedString->c_str[index]=='\\') + escapedCharacterCount++; + } + if (escapedCharacterCount==0) + return *this; + + Clone(); + Realloc(sharedString, strLen+escapedCharacterCount); + int writeIndex, readIndex; + writeIndex = strLen+escapedCharacterCount; + readIndex=strLen; + while (readIndex>=0) + { + if (sharedString->c_str[readIndex]=='\'' || + sharedString->c_str[readIndex]=='"' || + sharedString->c_str[readIndex]=='\\') + { + sharedString->c_str[writeIndex--]=sharedString->c_str[readIndex--]; + sharedString->c_str[writeIndex--]='\\'; + } + else + { + sharedString->c_str[writeIndex--]=sharedString->c_str[readIndex--]; + } + } + return *this; +} +RakNet::RakString RakString::FormatForPUTOrPost(const char* type, const char* uri, const char* contentType, const char* body, const char* extraHeaders) +{ + RakString out; + RakString host; + RakString remotePath; + RakNet::RakString header; + RakString uriRs; + uriRs = uri; + uriRs.SplitURI(header, host, remotePath); + + if (host.IsEmpty() || remotePath.IsEmpty()) + return out; + +// RakString bodyEncoded = body; +// bodyEncoded.URLEncode(); + + if (extraHeaders!=0 && extraHeaders[0]) + { + out.Set("%s %s HTTP/1.1\r\n" + "%s\r\n" + "Host: %s\r\n" + "Content-Type: %s\r\n" + "Content-Length: %u\r\n" + "\r\n" + "%s", + type, + remotePath.C_String(), + extraHeaders, + host.C_String(), + contentType, + //bodyEncoded.GetLength(), + //bodyEncoded.C_String()); + strlen(body), + body); + } + else + { + out.Set("%s %s HTTP/1.1\r\n" + "Host: %s\r\n" + "Content-Type: %s\r\n" + "Content-Length: %u\r\n" + "\r\n" + "%s", + type, + remotePath.C_String(), + host.C_String(), + contentType, + //bodyEncoded.GetLength(), + //bodyEncoded.C_String()); + strlen(body), + body); + } + + return out; +} +RakString RakString::FormatForPOST(const char* uri, const char* contentType, const char* body, const char* extraHeaders) +{ + return FormatForPUTOrPost("POST", uri, contentType, body, extraHeaders); +} +RakString RakString::FormatForPUT(const char* uri, const char* contentType, const char* body, const char* extraHeaders) +{ + return FormatForPUTOrPost("PUT", uri, contentType, body, extraHeaders); +} +RakString RakString::FormatForGET(const char* uri, const char* extraHeaders) +{ + RakString out; + RakString host; + RakString remotePath; + RakNet::RakString header; + RakNet::RakString uriRs; + uriRs = uri; + + uriRs.SplitURI(header, host, remotePath); + if (host.IsEmpty() || remotePath.IsEmpty()) + return out; + + if (extraHeaders && extraHeaders[0]) + { + out.Set("GET %s HTTP/1.1\r\n" + "%s\r\n" + "Host: %s\r\n" + "\r\n", + remotePath.C_String(), + extraHeaders, + host.C_String()); + } + else + { + out.Set("GET %s HTTP/1.1\r\n" + "Host: %s\r\n" + "\r\n", + remotePath.C_String(), + host.C_String()); + + } + + + return out; +} +RakString RakString::FormatForDELETE(const char* uri, const char* extraHeaders) +{ + RakString out; + RakString host; + RakString remotePath; + RakNet::RakString header; + RakNet::RakString uriRs; + uriRs = uri; + + uriRs.SplitURI(header, host, remotePath); + if (host.IsEmpty() || remotePath.IsEmpty()) + return out; + + if (extraHeaders && extraHeaders[0]) + { + out.Set("DELETE %s HTTP/1.1\r\n" + "%s\r\n" + "Content-Length: 0\r\n" + "Host: %s\r\n" + "Connection: close\r\n" + "\r\n", + remotePath.C_String(), + extraHeaders, + host.C_String()); + } + else + { + out.Set("DELETE %s HTTP/1.1\r\n" + "Content-Length: 0\r\n" + "Host: %s\r\n" + "Connection: close\r\n" + "\r\n", + remotePath.C_String(), + host.C_String()); + } + + return out; +} +RakNet::RakString& RakString::MakeFilePath(void) +{ + if (IsEmpty()) + return *this; + + RakNet::RakString fixedString = *this; + fixedString.Clone(); + for (int i=0; fixedString.sharedString->c_str[i]; i++) + { +#ifdef _WIN32 + if (fixedString.sharedString->c_str[i]=='/') + fixedString.sharedString->c_str[i]='\\'; +#else + if (fixedString.sharedString->c_str[i]=='\\') + fixedString.sharedString->c_str[i]='/'; +#endif + } + +#ifdef _WIN32 + if (fixedString.sharedString->c_str[strlen(fixedString.sharedString->c_str)-1]!='\\') + { + fixedString+='\\'; + } +#else + if (fixedString.sharedString->c_str[strlen(fixedString.sharedString->c_str)-1]!='/') + { + fixedString+='/'; + } +#endif + + if (fixedString!=*this) + *this = fixedString; + return *this; +} +void RakString::FreeMemory(void) +{ + LockMutex(); + FreeMemoryNoMutex(); + UnlockMutex(); +} +void RakString::FreeMemoryNoMutex(void) +{ + for (unsigned int i=0; i < freeList.Size(); i++) + { + RakNet::OP_DELETE(freeList[i]->refCountMutex,_FILE_AND_LINE_); + rakFree_Ex(freeList[i], _FILE_AND_LINE_ ); + } + freeList.Clear(false, _FILE_AND_LINE_); +} +void RakString::Serialize(BitStream *bs) const +{ + Serialize(sharedString->c_str, bs); +} +void RakString::Serialize(const char *str, BitStream *bs) +{ + unsigned short l = (unsigned short) strlen(str); + bs->Write(l); + bs->WriteAlignedBytes((const unsigned char*) str, (const unsigned int) l); +} +void RakString::SerializeCompressed(BitStream *bs, uint8_t languageId, bool writeLanguageId) const +{ + SerializeCompressed(C_String(), bs, languageId, writeLanguageId); +} +void RakString::SerializeCompressed(const char *str, BitStream *bs, uint8_t languageId, bool writeLanguageId) +{ + if (writeLanguageId) + bs->WriteCompressed(languageId); + StringCompressor::Instance()->EncodeString(str,0xFFFF,bs,languageId); +} +bool RakString::Deserialize(BitStream *bs) +{ + Clear(); + + bool b; + unsigned short l; + b=bs->Read(l); + if (l>0) + { + Allocate(((unsigned int) l)+1); + b=bs->ReadAlignedBytes((unsigned char*) sharedString->c_str, l); + if (b) + sharedString->c_str[l]=0; + else + Clear(); + } + else + bs->AlignReadToByteBoundary(); + return b; +} +bool RakString::Deserialize(char *str, BitStream *bs) +{ + bool b; + unsigned short l; + b=bs->Read(l); + if (b && l>0) + b=bs->ReadAlignedBytes((unsigned char*) str, l); + + if (b==false) + str[0]=0; + + str[l]=0; + return b; +} +bool RakString::DeserializeCompressed(BitStream *bs, bool readLanguageId) +{ + uint8_t languageId; + if (readLanguageId) + bs->ReadCompressed(languageId); + else + languageId=0; + return StringCompressor::Instance()->DecodeString(this,0xFFFF,bs,languageId); +} +bool RakString::DeserializeCompressed(char *str, BitStream *bs, bool readLanguageId) +{ + uint8_t languageId; + if (readLanguageId) + bs->ReadCompressed(languageId); + else + languageId=0; + return StringCompressor::Instance()->DecodeString(str,0xFFFF,bs,languageId); +} +const char *RakString::ToString(int64_t i) +{ + static int index=0; + static char buff[64][64]; +#if defined(_WIN32) + sprintf(buff[index], "%I64d", i); +#else + sprintf(buff[index], "%lld", (long long unsigned int) i); +#endif + int lastIndex=index; + if (++index==64) + index=0; + return buff[lastIndex]; +} +const char *RakString::ToString(uint64_t i) +{ + static int index=0; + static char buff[64][64]; +#if defined(_WIN32) + sprintf(buff[index], "%I64u", i); +#else + sprintf(buff[index], "%llu", (long long unsigned int) i); +#endif + int lastIndex=index; + if (++index==64) + index=0; + return buff[lastIndex]; +} +void RakString::Clear(void) +{ + Free(); +} +void RakString::Allocate(size_t len) +{ + RakString::LockMutex(); + // sharedString = RakString::pool.Allocate( _FILE_AND_LINE_ ); + if (RakString::freeList.Size()==0) + { + //RakString::sharedStringFreeList=(RakString::SharedString*) rakRealloc_Ex(RakString::sharedStringFreeList,(RakString::sharedStringFreeListAllocationCount+1024)*sizeof(RakString::SharedString), _FILE_AND_LINE_); + unsigned i; + for (i=0; i < 128; i++) + { + // RakString::freeList.Insert(RakString::sharedStringFreeList+i+RakString::sharedStringFreeListAllocationCount); + // RakString::freeList.Insert((RakString::SharedString*)rakMalloc_Ex(sizeof(RakString::SharedString), _FILE_AND_LINE_), _FILE_AND_LINE_); + + RakString::SharedString *ss; + ss = (RakString::SharedString*) rakMalloc_Ex(sizeof(RakString::SharedString), _FILE_AND_LINE_); + ss->refCountMutex=RakNet::OP_NEW(_FILE_AND_LINE_); + RakString::freeList.Insert(ss, _FILE_AND_LINE_); + } + //RakString::sharedStringFreeListAllocationCount+=1024; + } + sharedString = RakString::freeList[RakString::freeList.Size()-1]; + RakString::freeList.RemoveAtIndex(RakString::freeList.Size()-1); + RakString::UnlockMutex(); + + const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; + sharedString->refCount=1; + if (len <= smallStringSize) + { + sharedString->bytesUsed=smallStringSize; + sharedString->c_str=sharedString->smallString; + } + else + { + sharedString->bytesUsed=len<<1; + sharedString->bigString=(char*)rakMalloc_Ex(sharedString->bytesUsed, _FILE_AND_LINE_); + sharedString->c_str=sharedString->bigString; + } +} +void RakString::Assign(const char *str) +{ + if (str==0 || str[0]==0) + { + sharedString=&emptyString; + return; + } + + size_t len = strlen(str)+1; + Allocate(len); + memcpy(sharedString->c_str, str, len); +} +void RakString::Assign(const char *str, va_list ap) +{ + if (str==0 || str[0]==0) + { + sharedString=&emptyString; + return; + } + + char stackBuff[512]; + if (_vsnprintf(stackBuff, 512, str, ap)!=-1 +#ifndef _WIN32 + // Here Windows will return -1 if the string is too long; Linux just truncates the string. + && strlen(str) <511 +#endif + ) + { + Assign(stackBuff); + return; + } + char *buff=0, *newBuff; + size_t buffSize=8096; + while (1) + { + newBuff = (char*) rakRealloc_Ex(buff, buffSize,__FILE__,__LINE__); + if (newBuff==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + if (buff!=0) + { + Assign(buff); + rakFree_Ex(buff,__FILE__,__LINE__); + } + else + { + Assign(stackBuff); + } + return; + } + buff=newBuff; + if (_vsnprintf(buff, buffSize, str, ap)!=-1) + { + Assign(buff); + rakFree_Ex(buff,__FILE__,__LINE__); + return; + } + buffSize*=2; + } +} +RakNet::RakString RakString::Assign(const char *str,size_t pos, size_t n ) +{ + size_t incomingLen=strlen(str); + + Clone(); + + if (str==0 || str[0]==0||pos>=incomingLen) + { + sharedString=&emptyString; + return (*this); + } + + if (pos+n>=incomingLen) + { + n=incomingLen-pos; + + } + const char * tmpStr=&(str[pos]); + + size_t len = n+1; + Allocate(len); + memcpy(sharedString->c_str, tmpStr, len); + sharedString->c_str[n]=0; + + return (*this); +} + +RakNet::RakString RakString::NonVariadic(const char *str) +{ + RakNet::RakString rs; + rs=str; + return rs; +} +unsigned long RakString::ToInteger(const char *str) +{ + unsigned long hash = 0; + int c; + + while ((c = *str++)) + hash = c + (hash << 6) + (hash << 16) - hash; + + return hash; +} +unsigned long RakString::ToInteger(const RakString &rs) +{ + return RakString::ToInteger(rs.C_String()); +} +int RakString::ReadIntFromSubstring(const char *str, size_t pos, size_t n) +{ + char tmp[32]; + if (n >= 32) + return 0; + for (size_t i=0; i < n; i++) + tmp[i]=str[i+pos]; + return atoi(tmp); +} +void RakString::AppendBytes(const char *bytes, unsigned int count) +{ + if (IsEmpty()) + { + Allocate(count); + memcpy(sharedString->c_str, bytes, count+1); + sharedString->c_str[count]=0; + } + else + { + Clone(); + unsigned int length=(unsigned int) GetLength(); + Realloc(sharedString, count+length+1); + memcpy(sharedString->c_str+length, bytes, count); + sharedString->c_str[length+count]=0; + } + + +} +void RakString::Clone(void) +{ + RakAssert(sharedString!=&emptyString); + if (sharedString==&emptyString) + { + return; + } + + // Empty or solo then no point to cloning + sharedString->refCountMutex->Lock(); + if (sharedString->refCount==1) + { + sharedString->refCountMutex->Unlock(); + return; + } + + sharedString->refCount--; + sharedString->refCountMutex->Unlock(); + Assign(sharedString->c_str); +} +void RakString::Free(void) +{ + if (sharedString==&emptyString) + return; + sharedString->refCountMutex->Lock(); + sharedString->refCount--; + if (sharedString->refCount==0) + { + sharedString->refCountMutex->Unlock(); + const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; + if (sharedString->bytesUsed>smallStringSize) + rakFree_Ex(sharedString->bigString, _FILE_AND_LINE_ ); + /* + poolMutex->Lock(); + pool.Release(sharedString); + poolMutex->Unlock(); + */ + + RakString::LockMutex(); + RakString::freeList.Insert(sharedString, _FILE_AND_LINE_); + RakString::UnlockMutex(); + + sharedString=&emptyString; + } + else + { + sharedString->refCountMutex->Unlock(); + } + sharedString=&emptyString; +} +unsigned char RakString::ToLower(unsigned char c) +{ + if (c >= 'A' && c <= 'Z') + return c-'A'+'a'; + return c; +} +unsigned char RakString::ToUpper(unsigned char c) +{ + if (c >= 'a' && c <= 'z') + return c-'a'+'A'; + return c; +} +void RakString::LockMutex(void) +{ + GetPoolMutex().Lock(); +} +void RakString::UnlockMutex(void) +{ + GetPoolMutex().Unlock(); +} + +/* +#include "include/raknet/RakString.hpp" +#include +#include "include/raknet/GetTime.hpp" + +using namespace RakNet; + +int main(void) +{ + RakString s3("Hello world"); + RakString s5=s3; + + RakString s1; + RakString s2('a'); + + RakString s4("%i %f", 5, 6.0); + + RakString s6=s3; + RakString s7=s6; + RakString s8=s6; + RakString s9; + s9=s9; + RakString s10(s3); + RakString s11=s10 + s4 + s9 + s2; + s11+=RakString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + RakString s12("Test"); + s12+=s11; + bool b1 = s12==s12; + s11=s5; + s12.ToUpper(); + s12.ToLower(); + RakString s13; + bool b3 = s13.IsEmpty(); + s13.Set("blah %s", s12.C_String()); + bool b4 = s13.IsEmpty(); + size_t i1=s13.GetLength(); + s3.Clear(_FILE_AND_LINE_); + s4.Clear(_FILE_AND_LINE_); + s5.Clear(_FILE_AND_LINE_); + s5.Clear(_FILE_AND_LINE_); + s6.Printf(); + s7.Printf(); + RAKNET_DEBUG_PRINTF("\n"); + + static const int repeatCount=750; + DataStructures::List rakStringList; + DataStructures::List stdStringList; + DataStructures::List referenceStringList; + char *c; + unsigned i; + RakNet::TimeMS beforeReferenceList, beforeRakString, beforeStdString, afterStdString; + + unsigned loop; + for (loop=0; loop<2; loop++) + { + beforeReferenceList=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + { + c = RakNet::OP_NEW_ARRAY(56,_FILE_AND_LINE_ ); + strcpy(c, "Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); + referenceStringList.Insert(c); + } + beforeRakString=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + rakStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); + beforeStdString=RakNet::GetTimeMS(); + + for (i=0; i < repeatCount; i++) + stdStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); + afterStdString=RakNet::GetTimeMS(); + RAKNET_DEBUG_PRINTF("Insertion 1 Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); + + beforeReferenceList=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + { + RakNet::OP_DELETE_ARRAY(referenceStringList[0], _FILE_AND_LINE_); + referenceStringList.RemoveAtIndex(0); + } + beforeRakString=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + rakStringList.RemoveAtIndex(0); + beforeStdString=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + stdStringList.RemoveAtIndex(0); + afterStdString=RakNet::GetTimeMS(); + RAKNET_DEBUG_PRINTF("RemoveHead Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); + + beforeReferenceList=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + { + c = RakNet::OP_NEW_ARRAY(56, _FILE_AND_LINE_ ); + strcpy(c, "Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); + referenceStringList.Insert(0); + } + beforeRakString=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + rakStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); + beforeStdString=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + stdStringList.Insert("Aalsdkj alsdjf laksdjf ;lasdfj ;lasjfd"); + afterStdString=RakNet::GetTimeMS(); + RAKNET_DEBUG_PRINTF("Insertion 2 Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); + + beforeReferenceList=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + { + RakNet::OP_DELETE_ARRAY(referenceStringList[referenceStringList.Size()-1], _FILE_AND_LINE_); + referenceStringList.RemoveAtIndex(referenceStringList.Size()-1); + } + beforeRakString=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + rakStringList.RemoveAtIndex(rakStringList.Size()-1); + beforeStdString=RakNet::GetTimeMS(); + for (i=0; i < repeatCount; i++) + stdStringList.RemoveAtIndex(stdStringList.Size()-1); + afterStdString=RakNet::GetTimeMS(); + RAKNET_DEBUG_PRINTF("RemoveTail Ref=%i Rak=%i, Std=%i\n", beforeRakString-beforeReferenceList, beforeStdString-beforeRakString, afterStdString-beforeStdString); + + } + + printf("Done."); + char str[128]; + Gets(str, sizeof(str)); + return 1; +} +*/ diff --git a/src/raknet/RakThread.cpp b/src/raknet/RakThread.cpp new file mode 100644 index 0000000..14f3b50 --- /dev/null +++ b/src/raknet/RakThread.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/RakThread.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakNetDefines.hpp" +#include "include/raknet/RakSleep.hpp" +#include "include/raknet/RakMemoryOverride.hpp" + +using namespace RakNet; + + + + +#if defined(_WIN32) + #include "include/raknet/WindowsIncludes.hpp" + #include + #if !defined(_WIN32_WCE) + #include + #endif + + + + +#else +#include +#endif + +#if defined(_WIN32_WCE) || defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) +int RakThread::Create( LPTHREAD_START_ROUTINE start_address, void *arglist, int priority) +#elif defined(_WIN32) +int RakThread::Create( unsigned __stdcall start_address( void* ), void *arglist, int priority) + + + +#else +int RakThread::Create( void* start_address( void* ), void *arglist, int priority) +#endif +{ +#ifdef _WIN32 + HANDLE threadHandle; + unsigned threadID = 0; + + +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) + threadHandle = CreateThread(NULL,0,start_address,arglist,CREATE_SUSPENDED, 0); +#elif defined _WIN32_WCE + threadHandle = CreateThread(NULL,MAX_ALLOCA_STACK_ALLOCATION*2,start_address,arglist,0,(DWORD*)&threadID); +#else + threadHandle = (HANDLE) _beginthreadex( NULL, MAX_ALLOCA_STACK_ALLOCATION*2, start_address, arglist, 0, &threadID ); +#endif + + SetThreadPriority(threadHandle, priority); + +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) + ResumeThread(threadHandle); +#endif + + if (threadHandle==0) + { + return 1; + } + else + { + CloseHandle( threadHandle ); + return 0; + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#else + pthread_t threadHandle; + // Create thread linux + pthread_attr_t attr; + sched_param param; + param.sched_priority=priority; + pthread_attr_init( &attr ); + pthread_attr_setschedparam(&attr, ¶m); + + + + + + pthread_attr_setstacksize(&attr, MAX_ALLOCA_STACK_ALLOCATION*2); + + pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED ); + int res = pthread_create( &threadHandle, &attr, start_address, arglist ); + RakAssert(res==0 && "pthread_create in RakThread.cpp failed.") + return res; +#endif +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/raknet/RakWString.cpp b/src/raknet/RakWString.cpp new file mode 100644 index 0000000..d565bab --- /dev/null +++ b/src/raknet/RakWString.cpp @@ -0,0 +1,412 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/RakWString.hpp" +#include "include/raknet/BitStream.hpp" +#include +#include +#include + +using namespace RakNet; + +// From http://www.joelonsoftware.com/articles/Unicode.html +// Only code points 128 and above are stored using 2, 3, in fact, up to 6 bytes. +#define MAX_BYTES_PER_UNICODE_CHAR sizeof(wchar_t) + +RakWString::RakWString() +{ + c_str=0; + c_strCharLength=0; +} +RakWString::RakWString( const RakString &right ) +{ + c_str=0; + c_strCharLength=0; + *this=right; +} +RakWString::RakWString( const char *input ) +{ + c_str=0; + c_strCharLength=0; + *this = input; +} +RakWString::RakWString( const wchar_t *input ) +{ + c_str=0; + c_strCharLength=0; + *this = input; +} +RakWString::RakWString( const RakWString & right) +{ + c_str=0; + c_strCharLength=0; + *this = right; +} +RakWString::~RakWString() +{ + rakFree_Ex(c_str,_FILE_AND_LINE_); +} +RakWString& RakWString::operator = ( const RakWString& right ) +{ + Clear(); + if (right.IsEmpty()) + return *this; + c_str = (wchar_t *) rakMalloc_Ex( (right.GetLength() + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + if (!c_str) + { + c_strCharLength=0; + notifyOutOfMemory(_FILE_AND_LINE_); + return *this; + } + c_strCharLength = right.GetLength(); + memcpy(c_str,right.C_String(),(right.GetLength() + 1) * MAX_BYTES_PER_UNICODE_CHAR); + + return *this; +} +RakWString& RakWString::operator = ( const RakString& right ) +{ + return *this = right.C_String(); +} +RakWString& RakWString::operator = ( const wchar_t * const str ) +{ + Clear(); + if (str==0) + return *this; + c_strCharLength = wcslen(str); + if (c_strCharLength==0) + return *this; + c_str = (wchar_t *) rakMalloc_Ex( (c_strCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + if (!c_str) + { + c_strCharLength=0; + notifyOutOfMemory(_FILE_AND_LINE_); + return *this; + } + wcscpy(c_str,str); + + return *this; +} +RakWString& RakWString::operator = ( wchar_t *str ) +{ + *this = ( const wchar_t * const) str; + return *this; +} +RakWString& RakWString::operator = ( const char * const str ) +{ + Clear(); + +// Not supported on android +#if !defined(ANDROID) + if (str==0) + return *this; + if (str[0]==0) + return *this; + + c_strCharLength = mbstowcs(NULL, str, 0); + c_str = (wchar_t *) rakMalloc_Ex( (c_strCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + if (!c_str) + { + c_strCharLength=0; + notifyOutOfMemory(_FILE_AND_LINE_); + return *this; + } + + c_strCharLength = mbstowcs(c_str, str, c_strCharLength+1); + if (c_strCharLength == (size_t) (-1)) + { + RAKNET_DEBUG_PRINTF("Couldn't convert string--invalid multibyte character.\n"); + Clear(); + return *this; + } +#else + // mbstowcs not supported on android + RakAssert("mbstowcs not supported on Android" && 0); +#endif // defined(ANDROID) + + return *this; +} +RakWString& RakWString::operator = ( char *str ) +{ + *this = ( const char * const) str; + return *this; +} +RakWString& RakWString::operator +=( const RakWString& right) +{ + if (right.IsEmpty()) + return *this; + size_t newCharLength = c_strCharLength + right.GetLength(); + wchar_t *newCStr; + bool isEmpty = IsEmpty(); + if (isEmpty) + newCStr = (wchar_t *) rakMalloc_Ex( (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + else + newCStr = (wchar_t *) rakRealloc_Ex( c_str, (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + if (!newCStr) + { + notifyOutOfMemory(_FILE_AND_LINE_); + return *this; + } + c_str = newCStr; + c_strCharLength = newCharLength; + if (isEmpty) + { + memcpy(newCStr,right.C_String(),(right.GetLength() + 1) * MAX_BYTES_PER_UNICODE_CHAR); + } + else + { + wcscat(c_str, right.C_String()); + } + + return *this; +} +RakWString& RakWString::operator += ( const wchar_t * const right ) +{ + if (right==0) + return *this; + size_t rightLength = wcslen(right); + size_t newCharLength = c_strCharLength + rightLength; + wchar_t *newCStr; + bool isEmpty = IsEmpty(); + if (isEmpty) + newCStr = (wchar_t *) rakMalloc_Ex( (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + else + newCStr = (wchar_t *) rakRealloc_Ex( c_str, (newCharLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + if (!newCStr) + { + notifyOutOfMemory(_FILE_AND_LINE_); + return *this; + } + c_str = newCStr; + c_strCharLength = newCharLength; + if (isEmpty) + { + memcpy(newCStr,right,(rightLength + 1) * MAX_BYTES_PER_UNICODE_CHAR); + } + else + { + wcscat(c_str, right); + } + + return *this; +} +RakWString& RakWString::operator += ( wchar_t *right ) +{ + return *this += (const wchar_t * const) right; +} +bool RakWString::operator==(const RakWString &right) const +{ + if (GetLength()!=right.GetLength()) + return false; + return wcscmp(C_String(),right.C_String())==0; +} +bool RakWString::operator < ( const RakWString& right ) const +{ + return wcscmp(C_String(),right.C_String())<0; +} +bool RakWString::operator <= ( const RakWString& right ) const +{ + return wcscmp(C_String(),right.C_String())<=0; +} +bool RakWString::operator > ( const RakWString& right ) const +{ + return wcscmp(C_String(),right.C_String())>0; +} +bool RakWString::operator >= ( const RakWString& right ) const +{ + return wcscmp(C_String(),right.C_String())>=0; +} +bool RakWString::operator!=(const RakWString &right) const +{ + if (GetLength()!=right.GetLength()) + return true; + return wcscmp(C_String(),right.C_String())!=0; +} +void RakWString::Set( wchar_t *str ) +{ + *this = str; +} +bool RakWString::IsEmpty(void) const +{ + return GetLength()==0; +} +size_t RakWString::GetLength(void) const +{ + return c_strCharLength; +} +unsigned long RakWString::ToInteger(const RakWString &rs) +{ + unsigned long hash = 0; + int c; + + const char *str = (const char *)rs.C_String(); + size_t i; + for (i=0; i < rs.GetLength()*MAX_BYTES_PER_UNICODE_CHAR*sizeof(wchar_t); i++) + { + c = *str++; + hash = c + (hash << 6) + (hash << 16) - hash; + } + + return hash; +} +int RakWString::StrCmp(const RakWString &right) const +{ + return wcscmp(C_String(), right.C_String()); +} +int RakWString::StrICmp(const RakWString &right) const +{ +#ifdef _WIN32 + return _wcsicmp(C_String(), right.C_String()); +#else + // Not supported + return wcscmp(C_String(), right.C_String()); +#endif +} +void RakWString::Clear(void) +{ + rakFree_Ex(c_str,_FILE_AND_LINE_); + c_str=0; + c_strCharLength=0; +} +void RakWString::Printf(void) +{ + printf("%ls", C_String()); +} +void RakWString::FPrintf(FILE *fp) +{ + fprintf(fp,"%ls", C_String()); +} +void RakWString::Serialize(BitStream *bs) const +{ + Serialize(C_String(), bs); +} +void RakWString::Serialize(const wchar_t * const str, BitStream *bs) +{ +#if 0 + char *multiByteBuffer; + size_t allocated = wcslen(str)*MAX_BYTES_PER_UNICODE_CHAR; + multiByteBuffer = (char*) rakMalloc_Ex(allocated, _FILE_AND_LINE_); + size_t used = wcstombs(multiByteBuffer, str, allocated); + bs->WriteCasted(used); + bs->WriteAlignedBytes((const unsigned char*) multiByteBuffer,(const unsigned int) used); + rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); +#else + size_t mbByteLength = wcslen(str); + bs->WriteCasted(mbByteLength); + for (unsigned int i=0; i < mbByteLength; i++) + { + uint16_t t; + t = (uint16_t) str[i]; + // Force endian swapping, and write to 16 bits + bs->Write(t); + } +#endif +} +bool RakWString::Deserialize(BitStream *bs) +{ + Clear(); + + size_t mbByteLength; + bs->ReadCasted(mbByteLength); + if (mbByteLength>0) + { +#if 0 + char *multiByteBuffer; + multiByteBuffer = (char*) rakMalloc_Ex(mbByteLength+1, _FILE_AND_LINE_); + bool result = bs->ReadAlignedBytes((unsigned char*) multiByteBuffer,(const unsigned int) mbByteLength); + if (result==false) + { + rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); + return false; + } + multiByteBuffer[mbByteLength]=0; + c_str = (wchar_t *) rakMalloc_Ex( (mbByteLength + 1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + c_strCharLength = mbstowcs(c_str, multiByteBuffer, mbByteLength); + rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); + c_str[c_strCharLength]=0; +#else + c_str = (wchar_t*) rakMalloc_Ex((mbByteLength+1) * MAX_BYTES_PER_UNICODE_CHAR, _FILE_AND_LINE_); + c_strCharLength = mbByteLength; + for (unsigned int i=0; i < mbByteLength; i++) + { + uint16_t t; + // Force endian swapping, and read 16 bits + bs->Read(t); + c_str[i]=t; + } + c_str[mbByteLength]=0; +#endif + return true; + } + else + { + return true; + } +} +bool RakWString::Deserialize(wchar_t *str, BitStream *bs) +{ + size_t mbByteLength; + bs->ReadCasted(mbByteLength); + if (mbByteLength>0) + { +#if 0 + char *multiByteBuffer; + multiByteBuffer = (char*) rakMalloc_Ex(mbByteLength+1, _FILE_AND_LINE_); + bool result = bs->ReadAlignedBytes((unsigned char*) multiByteBuffer,(const unsigned int) mbByteLength); + if (result==false) + { + rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); + return false; + } + multiByteBuffer[mbByteLength]=0; + size_t c_strCharLength = mbstowcs(str, multiByteBuffer, mbByteLength); + rakFree_Ex(multiByteBuffer, _FILE_AND_LINE_); + str[c_strCharLength]=0; +#else + for (unsigned int i=0; i < mbByteLength; i++) + { + uint16_t t; + // Force endian swapping, and read 16 bits + bs->Read(t); + str[i]=t; + } + str[mbByteLength]=0; +#endif + return true; + } + else + { + wcscpy(str,L""); + } + return true; +} + +/* +RakNet::BitStream bsTest; +RakNet::RakWString testString("cat"), testString2; +testString = "Hllo"; +testString = L"Hello"; +testString += L" world"; +testString2 += testString2; +RakNet::RakWString ts3(L" from here"); +testString2+=ts3; +RakNet::RakWString ts4(L" 222"); +testString2=ts4; +RakNet::RakString rs("rakstring"); +testString2+=rs; +testString2=rs; +bsTest.Write(L"one"); +bsTest.Write(testString2); +bsTest.SetReadOffset(0); +RakNet::RakWString ts5, ts6; +wchar_t buff[99]; +wchar_t *wptr = (wchar_t*)buff; +bsTest.Read(wptr); +bsTest.Read(ts5); +*/ diff --git a/src/raknet/Rand.cpp b/src/raknet/Rand.cpp new file mode 100644 index 0000000..b6fcc4a --- /dev/null +++ b/src/raknet/Rand.cpp @@ -0,0 +1,274 @@ +/** +* +* Grabbed by Kevin from http://www.math.keio.ac.jp/~matumoto/cokus.c +* This is the ``Mersenne Twister'' random number generator MT19937, which +* generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) +* starting from any odd seed in 0..(2^32 - 1). This version is a recode +* by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by +* Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in +* July-August 1997). +* +* Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha +* running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to +* generate 300 million random numbers; after recoding: 24.0 sec. for the same +* (i.e., 46.5% of original time), so speed is now about 12.5 million random +* number generations per second on this machine. +* +* According to the URL +* (and paraphrasing a bit in places), the Mersenne Twister is ``designed +* with consideration of the flaws of various existing generators,'' has +* a period of 2^19937 - 1, gives a sequence that is 623-dimensionally +* equidistributed, and ``has passed many stringent tests, including the +* die-hard test of G. Marsaglia and the load test of P. Hellekalek and +* S. Wegenkittl.'' It is efficient in memory usage (typically using 2506 +* to 5012 bytes of static data, depending on data type sizes, and the code +* is quite short as well). It generates random numbers in batches of 624 +* at a time, so the caching and pipelining of modern systems is exploited. +* It is also divide- and mod-free. +* +* Licensing is free http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/elicense.html +* +* The code as Shawn received it included the following notice: +* +* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When +* you use this, send an e-mail to with +* an appropriate reference to your work. +* +* It would be nice to CC: when you write. +*/ + +#include +#include +#include +#include "include/raknet/Rand.hpp" + +// +// uint32 must be an unsigned integer type capable of holding at least 32 +// bits; exactly 32 should be fastest, but 64 is better on an Alpha with +// GCC at -O3 optimization so try your options and see what's best for you +// + +//typedef unsigned int uint32; + +#define N (624) // length of state vector +#define M (397) // a period parameter +#define K (0x9908B0DFU) // a magic constant +#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u +#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u +#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u +#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v + +static unsigned int _state[ N + 1 ]; // state vector + 1 extra to not violate ANSI C +static unsigned int *_next; // next random value is computed from here +static int _left = -1; // can *next++ this many times before reloading + +using namespace RakNet; + +void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &left ); +unsigned int reloadMT( unsigned int *state, unsigned int *&next, int &left ); +unsigned int randomMT( unsigned int *state, unsigned int *&next, int &left ); +void fillBufferMT( void *buffer, unsigned int bytes, unsigned int *state, unsigned int *&next, int &left ); +float frandomMT( unsigned int *state, unsigned int *&next, int &left ); + +// Uses global vars +void seedMT( unsigned int seed ) +{ + seedMT(seed, _state, _next, _left); +} +unsigned int reloadMT( void ) +{ + return reloadMT(_state, _next, _left); +} +unsigned int randomMT( void ) +{ + return randomMT(_state, _next, _left); +} +float frandomMT( void ) +{ + return frandomMT(_state, _next, _left); +} +void fillBufferMT( void *buffer, unsigned int bytes ) +{ + fillBufferMT(buffer, bytes, _state, _next, _left); +} + +void seedMT( unsigned int seed, unsigned int *state, unsigned int *&next, int &left ) // Defined in cokus_c.c +{ + (void) next; + + // + // We initialize state[0..(N-1)] via the generator + // + // x_new = (69069 * x_old) mod 2^32 + // + // from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's + // _The Art of Computer Programming_, Volume 2, 3rd ed. + // + // Notes (SJC): I do not know what the initial state requirements + // of the Mersenne Twister are, but it seems this seeding generator + // could be better. It achieves the maximum period for its modulus + // (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if + // x_initial can be even, you have sequences like 0, 0, 0, ...; + // 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31, + // 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below. + // + // Even if x_initial is odd, if x_initial is 1 mod 4 then + // + // the lowest bit of x is always 1, + // the next-to-lowest bit of x is always 0, + // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , + // the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... , + // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... , + // ... + // + // and if x_initial is 3 mod 4 then + // + // the lowest bit of x is always 1, + // the next-to-lowest bit of x is always 1, + // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , + // the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... , + // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... , + // ... + // + // The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is + // 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It + // also does well in the dimension 2..5 spectral tests, but it could be + // better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth). + // + // Note that the random number user does not see the values generated + // here directly since reloadMT() will always munge them first, so maybe + // none of all of this matters. In fact, the seed values made here could + // even be extra-special desirable if the Mersenne Twister theory says + // so-- that's why the only change I made is to restrict to odd seeds. + // + + register unsigned int x = ( seed | 1U ) & 0xFFFFFFFFU, *s = state; + register int j; + + for ( left = 0, *s++ = x, j = N; --j; + *s++ = ( x *= 69069U ) & 0xFFFFFFFFU ) + + ; +} + + +unsigned int reloadMT( unsigned int *state, unsigned int *&next, int &left ) +{ + register unsigned int * p0 = state, *p2 = state + 2, *pM = state + M, s0, s1; + register int j; + + if ( left < -1 ) + seedMT( 4357U ); + + left = N - 1, next = state + 1; + + for ( s0 = state[ 0 ], s1 = state[ 1 ], j = N - M + 1; --j; s0 = s1, s1 = *p2++ ) + * p0++ = *pM++ ^ ( mixBits( s0, s1 ) >> 1 ) ^ ( loBit( s1 ) ? K : 0U ); + + for ( pM = state, j = M; --j; s0 = s1, s1 = *p2++ ) + * p0++ = *pM++ ^ ( mixBits( s0, s1 ) >> 1 ) ^ ( loBit( s1 ) ? K : 0U ); + + s1 = state[ 0 ], *p0 = *pM ^ ( mixBits( s0, s1 ) >> 1 ) ^ ( loBit( s1 ) ? K : 0U ); + + s1 ^= ( s1 >> 11 ); + + s1 ^= ( s1 << 7 ) & 0x9D2C5680U; + + s1 ^= ( s1 << 15 ) & 0xEFC60000U; + + return ( s1 ^ ( s1 >> 18 ) ); +} + + +unsigned int randomMT( unsigned int *state, unsigned int *&next, int &left ) +{ + unsigned int y; + + if ( --left < 0 ) + return ( reloadMT(state, next, left) ); + + y = *next++; + + y ^= ( y >> 11 ); + + y ^= ( y << 7 ) & 0x9D2C5680U; + + y ^= ( y << 15 ) & 0xEFC60000U; + + return ( y ^ ( y >> 18 ) ); + + // This change made so the value returned is in the same range as what rand() returns + // return(y ^ (y >> 18)) % 32767; +} + +void fillBufferMT( void *buffer, unsigned int bytes, unsigned int *state, unsigned int *&next, int &left ) +{ + unsigned int offset=0; + unsigned int r; + while (bytes-offset>=sizeof(r)) + { + r = randomMT(state, next, left); + memcpy((char*)buffer+offset, &r, sizeof(r)); + offset+=sizeof(r); + } + + r = randomMT(state, next, left); + memcpy((char*)buffer+offset, &r, bytes-offset); +} + +float frandomMT( unsigned int *state, unsigned int *&next, int &left ) +{ + return ( float ) ( ( double ) randomMT(state, next, left) / 4294967296.0 ); +} +RakNetRandom::RakNetRandom() +{ + left=-1; +} +RakNetRandom::~RakNetRandom() +{ +} +void RakNetRandom::SeedMT( unsigned int seed ) +{ + printf("%i\n",seed); + seedMT(seed, state, next, left); +} + +unsigned int RakNetRandom::ReloadMT( void ) +{ + return reloadMT(state, next, left); +} + +unsigned int RakNetRandom::RandomMT( void ) +{ + return randomMT(state, next, left); +} + +float RakNetRandom::FrandomMT( void ) +{ + return frandomMT(state, next, left); +} + +void RakNetRandom::FillBufferMT( void *buffer, unsigned int bytes ) +{ + fillBufferMT(buffer, bytes, state, next, left); +} + +/* +int main(void) +{ +int j; + +// you can seed with any uint32, but the best are odds in 0..(2^32 - 1) + +seedMT(4357U); + +// print the first 2,002 random numbers seven to a line as an example + +for(j=0; j<2002; j++) +RAKNET_DEBUG_PRINTF(" %10lu%s", (unsigned int) randomMT(), (j%7)==6 ? "\n" : ""); + +return(EXIT_SUCCESS); +} + +*/ + diff --git a/src/raknet/RandSync.cpp b/src/raknet/RandSync.cpp new file mode 100644 index 0000000..71d8006 --- /dev/null +++ b/src/raknet/RandSync.cpp @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/RandSync.hpp" +#include "include/raknet/BitStream.hpp" +#include +#include + +namespace RakNet +{ + +RakNetRandomSync::RakNetRandomSync() +{ + seed = (uint32_t) -1; + callCount = 0; + usedValueBufferCount = 0; +} +RakNetRandomSync::~RakNetRandomSync() +{ +} +void RakNetRandomSync::SeedMT( uint32_t _seed ) +{ + seed = _seed; + rnr.SeedMT( seed ); + callCount = 0; + usedValueBufferCount = 0; +} +void RakNetRandomSync::SeedMT( uint32_t _seed, uint32_t skipValues ) +{ + SeedMT(_seed); + Skip(skipValues); +} +float RakNetRandomSync::FrandomMT( void ) +{ + return ( float ) ( ( double ) RandomMT() / (double) UINT_MAX ); +} +unsigned int RakNetRandomSync::RandomMT( void ) +{ + if (usedValueBufferCount > 0) + { + --usedValueBufferCount; + if (usedValueBufferCount < usedValues.Size()) + { + // The remote system had less calls than the current system, so return values from the past + return usedValues[usedValues.Size()-usedValueBufferCount-1]; + } + else + { + // Unknown past value, too far back + // Return true random + return rnr.RandomMT(); + } + } + else + { + // Get random number and store what it is + usedValues.Push(rnr.RandomMT(), _FILE_AND_LINE_); + ++callCount; + while (usedValues.Size()>64) + usedValues.Pop(); + return usedValues[usedValues.Size()-1]; + } +} +uint32_t RakNetRandomSync::GetSeed( void ) const +{ + return seed; +} +uint32_t RakNetRandomSync::GetCallCount( void ) const +{ + return callCount; +} +void RakNetRandomSync::SetCallCount( uint32_t i ) +{ + callCount = i; +} +void RakNetRandomSync::SerializeConstruction(RakNet::BitStream *constructionBitstream) +{ + constructionBitstream->Write(seed); + constructionBitstream->Write(callCount); +} +bool RakNetRandomSync::DeserializeConstruction(RakNet::BitStream *constructionBitstream) +{ + uint32_t _seed; + uint32_t _skipValues; + constructionBitstream->Read(_seed); + bool success = constructionBitstream->Read(_skipValues); + if (success) + SeedMT(_seed, _skipValues); + return success; +} +void RakNetRandomSync::Serialize(RakNet::BitStream *outputBitstream) +{ + outputBitstream->Write(callCount); +} +void RakNetRandomSync::Deserialize(RakNet::BitStream *outputBitstream) +{ + uint32_t _callCount; + outputBitstream->Read(_callCount); + if (_callCount < callCount ) + { + // We locally read more values than the remote system + // The next n calls should come from buffered values + usedValueBufferCount = callCount - _callCount; + } + else if (_callCount > callCount ) + { + // Remote system read more values than us + uint32_t diff = _callCount - callCount; + if (diff <= usedValueBufferCount) + usedValueBufferCount -= diff; + if (diff > 0) + Skip(diff); + } +} +void RakNetRandomSync::Skip( uint32_t count ) +{ + for (uint32_t i = 0; i < count; i++) + rnr.RandomMT(); + callCount+=count; +} + +} // namespace RakNet + +/* +RakNetRandomSync r1, r2; +BitStream bsTest; +r1.SeedMT(0); +r1.SerializeConstruction(&bsTest); +bsTest.SetReadOffset(0); +r2.DeserializeConstruction(&bsTest); +printf("1. (r1) %f\n", r1.FrandomMT()); +printf("1. (r2) %f\n", r2.FrandomMT()); +printf("2. (r1) %f\n", r1.FrandomMT()); +printf("2. (r2) %f\n", r2.FrandomMT()); +printf("3. (r1) %f\n", r1.FrandomMT()); +printf("3. (r2) %f\n", r2.FrandomMT()); +printf("4. (r1) %f\n", r1.FrandomMT()); +printf("4. (r2) %f\n", r2.FrandomMT()); +printf("5. (r2) %f\n", r2.FrandomMT()); +printf("6. (r2) %f\n", r2.FrandomMT()); +printf("7. (r2) %f\n", r2.FrandomMT()); +bsTest.Reset(); +r1.Serialize(&bsTest); +bsTest.SetReadOffset(0); +r2.Deserialize(&bsTest); +printf("Synched r2 to match r1\n"); +printf("5. (r1) %f\n", r1.FrandomMT()); +printf("5. (r2) %f --Should continue sequence from 5-\n", r2.FrandomMT()); +printf("6. (r1) %f\n", r1.FrandomMT()); +printf("6. (r2) %f\n", r2.FrandomMT()); +printf("7. (r1) %f -- Extra call to r1, no r2 equivalent --\n", r1.FrandomMT()); +printf("8. (r1) %f -- Extra call to r1, no r2 equivalent --\n", r1.FrandomMT()); +bsTest.Reset(); +r1.Serialize(&bsTest); +bsTest.SetReadOffset(0); +r2.Deserialize(&bsTest); +printf("Synched r2 to match r1\n"); +printf("9. (r1) %f\n", r1.FrandomMT()); +printf("9. (r2) %f --SKIPPED 7,8, SHOULD MATCH 9-\n", r2.FrandomMT()); +*/ \ No newline at end of file diff --git a/src/raknet/ReadyEvent.cpp b/src/raknet/ReadyEvent.cpp new file mode 100644 index 0000000..f5943c9 --- /dev/null +++ b/src/raknet/ReadyEvent.cpp @@ -0,0 +1,572 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_ReadyEvent==1 + +#include "include/raknet/ReadyEvent.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakAssert.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +int RakNet::ReadyEvent::RemoteSystemCompByGuid( const RakNetGUID &key, const RemoteSystem &data ) +{ + if (key < data.rakNetGuid) + return -1; + else if (key==data.rakNetGuid) + return 0; + else + return 1; +} + +int RakNet::ReadyEvent::ReadyEventNodeComp( const int &key, ReadyEvent::ReadyEventNode * const &data ) +{ + if (key < data->eventId) + return -1; + else if (key==data->eventId) + return 0; + else + return 1; +} + +STATIC_FACTORY_DEFINITIONS(ReadyEvent,ReadyEvent); + +ReadyEvent::ReadyEvent() +{ + channel=0; +} + +ReadyEvent::~ReadyEvent() +{ + Clear(); +} + + +bool ReadyEvent::SetEvent(int eventId, bool isReady) +{ + bool objectExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists==false) + { + // Totally new event + CreateNewEvent(eventId, isReady); + } + else + { + return SetEventByIndex(eventIndex, isReady); + } + return true; +} +void ReadyEvent::ForceCompletion(int eventId) +{ + bool objectExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists==false) + { + // Totally new event + CreateNewEvent(eventId, true); + eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + } + + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + ren->eventStatus=ID_READY_EVENT_FORCE_ALL_SET; + UpdateReadyStatus(eventIndex); +} +bool ReadyEvent::DeleteEvent(int eventId) +{ + bool objectExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + RakNet::OP_DELETE(readyEventNodeList[eventIndex], _FILE_AND_LINE_); + readyEventNodeList.RemoveAtIndex(eventIndex); + return true; + } + return false; +} +bool ReadyEvent::IsEventSet(int eventId) +{ + bool objectExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + return readyEventNodeList[eventIndex]->eventStatus==ID_READY_EVENT_SET || readyEventNodeList[eventIndex]->eventStatus==ID_READY_EVENT_ALL_SET; + } + return false; +} +bool ReadyEvent::IsEventCompletionProcessing(int eventId) const +{ + bool objectExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + bool anyAllReady=false; + bool allAllReady=true; + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) + return false; + for (unsigned i=0; i < ren->systemList.Size(); i++) + { + if (ren->systemList[i].lastReceivedStatus==ID_READY_EVENT_ALL_SET) + anyAllReady=true; + else + allAllReady=false; + } + return anyAllReady==true && allAllReady==false; + } + return false; +} +bool ReadyEvent::IsEventCompleted(int eventId) const +{ + bool objectExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + return IsEventCompletedByIndex(eventIndex); + } + return false; +} + +bool ReadyEvent::HasEvent(int eventId) +{ + return readyEventNodeList.HasData(eventId); +} + +unsigned ReadyEvent::GetEventListSize(void) const +{ + return readyEventNodeList.Size(); +} + +int ReadyEvent::GetEventAtIndex(unsigned index) const +{ + return readyEventNodeList[index]->eventId; +} + +bool ReadyEvent::AddToWaitList(int eventId, RakNetGUID guid) +{ + bool eventExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &eventExists); + if (eventExists==false) + eventIndex=CreateNewEvent(eventId, false); + + // Don't do this, otherwise if we are trying to start a 3 player game, it will not allow the 3rd player to hit ready if the first two players have already done so + //if (IsLocked(eventIndex)) + // return false; // Not in the list, but event is already completed, or is starting to complete, and adding more waiters would fail this. + + unsigned i; + unsigned numAdded=0; + if (guid==UNASSIGNED_RAKNET_GUID) + { + for (i=0; i < rakPeerInterface->GetMaximumNumberOfPeers(); i++) + { + RakNetGUID firstGuid = rakPeerInterface->GetGUIDFromIndex(i); + if (firstGuid!=UNASSIGNED_RAKNET_GUID) + { + numAdded+=AddToWaitListInternal(eventIndex, firstGuid); + } + } + } + else + { + numAdded=AddToWaitListInternal(eventIndex, guid); + } + + if (numAdded>0) + UpdateReadyStatus(eventIndex); + return numAdded>0; +} +bool ReadyEvent::RemoveFromWaitList(int eventId, RakNetGUID guid) +{ + bool eventExists; + unsigned eventIndex = readyEventNodeList.GetIndexFromKey(eventId, &eventExists); + if (eventExists) + { + if (guid==UNASSIGNED_RAKNET_GUID) + { + // Remove all waiters + readyEventNodeList[eventIndex]->systemList.Clear(false, _FILE_AND_LINE_); + UpdateReadyStatus(eventIndex); + } + else + { + bool systemExists; + unsigned systemIndex = readyEventNodeList[eventIndex]->systemList.GetIndexFromKey(guid, &systemExists); + if (systemExists) + { + bool isCompleted = IsEventCompletedByIndex(eventIndex); + readyEventNodeList[eventIndex]->systemList.RemoveAtIndex(systemIndex); + + if (isCompleted==false && IsEventCompletedByIndex(eventIndex)) + PushCompletionPacket(readyEventNodeList[eventIndex]->eventId); + + UpdateReadyStatus(eventIndex); + + return true; + } + } + } + + return false; +} +bool ReadyEvent::IsInWaitList(int eventId, RakNetGUID guid) +{ + bool objectExists; + unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + return readyEventNodeList[readyIndex]->systemList.HasData(guid); + } + return false; +} + +unsigned ReadyEvent::GetRemoteWaitListSize(int eventId) const +{ + bool objectExists; + unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + return readyEventNodeList[readyIndex]->systemList.Size(); + } + return 0; +} + +RakNetGUID ReadyEvent::GetFromWaitListAtIndex(int eventId, unsigned index) const +{ + bool objectExists; + unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + return readyEventNodeList[readyIndex]->systemList[index].rakNetGuid; + } + return UNASSIGNED_RAKNET_GUID; +} +ReadyEventSystemStatus ReadyEvent::GetReadyStatus(int eventId, RakNetGUID guid) +{ + bool objectExists; + unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + ReadyEventNode *ren = readyEventNodeList[readyIndex]; + unsigned systemIndex = ren->systemList.GetIndexFromKey(guid, &objectExists); + if (objectExists==false) + return RES_NOT_WAITING; + if (ren->systemList[systemIndex].lastReceivedStatus==ID_READY_EVENT_SET) + return RES_READY; + if (ren->systemList[systemIndex].lastReceivedStatus==ID_READY_EVENT_UNSET) + return RES_WAITING; + if (ren->systemList[systemIndex].lastReceivedStatus==ID_READY_EVENT_ALL_SET) + return RES_ALL_READY; + } + + return RES_UNKNOWN_EVENT; +} +void ReadyEvent::SetSendChannel(unsigned char newChannel) +{ + channel=newChannel; +} +PluginReceiveResult ReadyEvent::OnReceive(Packet *packet) +{ + unsigned char packetIdentifier; + packetIdentifier = ( unsigned char ) packet->data[ 0 ]; + +// bool doPrint = packet->systemAddress.GetPort()==60002 || rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS).GetPort()==60002; + + switch (packetIdentifier) + { + case ID_READY_EVENT_UNSET: + case ID_READY_EVENT_SET: + case ID_READY_EVENT_ALL_SET: +// if (doPrint) {if (packet->systemAddress.GetPort()==60002) RAKNET_DEBUG_PRINTF("FROM 60002: "); else if (rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS).port==60002) RAKNET_DEBUG_PRINTF("TO 60002: "); RAKNET_DEBUG_PRINTF("ID_READY_EVENT_SET\n");} + OnReadyEventPacketUpdate(packet); + return RR_CONTINUE_PROCESSING; + case ID_READY_EVENT_FORCE_ALL_SET: + OnReadyEventForceAllSet(packet); + return RR_CONTINUE_PROCESSING; + case ID_READY_EVENT_QUERY: +// if (doPrint) {if (packet->systemAddress.GetPort()==60002) RAKNET_DEBUG_PRINTF("FROM 60002: "); else if (rakPeerInterface->GetInternalID(UNASSIGNED_SYSTEM_ADDRESS).port==60002) RAKNET_DEBUG_PRINTF("TO 60002: "); RAKNET_DEBUG_PRINTF("ID_READY_EVENT_QUERY\n");} + OnReadyEventQuery(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + return RR_CONTINUE_PROCESSING; +} +bool ReadyEvent::AddToWaitListInternal(unsigned eventIndex, RakNetGUID guid) +{ + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + bool objectExists; + unsigned systemIndex = ren->systemList.GetIndexFromKey(guid, &objectExists); + if (objectExists==false) + { + RemoteSystem rs; + rs.lastReceivedStatus=ID_READY_EVENT_UNSET; + rs.lastSentStatus=ID_READY_EVENT_UNSET; + rs.rakNetGuid=guid; + ren->systemList.InsertAtIndex(rs,systemIndex, _FILE_AND_LINE_); + + SendReadyStateQuery(ren->eventId, guid); + return true; + } + return false; +} +void ReadyEvent::OnReadyEventForceAllSet(Packet *packet) +{ + RakNet::BitStream incomingBitStream(packet->data, packet->length, false); + incomingBitStream.IgnoreBits(8); + int eventId; + incomingBitStream.Read(eventId); + bool objectExists; + unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + ReadyEventNode *ren = readyEventNodeList[readyIndex]; + if (ren->eventStatus!=ID_READY_EVENT_FORCE_ALL_SET) + { + ren->eventStatus=ID_READY_EVENT_FORCE_ALL_SET; + PushCompletionPacket(ren->eventId); + } + } +} +void ReadyEvent::OnReadyEventPacketUpdate(Packet *packet) +{ + RakNet::BitStream incomingBitStream(packet->data, packet->length, false); + incomingBitStream.IgnoreBits(8); + int eventId; + incomingBitStream.Read(eventId); + bool objectExists; + unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + ReadyEventNode *ren = readyEventNodeList[readyIndex]; + bool systemExists; + unsigned systemIndex = ren->systemList.GetIndexFromKey(packet->guid, &systemExists); + if (systemExists) + { + // Just return if no change + if (ren->systemList[systemIndex].lastReceivedStatus==packet->data[0]) + return; + + bool wasCompleted = IsEventCompletedByIndex(readyIndex); + ren->systemList[systemIndex].lastReceivedStatus=packet->data[0]; + // If forced all set, doesn't matter what the new packet is + if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) + return; + UpdateReadyStatus(readyIndex); + if (wasCompleted==false && IsEventCompletedByIndex(readyIndex)) + PushCompletionPacket(readyIndex); + } + } +} +void ReadyEvent::OnReadyEventQuery(Packet *packet) +{ + RakNet::BitStream incomingBitStream(packet->data, packet->length, false); + incomingBitStream.IgnoreBits(8); + int eventId; + incomingBitStream.Read(eventId); + bool objectExists; + unsigned readyIndex = readyEventNodeList.GetIndexFromKey(eventId, &objectExists); + if (objectExists) + { + unsigned systemIndex = readyEventNodeList[readyIndex]->systemList.GetIndexFromKey(packet->guid,&objectExists); + // Force the non-default send, because our initial send may have arrived at a system that didn't yet create the ready event + if (objectExists) + SendReadyUpdate(readyIndex, systemIndex, true); + } +} +void ReadyEvent::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) systemAddress; + (void) rakNetGUID; + (void) lostConnectionReason; + + RemoveFromAllLists(rakNetGUID); +} +void ReadyEvent::OnRakPeerShutdown(void) +{ + Clear(); +} + +bool ReadyEvent::SetEventByIndex(int eventIndex, bool isReady) +{ + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + if ((ren->eventStatus==ID_READY_EVENT_ALL_SET || ren->eventStatus==ID_READY_EVENT_SET) && isReady==true) + return false; // Success - no change + if (ren->eventStatus==ID_READY_EVENT_UNSET && isReady==false) + return false; // Success - no change + if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) + return false; // Can't change + + if (isReady) + ren->eventStatus=ID_READY_EVENT_SET; + else + ren->eventStatus=ID_READY_EVENT_UNSET; + + UpdateReadyStatus(eventIndex); + + // Check if now completed, and if so, tell the user about it + if (IsEventCompletedByIndex(eventIndex)) + { + PushCompletionPacket(ren->eventId); + } + + return true; +} + +bool ReadyEvent::IsEventCompletedByIndex(unsigned eventIndex) const +{ + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + unsigned i; + if (ren->eventStatus==ID_READY_EVENT_FORCE_ALL_SET) + return true; + if (ren->eventStatus!=ID_READY_EVENT_ALL_SET) + return false; + for (i=0; i < ren->systemList.Size(); i++) + if (ren->systemList[i].lastReceivedStatus!=ID_READY_EVENT_ALL_SET) + return false; + return true; +} + +void ReadyEvent::Clear(void) +{ + unsigned i; + for (i=0; i < readyEventNodeList.Size(); i++) + { + RakNet::OP_DELETE(readyEventNodeList[i], _FILE_AND_LINE_); + } + readyEventNodeList.Clear(false, _FILE_AND_LINE_); +} + +unsigned ReadyEvent::CreateNewEvent(int eventId, bool isReady) +{ + ReadyEventNode *ren = RakNet::OP_NEW( _FILE_AND_LINE_ ); + ren->eventId=eventId; + if (isReady==false) + ren->eventStatus=ID_READY_EVENT_UNSET; + else + ren->eventStatus=ID_READY_EVENT_SET; + return readyEventNodeList.Insert(eventId, ren, true, _FILE_AND_LINE_); +} +void ReadyEvent::UpdateReadyStatus(unsigned eventIndex) +{ + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + bool anyUnset; + unsigned i; + if (ren->eventStatus==ID_READY_EVENT_SET) + { + // If you are set, and no other systems are ID_READY_EVENT_UNSET, then change your status to ID_READY_EVENT_ALL_SET + anyUnset=false; + for (i=0; i < ren->systemList.Size(); i++) + { + if (ren->systemList[i].lastReceivedStatus==ID_READY_EVENT_UNSET) + { + anyUnset=true; + break; + } + } + if (anyUnset==false) + { + ren->eventStatus=ID_READY_EVENT_ALL_SET; + } + } + else if (ren->eventStatus==ID_READY_EVENT_ALL_SET) + { + // If you are all set, and any systems are ID_READY_EVENT_UNSET, then change your status to ID_READY_EVENT_SET + anyUnset=false; + for (i=0; i < ren->systemList.Size(); i++) + { + if (ren->systemList[i].lastReceivedStatus==ID_READY_EVENT_UNSET) + { + anyUnset=true; + break; + } + } + if (anyUnset==true) + { + ren->eventStatus=ID_READY_EVENT_SET; + } + } + BroadcastReadyUpdate(eventIndex, false); +} +void ReadyEvent::SendReadyUpdate(unsigned eventIndex, unsigned systemIndex, bool forceIfNotDefault) +{ + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + RakNet::BitStream bs; + // I do this rather than write true or false, so users that do not use BitStreams can still read the data + if ((ren->eventStatus!=ren->systemList[systemIndex].lastSentStatus) || + (forceIfNotDefault && ren->eventStatus!=ID_READY_EVENT_UNSET)) + { + bs.Write(ren->eventStatus); + bs.Write(ren->eventId); + SendUnified(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, channel, ren->systemList[systemIndex].rakNetGuid, false); + + ren->systemList[systemIndex].lastSentStatus=ren->eventStatus; + } + +} +void ReadyEvent::BroadcastReadyUpdate(unsigned eventIndex, bool forceIfNotDefault) +{ + ReadyEventNode *ren = readyEventNodeList[eventIndex]; + unsigned systemIndex; + for (systemIndex=0; systemIndex < ren->systemList.Size(); systemIndex++) + { + SendReadyUpdate(eventIndex, systemIndex, forceIfNotDefault); + } +} +void ReadyEvent::SendReadyStateQuery(unsigned eventId, RakNetGUID guid) +{ + RakNet::BitStream bs; + bs.Write((MessageID)ID_READY_EVENT_QUERY); + bs.Write(eventId); + SendUnified(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, channel, guid, false); +} +void ReadyEvent::RemoveFromAllLists(RakNetGUID guid) +{ + unsigned eventIndex; + for (eventIndex=0; eventIndex < readyEventNodeList.Size(); eventIndex++) + { + bool isCompleted = IsEventCompletedByIndex(eventIndex); + bool systemExists; + unsigned systemIndex; + + systemIndex = readyEventNodeList[eventIndex]->systemList.GetIndexFromKey(guid, &systemExists); + if (systemExists) + readyEventNodeList[eventIndex]->systemList.RemoveAtIndex(systemIndex); + + UpdateReadyStatus(eventIndex); + + if (isCompleted==false && IsEventCompletedByIndex(eventIndex)) + PushCompletionPacket(readyEventNodeList[eventIndex]->eventId); + } +} +void ReadyEvent::PushCompletionPacket(unsigned eventId) +{ + (void) eventId; + // Not necessary + /* + // Pass a packet to the user that we are now completed, as setting ourselves to signaled was the last thing being waited on + Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(int)); + RakNet::BitStream bs(p->data, sizeof(MessageID)+sizeof(int), false); + bs.SetWriteOffset(0); + bs.Write((MessageID)ID_READY_EVENT_ALL_SET); + bs.Write(eventId); + rakPeerInterface->PushBackPacket(p, false); + */ +} +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/RelayPlugin.cpp b/src/raknet/RelayPlugin.cpp new file mode 100644 index 0000000..cd2e26b --- /dev/null +++ b/src/raknet/RelayPlugin.cpp @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_RelayPlugin==1 + +#include "include/raknet/RelayPlugin.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/BitStream.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(RelayPlugin,RelayPlugin); + +RelayPlugin::RelayPlugin() +{ + acceptAddParticipantRequests=false; +} + +RelayPlugin::~RelayPlugin() +{ + DataStructures::List itemList; + DataStructures::List keyList; + strToGuidHash.GetAsList(itemList, keyList, _FILE_AND_LINE_); + guidToStrHash.Clear(_FILE_AND_LINE_); + for (unsigned int i=0; i < itemList.Size(); i++) + RakNet::OP_DELETE(itemList[i], _FILE_AND_LINE_); + for (unsigned int i=0; i < chatRooms.Size(); i++) + RakNet::OP_DELETE(chatRooms[i], _FILE_AND_LINE_); +} + +RelayPluginEnums RelayPlugin::AddParticipantOnServer(const RakString &key, const RakNetGUID &guid) +{ + ConnectionState cs = rakPeerInterface->GetConnectionState(guid); + if (cs!=IS_CONNECTED) + return RPE_ADD_CLIENT_TARGET_NOT_CONNECTED; + + if (strToGuidHash.HasData(key)==true) + return RPE_ADD_CLIENT_NAME_ALREADY_IN_USE; // Name already in use + + // If GUID is already in use, remove existing + StrAndGuidAndRoom *strAndGuidExisting; + if (guidToStrHash.Pop(strAndGuidExisting, guid, _FILE_AND_LINE_)) + { + strToGuidHash.Remove(strAndGuidExisting->str, _FILE_AND_LINE_); + RakNet::OP_DELETE(strAndGuidExisting, _FILE_AND_LINE_); + } + + StrAndGuidAndRoom *strAndGuid = RakNet::OP_NEW(_FILE_AND_LINE_); + strAndGuid->guid=guid; + strAndGuid->str=key; + + strToGuidHash.Push(key, strAndGuid, _FILE_AND_LINE_); + guidToStrHash.Push(guid, strAndGuid, _FILE_AND_LINE_); + + return RPE_ADD_CLIENT_SUCCESS; +} +void RelayPlugin::RemoveParticipantOnServer(const RakNetGUID &guid) +{ + StrAndGuidAndRoom *strAndGuid; + if (guidToStrHash.Pop(strAndGuid, guid, _FILE_AND_LINE_)) + { + LeaveGroup(&strAndGuid); + strToGuidHash.Remove(strAndGuid->str, _FILE_AND_LINE_); + RakNet::OP_DELETE(strAndGuid, _FILE_AND_LINE_); + } +} + +void RelayPlugin::SetAcceptAddParticipantRequests(bool accept) +{ + acceptAddParticipantRequests=accept; +} +void RelayPlugin::AddParticipantRequestFromClient(const RakString &key, const RakNetGUID &relayPluginServerGuid) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_ADD_CLIENT_REQUEST_FROM_CLIENT); + bsOut.WriteCompressed(key); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, relayPluginServerGuid, false); +} +void RelayPlugin::RemoveParticipantRequestFromClient(const RakNetGUID &relayPluginServerGuid) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_REMOVE_CLIENT_REQUEST_FROM_CLIENT); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, relayPluginServerGuid, false); +} +// Send a message to a server running RelayPlugin, to forward a message to the system identified by \a key +void RelayPlugin::SendToParticipant(const RakNetGUID &relayPluginServerGuid, const RakString &key, BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_MESSAGE_TO_SERVER_FROM_CLIENT); + bsOut.WriteCasted(priority); + bsOut.WriteCasted(reliability); + bsOut.Write(orderingChannel); + bsOut.WriteCompressed(key); + bsOut.Write(bitStream); + SendUnified(&bsOut, priority, reliability, orderingChannel, relayPluginServerGuid, false); +} +void RelayPlugin::SendGroupMessage(const RakNetGUID &relayPluginServerGuid, BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_GROUP_MESSAGE_FROM_CLIENT); + bsOut.WriteCasted(priority); + bsOut.WriteCasted(reliability); + bsOut.Write(orderingChannel); + bsOut.Write(bitStream); + SendUnified(&bsOut, priority, reliability, orderingChannel, relayPluginServerGuid, false); +} +void RelayPlugin::LeaveGroup(const RakNetGUID &relayPluginServerGuid) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_LEAVE_GROUP_REQUEST_FROM_CLIENT); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, relayPluginServerGuid, false); +} +void RelayPlugin::GetGroupList(const RakNetGUID &relayPluginServerGuid) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_GET_GROUP_LIST_REQUEST_FROM_CLIENT); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, relayPluginServerGuid, false); +} +PluginReceiveResult RelayPlugin::OnReceive(Packet *packet) +{ + if (packet->data[0]==ID_RELAY_PLUGIN) + { + switch (packet->data[1]) + { + case RPE_MESSAGE_TO_SERVER_FROM_CLIENT: + { + BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + PacketPriority priority; + PacketReliability reliability; + char orderingChannel; + unsigned char cIn; + bsIn.Read(cIn); + priority = (PacketPriority) cIn; + bsIn.Read(cIn); + reliability = (PacketReliability) cIn; + bsIn.Read(orderingChannel); + RakString key; + bsIn.ReadCompressed(key); + BitStream bsData; + bsIn.Read(&bsData); + StrAndGuidAndRoom **strAndGuid = strToGuidHash.Peek(key); + StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(packet->guid); + if (strAndGuid && strAndGuidSender) + { + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_MESSAGE_TO_CLIENT_FROM_SERVER); + bsOut.WriteCompressed( (*strAndGuidSender)->str ); + bsOut.AlignWriteToByteBoundary(); + bsOut.Write(bsData); + SendUnified(&bsOut, priority, reliability, orderingChannel, (*strAndGuid)->guid, false); + } + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + case RPE_ADD_CLIENT_REQUEST_FROM_CLIENT: + { + BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + RakString key; + bsIn.ReadCompressed(key); + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + if (acceptAddParticipantRequests) + bsOut.WriteCasted(AddParticipantOnServer(key, packet->guid)); + else + bsOut.WriteCasted(RPE_ADD_CLIENT_NOT_ALLOWED); + bsOut.WriteCompressed(key); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case RPE_REMOVE_CLIENT_REQUEST_FROM_CLIENT: + { + RemoveParticipantOnServer(packet->guid); + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case RPE_GROUP_MESSAGE_FROM_CLIENT: + { + OnGroupMessageFromClient(packet); + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case RPE_JOIN_GROUP_REQUEST_FROM_CLIENT: + { + OnJoinGroupRequestFromClient(packet); + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case RPE_LEAVE_GROUP_REQUEST_FROM_CLIENT: + { + OnLeaveGroupRequestFromClient(packet); + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case RPE_GET_GROUP_LIST_REQUEST_FROM_CLIENT: + { + SendChatRoomsList(packet->guid); + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + } + + return RR_CONTINUE_PROCESSING; +} + +void RelayPlugin::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + + RemoveParticipantOnServer(rakNetGUID); +} + +RelayPlugin::RP_Group* RelayPlugin::JoinGroup(RP_Group* room, StrAndGuidAndRoom **strAndGuidSender) +{ + if (strAndGuidSender==0) + return 0; + + NotifyUsersInRoom(room, RPE_USER_ENTERED_ROOM, (*strAndGuidSender)->str); + StrAndGuid sag; + sag.guid=(*strAndGuidSender)->guid; + sag.str=(*strAndGuidSender)->str; + + room->usersInRoom.Push(sag, _FILE_AND_LINE_); + (*strAndGuidSender)->currentRoom=room->roomName; + + return room; +} +void RelayPlugin::JoinGroupRequest(const RakNetGUID &relayPluginServerGuid, RakString groupName) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_JOIN_GROUP_REQUEST_FROM_CLIENT); + bsOut.WriteCompressed(groupName); + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, relayPluginServerGuid, false); +} +RelayPlugin::RP_Group* RelayPlugin::JoinGroup(RakNetGUID userGuid, RakString roomName) +{ + StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(userGuid); + if (strAndGuidSender) + { + if (roomName.IsEmpty()) + return 0; + + if ((*strAndGuidSender)->currentRoom==roomName) + return 0; + + if ((*strAndGuidSender)->currentRoom.IsEmpty()==false) + LeaveGroup(strAndGuidSender); + + RakString userName = (*strAndGuidSender)->str; + + for (unsigned int i=0; i < chatRooms.Size(); i++) + { + if (chatRooms[i]->roomName==roomName) + { + // Join existing room + return JoinGroup(chatRooms[i],strAndGuidSender); + } + } + + // Create new room + RP_Group *room = RakNet::OP_NEW(_FILE_AND_LINE_); + room->roomName=roomName; + chatRooms.Push(room, _FILE_AND_LINE_); + return JoinGroup(room,strAndGuidSender); + } + + return 0; +} +void RelayPlugin::LeaveGroup(StrAndGuidAndRoom **strAndGuidSender) +{ + if (strAndGuidSender==0) + return; + + RakString userName = (*strAndGuidSender)->str; + for (unsigned int i=0; i < chatRooms.Size(); i++) + { + if (chatRooms[i]->roomName==(*strAndGuidSender)->currentRoom) + { + (*strAndGuidSender)->currentRoom.Clear(); + + RP_Group *room = chatRooms[i]; + for (unsigned int j=0; j < room->usersInRoom.Size(); j++) + { + if (room->usersInRoom[j].guid==(*strAndGuidSender)->guid) + { + room->usersInRoom.RemoveAtIndexFast(j); + + if (room->usersInRoom.Size()==0) + { + RakNet::OP_DELETE(room, _FILE_AND_LINE_); + chatRooms.RemoveAtIndexFast(i); + return; + } + } + } + + NotifyUsersInRoom(room, RPE_USER_LEFT_ROOM, userName); + + return; + + } + } +} +void RelayPlugin::NotifyUsersInRoom(RP_Group *room, int msg, const RakString& message) +{ + for (unsigned int i=0; i < room->usersInRoom.Size(); i++) + { + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(msg); + bsOut.WriteCompressed(message); + + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, room->usersInRoom[i].guid, false); + } +} +void RelayPlugin::SendMessageToRoom(StrAndGuidAndRoom **strAndGuidSender, BitStream* message) +{ + if ((*strAndGuidSender)->currentRoom.IsEmpty()) + return; + + for (unsigned int i=0; i < chatRooms.Size(); i++) + { + if (chatRooms[i]->roomName==(*strAndGuidSender)->currentRoom) + { + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_GROUP_MSG_FROM_SERVER); + message->ResetReadPointer(); + bsOut.WriteCompressed((*strAndGuidSender)->str); + bsOut.AlignWriteToByteBoundary(); + bsOut.Write(message); + + RP_Group *room = chatRooms[i]; + for (unsigned int i=0; i < room->usersInRoom.Size(); i++) + { + if (room->usersInRoom[i].guid!=(*strAndGuidSender)->guid) + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, room->usersInRoom[i].guid, false); + } + + break; + } + } +} +void RelayPlugin::SendChatRoomsList(RakNetGUID target) +{ + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + bsOut.WriteCasted(RPE_GET_GROUP_LIST_REPLY_FROM_SERVER); + bsOut.WriteCasted(chatRooms.Size()); + for (unsigned int i=0; i < chatRooms.Size(); i++) + { + bsOut.WriteCompressed(chatRooms[i]->roomName); + bsOut.WriteCasted(chatRooms[i]->usersInRoom.Size()); + } + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, target, false); +} +void RelayPlugin::OnGroupMessageFromClient(Packet *packet) +{ + BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + PacketPriority priority; + PacketReliability reliability; + char orderingChannel; + unsigned char cIn; + bsIn.Read(cIn); + priority = (PacketPriority) cIn; + bsIn.Read(cIn); + reliability = (PacketReliability) cIn; + bsIn.Read(orderingChannel); + BitStream bsData; + bsIn.Read(&bsData); + + StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(packet->guid); + if (strAndGuidSender) + { + SendMessageToRoom(strAndGuidSender,&bsData); + } +} +void RelayPlugin::OnJoinGroupRequestFromClient(Packet *packet) +{ + BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + RakString groupName; + bsIn.ReadCompressed(groupName); + RelayPlugin::RP_Group *groupJoined = JoinGroup(packet->guid, groupName); + + BitStream bsOut; + bsOut.WriteCasted(ID_RELAY_PLUGIN); + if (groupJoined) + { + bsOut.WriteCasted(RPE_JOIN_GROUP_SUCCESS); + bsOut.WriteCasted(groupJoined->usersInRoom.Size()); + for (unsigned int i=0; i < groupJoined->usersInRoom.Size(); i++) + { + bsOut.WriteCompressed(groupJoined->usersInRoom[i].str); + } + } + else + { + bsOut.WriteCasted(RPE_JOIN_GROUP_FAILURE); + } + + SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); +} +void RelayPlugin::OnLeaveGroupRequestFromClient(Packet *packet) +{ + BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + StrAndGuidAndRoom **strAndGuidSender = guidToStrHash.Peek(packet->guid); + if (strAndGuidSender) + LeaveGroup(strAndGuidSender); +} +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/ReliabilityLayer.cpp b/src/raknet/ReliabilityLayer.cpp new file mode 100644 index 0000000..dda7541 --- /dev/null +++ b/src/raknet/ReliabilityLayer.cpp @@ -0,0 +1,3957 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + + +#include "include/raknet/ReliabilityLayer.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/PluginInterface2.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/Rand.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#ifdef USE_THREADED_SEND +#include "include/raknet/SendToThread.hpp" +#endif +#include + +using namespace RakNet; + +// Can't figure out which library has this function on the PS3 +double Ceil(double d) {if (((double)((int)d))==d) return d; return (int) (d+1.0);} + +// #if defined(new) +// #pragma push_macro("new") +// #undef new +// #define RELIABILITY_LAYER_NEW_UNDEF_ALLOCATING_QUEUE +// #endif + + +//#define _DEBUG_LOGGER + +#if CC_TIME_TYPE_BYTES==4 +static const CCTimeType MAX_TIME_BETWEEN_PACKETS= 350; // 350 milliseconds +static const CCTimeType HISTOGRAM_RESTART_CYCLE=10000; // Every 10 seconds reset the histogram +#else +static const CCTimeType MAX_TIME_BETWEEN_PACKETS= 350000; // 350 milliseconds +//static const CCTimeType HISTOGRAM_RESTART_CYCLE=10000000; // Every 10 seconds reset the histogram +#endif +static const int DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE=512; +static const CCTimeType STARTING_TIME_BETWEEN_PACKETS=MAX_TIME_BETWEEN_PACKETS; +//static const long double TIME_BETWEEN_PACKETS_INCREASE_MULTIPLIER_DEFAULT=.02; +//static const long double TIME_BETWEEN_PACKETS_DECREASE_MULTIPLIER_DEFAULT=1.0 / 9.0; + +typedef uint32_t BitstreamLengthEncoding; + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +//#define PRINT_TO_FILE_RELIABLE_ORDERED_TEST +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST +static unsigned int packetNumber=0; +static FILE *fp=0; +#endif + +//#define FLIP_SEND_ORDER_TEST +//#define LOG_TRIVIAL_NOTIFICATIONS + +BPSTracker::TimeAndValue2::TimeAndValue2() {} +BPSTracker::TimeAndValue2::~TimeAndValue2() {} +BPSTracker::TimeAndValue2::TimeAndValue2(RakNet::TimeUS t, uint64_t v1) : value1(v1), time(t) {} +//BPSTracker::TimeAndValue2::TimeAndValue2(RakNet::TimeUS t, uint64_t v1, uint64_t v2) : time(t), value1(v1), value2(v2) {} +BPSTracker::BPSTracker() {Reset(_FILE_AND_LINE_);} +BPSTracker::~BPSTracker() {} +//void BPSTracker::Reset(const char *file, unsigned int line) {total1=total2=lastSec1=lastSec2=0; dataQueue.Clear(file,line);} +void BPSTracker::Reset(const char *file, unsigned int line) {total1=lastSec1=0; dataQueue.Clear(file,line);} +//void BPSTracker::Push2(RakNetTimeUS time, uint64_t value1, uint64_t value2) {dataQueue.Push(TimeAndValue2(time,value1,value2),_FILE_AND_LINE_); total1+=value1; lastSec1+=value1; total2+=value2; lastSec2+=value2;} +//uint64_t BPSTracker::GetBPS2(RakNetTimeUS time) {ClearExpired2(time); return lastSec2;} +//void BPSTracker::GetBPS1And2(RakNetTimeUS time, uint64_t &out1, uint64_t &out2) {ClearExpired2(time); out1=lastSec1; out2=lastSec2;} +uint64_t BPSTracker::GetTotal1(void) const {return total1;} +//uint64_t BPSTracker::GetTotal2(void) const {return total2;} + +// void BPSTracker::ClearExpired2(RakNet::TimeUS time) { +// RakNet::TimeUS threshold=time; +// if (threshold < 1000000) +// return; +// threshold-=1000000; +// while (dataQueue.IsEmpty()==false && dataQueue.Peek().time < threshold) +// { +// lastSec1-=dataQueue.Peek().value1; +// lastSec2-=dataQueue.Peek().value2; +// dataQueue.Pop(); +// } +// } +void BPSTracker::ClearExpired1(RakNet::TimeUS time) +{ + while (dataQueue.IsEmpty()==false && +#if CC_TIME_TYPE_BYTES==8 + dataQueue.Peek().time+1000000 < time +#else + dataQueue.Peek().time+1000 < time +#endif + ) + { + lastSec1-=dataQueue.Peek().value1; + dataQueue.Pop(); + } +} + +struct DatagramHeaderFormat +{ +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + CCTimeType sourceSystemTime; +#endif + DatagramSequenceNumberType datagramNumber; + + // Use floats to save bandwidth + // float B; // Link capacity + float AS; // Data arrival rate + bool isACK; + bool isNAK; + bool isPacketPair; + bool hasBAndAS; + bool isContinuousSend; + bool needsBAndAs; + bool isValid; // To differentiate between what I serialized, and offline data + + static BitSize_t GetDataHeaderBitLength() + { + return BYTES_TO_BITS(GetDataHeaderByteLength()); + } + + static unsigned int GetDataHeaderByteLength() + { + //return 2 + 3 + sizeof(RakNet::TimeMS) + sizeof(float)*2; + return 2 + 3 + +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + sizeof(RakNetTimeMS) + +#endif + sizeof(float)*1; + } + + void Serialize(RakNet::BitStream *b) + { + // Not endian safe + // RakAssert(GetDataHeaderByteLength()==sizeof(DatagramHeaderFormat)); + // b->WriteAlignedBytes((const unsigned char*) this, sizeof(DatagramHeaderFormat)); + // return; + + b->Write(true); // IsValid + if (isACK) + { + b->Write(true); + b->Write(hasBAndAS); + b->AlignWriteToByteBoundary(); +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + RakNet::TimeMS timeMSLow=(RakNet::TimeMS) sourceSystemTime&0xFFFFFFFF; b->Write(timeMSLow); +#endif + if (hasBAndAS) + { + // b->Write(B); + b->Write(AS); + } + } + else if (isNAK) + { + b->Write(false); + b->Write(true); + } + else + { + b->Write(false); + b->Write(false); + b->Write(isPacketPair); + b->Write(isContinuousSend); + b->Write(needsBAndAs); + b->AlignWriteToByteBoundary(); +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + RakNet::TimeMS timeMSLow=(RakNet::TimeMS) sourceSystemTime&0xFFFFFFFF; b->Write(timeMSLow); +#endif + b->Write(datagramNumber); + } + } + void Deserialize(RakNet::BitStream *b) + { + // Not endian safe + // b->ReadAlignedBytes((unsigned char*) this, sizeof(DatagramHeaderFormat)); + // return; + + b->Read(isValid); + b->Read(isACK); + if (isACK) + { + isNAK=false; + isPacketPair=false; + b->Read(hasBAndAS); + b->AlignReadToByteBoundary(); +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + RakNet::TimeMS timeMS; b->Read(timeMS); sourceSystemTime=(CCTimeType) timeMS; +#endif + if (hasBAndAS) + { + // b->Read(B); + b->Read(AS); + } + } + else + { + b->Read(isNAK); + if (isNAK) + { + isPacketPair=false; + } + else + { + b->Read(isPacketPair); + b->Read(isContinuousSend); + b->Read(needsBAndAs); + b->AlignReadToByteBoundary(); +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + RakNet::TimeMS timeMS; b->Read(timeMS); sourceSystemTime=(CCTimeType) timeMS; +#endif + b->Read(datagramNumber); + } + } + } +}; + +#if !defined(__GNUC__) && !defined(__ARMCC) +#pragma warning(disable:4702) // unreachable code +#endif + +#ifdef _WIN32 +//#define _DEBUG_LOGGER +#ifdef _DEBUG_LOGGER +#include "include/raknet/WindowsIncludes.hpp" +#endif +#endif + +//#define DEBUG_SPLIT_PACKET_PROBLEMS +#if defined (DEBUG_SPLIT_PACKET_PROBLEMS) +static int waitFlag=-1; +#endif + +using namespace RakNet; + +int RakNet::SplitPacketChannelComp( SplitPacketIdType const &key, SplitPacketChannel* const &data ) +{ +#if PREALLOCATE_LARGE_MESSAGES==1 + if (key < data->returnedPacket->splitPacketId) + return -1; + if (key == data->returnedPacket->splitPacketId) + return 0; +#else + if (key < data->splitPacketList[0]->splitPacketId) + return -1; + if (key == data->splitPacketList[0]->splitPacketId) + return 0; +#endif + return 1; +} + +// DEFINE_MULTILIST_PTR_TO_MEMBER_COMPARISONS( InternalPacket, SplitPacketIndexType, splitPacketIndex ) +/* +bool operator<( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) +{ + return inputKey.Get() < cls->splitPacketIndex; +} +bool operator>( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) +{ + return inputKey.Get() > cls->splitPacketIndex; +} +bool operator==( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) +{ + return inputKey.Get() == cls->splitPacketIndex; +} +/// Semi-hack: This is necessary to call Sort() +bool operator<( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) +{ + return inputKey.Get()->splitPacketIndex < cls->splitPacketIndex; +} +bool operator>( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) +{ + return inputKey.Get()->splitPacketIndex > cls->splitPacketIndex; +} +bool operator==( const DataStructures::MLKeyRef &inputKey, const InternalPacket *cls ) +{ + return inputKey.Get()->splitPacketIndex == cls->splitPacketIndex; +} +*/ + +int SplitPacketIndexComp( SplitPacketIndexType const &key, InternalPacket* const &data ) +{ +if (key < data->splitPacketIndex) +return -1; +if (key == data->splitPacketIndex) +return 0; +return 1; +} + +//------------------------------------------------------------------------------------------------------- +// Constructor +//------------------------------------------------------------------------------------------------------- +// Add 21 to the default MTU so if we encrypt it can hold potentially 21 more bytes of extra data + padding. +ReliabilityLayer::ReliabilityLayer() +{ + +#ifdef _DEBUG + // Wait longer to disconnect in debug so I don't get disconnected while tracing + timeoutTime=30000; +#else + timeoutTime=10000; +#endif + +#ifdef _DEBUG + minExtraPing=extraPingVariance=0; + packetloss=(double) minExtraPing; +#endif + + +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + if (fp==0 && 0) + { + fp = fopen("reliableorderedoutput.txt", "wt"); + } +#endif + + InitializeVariables(); +//int i = sizeof(InternalPacket); + datagramHistoryMessagePool.SetPageSize(sizeof(MessageNumberNode)*128); + internalPacketPool.SetPageSize(sizeof(InternalPacket)*INTERNAL_PACKET_PAGE_SIZE); + refCountedDataPool.SetPageSize(sizeof(InternalPacketRefCountedData)*32); +} + +//------------------------------------------------------------------------------------------------------- +// Destructor +//------------------------------------------------------------------------------------------------------- +ReliabilityLayer::~ReliabilityLayer() +{ + FreeMemory( true ); // Free all memory immediately +} +//------------------------------------------------------------------------------------------------------- +// Resets the layer for reuse +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::Reset( bool resetVariables, int MTUSize, bool _useSecurity ) +{ + + FreeMemory( true ); // true because making a memory reset pending in the update cycle causes resets after reconnects. Instead, just call Reset from a single thread + if (resetVariables) + { + InitializeVariables(); + +#if LIBCAT_SECURITY==1 + useSecurity = _useSecurity; + + if (_useSecurity) + MTUSize -= cat::AuthenticatedEncryption::OVERHEAD_BYTES; +#else + (void) _useSecurity; +#endif // LIBCAT_SECURITY + congestionManager.Init(RakNet::GetTimeUS(), MTUSize - UDP_HEADER_SIZE); + } +} + +//------------------------------------------------------------------------------------------------------- +// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable packet +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::SetTimeoutTime( RakNet::TimeMS time ) +{ + timeoutTime=time; +} + +//------------------------------------------------------------------------------------------------------- +// Returns the value passed to SetTimeoutTime. or the default if it was never called +//------------------------------------------------------------------------------------------------------- +RakNet::TimeMS ReliabilityLayer::GetTimeoutTime(void) +{ + return timeoutTime; +} + +//------------------------------------------------------------------------------------------------------- +// Initialize the variables +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::InitializeVariables( void ) +{ + memset( orderedWriteIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType)); + memset( sequencedWriteIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType) ); + memset( orderedReadIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType) ); + memset( highestSequencedReadIndex, 0, NUMBER_OF_ORDERED_STREAMS * sizeof(OrderingIndexType) ); + memset( &statistics, 0, sizeof( statistics ) ); + memset( &heapIndexOffsets, 0, sizeof( heapIndexOffsets ) ); + + statistics.connectionStartTime = RakNet::GetTimeUS(); + splitPacketId = 0; + elapsedTimeSinceLastUpdate=0; + throughputCapCountdown=0; + sendReliableMessageNumberIndex = 0; + internalOrderIndex=0; + timeToNextUnreliableCull=0; + unreliableLinkedListHead=0; + lastUpdateTime= RakNet::GetTimeUS(); + bandwidthExceededStatistic=false; + remoteSystemTime=0; + unreliableTimeout=0; + lastBpsClear=0; + + // Disable packet pairs + countdownToNextPacketPair=15; + + nextAllowedThroughputSample=0; + deadConnection = cheater = false; + timeOfLastContinualSend=0; + + // timeResendQueueNonEmpty = 0; + timeLastDatagramArrived=RakNet::GetTimeMS(); + // packetlossThisSample=false; + // backoffThisSample=0; + // packetlossThisSampleResendCount=0; + // lastPacketlossTime=0; + statistics.messagesInResendBuffer=0; + statistics.bytesInResendBuffer=0; + + receivedPacketsBaseIndex=0; + resetReceivedPackets=true; + receivePacketCount=0; + + // SetPing( 1000 ); + + timeBetweenPackets=STARTING_TIME_BETWEEN_PACKETS; + + ackPingIndex=0; + ackPingSum=(CCTimeType)0; + + nextSendTime=lastUpdateTime; + //nextLowestPingReset=(CCTimeType)0; + // continuousSend=false; + + // histogramStart=(CCTimeType)0; + // histogramBitsSent=0; + unacknowledgedBytes=0; + resendLinkedListHead=0; + totalUserDataBytesAcked=0; + + datagramHistoryPopCount=0; + + InitHeapWeights(); + for (int i=0; i < NUMBER_OF_PRIORITIES; i++) + { + statistics.messageInSendBuffer[i]=0; + statistics.bytesInSendBuffer[i]=0.0; + } + + for (int i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) + { + bpsMetrics[i].Reset(_FILE_AND_LINE_); + } +} + +//------------------------------------------------------------------------------------------------------- +// Frees all allocated memory +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::FreeMemory( bool freeAllImmediately ) +{ + (void) freeAllImmediately; + FreeThreadSafeMemory(); +} + +void ReliabilityLayer::FreeThreadSafeMemory( void ) +{ + unsigned i,j; + InternalPacket *internalPacket; + + ClearPacketsAndDatagrams(); + + for (i=0; i < splitPacketChannelList.Size(); i++) + { + for (j=0; j < splitPacketChannelList[i]->splitPacketList.Size(); j++) + { + FreeInternalPacketData(splitPacketChannelList[i]->splitPacketList[j], _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( splitPacketChannelList[i]->splitPacketList[j] ); + } +#if PREALLOCATE_LARGE_MESSAGES==1 + if (splitPacketChannelList[i]->returnedPacket) + { + FreeInternalPacketData(splitPacketChannelList[i]->returnedPacket, __FILE__, __LINE__ ); + ReleaseToInternalPacketPool( splitPacketChannelList[i]->returnedPacket ); + } +#endif + RakNet::OP_DELETE(splitPacketChannelList[i], __FILE__, __LINE__); + } + splitPacketChannelList.Clear(false, _FILE_AND_LINE_); + + while ( outputQueue.Size() > 0 ) + { + internalPacket = outputQueue.Pop(); + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + } + + outputQueue.ClearAndForceAllocation( 32, _FILE_AND_LINE_ ); + + /* + for ( i = 0; i < orderingList.Size(); i++ ) + { + if ( orderingList[ i ] ) + { + DataStructures::LinkedList* theList = orderingList[ i ]; + + if ( theList ) + { + while ( theList->Size() ) + { + internalPacket = orderingList[ i ]->Pop(); + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + } + + RakNet::OP_DELETE(theList, _FILE_AND_LINE_); + } + } + } + + orderingList.Clear(false, _FILE_AND_LINE_); + */ + + for (i=0; i < NUMBER_OF_ORDERED_STREAMS; i++) + { + for (j=0; j < orderingHeaps[i].Size(); j++) + { + FreeInternalPacketData(orderingHeaps[i][j], _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( orderingHeaps[i][j] ); + } + orderingHeaps[i].Clear(true, _FILE_AND_LINE_); + } + + //resendList.ForEachData(DeleteInternalPacket); + // resendTree.Clear(_FILE_AND_LINE_); + memset(resendBuffer, 0, sizeof(resendBuffer)); + statistics.messagesInResendBuffer=0; + statistics.bytesInResendBuffer=0; + + if (resendLinkedListHead) + { + InternalPacket *prev; + InternalPacket *iter = resendLinkedListHead; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + if (iter->data) + FreeInternalPacketData(iter, _FILE_AND_LINE_ ); + prev=iter; + iter=iter->resendNext; + if (iter==resendLinkedListHead) + { + ReleaseToInternalPacketPool(prev); + break; + } + ReleaseToInternalPacketPool(prev); + } + resendLinkedListHead=0; + } + unacknowledgedBytes=0; + + // acknowlegements.Clear(_FILE_AND_LINE_); + + for ( j=0 ; j < outgoingPacketBuffer.Size(); j++ ) + { + if ( outgoingPacketBuffer[ j ]->data) + FreeInternalPacketData( outgoingPacketBuffer[ j ], _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( outgoingPacketBuffer[ j ] ); + } + + outgoingPacketBuffer.Clear(true, _FILE_AND_LINE_); + +#ifdef _DEBUG + for (unsigned i = 0; i < delayList.Size(); i++ ) + RakNet::OP_DELETE(delayList[ i ], __FILE__, __LINE__); + delayList.Clear(__FILE__, __LINE__); +#endif + + unreliableWithAckReceiptHistory.Clear(false, _FILE_AND_LINE_); + + packetsToSendThisUpdate.Clear(false, _FILE_AND_LINE_); + packetsToSendThisUpdate.Preallocate(512, _FILE_AND_LINE_); + packetsToDeallocThisUpdate.Clear(false, _FILE_AND_LINE_); + packetsToDeallocThisUpdate.Preallocate(512, _FILE_AND_LINE_); + packetsToSendThisUpdateDatagramBoundaries.Clear(false, _FILE_AND_LINE_); + packetsToSendThisUpdateDatagramBoundaries.Preallocate(128, _FILE_AND_LINE_); + datagramSizesInBytes.Clear(false, _FILE_AND_LINE_); + datagramSizesInBytes.Preallocate(128, _FILE_AND_LINE_); + + internalPacketPool.Clear(_FILE_AND_LINE_); + + refCountedDataPool.Clear(_FILE_AND_LINE_); + + /* + DataStructures::Page *cur = datagramMessageIDTree.GetListHead(); + while (cur) + { + int treeIndex; + for (treeIndex=0; treeIndex < cur->size; treeIndex++) + ReleaseToDatagramMessageIDPool(cur->data[treeIndex]); + cur=cur->resendNext; + } + datagramMessageIDTree.Clear(_FILE_AND_LINE_); + datagramMessageIDPool.Clear(_FILE_AND_LINE_); + */ + + while (datagramHistory.Size()) + { + RemoveFromDatagramHistory(datagramHistoryPopCount); + datagramHistory.Pop(); + datagramHistoryPopCount++; + } + datagramHistoryMessagePool.Clear(_FILE_AND_LINE_); + datagramHistoryPopCount=0; + + acknowlegements.Clear(); + NAKs.Clear(); + + unreliableLinkedListHead=0; +} + +//------------------------------------------------------------------------------------------------------- +// Packets are read directly from the socket layer and skip the reliability +//layer because unconnected players do not use the reliability layer +// This function takes packet data after a player has been confirmed as +//connected. The game should not use that data directly +// because some data is used internally, such as packet acknowledgment and +//split packets +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::HandleSocketReceiveFromConnectedPlayer( + const char *buffer, unsigned int length, SystemAddress &systemAddress, DataStructures::List &messageHandlerList, int MTUSize, + RakNetSocket2 *s, RakNetRandom *rnr, CCTimeType timeRead, + BitStream &updateBitStream) +{ +#ifdef _DEBUG + RakAssert( !( buffer == 0 ) ); +#endif + +#if CC_TIME_TYPE_BYTES==4 + timeRead/=1000; +#endif + + + bpsMetrics[(int) ACTUAL_BYTES_RECEIVED].Push1(timeRead,length); + + (void) MTUSize; + + if ( length <= 2 || buffer == 0 ) // Length of 1 is a connection request resend that we just ignore + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("length <= 2 || buffer == 0", BYTES_TO_BITS(length), systemAddress, true); + return true; + } + + timeLastDatagramArrived=RakNet::GetTimeMS(); + + // CCTimeType time; +// bool indexFound; +// int count, size; + DatagramSequenceNumberType holeCount; + unsigned i; + +#if LIBCAT_SECURITY==1 + if (useSecurity) + { + unsigned int received = length; + + if (!auth_enc.Decrypt((cat::u8*)buffer, received)) + return false; + + length = received; + } +#endif + + RakNet::BitStream socketData( (unsigned char*) buffer, length, false ); // Convert the incoming data to a bitstream for easy parsing + // time = RakNet::GetTimeUS(); + + // Set to the current time if it is not zero, and we get incoming data + // if (timeResendQueueNonEmpty!=0) + // timeResendQueueNonEmpty=timeRead; + + DatagramHeaderFormat dhf; + dhf.Deserialize(&socketData); + if (dhf.isValid==false) + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("dhf.isValid==false", BYTES_TO_BITS(length), systemAddress, true); + + return true; + } + if (dhf.isACK) + { + DatagramSequenceNumberType datagramNumber; + // datagramNumber=dhf.datagramNumber; + +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + RakNet::TimeMS timeMSLow=(RakNet::TimeMS) timeRead&0xFFFFFFFF; + CCTimeType rtt = timeMSLow-dhf.sourceSystemTime; +#if CC_TIME_TYPE_BYTES==4 + if (rtt > 10000) +#else + if (rtt > 10000000) +#endif + { + // Sanity check. This could happen due to type overflow, especially since I only send the low 4 bytes to reduce bandwidth + rtt=(CCTimeType) congestionManager.GetRTT(); + } + // RakAssert(rtt < 500000); + // printf("%i ", (RakNet::TimeMS)(rtt/1000)); + ackPing=rtt; +#endif + +#ifdef _DEBUG + if (dhf.hasBAndAS==false) + { + // dhf.B=0; + dhf.AS=0; + } +#endif + // congestionManager.OnAck(timeRead, rtt, dhf.hasBAndAS, dhf.B, dhf.AS, totalUserDataBytesAcked ); + + + incomingAcks.Clear(); + if (incomingAcks.Deserialize(&socketData)==false) + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingAcks.Deserialize failed", BYTES_TO_BITS(length), systemAddress, true); + + return false; + } + for (i=0; iincomingAcks.ranges[i].maxIndex || (incomingAcks.ranges[i].maxIndex == (uint24_t)(0xFFFFFFFF))) + { + RakAssert(incomingAcks.ranges[i].minIndex<=incomingAcks.ranges[i].maxIndex); + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingAcks minIndex > maxIndex or maxIndex is max value", BYTES_TO_BITS(length), systemAddress, true); + return false; + } + for (datagramNumber=incomingAcks.ranges[i].minIndex; datagramNumber >= incomingAcks.ranges[i].minIndex && datagramNumber <= incomingAcks.ranges[i].maxIndex; datagramNumber++) + { + CCTimeType whenSent; + + if (unreliableWithAckReceiptHistory.Size()>0) + { + unsigned int k=0; + while (k < unreliableWithAckReceiptHistory.Size()) + { + if (unreliableWithAckReceiptHistory[k].datagramNumber == datagramNumber) + { + InternalPacket *ackReceipt = AllocateFromInternalPacketPool(); + AllocInternalPacketData(ackReceipt, 5, false, _FILE_AND_LINE_ ); + ackReceipt->dataBitLength=BYTES_TO_BITS(5); + ackReceipt->data[0]=(MessageID)ID_SND_RECEIPT_ACKED; + memcpy(ackReceipt->data+sizeof(MessageID), &unreliableWithAckReceiptHistory[k].sendReceiptSerial, sizeof(uint32_t)); + outputQueue.Push(ackReceipt, _FILE_AND_LINE_ ); + + // Remove, swap with last + unreliableWithAckReceiptHistory.RemoveAtIndex(k); + } + else + k++; + } + } + + MessageNumberNode *messageNumberNode = GetMessageNumberNodeByDatagramIndex(datagramNumber, &whenSent); + if (messageNumberNode) + { + // printf("%p Got ack for %i\n", this, datagramNumber.val); +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + congestionManager.OnAck(timeRead, rtt, dhf.hasBAndAS, 0, dhf.AS, totalUserDataBytesAcked, bandwidthExceededStatistic, datagramNumber ); +#else + CCTimeType ping; + if (timeRead>whenSent) + ping=timeRead-whenSent; + else + ping=0; + congestionManager.OnAck(timeRead, ping, dhf.hasBAndAS, 0, dhf.AS, totalUserDataBytesAcked, bandwidthExceededStatistic, datagramNumber ); +#endif + while (messageNumberNode) + { + // TESTING1 +// printf("Remove %i on ack for datagramNumber=%i.\n", messageNumberNode->messageNumber.val, datagramNumber.val); + + RemovePacketFromResendListAndDeleteOlderReliableSequenced( messageNumberNode->messageNumber, timeRead, messageHandlerList, systemAddress ); + messageNumberNode=messageNumberNode->next; + } + + RemoveFromDatagramHistory(datagramNumber); + } +// else if (isReliable) +// { +// // Previously used slot, rather than empty unreliable slot +// printf("%p Ack %i is duplicate\n", this, datagramNumber.val); +// +// congestionManager.OnDuplicateAck(timeRead, datagramNumber); +// } + } + } + } + else if (dhf.isNAK) + { + DatagramSequenceNumberType messageNumber; + DataStructures::RangeList incomingNAKs; + if (incomingNAKs.Deserialize(&socketData)==false) + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingNAKs.Deserialize failed", BYTES_TO_BITS(length), systemAddress, true); + + return false; + } + for (i=0; iincomingNAKs.ranges[i].maxIndex) + { + RakAssert(incomingNAKs.ranges[i].minIndex<=incomingNAKs.ranges[i].maxIndex); + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("incomingNAKs minIndex>maxIndex", BYTES_TO_BITS(length), systemAddress, true); + + return false; + } + // Sanity check + //RakAssert(incomingNAKs.ranges[i].maxIndex.val-incomingNAKs.ranges[i].minIndex.val<1000); + for (messageNumber=incomingNAKs.ranges[i].minIndex; messageNumber >= incomingNAKs.ranges[i].minIndex && messageNumber <= incomingNAKs.ranges[i].maxIndex; messageNumber++) + { + congestionManager.OnNAK(timeRead, messageNumber); + + // REMOVEME + // printf("%p NAK %i\n", this, dhf.datagramNumber.val); + + + CCTimeType timeSent; + MessageNumberNode *messageNumberNode = GetMessageNumberNodeByDatagramIndex(messageNumber, &timeSent); + while (messageNumberNode) + { + // Update timers so resends occur immediately + InternalPacket *internalPacket = resendBuffer[messageNumberNode->messageNumber & (uint32_t) RESEND_BUFFER_ARRAY_MASK]; + if (internalPacket) + { + if (internalPacket->nextActionTime!=0) + { + internalPacket->nextActionTime=timeRead; + } + } + + messageNumberNode=messageNumberNode->next; + } + } + } + } + else + { + uint32_t skippedMessageCount; + if (!congestionManager.OnGotPacket(dhf.datagramNumber, dhf.isContinuousSend, timeRead, length, &skippedMessageCount)) + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("congestionManager.OnGotPacket failed", BYTES_TO_BITS(length), systemAddress, true); + + return true; + } + if (dhf.isPacketPair) + congestionManager.OnGotPacketPair(dhf.datagramNumber, length, timeRead); + + DatagramHeaderFormat dhfNAK; + dhfNAK.isNAK=true; + uint32_t skippedMessageOffset; + for (skippedMessageOffset=skippedMessageCount; skippedMessageOffset > 0; skippedMessageOffset--) + { + NAKs.Insert(dhf.datagramNumber-skippedMessageOffset); + } + remoteSystemNeedsBAndAS=dhf.needsBAndAs; + + // Ack dhf.datagramNumber + // Ack even unreliable messages for congestion control, just don't resend them on no ack +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + SendAcknowledgementPacket( dhf.datagramNumber, dhf.sourceSystemTime); +#else + SendAcknowledgementPacket( dhf.datagramNumber, 0); +#endif + + InternalPacket* internalPacket = CreateInternalPacketFromBitStream( &socketData, timeRead ); + if (internalPacket==0) + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("CreateInternalPacketFromBitStream failed", BYTES_TO_BITS(length), systemAddress, true); + + return true; + } + + while ( internalPacket ) + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + { +#if CC_TIME_TYPE_BYTES==4 + messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, receivePacketCount, systemAddress, timeRead, false); +#else + messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, receivePacketCount, systemAddress, (RakNet::TimeMS)(timeRead/(CCTimeType)1000), false); +#endif + } + + { + + // resetReceivedPackets is set from a non-threadsafe function. + // We do the actual reset in this function so the data is not modified by multiple threads + if (resetReceivedPackets) + { + hasReceivedPacketQueue.ClearAndForceAllocation(DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE, _FILE_AND_LINE_); + receivedPacketsBaseIndex=0; + resetReceivedPackets=false; + } + + // Check for corrupt orderingChannel + if ( + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED + ) + { + if ( internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) + { + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS", BYTES_TO_BITS(length), systemAddress, true); + + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + } + + // 8/12/09 was previously not checking if the message was reliable. However, on packetloss this would mean you'd eventually exceed the + // hole count because unreliable messages were never resent, and you'd stop getting messages + if (internalPacket->reliability == RELIABLE || internalPacket->reliability == RELIABLE_SEQUENCED || internalPacket->reliability == RELIABLE_ORDERED ) + { + // If the following conditional is true then this either a duplicate packet + // or an older out of order packet + // The subtraction unsigned overflow is intentional + holeCount = (DatagramSequenceNumberType)(internalPacket->reliableMessageNumber-receivedPacketsBaseIndex); + const DatagramSequenceNumberType typeRange = (DatagramSequenceNumberType)(uint32_t)-1; + + // TESTING1 +// printf("waiting on reliableMessageNumber=%i holeCount=%i datagramNumber=%i\n", receivedPacketsBaseIndex.val, holeCount.val, dhf.datagramNumber.val); + + if (holeCount==(DatagramSequenceNumberType) 0) + { + // Got what we were expecting + if (hasReceivedPacketQueue.Size()) + hasReceivedPacketQueue.Pop(); + ++receivedPacketsBaseIndex; + } + else if (holeCount > typeRange/(DatagramSequenceNumberType) 2) + { + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("holeCount > typeRange/(DatagramSequenceNumberType) 2", BYTES_TO_BITS(length), systemAddress, false); + + // Duplicate packet + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + else if ((unsigned int) holeCountOnReliabilityLayerNotification("Higher count pushed to hasReceivedPacketQueue", BYTES_TO_BITS(length), systemAddress, false); +#endif + + // Fill in the hole + hasReceivedPacketQueue[holeCount]=false; // We got the packet at holeCount + } + else + { + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + +#ifdef LOG_TRIVIAL_NOTIFICATIONS + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Duplicate packet ignored", BYTES_TO_BITS(length), systemAddress, false); +#endif + + // Duplicate packet + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + } + else // holeCount>=receivedPackets.Size() + { + if (holeCount > (DatagramSequenceNumberType) 1000000) + { + RakAssert("Hole count too high. See ReliabilityLayer.hpp" && 0); + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("holeCount > 1000000", BYTES_TO_BITS(length), systemAddress, true); + + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + // Would crash due to out of memory! + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + +#ifdef LOG_TRIVIAL_NOTIFICATIONS + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Adding to hasReceivedPacketQueue later ordered message", BYTES_TO_BITS(length), systemAddress, false); +#endif + + // Fix - sending on a higher priority gives us a very very high received packets base index if we formerly had pre-split a lot of messages and + // used that as the message number. Because of this, a lot of time is spent in this linear loop and the timeout time expires because not + // all of the message is sent in time. + // Fixed by late assigning message IDs on the sender + + // Add 0 times to the queue until (reliableMessageNumber - baseIndex) < queue size. + while ((unsigned int)(holeCount) > hasReceivedPacketQueue.Size()) + hasReceivedPacketQueue.Push(true, _FILE_AND_LINE_ ); // time+(CCTimeType)60 * (CCTimeType)1000 * (CCTimeType)1000); // Didn't get this packet - set the time to give up waiting + hasReceivedPacketQueue.Push(false, _FILE_AND_LINE_ ); // Got the packet +#ifdef _DEBUG + // If this assert hits then DatagramSequenceNumberType has overflowed + RakAssert(hasReceivedPacketQueue.Size() < (unsigned int)((DatagramSequenceNumberType)(const uint32_t)(-1))); +#endif + } + + while ( hasReceivedPacketQueue.Size()>0 && hasReceivedPacketQueue.Peek()==false ) + { + hasReceivedPacketQueue.Pop(); + ++receivedPacketsBaseIndex; + } + } + + // If the allocated buffer is > DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE and it is 3x greater than the number of elements actually being used + if (hasReceivedPacketQueue.AllocationSize() > (unsigned int) DEFAULT_HAS_RECEIVED_PACKET_QUEUE_SIZE && hasReceivedPacketQueue.AllocationSize() > hasReceivedPacketQueue.Size() * 3) + hasReceivedPacketQueue.Compress(_FILE_AND_LINE_); + + + /* + if ( internalPacket->reliability == RELIABLE_SEQUENCED || internalPacket->reliability == UNRELIABLE_SEQUENCED ) + { +#ifdef _DEBUG + RakAssert( internalPacket->orderingChannel < NUMBER_OF_ORDERED_STREAMS ); +#endif + + if ( internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) + { + + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS", BYTES_TO_BITS(length), systemAddress); + + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + + if ( IsOlderOrderedPacket( internalPacket->orderingIndex, waitingForSequencedPacketReadIndex[ internalPacket->orderingChannel ] ) == false ) + { + // Is this a split packet? + if ( internalPacket->splitPacketCount > 0 ) + { + // Generate the split + // Verify some parameters to make sure we don't get junk data + + + // Check for a rebuilt packet + InsertIntoSplitPacketList( internalPacket, timeRead ); + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + // Sequenced + internalPacket = BuildPacketFromSplitPacketList( internalPacket->splitPacketId, timeRead, + s, systemAddress, rnr, remotePortRakNetWasStartedOn_PS3, extraSocketOptions); + + if ( internalPacket ) + { + // Update our index to the newest packet + waitingForSequencedPacketReadIndex[ internalPacket->orderingChannel ] = internalPacket->orderingIndex + (OrderingIndexType)1; + + // If there is a rebuilt packet, add it to the output queue + outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); + internalPacket = 0; + } + + // else don't have all the parts yet + } + else + { + // Update our index to the newest packet + waitingForSequencedPacketReadIndex[ internalPacket->orderingChannel ] = internalPacket->orderingIndex + (OrderingIndexType)1; + + // Not a split packet. Add the packet to the output queue + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); + internalPacket = 0; + } + } + else + { + // Older sequenced packet. Discard it + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + } + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + + // Is this an unsequenced split packet? + if ( internalPacket->splitPacketCount > 0 ) + { + // Check for a rebuilt packet + if ( internalPacket->reliability != RELIABLE_ORDERED ) + internalPacket->orderingChannel = 255; // Use 255 to designate not sequenced and not ordered + + InsertIntoSplitPacketList( internalPacket, timeRead ); + + internalPacket = BuildPacketFromSplitPacketList( internalPacket->splitPacketId, timeRead, + s, systemAddress, rnr, remotePortRakNetWasStartedOn_PS3, extraSocketOptions); + + if ( internalPacket == 0 ) + { + + // Don't have all the parts yet + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + } + */ + + /* + if ( internalPacket->reliability == RELIABLE_ORDERED ) + { +#ifdef _DEBUG + RakAssert( internalPacket->orderingChannel < NUMBER_OF_ORDERED_STREAMS ); +#endif + + if ( internalPacket->orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) + { + // Invalid packet + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_IGNORED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + if ( waitingForOrderedPacketReadIndex[ internalPacket->orderingChannel ] == internalPacket->orderingIndex ) + { + // Get the list to hold ordered packets for this stream + DataStructures::LinkedList *orderingListAtOrderingStream; + unsigned char orderingChannelCopy = internalPacket->orderingChannel; + + // Push the packet for the user to read + outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); + internalPacket = 0; // Don't reference this any longer since other threads access it + + // Wait for the resendNext ordered packet in sequence + waitingForOrderedPacketReadIndex[ orderingChannelCopy ] ++; // This wraps + + orderingListAtOrderingStream = GetOrderingListAtOrderingStream( orderingChannelCopy ); + + if ( orderingListAtOrderingStream != 0) + { + while ( orderingListAtOrderingStream->Size() > 0 ) + { + // Cycle through the list until nothing is found + orderingListAtOrderingStream->Beginning(); + indexFound=false; + size=orderingListAtOrderingStream->Size(); + count=0; + + while (count++ < size) + { + if ( orderingListAtOrderingStream->Peek()->orderingIndex == waitingForOrderedPacketReadIndex[ orderingChannelCopy ] ) + { + outputQueue.Push( orderingListAtOrderingStream->Pop(), _FILE_AND_LINE_ ); + waitingForOrderedPacketReadIndex[ orderingChannelCopy ]++; + indexFound=true; + } + else + (*orderingListAtOrderingStream)++; + } + + if (indexFound==false) + break; + } + } + internalPacket = 0; + } + else + { + // This is a newer ordered packet than we are waiting for. Store it for future use + AddToOrderingList( internalPacket ); + } + + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + */ + + // Is this a split packet? If so then reassemble + if ( internalPacket->splitPacketCount > 0 ) + { + // Check for a rebuilt packet + if ( internalPacket->reliability != RELIABLE_ORDERED && internalPacket->reliability!=RELIABLE_SEQUENCED && internalPacket->reliability!=UNRELIABLE_SEQUENCED) + internalPacket->orderingChannel = 255; // Use 255 to designate not sequenced and not ordered + + InsertIntoSplitPacketList( internalPacket, timeRead ); + + internalPacket = BuildPacketFromSplitPacketList( internalPacket->splitPacketId, timeRead, + s, systemAddress, rnr, updateBitStream); + + if ( internalPacket == 0 ) + { +#ifdef LOG_TRIVIAL_NOTIFICATIONS + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("BuildPacketFromSplitPacketList did not return anything.", BYTES_TO_BITS(length), systemAddress, false); +#endif + + // Don't have all the parts yet + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + } + +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + unsigned char packetId; + char *type="UNDEFINED"; +#endif + if (internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED) + { +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + + // ___________________ + BitStream bitStream(internalPacket->data, BITS_TO_BYTES(internalPacket->dataBitLength), false); + unsigned int receivedPacketNumber; + RakNet::Time receivedTime; + unsigned char streamNumber; + PacketReliability reliability; + // ___________________ + + + bitStream.IgnoreBits(8); // Ignore ID_TIMESTAMP + bitStream.Read(receivedTime); + bitStream.Read(packetId); + bitStream.Read(receivedPacketNumber); + bitStream.Read(streamNumber); + bitStream.Read(reliability); + if (packetId==ID_USER_PACKET_ENUM+1) + { + + if (reliability==UNRELIABLE_SEQUENCED) + type="UNRELIABLE_SEQUENCED"; + else if (reliability==RELIABLE_ORDERED) + type="RELIABLE_ORDERED"; + else + type="RELIABLE_SEQUENCED"; + } + // ___________________ +#endif + + + if (internalPacket->orderingIndex==orderedReadIndex[internalPacket->orderingChannel]) + { + // Has current ordering index + if (internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == UNRELIABLE_SEQUENCED) + { + // Is sequenced + if (IsOlderOrderedPacket(internalPacket->sequencingIndex,highestSequencedReadIndex[internalPacket->orderingChannel])==false) + { + // Expected or highest known value + +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + if (packetId==ID_USER_PACKET_ENUM+1 && fp) + { + fprintf(fp, "Returning %i, %s by fallthrough. OI=%i. SI=%i.\n", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); + fflush(fp); + } + + if (packetId==ID_USER_PACKET_ENUM+1) + { + if (receivedPacketNumberorderingChannel] = internalPacket->sequencingIndex+(OrderingIndexType)1; + + // Fallthrough, returned to user below + } + else + { +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + if (packetId==ID_USER_PACKET_ENUM+1 && fp) + { + fprintf(fp, "Discarding %i, %s late sequenced. OI=%i. SI=%i.\n", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); + fflush(fp); + } +#endif + +#ifdef LOG_TRIVIAL_NOTIFICATIONS + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Sequenced rejected: lower than highest known value", BYTES_TO_BITS(length), systemAddress, false); +#endif + + // Lower than highest known value + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + } + else + { + // Push to output buffer immediately + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); + +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + if (packetId==ID_USER_PACKET_ENUM+1 && fp) + { + fprintf(fp, "outputting immediate %i, %s. OI=%i. SI=%i.", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); + if (orderingHeaps[internalPacket->orderingChannel].Size()==0) + fprintf(fp, "heap empty\n"); + else + fprintf(fp, "heap head=%i\n", orderingHeaps[internalPacket->orderingChannel].Peek()->orderingIndex.val); + + if (receivedPacketNumberorderingChannel]++; + highestSequencedReadIndex[internalPacket->orderingChannel] = 0; + + // Return off heap until order lost + while (orderingHeaps[internalPacket->orderingChannel].Size()>0 && + orderingHeaps[internalPacket->orderingChannel].Peek()->orderingIndex==orderedReadIndex[internalPacket->orderingChannel]) + { + internalPacket = orderingHeaps[internalPacket->orderingChannel].Pop(0); + +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + BitStream bitStream2(internalPacket->data, BITS_TO_BYTES(internalPacket->dataBitLength), false); + bitStream2.IgnoreBits(8); // Ignore ID_TIMESTAMP + bitStream2.Read(receivedTime); + bitStream2.IgnoreBits(8); // Ignore ID_USER_ENUM+1 + bitStream2.Read(receivedPacketNumber); + bitStream2.Read(streamNumber); + bitStream2.Read(reliability); + char *type="UNDEFINED"; + if (reliability==UNRELIABLE_SEQUENCED) + type="UNRELIABLE_SEQUENCED"; + else if (reliability==RELIABLE_ORDERED) + type="RELIABLE_ORDERED"; + + if (packetId==ID_USER_PACKET_ENUM+1 && fp) + { + fprintf(fp, "Heap pop %i, %s. OI=%i. SI=%i.\n", receivedPacketNumber, type, internalPacket->orderingIndex.val, internalPacket->sequencingIndex); + fflush(fp); + + if (receivedPacketNumberdataBitLength)); + outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); + + if (internalPacket->reliability == RELIABLE_ORDERED) + { + orderedReadIndex[internalPacket->orderingChannel]++; + } + else + { + highestSequencedReadIndex[internalPacket->orderingChannel] = internalPacket->sequencingIndex; + } + } + + // Done + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + } + else if (IsOlderOrderedPacket(internalPacket->orderingIndex,orderedReadIndex[internalPacket->orderingChannel])==false) + { + // internalPacket->_orderingIndex is greater + // If a message has a greater ordering index, and is sequenced or ordered, buffer it + // Sequenced has a lower heap weight, ordered has max sequenced weight + + // Keep orderedHoleCount count small + if (orderingHeaps[internalPacket->orderingChannel].Size()==0) + heapIndexOffsets[internalPacket->orderingChannel]=orderedReadIndex[internalPacket->orderingChannel]; + + reliabilityHeapWeightType orderedHoleCount = internalPacket->orderingIndex-heapIndexOffsets[internalPacket->orderingChannel]; + reliabilityHeapWeightType weight = orderedHoleCount*1048576; + if (internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == UNRELIABLE_SEQUENCED) + weight+=internalPacket->sequencingIndex; + else + weight+=(1048576-1); + orderingHeaps[internalPacket->orderingChannel].Push(weight, internalPacket, _FILE_AND_LINE_); + +#ifdef PRINT_TO_FILE_RELIABLE_ORDERED_TEST + if (packetId==ID_USER_PACKET_ENUM+1 && fp) + { + fprintf(fp, "Heap push %i, %s, weight=%" PRINTF_64_BIT_MODIFIER "u. OI=%i. waiting on %i. SI=%i.\n", receivedPacketNumber, type, weight, internalPacket->orderingIndex.val, orderedReadIndex[internalPacket->orderingChannel].val, internalPacket->sequencingIndex); + fflush(fp); + } +#endif + +#ifdef LOG_TRIVIAL_NOTIFICATIONS + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Larger number ordered packet leaving holes", BYTES_TO_BITS(length), systemAddress, false); +#endif + + // Buffered, nothing to do + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + else + { + // Out of order + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + +#ifdef LOG_TRIVIAL_NOTIFICATIONS + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + messageHandlerList[messageHandlerIndex]->OnReliabilityLayerNotification("Rejected older resend", BYTES_TO_BITS(length), systemAddress, false); +#endif + + // Ignored, nothing to do + goto CONTINUE_SOCKET_DATA_PARSE_LOOP; + } + + } + + bpsMetrics[(int) USER_MESSAGE_BYTES_RECEIVED_PROCESSED].Push1(timeRead,BITS_TO_BYTES(internalPacket->dataBitLength)); + + // Nothing special about this packet. Add it to the output queue + outputQueue.Push( internalPacket, _FILE_AND_LINE_ ); + + internalPacket = 0; + } + + // Used for a goto to jump to the resendNext packet immediately + +CONTINUE_SOCKET_DATA_PARSE_LOOP: + // Parse the bitstream to create an internal packet + internalPacket = CreateInternalPacketFromBitStream( &socketData, timeRead ); + } + + } + + + receivePacketCount++; + + return true; +} + +//------------------------------------------------------------------------------------------------------- +// This gets an end-user packet already parsed out. Returns number of BITS put into the buffer +//------------------------------------------------------------------------------------------------------- +BitSize_t ReliabilityLayer::Receive( unsigned char **data ) +{ + InternalPacket * internalPacket; + + if ( outputQueue.Size() > 0 ) + { + // #ifdef _DEBUG + // RakAssert(bitStream->GetNumberOfBitsUsed()==0); + // #endif + internalPacket = outputQueue.Pop(); + + BitSize_t bitLength; + *data = internalPacket->data; + bitLength = internalPacket->dataBitLength; + ReleaseToInternalPacketPool( internalPacket ); + return bitLength; + } + + else + { + return 0; + } + +} + +//------------------------------------------------------------------------------------------------------- +// Puts data on the send queue +// bitStream contains the data to send +// priority is what priority to send the data at +// reliability is what reliability to use +// ordering channel is from 0 to 255 and specifies what stream to use +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::Send( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, unsigned char orderingChannel, bool makeDataCopy, int MTUSize, CCTimeType currentTime, uint32_t receipt ) +{ +#ifdef _DEBUG + RakAssert( !( reliability >= NUMBER_OF_RELIABILITIES || reliability < 0 ) ); + RakAssert( !( priority > NUMBER_OF_PRIORITIES || priority < 0 ) ); + RakAssert( !( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) ); + RakAssert( numberOfBitsToSend > 0 ); +#endif + +#if CC_TIME_TYPE_BYTES==4 + currentTime/=1000; +#endif + + (void) MTUSize; + + // int a = BITS_TO_BYTES(numberOfBitsToSend); + + // Fix any bad parameters + if ( reliability > RELIABLE_ORDERED_WITH_ACK_RECEIPT || reliability < 0 ) + reliability = RELIABLE; + + if ( priority > NUMBER_OF_PRIORITIES || priority < 0 ) + priority = HIGH_PRIORITY; + + if ( orderingChannel >= NUMBER_OF_ORDERED_STREAMS ) + orderingChannel = 0; + + unsigned int numberOfBytesToSend=(unsigned int) BITS_TO_BYTES(numberOfBitsToSend); + if ( numberOfBitsToSend == 0 ) + { + return false; + } + InternalPacket * internalPacket = AllocateFromInternalPacketPool(); + if (internalPacket==0) + { + notifyOutOfMemory(_FILE_AND_LINE_); + return false; // Out of memory + } + + bpsMetrics[(int) USER_MESSAGE_BYTES_PUSHED].Push1(currentTime,numberOfBytesToSend); + + internalPacket->creationTime = currentTime; + + if ( makeDataCopy ) + { + AllocInternalPacketData(internalPacket, numberOfBytesToSend, true, _FILE_AND_LINE_ ); + //internalPacket->data = (unsigned char*) rakMalloc_Ex( numberOfBytesToSend, _FILE_AND_LINE_ ); + memcpy( internalPacket->data, data, numberOfBytesToSend ); + } + else + { + // Allocated the data elsewhere, delete it in here + //internalPacket->data = ( unsigned char* ) data; + AllocInternalPacketData(internalPacket, (unsigned char*) data ); + } + + internalPacket->dataBitLength = numberOfBitsToSend; + internalPacket->messageInternalOrder = internalOrderIndex++; + internalPacket->priority = priority; + internalPacket->reliability = reliability; + internalPacket->sendReceiptSerial=receipt; + + // Calculate if I need to split the packet + // int headerLength = BITS_TO_BYTES( GetMessageHeaderLengthBits( internalPacket, true ) ); + + unsigned int maxDataSizeBytes = GetMaxDatagramSizeExcludingMessageHeaderBytes() - BITS_TO_BYTES(GetMaxMessageHeaderLengthBits()); + + bool splitPacket = numberOfBytesToSend > maxDataSizeBytes; + + // If a split packet, we might have to upgrade the reliability + if ( splitPacket ) + { + // Split packets cannot be unreliable, in case that one part doesn't arrive and the whole cannot be reassembled. + // One part could not arrive either due to packetloss or due to unreliable discard + if (internalPacket->reliability==UNRELIABLE) + internalPacket->reliability=RELIABLE; + else if (internalPacket->reliability==UNRELIABLE_WITH_ACK_RECEIPT) + internalPacket->reliability=RELIABLE_WITH_ACK_RECEIPT; + else if (internalPacket->reliability==UNRELIABLE_SEQUENCED) + internalPacket->reliability=RELIABLE_SEQUENCED; +// else if (internalPacket->reliability==UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT) +// internalPacket->reliability=RELIABLE_SEQUENCED_WITH_ACK_RECEIPT; + } + + // ++sendMessageNumberIndex; + + if ( internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == UNRELIABLE_SEQUENCED +// || +// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || +// internalPacket->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT + ) + { + // Assign the sequence stream and index + internalPacket->orderingChannel = orderingChannel; + internalPacket->orderingIndex = orderedWriteIndex[ orderingChannel ]; + internalPacket->sequencingIndex = sequencedWriteIndex[ orderingChannel ]++; + + // This packet supersedes all other sequenced packets on the same ordering channel + // Delete all packets in all send lists that are sequenced and on the same ordering channel + // UPDATE: + // Disabled. We don't have enough info to consistently do this. Sometimes newer data does supercede + // older data such as with constantly declining health, but not in all cases. + // For example, with sequenced unreliable sound packets just because you send a newer one doesn't mean you + // don't need the older ones because the odds are they will still arrive in order + /* + for (int i=0; i < NUMBER_OF_PRIORITIES; i++) + { + DeleteSequencedPacketsInList(orderingChannel, sendQueue[i]); + } + */ + } + else if ( internalPacket->reliability == RELIABLE_ORDERED || internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT ) + { + // Assign the ordering channel and index + internalPacket->orderingChannel = orderingChannel; + internalPacket->orderingIndex = orderedWriteIndex[ orderingChannel ] ++; + sequencedWriteIndex[ orderingChannel ]=0; + } + + if ( splitPacket ) // If it uses a secure header it will be generated here + { + // Must split the packet. This will also generate the SHA1 if it is required. It also adds it to the send list. + //InternalPacket packetCopy; + //memcpy(&packetCopy, internalPacket, sizeof(InternalPacket)); + //sendPacketSet[priority].CancelWriteLock(internalPacket); + //SplitPacket( &packetCopy, MTUSize ); + SplitPacket( internalPacket ); + //RakNet::OP_DELETE_ARRAY(packetCopy.data, _FILE_AND_LINE_); + return true; + } + + RakAssert(internalPacket->dataBitLengthdataBitLengthmessageNumberAssigned==false); + outgoingPacketBuffer.Push( GetNextWeight(internalPacket->priority), internalPacket, _FILE_AND_LINE_ ); + RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthpriority]++; + statistics.bytesInSendBuffer[(int)internalPacket->priority]+=(double) BITS_TO_BYTES(internalPacket->dataBitLength); + + // sendPacketSet[priority].WriteUnlock(); + return true; +} +//------------------------------------------------------------------------------------------------------- +// Run this once per game cycle. Handles internal lists and actually does the send +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::Update( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, + unsigned bitsPerSecondLimit, + DataStructures::List &messageHandlerList, + RakNetRandom *rnr, + BitStream &updateBitStream) + +{ + (void) MTUSize; + + RakNet::TimeMS timeMs; +#if CC_TIME_TYPE_BYTES==4 + time/=1000; + timeMs=time; +#else + timeMs=(RakNet::TimeMS) (time/(CCTimeType)1000); +#endif + +#ifdef _DEBUG + while (delayList.Size()) + { + if (delayList.Peek()->sendTime <= timeMs) + { + DataAndTime *dat = delayList.Pop(); +// SocketLayer::SendTo( dat->s, dat->data, dat->length, systemAddress, __FILE__, __LINE__ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) dat->data; + bsp.length = dat->length; + bsp.systemAddress = systemAddress; + dat->s->Send(&bsp, _FILE_AND_LINE_); + + RakNet::OP_DELETE(dat,__FILE__,__LINE__); + } + else + { + break; + } + } +#endif + + // This line is necessary because the timer isn't accurate + if (time <= lastUpdateTime) + { + // Always set the last time in case of overflow + lastUpdateTime=time; + return; + } + + CCTimeType timeSinceLastTick = time - lastUpdateTime; + lastUpdateTime=time; +#if CC_TIME_TYPE_BYTES==4 + if (timeSinceLastTick>100) + timeSinceLastTick=100; +#else + if (timeSinceLastTick>100000) + timeSinceLastTick=100000; +#endif + + if (unreliableTimeout>0) + { + if (timeSinceLastTick>=timeToNextUnreliableCull) + { + if (unreliableLinkedListHead) + { + // Cull out all unreliable messages that have exceeded the timeout + InternalPacket *cur = unreliableLinkedListHead; + InternalPacket *end = unreliableLinkedListHead->unreliablePrev; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + if (time > cur->creationTime+(CCTimeType)unreliableTimeout) + { + // Flag invalid, and clear the memory. Still needs to be removed from the sendPacketSet later + // This fixes a problem where a remote system disconnects, but we don't know it yet, and memory consumption increases to a huge value + FreeInternalPacketData(cur, _FILE_AND_LINE_ ); + cur->data=0; + InternalPacket *next = cur->unreliableNext; + RemoveFromUnreliableLinkedList(cur); + + if (cur==end) + break; + + cur=next; + } + else + { + // if (cur==end) + // break; + // + // cur=cur->unreliableNext; + + // They should be inserted in-order, so no need to iterate past the first failure + break; + } + } + } + + timeToNextUnreliableCull=unreliableTimeout/(CCTimeType)2; + } + else + { + timeToNextUnreliableCull-=timeSinceLastTick; + } + } + + + // Due to thread vagarities and the way I store the time to avoid slow calls to RakNet::GetTime + // time may be less than lastAck +#if CC_TIME_TYPE_BYTES==4 + if ( statistics.messagesInResendBuffer!=0 && AckTimeout(time) ) +#else + if ( statistics.messagesInResendBuffer!=0 && AckTimeout(RakNet::TimeMS(time/(CCTimeType)1000)) ) +#endif + { + // SHOW - dead connection + // We've waited a very long time for a reliable packet to get an ack and it never has + deadConnection = true; + return; + } + + if (congestionManager.ShouldSendACKs(time,timeSinceLastTick)) + { + SendACKs(s, systemAddress, time, rnr, updateBitStream); + } + + if (NAKs.Size()>0) + { + updateBitStream.Reset(); + DatagramHeaderFormat dhfNAK; + dhfNAK.isNAK=true; + dhfNAK.isACK=false; + dhfNAK.isPacketPair=false; + dhfNAK.Serialize(&updateBitStream); + NAKs.Serialize(&updateBitStream, GetMaxDatagramSizeExcludingMessageHeaderBits(), true); + SendBitStream( s, systemAddress, &updateBitStream, rnr, time ); + } + + DatagramHeaderFormat dhf; + dhf.needsBAndAs=congestionManager.GetIsInSlowStart(); + dhf.isContinuousSend=bandwidthExceededStatistic; + // bandwidthExceededStatistic=sendPacketSet[0].IsEmpty()==false || + // sendPacketSet[1].IsEmpty()==false || + // sendPacketSet[2].IsEmpty()==false || + // sendPacketSet[3].IsEmpty()==false; + bandwidthExceededStatistic=outgoingPacketBuffer.Size()>0; + + const bool hasDataToSendOrResend = IsResendQueueEmpty()==false || bandwidthExceededStatistic; + RakAssert(NUMBER_OF_PRIORITIES==4); + congestionManager.Update(time, hasDataToSendOrResend); + + statistics.BPSLimitByOutgoingBandwidthLimit = BITS_TO_BYTES(bitsPerSecondLimit); + statistics.BPSLimitByCongestionControl = congestionManager.GetBytesPerSecondLimitByCongestionControl(); + + unsigned int i; + if (time > lastBpsClear+ +#if CC_TIME_TYPE_BYTES==4 + 100 +#else + 100000 +#endif + ) + { + for (i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) + { + bpsMetrics[i].ClearExpired1(time); + } + + lastBpsClear=time; + } + + if (unreliableWithAckReceiptHistory.Size()>0) + { + i=0; + while (i < unreliableWithAckReceiptHistory.Size()) + { + //if (unreliableWithAckReceiptHistory[i].nextActionTime < time) + if (time - unreliableWithAckReceiptHistory[i].nextActionTime < (((CCTimeType)-1)/2) ) + { + InternalPacket *ackReceipt = AllocateFromInternalPacketPool(); + AllocInternalPacketData(ackReceipt, 5, false, _FILE_AND_LINE_ ); + ackReceipt->dataBitLength=BYTES_TO_BITS(5); + ackReceipt->data[0]=(MessageID)ID_SND_RECEIPT_LOSS; + memcpy(ackReceipt->data+sizeof(MessageID), &unreliableWithAckReceiptHistory[i].sendReceiptSerial, sizeof(uint32_t)); + outputQueue.Push(ackReceipt, _FILE_AND_LINE_ ); + + // Remove, swap with last + unreliableWithAckReceiptHistory.RemoveAtIndex(i); + } + else + i++; + } + } + + if (hasDataToSendOrResend==true) + { + InternalPacket *internalPacket; + // bool forceSend=false; + bool pushedAnything; + BitSize_t nextPacketBitLength; + dhf.isACK=false; + dhf.isNAK=false; + dhf.hasBAndAS=false; + ResetPacketsAndDatagrams(); + + int transmissionBandwidth = congestionManager.GetTransmissionBandwidth(time, timeSinceLastTick, unacknowledgedBytes,dhf.isContinuousSend); + int retransmissionBandwidth = congestionManager.GetRetransmissionBandwidth(time, timeSinceLastTick, unacknowledgedBytes,dhf.isContinuousSend); + if (retransmissionBandwidth>0 || transmissionBandwidth>0) + { + statistics.isLimitedByCongestionControl=false; + + allDatagramSizesSoFar=0; + + // Keep filling datagrams until we exceed retransmission bandwidth + while ((int)BITS_TO_BYTES(allDatagramSizesSoFar)messageNumberAssigned==true); + + //if ( internalPacket->nextActionTime < time ) + if ( time - internalPacket->nextActionTime < (((CCTimeType)-1)/2) ) + { + nextPacketBitLength = internalPacket->headerLength + internalPacket->dataBitLength; + if ( datagramSizeSoFar + nextPacketBitLength > GetMaxDatagramSizeExcludingMessageHeaderBits() ) + { + // Gathers all PushPackets() + PushDatagram(); + break; + } + + PopListHead(false); + + CC_DEBUG_PRINTF_2("Rs %i ", internalPacket->reliableMessageNumber.val); + + bpsMetrics[(int) USER_MESSAGE_BYTES_RESENT].Push1(time,BITS_TO_BYTES(internalPacket->dataBitLength)); + + // Testing1 +// if (internalPacket->reliability==RELIABLE_ORDERED || internalPacket->reliability==RELIABLE_ORDERED_WITH_ACK_RECEIPT) +// printf("RESEND reliableMessageNumber %i with datagram %i\n", internalPacket->reliableMessageNumber.val, congestionManager.GetNextDatagramSequenceNumber().val); + + PushPacket(time,internalPacket,true); // Affects GetNewTransmissionBandwidth() + internalPacket->timesSent++; + congestionManager.OnResend(time, internalPacket->nextActionTime); + internalPacket->retransmissionTime = congestionManager.GetRTOForRetransmission(internalPacket->timesSent); + internalPacket->nextActionTime = internalPacket->retransmissionTime+time; + + pushedAnything=true; + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + { +#if CC_TIME_TYPE_BYTES==4 + messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (RakNet::TimeMS) time, true); +#else + messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (RakNet::TimeMS)(time/(CCTimeType)1000), true); +#endif + } + + // Put the packet back into the resend list at the correct spot + // Don't make a copy since I'm reinserting an allocated struct + InsertPacketIntoResendList( internalPacket, time, false, false ); + + // Removeme + // printf("Resend:%i ", internalPacket->reliableMessageNumber); + } + else + { + // Filled one datagram. + // If the 2nd and it's time to send a datagram pair, will be marked as a pair + PushDatagram(); + break; + } + } + + if (pushedAnything==false) + break; + } + } + else + { + statistics.isLimitedByCongestionControl=true; + } + + if ((int)BITS_TO_BYTES(allDatagramSizesSoFar)messageNumberAssigned==false); + RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthdata==0) + { + //sendPacketSet[ i ].Pop(); + outgoingPacketBuffer.Pop(0); + RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthpriority]--; + statistics.bytesInSendBuffer[(int)internalPacket->priority]-=(double) BITS_TO_BYTES(internalPacket->dataBitLength); + ReleaseToInternalPacketPool( internalPacket ); + continue; + } + + internalPacket->headerLength=GetMessageHeaderLengthBits(internalPacket); + nextPacketBitLength = internalPacket->headerLength + internalPacket->dataBitLength; + if ( datagramSizeSoFar + nextPacketBitLength > GetMaxDatagramSizeExcludingMessageHeaderBits() ) + { + // Hit MTU. May still push packets if smaller ones exist at a lower priority + RakAssert(datagramSizeSoFar!=0); + RakAssert(internalPacket->dataBitLengthreliability == RELIABLE || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED || + internalPacket->reliability == RELIABLE_WITH_ACK_RECEIPT || +// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || + internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + isReliable = true; + else + isReliable = false; + + //sendPacketSet[ i ].Pop(); + outgoingPacketBuffer.Pop(0); + RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthmessageNumberAssigned==false); + statistics.messageInSendBuffer[(int)internalPacket->priority]--; + statistics.bytesInSendBuffer[(int)internalPacket->priority]-=(double) BITS_TO_BYTES(internalPacket->dataBitLength); + if (isReliable + /* + I thought about this and agree that UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT and RELIABLE_SEQUENCED_WITH_ACK_RECEIPT is not useful unless you also know if the message was discarded. + + The problem is that internally, message numbers are only assigned to reliable messages, because message numbers are only used to discard duplicate message receipt and only reliable messages get sent more than once. However, without message numbers getting assigned and transmitted, there is no way to tell the sender about which messages were discarded. In fact, in looking this over I realized that UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT introduced a bug, because the remote system assumes all message numbers are used (no holes). With that send type, on packetloss, a permanent hole would have been created which eventually would cause the system to discard all further packets. + + So I have two options. Either do not support ack receipts when sending sequenced, or write complex and major new systems. UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT would need to send the message ID number on a special channel which allows for non-delivery. And both of them would need to have a special range list to indicate which message numbers were not delivered, so when acks are sent that can be indicated as well. A further problem is that the ack itself can be lost - it is possible that the message can arrive but be discarded, yet the ack is lost. On resend, the resent message would be ignored as duplicate, and you'd never get the discard message either (unless I made a special buffer for that case too). +*/ +// || + // If needs an ack receipt, keep the internal packet around in the list +// internalPacket->reliability == UNRELIABLE_WITH_ACK_RECEIPT || +// internalPacket->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT + ) + { + internalPacket->messageNumberAssigned=true; + internalPacket->reliableMessageNumber=sendReliableMessageNumberIndex; + internalPacket->retransmissionTime = congestionManager.GetRTOForRetransmission(internalPacket->timesSent+1); + internalPacket->nextActionTime = internalPacket->retransmissionTime+time; +#if CC_TIME_TYPE_BYTES==4 + const CCTimeType threshhold = 10000; +#else + const CCTimeType threshhold = 10000000; +#endif + if (internalPacket->nextActionTime-time > threshhold) + { + // int a=5; + RakAssert(time-internalPacket->nextActionTime < threshhold); + } + //resendTree.Insert( internalPacket->reliableMessageNumber, internalPacket); + if (resendBuffer[internalPacket->reliableMessageNumber & (uint32_t) RESEND_BUFFER_ARRAY_MASK]!=0) + { + // bool overflow = ResendBufferOverflow(); + RakAssert(0); + } + resendBuffer[internalPacket->reliableMessageNumber & (uint32_t) RESEND_BUFFER_ARRAY_MASK] = internalPacket; + statistics.messagesInResendBuffer++; + statistics.bytesInResendBuffer+=BITS_TO_BYTES(internalPacket->dataBitLength); + + // printf("pre:%i ", unacknowledgedBytes); + + InsertPacketIntoResendList( internalPacket, time, true, isReliable); + + + // printf("post:%i ", unacknowledgedBytes); + sendReliableMessageNumberIndex++; + } + else if (internalPacket->reliability == UNRELIABLE_WITH_ACK_RECEIPT) + { + unreliableWithAckReceiptHistory.Push(UnreliableWithAckReceiptNode( + congestionManager.GetNextDatagramSequenceNumber() + packetsToSendThisUpdateDatagramBoundaries.Size(), + internalPacket->sendReceiptSerial, + congestionManager.GetRTOForRetransmission(internalPacket->timesSent+1)+time + ), _FILE_AND_LINE_); + } + + // If isReliable is false, the packet and its contents will be added to a list to be freed in ClearPacketsAndDatagrams + // However, the internalPacket structure will remain allocated and be in the resendBuffer list if it requires a receipt + bpsMetrics[(int) USER_MESSAGE_BYTES_SENT].Push1(time,BITS_TO_BYTES(internalPacket->dataBitLength)); + + // Testing1 +// if (internalPacket->reliability==RELIABLE_ORDERED || internalPacket->reliability==RELIABLE_ORDERED_WITH_ACK_RECEIPT) +// printf("SEND reliableMessageNumber %i in datagram %i\n", internalPacket->reliableMessageNumber.val, congestionManager.GetNextDatagramSequenceNumber().val); + + PushPacket(time,internalPacket, isReliable); + internalPacket->timesSent++; + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + { +#if CC_TIME_TYPE_BYTES==4 + messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (RakNet::TimeMS)time, true); +#else + messageHandlerList[messageHandlerIndex]->OnInternalPacket(internalPacket, packetsToSendThisUpdateDatagramBoundaries.Size()+congestionManager.GetNextDatagramSequenceNumber(), systemAddress, (RakNet::TimeMS)(time/(CCTimeType)1000), true); +#endif + } + pushedAnything=true; + + if (ResendBufferOverflow()) + break; + } + // if (ResendBufferOverflow()) + // break; + // }z + + // No datagrams pushed? + if (datagramSizeSoFar==0) + break; + + // Filled one datagram. + // If the 2nd and it's time to send a datagram pair, will be marked as a pair + PushDatagram(); + } + } + + + for (unsigned int datagramIndex=0; datagramIndex < packetsToSendThisUpdateDatagramBoundaries.Size(); datagramIndex++) + { + if (datagramIndex>0) + dhf.isContinuousSend=true; + MessageNumberNode* messageNumberNode = 0; + dhf.datagramNumber=congestionManager.GetAndIncrementNextDatagramSequenceNumber(); + dhf.isPacketPair=datagramsToSendThisUpdateIsPair[datagramIndex]; + + //printf("%p pushing datagram %i\n", this, dhf.datagramNumber.val); + + bool isSecondOfPacketPair=dhf.isPacketPair && datagramIndex>0 && datagramsToSendThisUpdateIsPair[datagramIndex-1]; + unsigned int msgIndex, msgTerm; + if (datagramIndex==0) + { + msgIndex=0; + msgTerm=packetsToSendThisUpdateDatagramBoundaries[0]; + } + else + { + msgIndex=packetsToSendThisUpdateDatagramBoundaries[datagramIndex-1]; + msgTerm=packetsToSendThisUpdateDatagramBoundaries[datagramIndex]; + } + + // More accurate time to reset here +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + dhf.sourceSystemTime=RakNet::GetTimeUS(); +#endif + updateBitStream.Reset(); + dhf.Serialize(&updateBitStream); + CC_DEBUG_PRINTF_2("S%i ",dhf.datagramNumber.val); + + while (msgIndex < msgTerm) + { + // If reliable or needs receipt + if ( packetsToSendThisUpdate[msgIndex]->reliability != UNRELIABLE && + packetsToSendThisUpdate[msgIndex]->reliability != UNRELIABLE_SEQUENCED + ) + { + if (messageNumberNode==0) + { + messageNumberNode = AddFirstToDatagramHistory(dhf.datagramNumber, packetsToSendThisUpdate[msgIndex]->reliableMessageNumber, time); + } + else + { + messageNumberNode = AddSubsequentToDatagramHistory(messageNumberNode, packetsToSendThisUpdate[msgIndex]->reliableMessageNumber); + } + } + + RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); + WriteToBitStreamFromInternalPacket( &updateBitStream, packetsToSendThisUpdate[msgIndex], time ); + RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); + msgIndex++; + } + + if (isSecondOfPacketPair) + { + // Pad to size of first datagram + RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); + updateBitStream.PadWithZeroToByteLength(datagramSizesInBytes[datagramIndex-1]); + RakAssert(updateBitStream.GetNumberOfBytesUsed()<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); + } + + if (messageNumberNode==0) + { + // Unreliable, add dummy node + AddFirstToDatagramHistory(dhf.datagramNumber, time); + } + + // Store what message ids were sent with this datagram + // datagramMessageIDTree.Insert(dhf.datagramNumber,idList); + + congestionManager.OnSendBytes(time,UDP_HEADER_SIZE+DatagramHeaderFormat::GetDataHeaderByteLength()); + + SendBitStream( s, systemAddress, &updateBitStream, rnr, time ); + + bandwidthExceededStatistic=outgoingPacketBuffer.Size()>0; + // bandwidthExceededStatistic=sendPacketSet[0].IsEmpty()==false || + // sendPacketSet[1].IsEmpty()==false || + // sendPacketSet[2].IsEmpty()==false || + // sendPacketSet[3].IsEmpty()==false; + + + + if (bandwidthExceededStatistic==true) + timeOfLastContinualSend=time; + else + timeOfLastContinualSend=0; + } + + ClearPacketsAndDatagrams(); + + // Any data waiting to send after attempting to send, then bandwidth is exceeded + bandwidthExceededStatistic=outgoingPacketBuffer.Size()>0; + // bandwidthExceededStatistic=sendPacketSet[0].IsEmpty()==false || + // sendPacketSet[1].IsEmpty()==false || + // sendPacketSet[2].IsEmpty()==false || + // sendPacketSet[3].IsEmpty()==false; + } + + + // Keep on top of deleting old unreliable split packets so they don't clog the list. + //DeleteOldUnreliableSplitPackets( time ); +} + +//------------------------------------------------------------------------------------------------------- +// Writes a bitstream to the socket +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::SendBitStream( RakNetSocket2 *s, SystemAddress &systemAddress, RakNet::BitStream *bitStream, RakNetRandom *rnr, CCTimeType currentTime) +{ + (void) systemAddress; + (void) rnr; + + unsigned int length; + + length = (unsigned int) bitStream->GetNumberOfBytesUsed(); + + +#ifdef _DEBUG + if (packetloss > 0.0) + { + if (frandomMT() < packetloss) + return; + } + + if (minExtraPing > 0 || extraPingVariance > 0) + { +#ifdef FLIP_SEND_ORDER_TEST + // Flip order of sends without delaying them for testing + DataAndTime *dat = RakNet::OP_NEW(__FILE__,__LINE__); + memcpy(dat->data, ( char* ) bitStream->GetData(), length ); + dat->s=s; + dat->length=length; + dat->sendTime = 0; + dat->remotePortRakNetWasStartedOn_PS3=remotePortRakNetWasStartedOn_PS3; + dat->extraSocketOptions=extraSocketOptions; + delayList.PushAtHead(dat, 0, _FILE_AND_LINE_); +#else + RakNet::TimeMS delay = minExtraPing; + if (extraPingVariance>0) + delay += (randomMT() % extraPingVariance); + if (delay > 0) + { + DataAndTime *dat = RakNet::OP_NEW(__FILE__,__LINE__); + memcpy(dat->data, ( char* ) bitStream->GetData(), length ); + dat->s=s; + dat->length=length; + dat->sendTime = RakNet::GetTimeMS() + delay; + for (unsigned int i=0; i < delayList.Size(); i++) + { + if (dat->sendTime < delayList[i]->sendTime) + { + delayList.PushAtHead(dat, i, __FILE__, __LINE__); + dat=0; + break; + } + } + if (dat!=0) + delayList.Push(dat,__FILE__,__LINE__); + return; + } +#endif + } +#endif + +#if LIBCAT_SECURITY==1 + if (useSecurity) + { + unsigned char *buffer = reinterpret_cast( bitStream->GetData() ); + + int buffer_size = bitStream->GetNumberOfBitsAllocated() / 8; + + // Verify there is enough room for encrypted output and encrypt + // Encrypt() will increase length + bool success = auth_enc.Encrypt(buffer, buffer_size, length); + RakAssert(success); + } +#endif + + bpsMetrics[(int) ACTUAL_BYTES_SENT].Push1(currentTime,length); + + RakAssert(length <= congestionManager.GetMTU()); + +#ifdef USE_THREADED_SEND + SendToThread::SendToThreadBlock *block = SendToThread::AllocateBlock(); + memcpy(block->data, bitStream->GetData(), length); + block->dataWriteOffset=length; + block->extraSocketOptions=extraSocketOptions; + block->remotePortRakNetWasStartedOn_PS3=remotePortRakNetWasStartedOn_PS3; + block->s=s; + block->systemAddress=systemAddress; + SendToThread::ProcessBlock(block); +#else + // SocketLayer::SendTo( s, ( char* ) bitStream->GetData(), length, systemAddress, __FILE__, __LINE__ ); + + RNS2_SendParameters bsp; + bsp.data = (char*) bitStream->GetData(); + bsp.length = length; + bsp.systemAddress = systemAddress; + s->Send(&bsp, _FILE_AND_LINE_); +#endif +} + +//------------------------------------------------------------------------------------------------------- +// Are we waiting for any data to be sent out or be processed by the player? +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::IsOutgoingDataWaiting(void) +{ + if (outgoingPacketBuffer.Size()>0) + return true; + + // unsigned i; + // for ( i = 0; i < NUMBER_OF_PRIORITIES; i++ ) + // { + // if (sendPacketSet[ i ].Size() > 0) + // return true; + // } + + return + //acknowlegements.Size() > 0 || + //resendTree.IsEmpty()==false;// || outputQueue.Size() > 0 || orderingList.Size() > 0 || splitPacketChannelList.Size() > 0; + statistics.messagesInResendBuffer!=0; +} +bool ReliabilityLayer::AreAcksWaiting(void) +{ + return acknowlegements.Size() > 0; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::ApplyNetworkSimulator( double _packetloss, RakNet::TimeMS _minExtraPing, RakNet::TimeMS _extraPingVariance ) +{ +#ifdef _DEBUG + packetloss=_packetloss; + minExtraPing=_minExtraPing; + extraPingVariance=_extraPingVariance; + // if (ping < (unsigned int)(minExtraPing+extraPingVariance)*2) + // ping=(minExtraPing+extraPingVariance)*2; +#endif +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::SetSplitMessageProgressInterval(int interval) +{ + splitMessageProgressInterval=interval; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::SetUnreliableTimeout(RakNet::TimeMS timeoutMS) +{ +#if CC_TIME_TYPE_BYTES==4 + unreliableTimeout=timeoutMS; +#else + unreliableTimeout=(CCTimeType)timeoutMS*(CCTimeType)1000; +#endif +} + +//------------------------------------------------------------------------------------------------------- +// This will return true if we should not send at this time +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::IsSendThrottled( int MTUSize ) +{ + (void) MTUSize; + + return false; + // return resendList.Size() > windowSize; + + // Disabling this, because it can get stuck here forever + /* + unsigned packetsWaiting; + unsigned resendListDataSize=0; + unsigned i; + for (i=0; i < resendList.Size(); i++) + { + if (resendList[i]) + resendListDataSize+=resendList[i]->dataBitLength; + } + packetsWaiting = 1 + ((BITS_TO_BYTES(resendListDataSize)) / (MTUSize - UDP_HEADER_SIZE - 10)); // 10 to roughly estimate the raknet header + + return packetsWaiting >= windowSize; + */ +} + +//------------------------------------------------------------------------------------------------------- +// We lost a packet +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::UpdateWindowFromPacketloss( CCTimeType time ) +{ + (void) time; +} + +//------------------------------------------------------------------------------------------------------- +// Increase the window size +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::UpdateWindowFromAck( CCTimeType time ) +{ + (void) time; +} + +//------------------------------------------------------------------------------------------------------- +// Does what the function name says +//------------------------------------------------------------------------------------------------------- +unsigned ReliabilityLayer::RemovePacketFromResendListAndDeleteOlderReliableSequenced( const MessageNumberType messageNumber, CCTimeType time, DataStructures::List &messageHandlerList, const SystemAddress &systemAddress ) +{ + (void) time; + (void) messageNumber; + InternalPacket * internalPacket; + //InternalPacket *temp; +// PacketReliability reliability; // What type of reliability algorithm to use with this packet +// unsigned char orderingChannel; // What ordering channel this packet is on, if the reliability type uses ordering channels +// OrderingIndexType orderingIndex; // The ID used as identification for ordering channels + // unsigned j; + + for (unsigned int messageHandlerIndex=0; messageHandlerIndex < messageHandlerList.Size(); messageHandlerIndex++) + { +#if CC_TIME_TYPE_BYTES==4 + messageHandlerList[messageHandlerIndex]->OnAck(messageNumber, systemAddress, time); +#else + messageHandlerList[messageHandlerIndex]->OnAck(messageNumber, systemAddress, (RakNet::TimeMS)(time/(CCTimeType)1000)); +#endif + } + + // Testing1 +// if (resendLinkedListHead) +// { +// InternalPacket *internalPacket = resendLinkedListHead; +// do +// { +// internalPacket=internalPacket->resendNext; +// printf("%i ", internalPacket->reliableMessageNumber.val); +// } while (internalPacket!=resendLinkedListHead); +// printf("\n"); +// } + + // bool deleted; + // deleted=resendTree.Delete(messageNumber, internalPacket); + internalPacket = resendBuffer[messageNumber & RESEND_BUFFER_ARRAY_MASK]; + // May ask to remove twice, for example resend twice, then second ack + if (internalPacket && internalPacket->reliableMessageNumber==messageNumber) + { + // ValidateResendList(); + resendBuffer[messageNumber & RESEND_BUFFER_ARRAY_MASK]=0; + CC_DEBUG_PRINTF_2("AckRcv %i ", messageNumber); + + statistics.messagesInResendBuffer--; + statistics.bytesInResendBuffer-=BITS_TO_BYTES(internalPacket->dataBitLength); + +// orderingIndex = internalPacket->orderingIndex; + totalUserDataBytesAcked+=(double) BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength); + + // Return receipt if asked for + if (internalPacket->reliability>=RELIABLE_WITH_ACK_RECEIPT && + (internalPacket->splitPacketCount==0 || internalPacket->splitPacketIndex+1==internalPacket->splitPacketCount) + ) + { + InternalPacket *ackReceipt = AllocateFromInternalPacketPool(); + AllocInternalPacketData(ackReceipt, 5, false, _FILE_AND_LINE_ ); + ackReceipt->dataBitLength=BYTES_TO_BITS(5); + ackReceipt->data[0]=(MessageID)ID_SND_RECEIPT_ACKED; + memcpy(ackReceipt->data+sizeof(MessageID), &internalPacket->sendReceiptSerial, sizeof(internalPacket->sendReceiptSerial)); + outputQueue.Push(ackReceipt, _FILE_AND_LINE_ ); + } + + bool isReliable; + if ( internalPacket->reliability == RELIABLE || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED || + internalPacket->reliability == RELIABLE_WITH_ACK_RECEIPT || +// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || + internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + isReliable = true; + else + isReliable = false; + + RemoveFromList(internalPacket, isReliable); + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + + return 0; + } + else + { + + } + + return (unsigned)-1; +} + +//------------------------------------------------------------------------------------------------------- +// Acknowledge receipt of the packet with the specified messageNumber +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::SendAcknowledgementPacket( const DatagramSequenceNumberType messageNumber, CCTimeType time ) +{ + + // REMOVEME + // printf("%p Send ack %i\n", this, messageNumber.val); + + nextAckTimeToSend=time; + acknowlegements.Insert(messageNumber); + + //printf("ACK_DG:%i ", messageNumber.val); + + CC_DEBUG_PRINTF_2("AckPush %i ", messageNumber); + +} + +//------------------------------------------------------------------------------------------------------- +// Parse an internalPacket and figure out how many header bits would be +// written. Returns that number +//------------------------------------------------------------------------------------------------------- +BitSize_t ReliabilityLayer::GetMaxMessageHeaderLengthBits( void ) +{ + InternalPacket ip; + ip.reliability=RELIABLE_SEQUENCED; + ip.splitPacketCount=1; + return GetMessageHeaderLengthBits(&ip); +} +//------------------------------------------------------------------------------------------------------- +BitSize_t ReliabilityLayer::GetMessageHeaderLengthBits( const InternalPacket *const internalPacket ) +{ + BitSize_t bitLength; + + // bitStream->AlignWriteToByteBoundary(); // Potentially unaligned + // tempChar=(unsigned char)internalPacket->reliability; bitStream->WriteBits( (const unsigned char *)&tempChar, 3, true ); // 3 bits to write reliability. + // bool hasSplitPacket = internalPacket->splitPacketCount>0; bitStream->Write(hasSplitPacket); // Write 1 bit to indicate if splitPacketCount>0 + bitLength = 8*1; + + // bitStream->AlignWriteToByteBoundary(); + // RakAssert(internalPacket->dataBitLength < 65535); + // unsigned short s; s = (unsigned short) internalPacket->dataBitLength; bitStream->WriteAlignedVar16((const char*)& s); + bitLength += 8*2; + + if ( internalPacket->reliability == RELIABLE || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED || + internalPacket->reliability == RELIABLE_WITH_ACK_RECEIPT || +// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || + internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + bitLength += 8*3; // bitStream->Write(internalPacket->reliableMessageNumber); // Message sequence number + // bitStream->AlignWriteToByteBoundary(); // Potentially nothing else to write + + + + if ( internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_SEQUENCED + ) + { + bitLength += 8*3;; // bitStream->Write(internalPacket->_sequencingIndex); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. + } + + if ( internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED || + internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + { + bitLength += 8*3; // bitStream->Write(internalPacket->orderingIndex); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. + bitLength += 8*1; // tempChar=internalPacket->orderingChannel; bitStream->WriteAlignedVar8((const char*)& tempChar); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. 5 bits needed, write one byte + } + if (internalPacket->splitPacketCount>0) + { + bitLength += 8*4; // bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketCount); RakAssert(sizeof(SplitPacketIndexType)==4); // Only needed if splitPacketCount>0. 4 bytes + bitLength += 8*sizeof(SplitPacketIdType); // bitStream->WriteAlignedVar16((const char*)& internalPacket->splitPacketId); RakAssert(sizeof(SplitPacketIdType)==2); // Only needed if splitPacketCount>0. + bitLength += 8*4; // bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketIndex); // Only needed if splitPacketCount>0. 4 bytes + } + + return bitLength; +} + +//------------------------------------------------------------------------------------------------------- +// Parse an internalPacket and create a bitstream to represent this data +//------------------------------------------------------------------------------------------------------- +BitSize_t ReliabilityLayer::WriteToBitStreamFromInternalPacket( RakNet::BitStream *bitStream, const InternalPacket *const internalPacket, CCTimeType curTime ) +{ + (void) curTime; + + BitSize_t start = bitStream->GetNumberOfBitsUsed(); + unsigned char tempChar; + + // (Incoming data may be all zeros due to padding) + bitStream->AlignWriteToByteBoundary(); // Potentially unaligned + if (internalPacket->reliability==UNRELIABLE_WITH_ACK_RECEIPT) + tempChar=UNRELIABLE; + else if (internalPacket->reliability==RELIABLE_WITH_ACK_RECEIPT) + tempChar=RELIABLE; + else if (internalPacket->reliability==RELIABLE_ORDERED_WITH_ACK_RECEIPT) + tempChar=RELIABLE_ORDERED; + else + tempChar=(unsigned char)internalPacket->reliability; + + bitStream->WriteBits( (const unsigned char *)&tempChar, 3, true ); // 3 bits to write reliability. + + bool hasSplitPacket = internalPacket->splitPacketCount>0; bitStream->Write(hasSplitPacket); // Write 1 bit to indicate if splitPacketCount>0 + bitStream->AlignWriteToByteBoundary(); + RakAssert(internalPacket->dataBitLength < 65535); + unsigned short s; s = (unsigned short) internalPacket->dataBitLength; bitStream->WriteAlignedVar16((const char*)& s); + if ( internalPacket->reliability == RELIABLE || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED || + internalPacket->reliability == RELIABLE_WITH_ACK_RECEIPT || + internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + bitStream->Write(internalPacket->reliableMessageNumber); // Used for all reliable types + bitStream->AlignWriteToByteBoundary(); // Potentially nothing else to write + + if ( internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_SEQUENCED + ) + { + bitStream->Write(internalPacket->sequencingIndex); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. + } + + if ( internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED || + internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + { + bitStream->Write(internalPacket->orderingIndex); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. + tempChar=internalPacket->orderingChannel; bitStream->WriteAlignedVar8((const char*)& tempChar); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. 5 bits needed, write one byte + } + + if (internalPacket->splitPacketCount>0) + { + // printf("Write before\n"); + // bitStream->PrintBits(); + + bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketCount); RakAssert(sizeof(SplitPacketIndexType)==4); // Only needed if splitPacketCount>0. 4 bytes + bitStream->WriteAlignedVar16((const char*)& internalPacket->splitPacketId); RakAssert(sizeof(SplitPacketIdType)==2); // Only needed if splitPacketCount>0. + bitStream->WriteAlignedVar32((const char*)& internalPacket->splitPacketIndex); // Only needed if splitPacketCount>0. 4 bytes + + // printf("Write after\n"); + // bitStream->PrintBits(); + } + + // Write the actual data. + bitStream->WriteAlignedBytes( ( unsigned char* ) internalPacket->data, BITS_TO_BYTES( internalPacket->dataBitLength ) ); + + return bitStream->GetNumberOfBitsUsed() - start; +} + +//------------------------------------------------------------------------------------------------------- +// Parse a bitstream and create an internal packet to represent this data +//------------------------------------------------------------------------------------------------------- +InternalPacket* ReliabilityLayer::CreateInternalPacketFromBitStream( RakNet::BitStream *bitStream, CCTimeType time ) +{ + bool bitStreamSucceeded; + InternalPacket* internalPacket; + unsigned char tempChar; + bool hasSplitPacket=false; + bool readSuccess; + + if ( bitStream->GetNumberOfUnreadBits() < (int) sizeof( internalPacket->reliableMessageNumber ) * 8 ) + return 0; // leftover bits + + internalPacket = AllocateFromInternalPacketPool(); + if (internalPacket==0) + { + // Out of memory + RakAssert(0); + return 0; + } + internalPacket->creationTime = time; + + // (Incoming data may be all zeros due to padding) + bitStream->AlignReadToByteBoundary(); // Potentially unaligned + bitStream->ReadBits( ( unsigned char* ) ( &( tempChar ) ), 3 ); + internalPacket->reliability = (PacketReliability ) tempChar; + readSuccess=bitStream->Read(hasSplitPacket); // Read 1 bit to indicate if splitPacketCount>0 + bitStream->AlignReadToByteBoundary(); + unsigned short s; bitStream->ReadAlignedVar16((char*)&s); internalPacket->dataBitLength=s; // Length of message (2 bytes) + if ( internalPacket->reliability == RELIABLE || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED + // I don't write ACK_RECEIPT to the remote system +// || +// internalPacket->reliability == RELIABLE_WITH_ACK_RECEIPT || +// internalPacket->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || +// internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + bitStream->Read(internalPacket->reliableMessageNumber); // Message sequence number + else + internalPacket->reliableMessageNumber=(MessageNumberType)(uint32_t)-1; + bitStream->AlignReadToByteBoundary(); // Potentially nothing else to Read + + if ( internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_SEQUENCED + ) + { + bitStream->Read(internalPacket->sequencingIndex); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. + } + + if ( internalPacket->reliability == UNRELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_SEQUENCED || + internalPacket->reliability == RELIABLE_ORDERED || + internalPacket->reliability == RELIABLE_ORDERED_WITH_ACK_RECEIPT + ) + { + bitStream->Read(internalPacket->orderingIndex); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. 4 bytes. + readSuccess=bitStream->ReadAlignedVar8((char*)& internalPacket->orderingChannel); // Used for UNRELIABLE_SEQUENCED, RELIABLE_SEQUENCED, RELIABLE_ORDERED. 5 bits needed, Read one byte + } + else + internalPacket->orderingChannel=0; + + if (hasSplitPacket) + { +// printf("Read before\n"); +// bitStream->PrintBits(); + + bitStream->ReadAlignedVar32((char*)& internalPacket->splitPacketCount); // Only needed if splitPacketCount>0. 4 bytes + bitStream->ReadAlignedVar16((char*)& internalPacket->splitPacketId); // Only needed if splitPacketCount>0. + readSuccess=bitStream->ReadAlignedVar32((char*)& internalPacket->splitPacketIndex); // Only needed if splitPacketCount>0. 4 bytes + RakAssert(readSuccess); + +// printf("Read after\n"); +// bitStream->PrintBits(); + } + else + { + internalPacket->splitPacketCount=0; + } + + if (readSuccess==false || + internalPacket->dataBitLength==0 || + internalPacket->reliability>=NUMBER_OF_RELIABILITIES || + internalPacket->orderingChannel>=32 || + (hasSplitPacket && (internalPacket->splitPacketIndex >= internalPacket->splitPacketCount))) + { + // If this assert hits, encoding is garbage + RakAssert("Encoding is garbage" && 0); + ReleaseToInternalPacketPool( internalPacket ); + return 0; + } + + // Allocate memory to hold our data + AllocInternalPacketData(internalPacket, BITS_TO_BYTES( internalPacket->dataBitLength ), false, _FILE_AND_LINE_ ); + RakAssert(BITS_TO_BYTES( internalPacket->dataBitLength )data == 0) + { + RakAssert("Out of memory in ReliabilityLayer::CreateInternalPacketFromBitStream" && 0); + notifyOutOfMemory(_FILE_AND_LINE_); + ReleaseToInternalPacketPool( internalPacket ); + return 0; + } + + // Set the last byte to 0 so if ReadBits does not read a multiple of 8 the last bits are 0'ed out + internalPacket->data[ BITS_TO_BYTES( internalPacket->dataBitLength ) - 1 ] = 0; + + // Read the data the packet holds + bitStreamSucceeded = bitStream->ReadAlignedBytes( ( unsigned char* ) internalPacket->data, BITS_TO_BYTES( internalPacket->dataBitLength ) ); + + if ( bitStreamSucceeded == false ) + { + // If this hits, most likely the variable buff is too small in RunUpdateCycle in RakPeer.cpp + RakAssert("Couldn't read all the data" && 0); + + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + return 0; + } + + return internalPacket; +} + + +//------------------------------------------------------------------------------------------------------- +// Get the SHA1 code +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::GetSHA1( unsigned char * const buffer, unsigned int + nbytes, char code[ SHA1_LENGTH ] ) +{ + CSHA1 sha1; + + sha1.Reset(); + sha1.Update( ( unsigned char* ) buffer, nbytes ); + sha1.Final(); + memcpy( code, sha1.GetHash(), SHA1_LENGTH ); +} + +//------------------------------------------------------------------------------------------------------- +// Check the SHA1 code +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::CheckSHA1( char code[ SHA1_LENGTH ], unsigned char * + const buffer, unsigned int nbytes ) +{ + char code2[ SHA1_LENGTH ]; + GetSHA1( buffer, nbytes, code2 ); + + for ( int i = 0; i < SHA1_LENGTH; i++ ) + if ( code[ i ] != code2[ i ] ) + return false; + + return true; +} + +/* +//------------------------------------------------------------------------------------------------------- +// Search the specified list for sequenced packets on the specified ordering +// stream, optionally skipping those with splitPacketId, and delete them +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::List&theList, int splitPacketId ) +{ + unsigned i = 0; + + while ( i < theList.Size() ) + { + if ( ( + theList[ i ]->reliability == RELIABLE_SEQUENCED || + theList[ i ]->reliability == UNRELIABLE_SEQUENCED +// || +// theList[ i ]->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || +// theList[ i ]->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT + ) && + theList[ i ]->orderingChannel == orderingChannel && ( splitPacketId == -1 || theList[ i ]->splitPacketId != (unsigned int) splitPacketId ) ) + { + InternalPacket * internalPacket = theList[ i ]; + theList.RemoveAtIndex( i ); + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + } + + else + i++; + } +} + +//------------------------------------------------------------------------------------------------------- +// Search the specified list for sequenced packets with a value less than orderingIndex and delete them +// Note - I added functionality so you can use the Queue as a list (in this case for searching) but it is less efficient to do so than a regular list +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::Queue&theList ) +{ + InternalPacket * internalPacket; + int listSize = theList.Size(); + int i = 0; + + while ( i < listSize ) + { + if ( ( + theList[ i ]->reliability == RELIABLE_SEQUENCED || + theList[ i ]->reliability == UNRELIABLE_SEQUENCED +// || +// theList[ i ]->reliability == RELIABLE_SEQUENCED_WITH_ACK_RECEIPT || +// theList[ i ]->reliability == UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT + ) && theList[ i ]->orderingChannel == orderingChannel ) + { + internalPacket = theList[ i ]; + theList.RemoveAtIndex( i ); + FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + listSize--; + } + + else + i++; + } +} +*/ + +//------------------------------------------------------------------------------------------------------- +// Returns true if newPacketOrderingIndex is older than the waitingForPacketOrderingIndex +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::IsOlderOrderedPacket( OrderingIndexType newPacketOrderingIndex, OrderingIndexType waitingForPacketOrderingIndex ) +{ + OrderingIndexType maxRange = (OrderingIndexType) (uint32_t)-1; + + if ( waitingForPacketOrderingIndex > maxRange/(OrderingIndexType)2 ) + { + if ( newPacketOrderingIndex >= waitingForPacketOrderingIndex - maxRange/(OrderingIndexType)2+(OrderingIndexType)1 && newPacketOrderingIndex < waitingForPacketOrderingIndex ) + { + return true; + } + }else if ( newPacketOrderingIndex >= ( OrderingIndexType ) ( waitingForPacketOrderingIndex - (( OrderingIndexType ) maxRange/(OrderingIndexType)2+(OrderingIndexType)1) ) || + newPacketOrderingIndex < waitingForPacketOrderingIndex ) + { + return true; + } + + // Old packet + return false; +} + +//------------------------------------------------------------------------------------------------------- +// Split the passed packet into chunks under MTU_SIZEbytes (including headers) and save those new chunks +// Optimized version +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::SplitPacket( InternalPacket *internalPacket ) +{ + // Doing all sizes in bytes in this function so I don't write partial bytes with split packets + internalPacket->splitPacketCount = 1; // This causes GetMessageHeaderLengthBits to account for the split packet header + unsigned int headerLength = (unsigned int) BITS_TO_BYTES( GetMessageHeaderLengthBits( internalPacket ) ); + unsigned int dataByteLength = (unsigned int) BITS_TO_BYTES( internalPacket->dataBitLength ); + int maximumSendBlockBytes, byteOffset, bytesToSend; + SplitPacketIndexType splitPacketIndex; + int i; + InternalPacket **internalPacketArray; + + maximumSendBlockBytes = GetMaxDatagramSizeExcludingMessageHeaderBytes() - BITS_TO_BYTES(GetMaxMessageHeaderLengthBits()); + + // Calculate how many packets we need to create + internalPacket->splitPacketCount = ( ( dataByteLength - 1 ) / ( maximumSendBlockBytes ) + 1 ); + + // Optimization + // internalPacketArray = RakNet::OP_NEW(internalPacket->splitPacketCount, _FILE_AND_LINE_ ); + bool usedAlloca=false; +#if USE_ALLOCA==1 + if (sizeof( InternalPacket* ) * internalPacket->splitPacketCount < MAX_ALLOCA_STACK_ALLOCATION) + { + internalPacketArray = ( InternalPacket** ) alloca( sizeof( InternalPacket* ) * internalPacket->splitPacketCount ); + usedAlloca=true; + } + else +#endif + internalPacketArray = (InternalPacket**) rakMalloc_Ex( sizeof(InternalPacket*) * internalPacket->splitPacketCount, _FILE_AND_LINE_ ); + + for ( i = 0; i < ( int ) internalPacket->splitPacketCount; i++ ) + { + internalPacketArray[ i ] = AllocateFromInternalPacketPool(); + + //internalPacketArray[ i ] = (InternalPacket*) alloca( sizeof( InternalPacket ) ); + // internalPacketArray[ i ] = sendPacketSet[internalPacket->priority].WriteLock(); + *internalPacketArray[ i ]=*internalPacket; + internalPacketArray[ i ]->messageNumberAssigned=false; + + if (i!=0) + internalPacket->messageInternalOrder = internalOrderIndex++; + } + + // This identifies which packet this is in the set + splitPacketIndex = 0; + + InternalPacketRefCountedData *refCounter=0; + + // Do a loop to send out all the packets + do + { + byteOffset = splitPacketIndex * maximumSendBlockBytes; + bytesToSend = dataByteLength - byteOffset; + + if ( bytesToSend > maximumSendBlockBytes ) + bytesToSend = maximumSendBlockBytes; + + // Copy over our chunk of data + + AllocInternalPacketData(internalPacketArray[ splitPacketIndex ], &refCounter, internalPacket->data, internalPacket->data + byteOffset); + // internalPacketArray[ splitPacketIndex ]->data = (unsigned char*) rakMalloc_Ex( bytesToSend, _FILE_AND_LINE_ ); + // memcpy( internalPacketArray[ splitPacketIndex ]->data, internalPacket->data + byteOffset, bytesToSend ); + + if ( bytesToSend != maximumSendBlockBytes ) + internalPacketArray[ splitPacketIndex ]->dataBitLength = internalPacket->dataBitLength - splitPacketIndex * ( maximumSendBlockBytes << 3 ); + else + internalPacketArray[ splitPacketIndex ]->dataBitLength = bytesToSend << 3; + + internalPacketArray[ splitPacketIndex ]->splitPacketIndex = splitPacketIndex; + internalPacketArray[ splitPacketIndex ]->splitPacketId = splitPacketId; + internalPacketArray[ splitPacketIndex ]->splitPacketCount = internalPacket->splitPacketCount; + RakAssert(internalPacketArray[ splitPacketIndex ]->dataBitLengthsplitPacketCount ); + + splitPacketId++; // It's ok if this wraps to 0 + + // InternalPacket *workingPacket; + + // Tell the heap we are going to push a list of elements where each element in the list follows the heap order + RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthsplitPacketCount; i++ ) + { + internalPacketArray[ i ]->headerLength=headerLength; + RakAssert(internalPacketArray[ i ]->dataBitLengthpriority ].Push( internalPacketArray[ i ], _FILE_AND_LINE_ ); + RakAssert(internalPacketArray[ i ]->dataBitLengthmessageNumberAssigned==false); + outgoingPacketBuffer.PushSeries(GetNextWeight(internalPacketArray[ i ]->priority), internalPacketArray[ i ], _FILE_AND_LINE_); + RakAssert(outgoingPacketBuffer.Size()==0 || outgoingPacketBuffer.Peek()->dataBitLengthpriority]++; + statistics.bytesInSendBuffer[(int)(int)internalPacketArray[ i ]->priority]+=(double) BITS_TO_BYTES(internalPacketArray[ i ]->dataBitLength); + // workingPacket=sendPacketSet[internalPacket->priority].WriteLock(); + // memcpy(workingPacket, internalPacketArray[ i ], sizeof(InternalPacket)); + // sendPacketSet[internalPacket->priority].WriteUnlock(); + } + + // Do not delete, original is referenced by all split packets to avoid numerous allocations. See AllocInternalPacketData above + // FreeInternalPacketData(internalPacket, _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool( internalPacket ); + + if (usedAlloca==false) + rakFree_Ex(internalPacketArray, _FILE_AND_LINE_ ); +} + +//------------------------------------------------------------------------------------------------------- +// Insert a packet into the split packet list +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::InsertIntoSplitPacketList( InternalPacket * internalPacket, CCTimeType time ) +{ + bool objectExists; + unsigned index; + // Find in splitPacketChannelList if a SplitPacketChannel with this splitPacketId was already allocated. If not, allocate and insert the channel into the list. + index=splitPacketChannelList.GetIndexFromKey(internalPacket->splitPacketId, &objectExists); + if (objectExists==false) + { + SplitPacketChannel *newChannel = RakNet::OP_NEW( __FILE__, __LINE__ ); +#if PREALLOCATE_LARGE_MESSAGES==1 + index=splitPacketChannelList.Insert(internalPacket->splitPacketId, newChannel, true, __FILE__,__LINE__); + newChannel->returnedPacket=CreateInternalPacketCopy( internalPacket, 0, 0, time ); + newChannel->gotFirstPacket=false; + newChannel->splitPacketsArrived=0; + AllocInternalPacketData(newChannel->returnedPacket, BITS_TO_BYTES( internalPacket->dataBitLength*internalPacket->splitPacketCount ), false, __FILE__, __LINE__ ); + RakAssert(newChannel->returnedPacket->data); +#else + newChannel->firstPacket=0; + index=splitPacketChannelList.Insert(internalPacket->splitPacketId, newChannel, true, __FILE__,__LINE__); + // Preallocate to the final size, to avoid runtime copies + newChannel->splitPacketList.Preallocate(internalPacket->splitPacketCount, __FILE__,__LINE__); + +#endif + } + +#if PREALLOCATE_LARGE_MESSAGES==1 + splitPacketChannelList[index]->lastUpdateTime=time; + splitPacketChannelList[index]->splitPacketsArrived++; + splitPacketChannelList[index]->returnedPacket->dataBitLength+=internalPacket->dataBitLength; + + bool dealloc; + if (internalPacket->splitPacketIndex==0) + { + splitPacketChannelList[index]->gotFirstPacket=true; + splitPacketChannelList[index]->stride=BITS_TO_BYTES(internalPacket->dataBitLength); + + for (unsigned int j=0; j < splitPacketChannelList[index]->splitPacketList.Size(); j++) + { + memcpy(splitPacketChannelList[index]->returnedPacket->data+internalPacket->splitPacketIndex*splitPacketChannelList[index]->stride, internalPacket->data, (size_t) BITS_TO_BYTES(internalPacket->dataBitLength)); + FreeInternalPacketData(splitPacketChannelList[index]->splitPacketList[j], __FILE__, __LINE__ ); + ReleaseToInternalPacketPool(splitPacketChannelList[index]->splitPacketList[j]); + } + + memcpy(splitPacketChannelList[index]->returnedPacket->data, internalPacket->data, (size_t) BITS_TO_BYTES(internalPacket->dataBitLength)); + splitPacketChannelList[index]->splitPacketList.Clear(true,__FILE__,__LINE__); + dealloc=true; + } + else + { + if (splitPacketChannelList[index]->gotFirstPacket==true) + { + memcpy(splitPacketChannelList[index]->returnedPacket->data+internalPacket->splitPacketIndex*splitPacketChannelList[index]->stride, internalPacket->data, (size_t) BITS_TO_BYTES(internalPacket->dataBitLength)); + dealloc=true; + } + else + { + splitPacketChannelList[index]->splitPacketList.Push(internalPacket,__FILE__,__LINE__); + dealloc=false; + } + } + + if (splitPacketChannelList[index]->gotFirstPacket==true && + splitMessageProgressInterval && + // splitPacketChannelList[index]->firstPacket && + // splitPacketChannelList[index]->splitPacketList.Size()!=splitPacketChannelList[index]->firstPacket->splitPacketCount && + // (splitPacketChannelList[index]->splitPacketList.Size()%splitMessageProgressInterval)==0 + splitPacketChannelList[index]->gotFirstPacket && + splitPacketChannelList[index]->splitPacketsArrived!=splitPacketChannelList[index]->returnedPacket->splitPacketCount && + (splitPacketChannelList[index]->splitPacketsArrived%splitMessageProgressInterval)==0 + ) + { + // Return ID_DOWNLOAD_PROGRESS + // Write splitPacketIndex (SplitPacketIndexType) + // Write splitPacketCount (SplitPacketIndexType) + // Write byteLength (4) + // Write data, splitPacketChannelList[index]->splitPacketList[0]->data + InternalPacket *progressIndicator = AllocateFromInternalPacketPool(); + // unsigned int len = sizeof(MessageID) + sizeof(unsigned int)*2 + sizeof(unsigned int) + (unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); + unsigned int l = (unsigned int) splitPacketChannelList[index]->stride; + const unsigned int len = sizeof(MessageID) + sizeof(unsigned int)*2 + sizeof(unsigned int) + l; + AllocInternalPacketData(progressIndicator, len, false, __FILE__, __LINE__ ); + progressIndicator->dataBitLength=BYTES_TO_BITS(len); + progressIndicator->data[0]=(MessageID)ID_DOWNLOAD_PROGRESS; + unsigned int temp; + // temp=splitPacketChannelList[index]->splitPacketList.Size(); + temp=splitPacketChannelList[index]->splitPacketsArrived; + memcpy(progressIndicator->data+sizeof(MessageID), &temp, sizeof(unsigned int)); + temp=(unsigned int)internalPacket->splitPacketCount; + memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*1, &temp, sizeof(unsigned int)); + // temp=(unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); + temp=(unsigned int) BITS_TO_BYTES(l); + memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*2, &temp, sizeof(unsigned int)); + //memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*3, splitPacketChannelList[index]->firstPacket->data, (size_t) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength)); + memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*3, splitPacketChannelList[index]->returnedPacket->data, (size_t) BITS_TO_BYTES(l)); + } + + if (dealloc) + { + FreeInternalPacketData(internalPacket, __FILE__, __LINE__ ); + ReleaseToInternalPacketPool(internalPacket); + } +#else + // Insert the packet into the SplitPacketChannel + splitPacketChannelList[index]->splitPacketList.Insert(internalPacket, __FILE__, __LINE__ ); + splitPacketChannelList[index]->lastUpdateTime=time; + + // If the index is 0, then this is the first packet. Record this so it can be returned to the user with download progress + if (internalPacket->splitPacketIndex==0) + splitPacketChannelList[index]->firstPacket=internalPacket; + + // Return download progress if we have the first packet, the list is not complete, and there are enough packets to justify it + if (splitMessageProgressInterval && + splitPacketChannelList[index]->firstPacket && + splitPacketChannelList[index]->splitPacketList.Size()!=splitPacketChannelList[index]->firstPacket->splitPacketCount && + (splitPacketChannelList[index]->splitPacketList.Size()%splitMessageProgressInterval)==0) + { + // Return ID_DOWNLOAD_PROGRESS + // Write splitPacketIndex (SplitPacketIndexType) + // Write splitPacketCount (SplitPacketIndexType) + // Write byteLength (4) + // Write data, splitPacketChannelList[index]->splitPacketList[0]->data + InternalPacket *progressIndicator = AllocateFromInternalPacketPool(); + unsigned int length = sizeof(MessageID) + sizeof(unsigned int)*2 + sizeof(unsigned int) + (unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); + AllocInternalPacketData(progressIndicator, length, false, __FILE__, __LINE__ ); + progressIndicator->dataBitLength=BYTES_TO_BITS(length); + progressIndicator->data[0]=(MessageID)ID_DOWNLOAD_PROGRESS; + unsigned int temp; + temp=splitPacketChannelList[index]->splitPacketList.Size(); + memcpy(progressIndicator->data+sizeof(MessageID), &temp, sizeof(unsigned int)); + temp=(unsigned int)internalPacket->splitPacketCount; + memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*1, &temp, sizeof(unsigned int)); + temp=(unsigned int) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength); + memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*2, &temp, sizeof(unsigned int)); + + memcpy(progressIndicator->data+sizeof(MessageID)+sizeof(unsigned int)*3, splitPacketChannelList[index]->firstPacket->data, (size_t) BITS_TO_BYTES(splitPacketChannelList[index]->firstPacket->dataBitLength)); + outputQueue.Push(progressIndicator, __FILE__, __LINE__ ); + } + +#endif +} + +//------------------------------------------------------------------------------------------------------- +// Take all split chunks with the specified splitPacketId and try to +//reconstruct a packet. If we can, allocate and return it. Otherwise return 0 +// Optimized version +//------------------------------------------------------------------------------------------------------- +InternalPacket * ReliabilityLayer::BuildPacketFromSplitPacketList( SplitPacketChannel *splitPacketChannel, CCTimeType time ) +{ +#if PREALLOCATE_LARGE_MESSAGES==1 + InternalPacket *returnedPacket=splitPacketChannel->returnedPacket; + RakNet::OP_DELETE(splitPacketChannel, __FILE__, __LINE__); + (void) time; + return returnedPacket; +#else + unsigned int j; + InternalPacket * internalPacket, *splitPacket; + // int splitPacketPartLength; + + // Reconstruct + internalPacket = CreateInternalPacketCopy( splitPacketChannel->splitPacketList[0], 0, 0, time ); + internalPacket->dataBitLength=0; + for (j=0; j < splitPacketChannel->splitPacketList.Size(); j++) + internalPacket->dataBitLength+=splitPacketChannel->splitPacketList[j]->dataBitLength; + // splitPacketPartLength=BITS_TO_BYTES(splitPacketChannel->firstPacket->dataBitLength); + + internalPacket->data = (unsigned char*) rakMalloc_Ex( (size_t) BITS_TO_BYTES( internalPacket->dataBitLength ), _FILE_AND_LINE_ ); + internalPacket->allocationScheme=InternalPacket::NORMAL; + + BitSize_t offset = 0; + for (j=0; j < splitPacketChannel->splitPacketList.Size(); j++) + { + splitPacket=splitPacketChannel->splitPacketList[j]; + memcpy(internalPacket->data + BITS_TO_BYTES(offset), splitPacket->data, (size_t)BITS_TO_BYTES(splitPacketChannel->splitPacketList[j]->dataBitLength)); + offset += splitPacketChannel->splitPacketList[j]->dataBitLength; + } + + for (j=0; j < splitPacketChannel->splitPacketList.Size(); j++) + { + FreeInternalPacketData(splitPacketChannel->splitPacketList[j], _FILE_AND_LINE_ ); + ReleaseToInternalPacketPool(splitPacketChannel->splitPacketList[j]); + } + RakNet::OP_DELETE(splitPacketChannel, __FILE__, __LINE__); + + return internalPacket; +#endif +} +//------------------------------------------------------------------------------------------------------- +InternalPacket * ReliabilityLayer::BuildPacketFromSplitPacketList( SplitPacketIdType splitPacketId, CCTimeType time, + RakNetSocket2 *s, SystemAddress &systemAddress, RakNetRandom *rnr, + BitStream &updateBitStream) +{ + unsigned int i; + bool objectExists; + SplitPacketChannel *splitPacketChannel; + InternalPacket * internalPacket; + + // Find in splitPacketChannelList the SplitPacketChannel with this splitPacketId + i=splitPacketChannelList.GetIndexFromKey(splitPacketId, &objectExists); + splitPacketChannel=splitPacketChannelList[i]; + +#if PREALLOCATE_LARGE_MESSAGES==1 + if (splitPacketChannel->splitPacketsArrived==splitPacketChannel->returnedPacket->splitPacketCount) +#else + if (splitPacketChannel->splitPacketList.Size()==splitPacketChannel->splitPacketList[0]->splitPacketCount) +#endif + { + // Ack immediately, because for large files this can take a long time + SendACKs(s, systemAddress, time, rnr, updateBitStream); + internalPacket=BuildPacketFromSplitPacketList(splitPacketChannel,time); + splitPacketChannelList.RemoveAtIndex(i); + return internalPacket; + } + else + { + return 0; + } +} +/* +//------------------------------------------------------------------------------------------------------- +// Delete any unreliable split packets that have long since expired +void ReliabilityLayer::DeleteOldUnreliableSplitPackets( CCTimeType time ) +{ +unsigned i,j; +i=0; +while (i < splitPacketChannelList.Size()) +{ +#if CC_TIME_TYPE_BYTES==4 +if (time > splitPacketChannelList[i]->lastUpdateTime + timeoutTime && +#else +if (time > splitPacketChannelList[i]->lastUpdateTime + (CCTimeType)timeoutTime*(CCTimeType)1000 && +#endif +(splitPacketChannelList[i]->splitPacketList[0]->reliability==UNRELIABLE || splitPacketChannelList[i]->splitPacketList[0]->reliability==UNRELIABLE_SEQUENCED)) +{ +for (j=0; j < splitPacketChannelList[i]->splitPacketList.Size(); j++) +{ +RakNet::OP_DELETE_ARRAY(splitPacketChannelList[i]->splitPacketList[j]->data, _FILE_AND_LINE_); +ReleaseToInternalPacketPool(splitPacketChannelList[i]->splitPacketList[j]); +} +RakNet::OP_DELETE(splitPacketChannelList[i], _FILE_AND_LINE_); +splitPacketChannelList.RemoveAtIndex(i); +} +else +i++; +} +} +*/ + +//------------------------------------------------------------------------------------------------------- +// Creates a copy of the specified internal packet with data copied from the original starting at dataByteOffset for dataByteLength bytes. +// Does not copy any split data parameters as that information is always generated does not have any reason to be copied +//------------------------------------------------------------------------------------------------------- +InternalPacket * ReliabilityLayer::CreateInternalPacketCopy( InternalPacket *original, int dataByteOffset, int dataByteLength, CCTimeType time ) +{ + InternalPacket * copy = AllocateFromInternalPacketPool(); +#ifdef _DEBUG + // Remove accessing undefined memory error + memset( copy, 255, sizeof( InternalPacket ) ); +#endif + // Copy over our chunk of data + + if ( dataByteLength > 0 ) + { + AllocInternalPacketData(copy, BITS_TO_BYTES(dataByteLength ), false, _FILE_AND_LINE_ ); + memcpy( copy->data, original->data + dataByteOffset, dataByteLength ); + } + else + copy->data = 0; + + copy->dataBitLength = dataByteLength << 3; + copy->creationTime = time; + copy->nextActionTime = 0; + copy->orderingIndex = original->orderingIndex; + copy->sequencingIndex = original->sequencingIndex; + copy->orderingChannel = original->orderingChannel; + copy->reliableMessageNumber = original->reliableMessageNumber; + copy->priority = original->priority; + copy->reliability = original->reliability; +#if PREALLOCATE_LARGE_MESSAGES==1 + copy->splitPacketCount = original->splitPacketCount; + copy->splitPacketId = original->splitPacketId; + copy->splitPacketIndex = original->splitPacketIndex; +#endif + + return copy; +} + +//------------------------------------------------------------------------------------------------------- +// Get the specified ordering list +//------------------------------------------------------------------------------------------------------- +/* +DataStructures::LinkedList *ReliabilityLayer::GetOrderingListAtOrderingStream( unsigned char orderingChannel ) +{ + if ( orderingChannel >= orderingList.Size() ) + return 0; + + return orderingList[ orderingChannel ]; +} + +//------------------------------------------------------------------------------------------------------- +// Add the internal packet to the ordering list in order based on order index +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::AddToOrderingList( InternalPacket * internalPacket ) +{ + } +*/ + +//------------------------------------------------------------------------------------------------------- +// Inserts a packet into the resend list in order +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::InsertPacketIntoResendList( InternalPacket *internalPacket, CCTimeType time, bool firstResend, bool modifyUnacknowledgedBytes ) +{ + (void) firstResend; + (void) time; + (void) internalPacket; + + AddToListTail(internalPacket, modifyUnacknowledgedBytes); + RakAssert(internalPacket->nextActionTime!=0); + +} + +//------------------------------------------------------------------------------------------------------- +// Were you ever unable to deliver a packet despite retries? +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::IsDeadConnection( void ) const +{ + return deadConnection; +} + +//------------------------------------------------------------------------------------------------------- +// Causes IsDeadConnection to return true +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::KillConnection( void ) +{ + deadConnection=true; +} + + +//------------------------------------------------------------------------------------------------------- +// Statistics +//------------------------------------------------------------------------------------------------------- +RakNetStatistics * ReliabilityLayer::GetStatistics( RakNetStatistics *rns ) +{ + unsigned i; + RakNet::TimeUS time = RakNet::GetTimeUS(); + uint64_t uint64Denominator; + double doubleDenominator; + + for (i=0; i < RNS_PER_SECOND_METRICS_COUNT; i++) + { + statistics.valueOverLastSecond[i]=bpsMetrics[i].GetBPS1Threadsafe(time); + statistics.runningTotal[i]=bpsMetrics[i].GetTotal1(); + } + + memcpy(rns, &statistics, sizeof(statistics)); + + if (rns->valueOverLastSecond[USER_MESSAGE_BYTES_SENT]+rns->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT]>0) + rns->packetlossLastSecond=(float)((double) rns->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT]/((double) rns->valueOverLastSecond[USER_MESSAGE_BYTES_SENT]+(double) rns->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT])); + else + rns->packetlossLastSecond=0.0f; + + rns->packetlossTotal=0.0f; + uint64Denominator=(rns->runningTotal[USER_MESSAGE_BYTES_SENT]+rns->runningTotal[USER_MESSAGE_BYTES_RESENT]); + if (uint64Denominator!=0&&rns->runningTotal[USER_MESSAGE_BYTES_SENT]/uint64Denominator>0) + { + doubleDenominator=((double) rns->runningTotal[USER_MESSAGE_BYTES_SENT]+(double) rns->runningTotal[USER_MESSAGE_BYTES_RESENT]); + if(doubleDenominator!=0) + { + rns->packetlossTotal=(float)((double) rns->runningTotal[USER_MESSAGE_BYTES_RESENT]/doubleDenominator); + } + } + + rns->isLimitedByCongestionControl=statistics.isLimitedByCongestionControl; + rns->BPSLimitByCongestionControl=statistics.BPSLimitByCongestionControl; + rns->isLimitedByOutgoingBandwidthLimit=statistics.isLimitedByOutgoingBandwidthLimit; + rns->BPSLimitByOutgoingBandwidthLimit=statistics.BPSLimitByOutgoingBandwidthLimit; + + return rns; +} + +//------------------------------------------------------------------------------------------------------- +// Returns the number of packets in the resend queue, not counting holes +//------------------------------------------------------------------------------------------------------- +unsigned int ReliabilityLayer::GetResendListDataSize(void) const +{ + // Not accurate but thread-safe. The commented version might crash if the queue is cleared while we loop through it + // return resendTree.Size(); + return statistics.messagesInResendBuffer; +} + +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::AckTimeout(RakNet::Time curTime) +{ + // I check timeLastDatagramArrived-curTime because with threading it is possible that timeLastDatagramArrived is + // slightly greater than curTime, in which case this is NOT an ack timeout + return (timeLastDatagramArrived-curTime)>10000 && curTime-timeLastDatagramArrived>timeoutTime; +} +//------------------------------------------------------------------------------------------------------- +CCTimeType ReliabilityLayer::GetNextSendTime(void) const +{ + return nextSendTime; +} +//------------------------------------------------------------------------------------------------------- +CCTimeType ReliabilityLayer::GetTimeBetweenPackets(void) const +{ + return timeBetweenPackets; +} +//------------------------------------------------------------------------------------------------------- +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 +CCTimeType ReliabilityLayer::GetAckPing(void) const +{ + return ackPing; +} +#endif +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::ResetPacketsAndDatagrams(void) +{ + packetsToSendThisUpdate.Clear(true, _FILE_AND_LINE_); + packetsToDeallocThisUpdate.Clear(true, _FILE_AND_LINE_); + packetsToSendThisUpdateDatagramBoundaries.Clear(true, _FILE_AND_LINE_); + datagramsToSendThisUpdateIsPair.Clear(true, _FILE_AND_LINE_); + datagramSizesInBytes.Clear(true, _FILE_AND_LINE_); + datagramSizeSoFar=0; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::PushPacket(CCTimeType time, InternalPacket *internalPacket, bool isReliable) +{ + BitSize_t bitsForThisPacket=BYTES_TO_BITS(BITS_TO_BYTES(internalPacket->dataBitLength)+BITS_TO_BYTES(internalPacket->headerLength)); + datagramSizeSoFar+=bitsForThisPacket; + RakAssert(BITS_TO_BYTES(datagramSizeSoFar)headerLength==GetMessageHeaderLengthBits(internalPacket)); + +// This code tells me how much time elapses between when you send, and when the message actually goes out +// if (internalPacket->data[0]==0) +// { +// RakNet::TimeMS t; +// RakNet::BitStream bs(internalPacket->data+1,sizeof(t),false); +// bs.Read(t); +// RakNet::TimeMS curTime=RakNet::GetTimeMS(); +// RakNet::TimeMS diff = curTime-t; +// } + + congestionManager.OnSendBytes(time, BITS_TO_BYTES(internalPacket->dataBitLength)+BITS_TO_BYTES(internalPacket->headerLength)); +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::PushDatagram(void) +{ + if (datagramSizeSoFar>0) + { + packetsToSendThisUpdateDatagramBoundaries.Push(packetsToSendThisUpdate.Size(), _FILE_AND_LINE_ ); + datagramsToSendThisUpdateIsPair.Push(false, _FILE_AND_LINE_ ); + RakAssert(BITS_TO_BYTES(datagramSizeSoFar)=2) + { + datagramsToSendThisUpdateIsPair[datagramsToSendThisUpdateIsPair.Size()-2]=true; + datagramsToSendThisUpdateIsPair[datagramsToSendThisUpdateIsPair.Size()-1]=true; + return true; + } + return false; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::ClearPacketsAndDatagrams(void) +{ + unsigned int i; + for (i=0; i < packetsToDeallocThisUpdate.Size(); i++) + { + // packetsToDeallocThisUpdate holds a boolean indicating if packetsToSendThisUpdate at this index should be freed + if (packetsToDeallocThisUpdate[i]) + { + RemoveFromUnreliableLinkedList(packetsToSendThisUpdate[i]); + FreeInternalPacketData(packetsToSendThisUpdate[i], _FILE_AND_LINE_ ); + // if (keepInternalPacketIfNeedsAck==false || packetsToSendThisUpdate[i]->reliabilityresendNext=internalPacket; + internalPacket->resendPrev=internalPacket; + resendLinkedListHead=internalPacket; + return; + } + internalPacket->resendPrev->resendNext = internalPacket->resendNext; + internalPacket->resendNext->resendPrev = internalPacket->resendPrev; + internalPacket->resendNext=resendLinkedListHead; + internalPacket->resendPrev=resendLinkedListHead->resendPrev; + internalPacket->resendPrev->resendNext=internalPacket; + resendLinkedListHead->resendPrev=internalPacket; + resendLinkedListHead=internalPacket; + RakAssert(internalPacket->headerLength+internalPacket->dataBitLength>0); + + //ValidateResendList(); +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::RemoveFromList(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes) +{ + InternalPacket *newPosition; + internalPacket->resendPrev->resendNext = internalPacket->resendNext; + internalPacket->resendNext->resendPrev = internalPacket->resendPrev; + newPosition = internalPacket->resendNext; + if ( internalPacket == resendLinkedListHead ) + resendLinkedListHead = newPosition; + if (resendLinkedListHead==internalPacket) + resendLinkedListHead=0; + + if (modifyUnacknowledgedBytes) + { + RakAssert(unacknowledgedBytes>=BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength)); + unacknowledgedBytes-=BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength); + // printf("-unacknowledgedBytes:%i ", unacknowledgedBytes); + + +// ValidateResendList(); + } +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::AddToListTail(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes) +{ + if (modifyUnacknowledgedBytes) + { + unacknowledgedBytes+=BITS_TO_BYTES(internalPacket->headerLength+internalPacket->dataBitLength); + // printf("+unacknowledgedBytes:%i ", unacknowledgedBytes); + } + + if (resendLinkedListHead==0) + { + internalPacket->resendNext=internalPacket; + internalPacket->resendPrev=internalPacket; + resendLinkedListHead=internalPacket; + return; + } + internalPacket->resendNext=resendLinkedListHead; + internalPacket->resendPrev=resendLinkedListHead->resendPrev; + internalPacket->resendPrev->resendNext=internalPacket; + resendLinkedListHead->resendPrev=internalPacket; + +// ValidateResendList(); + +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::PopListHead(bool modifyUnacknowledgedBytes) +{ + RakAssert(resendLinkedListHead!=0); + RemoveFromList(resendLinkedListHead, modifyUnacknowledgedBytes); +} +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::IsResendQueueEmpty(void) const +{ + return resendLinkedListHead==0; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::SendACKs(RakNetSocket2 *s, SystemAddress &systemAddress, CCTimeType time, RakNetRandom *rnr, BitStream &updateBitStream) +{ + BitSize_t maxDatagramPayload = GetMaxDatagramSizeExcludingMessageHeaderBits(); + + while (acknowlegements.Size()>0) + { + // Send acks + updateBitStream.Reset(); + DatagramHeaderFormat dhf; + dhf.isACK=true; + dhf.isNAK=false; + dhf.isPacketPair=false; +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + dhf.sourceSystemTime=time; +#endif + double B; + double AS; + bool hasBAndAS; + if (remoteSystemNeedsBAndAS) + { + congestionManager.OnSendAckGetBAndAS(time, &hasBAndAS,&B,&AS); + dhf.AS=(float)AS; + dhf.hasBAndAS=hasBAndAS; + } + else + dhf.hasBAndAS=false; +#if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1 + dhf.sourceSystemTime=nextAckTimeToSend; +#endif + // dhf.B=(float)B; + updateBitStream.Reset(); + dhf.Serialize(&updateBitStream); + CC_DEBUG_PRINTF_1("AckSnd "); + acknowlegements.Serialize(&updateBitStream, maxDatagramPayload, true); + SendBitStream( s, systemAddress, &updateBitStream, rnr, time ); + congestionManager.OnSendAck(time,updateBitStream.GetNumberOfBytesUsed()); + + // I think this is causing a bug where if the estimated bandwidth is very low for the recipient, only acks ever get sent + // congestionManager.OnSendBytes(time,UDP_HEADER_SIZE+updateBitStream.GetNumberOfBytesUsed()); + } +} +/* +//------------------------------------------------------------------------------------------------------- +ReliabilityLayer::DatagramMessageIDList* ReliabilityLayer::AllocateFromDatagramMessageIDPool(void) +{ +DatagramMessageIDList*s; +s=datagramMessageIDPool.Allocate( _FILE_AND_LINE_ ); +// Call new operator, memoryPool doesn't do this +s = new ((void*)s) DatagramMessageIDList; +return s; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::ReleaseToDatagramMessageIDPool(DatagramMessageIDList* d) +{ +d->~DatagramMessageIDList(); +datagramMessageIDPool.Release(d); +} +*/ +//------------------------------------------------------------------------------------------------------- +InternalPacket* ReliabilityLayer::AllocateFromInternalPacketPool(void) +{ + InternalPacket *ip = internalPacketPool.Allocate( _FILE_AND_LINE_ ); + ip->reliableMessageNumber = (MessageNumberType) (uint32_t)-1; + ip->messageNumberAssigned=false; + ip->nextActionTime = 0; + ip->splitPacketCount = 0; + ip->splitPacketIndex = 0; + ip->splitPacketId = 0; + ip->allocationScheme=InternalPacket::NORMAL; + ip->data=0; + ip->timesSent=0; + return ip; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::ReleaseToInternalPacketPool(InternalPacket *ip) +{ + internalPacketPool.Release(ip, _FILE_AND_LINE_); +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::RemoveFromUnreliableLinkedList(InternalPacket *internalPacket) +{ + if (internalPacket->reliability==UNRELIABLE || + internalPacket->reliability==UNRELIABLE_SEQUENCED || + internalPacket->reliability==UNRELIABLE_WITH_ACK_RECEIPT +// || +// internalPacket->reliability==UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT + ) + { + InternalPacket *newPosition; + internalPacket->unreliablePrev->unreliableNext = internalPacket->unreliableNext; + internalPacket->unreliableNext->unreliablePrev = internalPacket->unreliablePrev; + newPosition = internalPacket->unreliableNext; + if ( internalPacket == unreliableLinkedListHead ) + unreliableLinkedListHead = newPosition; + if (unreliableLinkedListHead==internalPacket) + unreliableLinkedListHead=0; + } +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::AddToUnreliableLinkedList(InternalPacket *internalPacket) +{ + if (internalPacket->reliability==UNRELIABLE || + internalPacket->reliability==UNRELIABLE_SEQUENCED || + internalPacket->reliability==UNRELIABLE_WITH_ACK_RECEIPT +// || +// internalPacket->reliability==UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT + ) + { + if (unreliableLinkedListHead==0) + { + internalPacket->unreliableNext=internalPacket; + internalPacket->unreliablePrev=internalPacket; + unreliableLinkedListHead=internalPacket; + return; + } + internalPacket->unreliableNext=unreliableLinkedListHead; + internalPacket->unreliablePrev=unreliableLinkedListHead->unreliablePrev; + internalPacket->unreliablePrev->unreliableNext=internalPacket; + unreliableLinkedListHead->unreliablePrev=internalPacket; + } +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::ValidateResendList(void) const +{ +// unsigned int count1=0, count2=0; +// for (unsigned int i=0; i < RESEND_BUFFER_ARRAY_LENGTH; i++) +// if (resendBuffer[i]) +// count1++; +// +// if (resendLinkedListHead) +// { +// InternalPacket *internalPacket = resendLinkedListHead; +// do +// { +// count2++; +// internalPacket=internalPacket->resendNext; +// } while (internalPacket!=resendLinkedListHead); +// } +// RakAssert(count1==count2); +// RakAssert(count2<=RESEND_BUFFER_ARRAY_LENGTH); +} +//------------------------------------------------------------------------------------------------------- +bool ReliabilityLayer::ResendBufferOverflow(void) const +{ + int index1 = sendReliableMessageNumberIndex & (uint32_t) RESEND_BUFFER_ARRAY_MASK; + // int index2 = (sendReliableMessageNumberIndex+(uint32_t)1) & (uint32_t) RESEND_BUFFER_ARRAY_MASK; + RakAssert(index1= datagramHistory.Size()) + return 0; + + *timeSent=datagramHistory[offsetIntoList].timeSent; + return datagramHistory[offsetIntoList].head; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::RemoveFromDatagramHistory(DatagramSequenceNumberType index) +{ + DatagramSequenceNumberType offsetIntoList = index - datagramHistoryPopCount; + MessageNumberNode *mnm = datagramHistory[offsetIntoList].head; + MessageNumberNode *next; + while (mnm) + { + next=mnm->next; + datagramHistoryMessagePool.Release(mnm, _FILE_AND_LINE_); + mnm=next; + } + datagramHistory[offsetIntoList].head=0; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, CCTimeType timeSent) +{ + (void) datagramNumber; + if (datagramHistory.Size()>DATAGRAM_MESSAGE_ID_ARRAY_LENGTH) + { + RemoveFromDatagramHistory(datagramHistoryPopCount); + datagramHistory.Pop(); + datagramHistoryPopCount++; + } + + datagramHistory.Push(DatagramHistoryNode(0, timeSent), _FILE_AND_LINE_); + // printf("%p Pushed empty DatagramHistoryNode to datagram history at index %i\n", this, datagramHistory.Size()-1); +} +//------------------------------------------------------------------------------------------------------- +ReliabilityLayer::MessageNumberNode* ReliabilityLayer::AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, DatagramSequenceNumberType messageNumber, CCTimeType timeSent) +{ + (void) datagramNumber; +// RakAssert(datagramHistoryPopCount+(unsigned int) datagramHistory.Size()==datagramNumber); + if (datagramHistory.Size()>DATAGRAM_MESSAGE_ID_ARRAY_LENGTH) + { + RemoveFromDatagramHistory(datagramHistoryPopCount); + datagramHistory.Pop(); + datagramHistoryPopCount++; + } + + MessageNumberNode *mnm = datagramHistoryMessagePool.Allocate(_FILE_AND_LINE_); + mnm->next=0; + mnm->messageNumber=messageNumber; + datagramHistory.Push(DatagramHistoryNode(mnm, timeSent), _FILE_AND_LINE_); + // printf("%p Pushed message %i to DatagramHistoryNode to datagram history at index %i\n", this, messageNumber.val, datagramHistory.Size()-1); + return mnm; +} +//------------------------------------------------------------------------------------------------------- +ReliabilityLayer::MessageNumberNode* ReliabilityLayer::AddSubsequentToDatagramHistory(MessageNumberNode *messageNumberNode, DatagramSequenceNumberType messageNumber) +{ + messageNumberNode->next=datagramHistoryMessagePool.Allocate(_FILE_AND_LINE_); + messageNumberNode->next->messageNumber=messageNumber; + messageNumberNode->next->next=0; + return messageNumberNode->next; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::AllocInternalPacketData(InternalPacket *internalPacket, InternalPacketRefCountedData **refCounter, unsigned char *externallyAllocatedPtr, unsigned char *ourOffset) +{ + internalPacket->allocationScheme=InternalPacket::REF_COUNTED; + internalPacket->data=ourOffset; + if (*refCounter==0) + { + *refCounter = refCountedDataPool.Allocate(_FILE_AND_LINE_); + // *refCounter = RakNet::OP_NEW(_FILE_AND_LINE_); + (*refCounter)->refCount=1; + (*refCounter)->sharedDataBlock=externallyAllocatedPtr; + } + else + (*refCounter)->refCount++; + internalPacket->refCountedData=(*refCounter); +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::AllocInternalPacketData(InternalPacket *internalPacket, unsigned char *externallyAllocatedPtr) +{ + internalPacket->allocationScheme=InternalPacket::NORMAL; + internalPacket->data=externallyAllocatedPtr; +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::AllocInternalPacketData(InternalPacket *internalPacket, unsigned int numBytes, bool allowStack, const char *file, unsigned int line) +{ + if (allowStack && numBytes <= sizeof(internalPacket->stackData)) + { + internalPacket->allocationScheme=InternalPacket::STACK; + internalPacket->data=internalPacket->stackData; + } + else + { + internalPacket->allocationScheme=InternalPacket::NORMAL; + internalPacket->data=(unsigned char*) rakMalloc_Ex(numBytes,file,line); + } +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::FreeInternalPacketData(InternalPacket *internalPacket, const char *file, unsigned int line) +{ + if (internalPacket==0) + return; + + if (internalPacket->allocationScheme==InternalPacket::REF_COUNTED) + { + if (internalPacket->refCountedData==0) + return; + + internalPacket->refCountedData->refCount--; + if (internalPacket->refCountedData->refCount==0) + { + rakFree_Ex(internalPacket->refCountedData->sharedDataBlock, file, line ); + internalPacket->refCountedData->sharedDataBlock=0; + // RakNet::OP_DELETE(internalPacket->refCountedData,file, line); + refCountedDataPool.Release(internalPacket->refCountedData,file, line); + internalPacket->refCountedData=0; + } + } + else if (internalPacket->allocationScheme==InternalPacket::NORMAL) + { + if (internalPacket->data==0) + return; + + rakFree_Ex(internalPacket->data, file, line ); + internalPacket->data=0; + } + else + { + // Data was on stack + internalPacket->data=0; + } +} +//------------------------------------------------------------------------------------------------------- +unsigned int ReliabilityLayer::GetMaxDatagramSizeExcludingMessageHeaderBytes(void) +{ + unsigned int val = congestionManager.GetMTU() - DatagramHeaderFormat::GetDataHeaderByteLength(); + +#if LIBCAT_SECURITY==1 + if (useSecurity) + val -= cat::AuthenticatedEncryption::OVERHEAD_BYTES; +#endif + + return val; +} +//------------------------------------------------------------------------------------------------------- +BitSize_t ReliabilityLayer::GetMaxDatagramSizeExcludingMessageHeaderBits(void) +{ + return BYTES_TO_BITS(GetMaxDatagramSizeExcludingMessageHeaderBytes()); +} +//------------------------------------------------------------------------------------------------------- +void ReliabilityLayer::InitHeapWeights(void) +{ + for (int priorityLevel=0; priorityLevel < NUMBER_OF_PRIORITIES; priorityLevel++) + outgoingPacketBufferNextWeights[priorityLevel]=(1<0) + { + int peekPL = outgoingPacketBuffer.Peek()->priority; + reliabilityHeapWeightType weight = outgoingPacketBuffer.PeekWeight(); + reliabilityHeapWeightType min = weight - (1<GetNetworkID() < data->replica->GetNetworkID()) + return -1; + if (replica3->GetNetworkID() > data->replica->GetNetworkID()) + return 1; + */ + + // 7/28/2013 - If GetNetworkID chagned during runtime, the list would be out of order and lookup would always fail or go out of bounds + // I remember before that I could not directly compare + if (replica3->referenceIndex < data->replica->referenceIndex) + return -1; + if (replica3->referenceIndex > data->replica->referenceIndex) + return 1; + return 0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +LastSerializationResult::LastSerializationResult() +{ + replica=0; + lastSerializationResultBS=0; + whenLastSerialized = RakNet::GetTime(); +} +LastSerializationResult::~LastSerializationResult() +{ + if (lastSerializationResultBS) + RakNet::OP_DELETE(lastSerializationResultBS,_FILE_AND_LINE_); +} +void LastSerializationResult::AllocBS(void) +{ + if (lastSerializationResultBS==0) + { + lastSerializationResultBS=RakNet::OP_NEW(_FILE_AND_LINE_); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ReplicaManager3::ReplicaManager3() +{ + defaultSendParameters.orderingChannel=0; + defaultSendParameters.priority=HIGH_PRIORITY; + defaultSendParameters.reliability=RELIABLE_ORDERED; + defaultSendParameters.sendReceipt=0; + autoSerializeInterval=30; + lastAutoSerializeOccurance=0; + autoCreateConnections=true; + autoDestroyConnections=true; + currentlyDeallocatingReplica=0; + + for (unsigned int i=0; i < 255; i++) + worldsArray[i]=0; + + AddWorld(0); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ReplicaManager3::~ReplicaManager3() +{ + if (autoDestroyConnections) + { + for (unsigned int i=0; i < worldsList.Size(); i++) + { + RakAssert(worldsList[i]->connectionList.Size()==0); + } + } + Clear(true); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::SetAutoManageConnections(bool autoCreate, bool autoDestroy) +{ + autoCreateConnections=autoCreate; + autoDestroyConnections=autoDestroy; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool ReplicaManager3::GetAutoCreateConnections(void) const +{ + return autoCreateConnections; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool ReplicaManager3::GetAutoDestroyConnections(void) const +{ + return autoDestroyConnections; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::AutoCreateConnectionList( + DataStructures::List &participantListIn, + DataStructures::List &participantListOut, + WorldId worldId) +{ + for (unsigned int index=0; index < participantListIn.Size(); index++) + { + if (GetConnectionByGUID(participantListIn[index], worldId)==0) + { + Connection_RM3 *connection = AllocConnection(rakPeerInterface->GetSystemAddressFromGuid(participantListIn[index]), participantListIn[index]); + if (connection) + { + PushConnection(connection); + participantListOut.Push(connection, _FILE_AND_LINE_); + } + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool ReplicaManager3::PushConnection(RakNet::Connection_RM3 *newConnection, WorldId worldId) +{ + if (newConnection==0) + return false; + if (GetConnectionByGUID(newConnection->GetRakNetGUID(), worldId)) + return false; + // Was this intended? + RakAssert(newConnection->GetRakNetGUID()!=rakPeerInterface->GetMyGUID()); + + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + unsigned int index = world->connectionList.GetIndexOf(newConnection); + if (index==(unsigned int)-1) + { + world->connectionList.Push(newConnection,_FILE_AND_LINE_); + + // Send message to validate the connection + newConnection->SendValidation(rakPeerInterface, worldId); + + Connection_RM3::ConstructionMode constructionMode = newConnection->QueryConstructionMode(); + if (constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) + { + unsigned int pushIdx; + for (pushIdx=0; pushIdx < world->userReplicaList.Size(); pushIdx++) + newConnection->OnLocalReference(world->userReplicaList[pushIdx], this); + } + } + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::DeallocReplicaNoBroadcastDestruction(RakNet::Connection_RM3 *connection, RakNet::Replica3 *replica3) +{ + currentlyDeallocatingReplica=replica3; + replica3->DeallocReplica(connection); + currentlyDeallocatingReplica=0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RakNet::Connection_RM3 * ReplicaManager3::PopConnection(unsigned int index, WorldId worldId) +{ + DataStructures::List replicaList; + DataStructures::List destructionList; + DataStructures::List broadcastList; + RakNet::Connection_RM3 *connection; + unsigned int index2; + RM3ActionOnPopConnection action; + + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + connection=world->connectionList[index]; + + // Clear out downloadGroup + connection->ClearDownloadGroup(rakPeerInterface); + + RakNetGUID guid = connection->GetRakNetGUID(); + // This might be wrong, I am relying on the variable creatingSystemGuid which is transmitted + // automatically from the first system to reference the object. However, if an object changes + // owners then it is not going to be returned here, and therefore QueryActionOnPopConnection() + // will not be called for the new owner. + GetReplicasCreatedByGuid(guid, replicaList); + + for (index2=0; index2 < replicaList.Size(); index2++) + { + action = replicaList[index2]->QueryActionOnPopConnection(connection); + replicaList[index2]->OnPoppedConnection(connection); + if (action==RM3AOPC_DELETE_REPLICA) + { + if (replicaList[index2]->GetNetworkIDManager()) + destructionList.Push( replicaList[index2]->GetNetworkID(), _FILE_AND_LINE_ ); + } + else if (action==RM3AOPC_DELETE_REPLICA_AND_BROADCAST_DESTRUCTION) + { + if (replicaList[index2]->GetNetworkIDManager()) + destructionList.Push( replicaList[index2]->GetNetworkID(), _FILE_AND_LINE_ ); + + broadcastList.Push( replicaList[index2], _FILE_AND_LINE_ ); + } + else if (action==RM3AOPC_DO_NOTHING) + { + for (unsigned int index3 = 0; index3 < connection->queryToSerializeReplicaList.Size(); index3++) + { + LastSerializationResult *lsr = connection->queryToSerializeReplicaList[index3]; + lsr->whenLastSerialized=0; + if (lsr->lastSerializationResultBS) + { + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + lsr->lastSerializationResultBS->bitStream[z].Reset(); + } + } + } + } + + BroadcastDestructionList(broadcastList, connection->GetSystemAddress()); + for (index2=0; index2 < destructionList.Size(); index2++) + { + // Do lookup in case DeallocReplica destroyed one of of the later Replica3 instances in the list + Replica3* replicaToDestroy = world->networkIDManager->GET_OBJECT_FROM_ID(destructionList[index2]); + if (replicaToDestroy) + { + replicaToDestroy->PreDestruction(connection); + replicaToDestroy->DeallocReplica(connection); + } + } + + world->connectionList.RemoveAtIndex(index); + return connection; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RakNet::Connection_RM3 * ReplicaManager3::PopConnection(RakNetGUID guid, WorldId worldId) +{ + unsigned int index; + + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + for (index=0; index < world->connectionList.Size(); index++) + { + if (world->connectionList[index]->GetRakNetGUID()==guid) + { + return PopConnection(index, worldId); + } + } + return 0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::Reference(RakNet::Replica3 *replica3, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + unsigned int index = ReferenceInternal(replica3, worldId); + + if (index!=(unsigned int)-1) + { + unsigned int pushIdx; + for (pushIdx=0; pushIdx < world->connectionList.Size(); pushIdx++) + { + Connection_RM3::ConstructionMode constructionMode = world->connectionList[pushIdx]->QueryConstructionMode(); + if (constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==Connection_RM3::QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) + { + world->connectionList[pushIdx]->OnLocalReference(replica3, this); + } + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int ReplicaManager3::ReferenceInternal(RakNet::Replica3 *replica3, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + unsigned int index; + index = world->userReplicaList.GetIndexOf(replica3); + if (index==(unsigned int)-1) + { + RakAssert(world->networkIDManager); + replica3->SetNetworkIDManager(world->networkIDManager); + // If it crashes on rakPeerInterface==0 then you didn't call RakPeerInterface::AttachPlugin() + if (replica3->creatingSystemGUID==UNASSIGNED_RAKNET_GUID) + replica3->creatingSystemGUID=rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); + replica3->replicaManager=this; + if (replica3->referenceIndex==(uint32_t)-1) + { + replica3->referenceIndex=nextReferenceIndex++; + } + world->userReplicaList.Push(replica3,_FILE_AND_LINE_); + return world->userReplicaList.Size()-1; + } + return (unsigned int) -1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::Dereference(RakNet::Replica3 *replica3, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + unsigned int index, index2; + for (index=0; index < world->userReplicaList.Size(); index++) + { + if (world->userReplicaList[index]==replica3) + { + world->userReplicaList.RemoveAtIndex(index); + break; + } + } + + // Remove from all connections + for (index2=0; index2 < world->connectionList.Size(); index2++) + { + world->connectionList[index2]->OnDereference(replica3, this); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::DereferenceList(DataStructures::List &replicaListIn, WorldId worldId) +{ + unsigned int index; + for (index=0; index < replicaListIn.Size(); index++) + Dereference(replicaListIn[index], worldId); +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::GetReplicasCreatedByMe(DataStructures::List &replicaListOut, WorldId worldId) +{ + //RakNetGUID myGuid = rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); + GetReplicasCreatedByGuid(rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS), replicaListOut, worldId); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::GetReferencedReplicaList(DataStructures::List &replicaListOut, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + replicaListOut=world->userReplicaList; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::GetReplicasCreatedByGuid(RakNetGUID guid, DataStructures::List &replicaListOut, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + replicaListOut.Clear(false,_FILE_AND_LINE_); + unsigned int index; + for (index=0; index < world->userReplicaList.Size(); index++) + { + if (world->userReplicaList[index]->creatingSystemGUID==guid) + replicaListOut.Push(world->userReplicaList[index],_FILE_AND_LINE_); + } +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned ReplicaManager3::GetReplicaCount(WorldId worldId) const +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + return world->userReplicaList.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Replica3 *ReplicaManager3::GetReplicaAtIndex(unsigned index, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + return world->userReplicaList[index]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int ReplicaManager3::GetConnectionCount(WorldId worldId) const +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + return world->connectionList.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Connection_RM3* ReplicaManager3::GetConnectionAtIndex(unsigned index, WorldId worldId) const +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + return world->connectionList[index]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Connection_RM3* ReplicaManager3::GetConnectionBySystemAddress(const SystemAddress &sa, WorldId worldId) const +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + unsigned int index; + for (index=0; index < world->connectionList.Size(); index++) + { + if (world->connectionList[index]->GetSystemAddress()==sa) + { + return world->connectionList[index]; + } + } + return 0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Connection_RM3* ReplicaManager3::GetConnectionByGUID(RakNetGUID guid, WorldId worldId) const +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + unsigned int index; + for (index=0; index < world->connectionList.Size(); index++) + { + if (world->connectionList[index]->GetRakNetGUID()==guid) + { + return world->connectionList[index]; + } + } + return 0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::SetDefaultOrderingChannel(char def) +{ + defaultSendParameters.orderingChannel=def; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::SetDefaultPacketPriority(PacketPriority def) +{ + defaultSendParameters.priority=def; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::SetDefaultPacketReliability(PacketReliability def) +{ + defaultSendParameters.reliability=def; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::SetAutoSerializeInterval(RakNet::Time intervalMS) +{ + autoSerializeInterval=intervalMS; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::GetConnectionsThatHaveReplicaConstructed(Replica3 *replica, DataStructures::List &connectionsThatHaveConstructedThisReplica, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + connectionsThatHaveConstructedThisReplica.Clear(false,_FILE_AND_LINE_); + unsigned int index; + for (index=0; index < world->connectionList.Size(); index++) + { + if (world->connectionList[index]->HasReplicaConstructed(replica)) + connectionsThatHaveConstructedThisReplica.Push(world->connectionList[index],_FILE_AND_LINE_); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool ReplicaManager3::GetAllConnectionDownloadsCompleted(WorldId worldId) const +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + unsigned int index; + for (index=0; index < world->connectionList.Size(); index++) + { + if (world->connectionList[index]->GetDownloadWasCompleted()==false) + return false; + } + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::Clear(bool deleteWorlds) +{ + for (unsigned int i=0; i < worldsList.Size(); i++) + { + worldsList[i]->Clear(this); + if (deleteWorlds) + { + worldsArray[worldsList[i]->worldId]=0; + delete worldsList[i]; + } + } + if (deleteWorlds) + worldsList.Clear(false, _FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +ReplicaManager3::RM3World::RM3World() +{ + networkIDManager=0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::RM3World::Clear(ReplicaManager3 *replicaManager3) +{ + if (replicaManager3->GetAutoDestroyConnections()) + { + for (unsigned int i=0; i < connectionList.Size(); i++) + replicaManager3->DeallocConnection(connectionList[i]); + } + else + { + // Clear out downloadGroup even if not auto destroying the connection, since the packets need to go back to RakPeer + for (unsigned int i=0; i < connectionList.Size(); i++) + connectionList[i]->ClearDownloadGroup(replicaManager3->GetRakPeerInterface()); + } + + for (unsigned int i=0; i < userReplicaList.Size(); i++) + { + userReplicaList[i]->replicaManager=0; + userReplicaList[i]->SetNetworkIDManager(0); + } + connectionList.Clear(true,_FILE_AND_LINE_); + userReplicaList.Clear(true,_FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +PRO ReplicaManager3::GetDefaultSendParameters(void) const +{ + return defaultSendParameters; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::AddWorld(WorldId worldId) +{ + RakAssert(worldsArray[worldId]==0 && "World already in use"); + + RM3World *newWorld = RakNet::OP_NEW(_FILE_AND_LINE_); + newWorld->worldId=worldId; + worldsArray[worldId]=newWorld; + worldsList.Push(newWorld,_FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::RemoveWorld(WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + for (unsigned int i=0; i < worldsList.Size(); i++) + { + if (worldsList[i]==worldsArray[worldId]) + { + RakNet::OP_DELETE(worldsList[i],_FILE_AND_LINE_); + worldsList.RemoveAtIndexFast(i); + break; + } + } + worldsArray[worldId]=0; + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +NetworkIDManager *ReplicaManager3::GetNetworkIDManager(WorldId worldId) const +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + return world->networkIDManager; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::SetNetworkIDManager(NetworkIDManager *_networkIDManager, WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + world->networkIDManager=_networkIDManager; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +PluginReceiveResult ReplicaManager3::OnReceive(Packet *packet) +{ + if (packet->length<2) + return RR_CONTINUE_PROCESSING; + + WorldId incomingWorldId; + + RakNet::Time timestamp=0; + unsigned char packetIdentifier, packetDataOffset; + if ( ( unsigned char ) packet->data[ 0 ] == ID_TIMESTAMP ) + { + if ( packet->length > sizeof( unsigned char ) + sizeof( RakNet::Time ) ) + { + packetIdentifier = ( unsigned char ) packet->data[ sizeof( unsigned char ) + sizeof( RakNet::Time ) ]; + // Required for proper endian swapping + RakNet::BitStream tsBs(packet->data+sizeof(MessageID),packet->length-1,false); + tsBs.Read(timestamp); + // Next line assumes worldId is only 1 byte + RakAssert(sizeof(WorldId)==1); + incomingWorldId=packet->data[sizeof( unsigned char )*2 + sizeof( RakNet::Time )]; + packetDataOffset=sizeof( unsigned char )*3 + sizeof( RakNet::Time ); + } + else + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + else + { + packetIdentifier = ( unsigned char ) packet->data[ 0 ]; + // Next line assumes worldId is only 1 byte + RakAssert(sizeof(WorldId)==1); + incomingWorldId=packet->data[sizeof( unsigned char )]; + packetDataOffset=sizeof( unsigned char )*2; + } + + if (worldsArray[incomingWorldId]==0) + return RR_CONTINUE_PROCESSING; + + switch (packetIdentifier) + { + case ID_REPLICA_MANAGER_CONSTRUCTION: + return OnConstruction(packet, packet->data, packet->length, packet->guid, packetDataOffset, incomingWorldId); + case ID_REPLICA_MANAGER_SERIALIZE: + return OnSerialize(packet, packet->data, packet->length, packet->guid, timestamp, packetDataOffset, incomingWorldId); + case ID_REPLICA_MANAGER_DOWNLOAD_STARTED: + if (packet->wasGeneratedLocally==false) + { + return OnDownloadStarted(packet, packet->data, packet->length, packet->guid, packetDataOffset, incomingWorldId); + } + else + break; + case ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE: + if (packet->wasGeneratedLocally==false) + { + return OnDownloadComplete(packet, packet->data, packet->length, packet->guid, packetDataOffset, incomingWorldId); + } + else + break; + case ID_REPLICA_MANAGER_SCOPE_CHANGE: + { + Connection_RM3 *connection = GetConnectionByGUID(packet->guid, incomingWorldId); + if (connection && connection->isValidated==false) + { + // This connection is now confirmed bidirectional + connection->isValidated=true; + // Reply back on validation + connection->SendValidation(rakPeerInterface,incomingWorldId); + } + } + } + + return RR_CONTINUE_PROCESSING; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::AutoConstructByQuery(ReplicaManager3 *replicaManager3, WorldId worldId) +{ + ValidateLists(replicaManager3); + + ConstructionMode constructionMode = QueryConstructionMode(); + + unsigned int index; + RM3ConstructionState constructionState; + LastSerializationResult *lsr; + index=0; + + constructedReplicasCulled.Clear(false,_FILE_AND_LINE_); + destroyedReplicasCulled.Clear(false,_FILE_AND_LINE_); + + if (constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) + { + while (index < queryToConstructReplicaList.Size()) + { + lsr=queryToConstructReplicaList[index]; + constructionState=lsr->replica->QueryConstruction(this, replicaManager3); + if (constructionState==RM3CS_ALREADY_EXISTS_REMOTELY || constructionState==RM3CS_ALREADY_EXISTS_REMOTELY_DO_NOT_CONSTRUCT) + { + OnReplicaAlreadyExists(index, replicaManager3); + if (constructionState==RM3CS_ALREADY_EXISTS_REMOTELY) + constructedReplicasCulled.Push(lsr->replica,_FILE_AND_LINE_); + + /* + if (constructionState==RM3CS_ALREADY_EXISTS_REMOTELY) + { + // Serialize construction data to this connection + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_REPLICA_MANAGER_3_SERIALIZE_CONSTRUCTION_EXISTING); + bsOut.Write(replicaManager3->GetWorldID()); + NetworkID networkId; + networkId=lsr->replica->GetNetworkID(); + bsOut.Write(networkId); + BitSize_t bitsWritten = bsOut.GetNumberOfBitsUsed(); + lsr->replica->SerializeConstructionExisting(&bsOut, this); + if (bsOut.GetNumberOfBitsUsed()!=bitsWritten) + replicaManager3->SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,GetSystemAddress(), false); + } + + // Serialize first serialization to this connection. + // This is done here, as it isn't done in PushConstruction + SerializeParameters sp; + RakNet::BitStream emptyBs; + for (index=0; index < (unsigned int) RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; index++) + { + sp.lastSentBitstream[index]=&emptyBs; + sp.pro[index]=replicaManager3->GetDefaultSendParameters(); + } + sp.bitsWrittenSoFar=0; + sp.destinationConnection=this; + sp.messageTimestamp=0; + sp.whenLastSerialized=0; + + RakNet::Replica3 *replica = lsr->replica; + + RM3SerializationResult res = replica->Serialize(&sp); + if (res!=RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION && + res!=RM3SR_DO_NOT_SERIALIZE && + res!=RM3SR_SERIALIZED_UNIQUELY) + { + bool allIndices[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + sp.bitsWrittenSoFar+=sp.outputBitstream[z].GetNumberOfBitsUsed(); + allIndices[z]=true; + } + if (SendSerialize(replica, allIndices, sp.outputBitstream, sp.messageTimestamp, sp.pro, replicaManager3->GetRakPeerInterface(), replicaManager3->GetWorldID())==SSICR_SENT_DATA) + lsr->replica->whenLastSerialized=RakNet::GetTimeMS(); + } + */ + } + else if (constructionState==RM3CS_SEND_CONSTRUCTION) + { + OnConstructToThisConnection(index, replicaManager3); + RakAssert(lsr->replica); + constructedReplicasCulled.Push(lsr->replica,_FILE_AND_LINE_); + } + else if (constructionState==RM3CS_NEVER_CONSTRUCT) + { + OnNeverConstruct(index, replicaManager3); + } + else// if (constructionState==RM3CS_NO_ACTION) + { + // Do nothing + index++; + } + } + + if (constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) + { + RM3DestructionState destructionState; + index=0; + while (index < queryToDestructReplicaList.Size()) + { + lsr=queryToDestructReplicaList[index]; + destructionState=lsr->replica->QueryDestruction(this, replicaManager3); + if (destructionState==RM3DS_SEND_DESTRUCTION) + { + OnSendDestructionFromQuery(index, replicaManager3); + destroyedReplicasCulled.Push(lsr->replica,_FILE_AND_LINE_); + } + else if (destructionState==RM3DS_DO_NOT_QUERY_DESTRUCTION) + { + OnDoNotQueryDestruction(index, replicaManager3); + } + else// if (destructionState==RM3CS_NO_ACTION) + { + // Do nothing + index++; + } + } + } + } + else if (constructionMode==QUERY_CONNECTION_FOR_REPLICA_LIST) + { + QueryReplicaList(constructedReplicasCulled,destroyedReplicasCulled); + + unsigned int idx1, idx2; + + // Create new + for (idx2=0; idx2 < constructedReplicasCulled.Size(); idx2++) + OnConstructToThisConnection(constructedReplicasCulled[idx2], replicaManager3); + + bool exists; + for (idx2=0; idx2 < destroyedReplicasCulled.Size(); idx2++) + { + exists=false; + bool objectExists; + idx1=constructedReplicaList.GetIndexFromKey(destroyedReplicasCulled[idx2], &objectExists); + if (objectExists) + { + constructedReplicaList.RemoveAtIndex(idx1); + + unsigned int j; + for (j=0; j < queryToSerializeReplicaList.Size(); j++) + { + if (queryToSerializeReplicaList[j]->replica==destroyedReplicasCulled[idx2] ) + { + queryToSerializeReplicaList.RemoveAtIndex(j); + break; + } + } + } + } + } + + SendConstruction(constructedReplicasCulled,destroyedReplicasCulled,replicaManager3->defaultSendParameters,replicaManager3->rakPeerInterface,worldId,replicaManager3); +} +void ReplicaManager3::Update(void) +{ + unsigned int index,index2,index3; + + WorldId worldId; + RM3World *world; + RakNet::Time time = RakNet::GetTime(); + + for (index3=0; index3 < worldsList.Size(); index3++) + { + world = worldsList[index3]; + worldId = world->worldId; + + for (index=0; index < world->connectionList.Size(); index++) + { + if (world->connectionList[index]->isValidated==false) + continue; + world->connectionList[index]->AutoConstructByQuery(this, worldId); + } + } + + if (time - lastAutoSerializeOccurance >= autoSerializeInterval) + { + for (index3=0; index3 < worldsList.Size(); index3++) + { + world = worldsList[index3]; + worldId = world->worldId; + + for (index=0; index < world->userReplicaList.Size(); index++) + { + world->userReplicaList[index]->forceSendUntilNextUpdate=false; + world->userReplicaList[index]->OnUserReplicaPreSerializeTick(); + } + + unsigned int index; + SerializeParameters sp; + sp.curTime=time; + Connection_RM3 *connection; + SendSerializeIfChangedResult ssicr; + LastSerializationResult *lsr; + + sp.messageTimestamp=0; + for (int i=0; i < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; i++) + sp.pro[i]=defaultSendParameters; + index2=0; + for (index=0; index < world->connectionList.Size(); index++) + { + connection = world->connectionList[index]; + sp.bitsWrittenSoFar=0; + index2=0; + sp.destinationConnection=connection; + + DataStructures::List replicasToSerialize; + replicasToSerialize.Clear(true, _FILE_AND_LINE_); + if (connection->QuerySerializationList(replicasToSerialize)) + { + // Update replica->lsr so we can lookup in the next block + // lsr is per connection / per replica + while (index2 < connection->queryToSerializeReplicaList.Size()) + { + connection->queryToSerializeReplicaList[index2]->replica->lsr=connection->queryToSerializeReplicaList[index2]; + index2++; + } + + + // User is manually specifying list of replicas to serialize + index2=0; + while (index2 < replicasToSerialize.Size()) + { + lsr=replicasToSerialize[index2]->lsr; + RakAssert(lsr->replica==replicasToSerialize[index2]); + + sp.whenLastSerialized=lsr->whenLastSerialized; + ssicr=connection->SendSerializeIfChanged(lsr, &sp, GetRakPeerInterface(), worldId, this, time); + if (ssicr==SSICR_SENT_DATA) + lsr->whenLastSerialized=time; + index2++; + } + } + else + { + while (index2 < connection->queryToSerializeReplicaList.Size()) + { + lsr=connection->queryToSerializeReplicaList[index2]; + + sp.destinationConnection=connection; + sp.whenLastSerialized=lsr->whenLastSerialized; + ssicr=connection->SendSerializeIfChanged(lsr, &sp, GetRakPeerInterface(), worldId, this, time); + if (ssicr==SSICR_SENT_DATA) + { + lsr->whenLastSerialized=time; + index2++; + } + else if (ssicr==SSICR_NEVER_SERIALIZE) + { + // Removed from the middle of the list + } + else + index2++; + } + } + } + } + + lastAutoSerializeOccurance=time; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + if (autoDestroyConnections) + { + Connection_RM3 *connection = PopConnection(rakNetGUID); + if (connection) + DeallocConnection(connection); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) isIncoming; + if (autoCreateConnections) + { + Connection_RM3 *connection = AllocConnection(systemAddress, rakNetGUID); + if (connection) + PushConnection(connection); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::OnRakPeerShutdown(void) +{ + if (autoDestroyConnections) + { + RM3World *world; + unsigned int index3; + for (index3=0; index3 < worldsList.Size(); index3++) + { + world = worldsList[index3]; + + while (world->connectionList.Size()) + { + Connection_RM3 *connection = PopConnection(world->connectionList.Size()-1, world->worldId); + if (connection) + DeallocConnection(connection); + } + } + } + + + Clear(false); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void ReplicaManager3::OnDetach(void) +{ + OnRakPeerShutdown(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +PluginReceiveResult ReplicaManager3::OnConstruction(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId) +{ + RM3World *world = worldsArray[worldId]; + + Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); + if (connection==0) + { + // Almost certainly a bug + RakAssert("Got OnConstruction but no connection yet" && 0); + return RR_CONTINUE_PROCESSING; + } + if (connection->groupConstructionAndSerialize) + { + connection->downloadGroup.Push(packet, __FILE__, __LINE__); + return RR_STOP_PROCESSING; + } + + RakNet::BitStream bsIn(packetData,packetDataLength,false); + bsIn.IgnoreBytes(packetDataOffset); + uint16_t constructionObjectListSize, destructionObjectListSize, index, index2; + BitSize_t streamEnd, writeAllocationIDEnd; + Replica3 *replica; + NetworkID networkId; + RakNetGUID creatingSystemGuid; + bool actuallyCreateObject=false; + + DataStructures::List actuallyCreateObjectList; + DataStructures::List constructionTickStack; + + RakAssert(world->networkIDManager); + + bsIn.Read(constructionObjectListSize); + for (index=0; index < constructionObjectListSize; index++) + { + bsIn.Read(streamEnd); + bsIn.Read(networkId); + Replica3* existingReplica = world->networkIDManager->GET_OBJECT_FROM_ID(networkId); + bsIn.Read(actuallyCreateObject); + actuallyCreateObjectList.Push(actuallyCreateObject, _FILE_AND_LINE_); + bsIn.AlignReadToByteBoundary(); + + if (actuallyCreateObject) + { + bsIn.Read(creatingSystemGuid); + bsIn.Read(writeAllocationIDEnd); + + //printf("OnConstruction: %i\n",networkId.guid.g); // Removeme + if (existingReplica) + { + existingReplica->replicaManager=this; + + // Network ID already in use + connection->OnDownloadExisting(existingReplica, this); + + constructionTickStack.Push(0, _FILE_AND_LINE_); + bsIn.SetReadOffset(streamEnd); + continue; + } + + bsIn.AlignReadToByteBoundary(); + replica = connection->AllocReplica(&bsIn, this); + if (replica==0) + { + constructionTickStack.Push(0, _FILE_AND_LINE_); + bsIn.SetReadOffset(streamEnd); + continue; + } + + // Go past the bitStream written to with WriteAllocationID(). Necessary in case the user didn't read out the bitStream the same way it was written + // bitOffset2 is already aligned + bsIn.SetReadOffset(writeAllocationIDEnd); + + replica->SetNetworkIDManager(world->networkIDManager); + replica->SetNetworkID(networkId); + + replica->replicaManager=this; + replica->creatingSystemGUID=creatingSystemGuid; + + if (!replica->QueryRemoteConstruction(connection) || + !replica->DeserializeConstruction(&bsIn, connection)) + { + DeallocReplicaNoBroadcastDestruction(connection, replica); + bsIn.SetReadOffset(streamEnd); + constructionTickStack.Push(0, _FILE_AND_LINE_); + continue; + } + + constructionTickStack.Push(replica, _FILE_AND_LINE_); + + // Register the replica + ReferenceInternal(replica, worldId); + } + else + { + if (existingReplica) + { + existingReplica->DeserializeConstructionExisting(&bsIn, connection); + constructionTickStack.Push(existingReplica, _FILE_AND_LINE_); + } + else + { + constructionTickStack.Push(0, _FILE_AND_LINE_); + } + } + + + bsIn.SetReadOffset(streamEnd); + bsIn.AlignReadToByteBoundary(); + } + + RakAssert(constructionTickStack.Size()==constructionObjectListSize); + RakAssert(actuallyCreateObjectList.Size()==constructionObjectListSize); + + RakNet::BitStream empty; + for (index=0; index < constructionObjectListSize; index++) + { + bool pdcWritten=false; + bsIn.Read(pdcWritten); + if (pdcWritten) + { + bsIn.AlignReadToByteBoundary(); + bsIn.Read(streamEnd); + bsIn.Read(networkId); + if (constructionTickStack[index]!=0) + { + bsIn.AlignReadToByteBoundary(); + if (actuallyCreateObjectList[index]) + constructionTickStack[index]->PostDeserializeConstruction(&bsIn, connection); + else + constructionTickStack[index]->PostDeserializeConstructionExisting(&bsIn, connection); + } + bsIn.SetReadOffset(streamEnd); + } + else + { + if (constructionTickStack[index]!=0) + { + if (actuallyCreateObjectList[index]) + constructionTickStack[index]->PostDeserializeConstruction(&empty, connection); + else + constructionTickStack[index]->PostDeserializeConstructionExisting(&empty, connection); + } + } + } + + for (index=0; index < constructionObjectListSize; index++) + { + if (constructionTickStack[index]!=0) + { + if (actuallyCreateObjectList[index]) + { + // Tell the connection(s) that this object exists since they just sent it to us + connection->OnDownloadFromThisSystem(constructionTickStack[index], this); + + for (index2=0; index2 < world->connectionList.Size(); index2++) + { + if (world->connectionList[index2]!=connection) + world->connectionList[index2]->OnDownloadFromOtherSystem(constructionTickStack[index], this); + } + } + } + } + + // Destructions + bool b = bsIn.Read(destructionObjectListSize); + (void) b; + RakAssert(b); + for (index=0; index < destructionObjectListSize; index++) + { + bsIn.Read(networkId); + bsIn.Read(streamEnd); + replica = world->networkIDManager->GET_OBJECT_FROM_ID(networkId); + if (replica==0) + { + // Unknown object + bsIn.SetReadOffset(streamEnd); + continue; + } + bsIn.Read(replica->deletingSystemGUID); + if (replica->DeserializeDestruction(&bsIn,connection)) + { + // Make sure it wasn't deleted in DeserializeDestruction + if (world->networkIDManager->GET_OBJECT_FROM_ID(networkId)) + { + replica->PreDestruction(connection); + + // Forward deletion by remote system + if (replica->QueryRelayDestruction(connection)) + BroadcastDestruction(replica,connection->GetSystemAddress()); + Dereference(replica); + DeallocReplicaNoBroadcastDestruction(connection, replica); + } + } + else + { + replica->PreDestruction(connection); + connection->OnDereference(replica, this); + } + + bsIn.AlignReadToByteBoundary(); + } + return RR_CONTINUE_PROCESSING; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +PluginReceiveResult ReplicaManager3::OnSerialize(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, RakNet::Time timestamp, unsigned char packetDataOffset, WorldId worldId) +{ + Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); + if (connection==0) + return RR_CONTINUE_PROCESSING; + if (connection->groupConstructionAndSerialize) + { + connection->downloadGroup.Push(packet, __FILE__, __LINE__); + return RR_STOP_PROCESSING; + } + + RM3World *world = worldsArray[worldId]; + RakAssert(world->networkIDManager); + RakNet::BitStream bsIn(packetData,packetDataLength,false); + bsIn.IgnoreBytes(packetDataOffset); + + struct DeserializeParameters ds; + ds.timeStamp=timestamp; + ds.sourceConnection=connection; + + Replica3 *replica; + NetworkID networkId; + BitSize_t bitsUsed; + bsIn.Read(networkId); + //printf("OnSerialize: %i\n",networkId.guid.g); // Removeme + replica = world->networkIDManager->GET_OBJECT_FROM_ID(networkId); + if (replica) + { + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + bsIn.Read(ds.bitstreamWrittenTo[z]); + if (ds.bitstreamWrittenTo[z]) + { + bsIn.ReadCompressed(bitsUsed); + bsIn.AlignReadToByteBoundary(); + bsIn.Read(ds.serializationBitstream[z], bitsUsed); + } + } + replica->Deserialize(&ds); + } + return RR_CONTINUE_PROCESSING; +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +PluginReceiveResult ReplicaManager3::OnDownloadStarted(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId) +{ + Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); + if (connection==0) + return RR_CONTINUE_PROCESSING; + if (connection->QueryGroupDownloadMessages() && + // ID_DOWNLOAD_STARTED will be processed twice, being processed the second time once ID_DOWNLOAD_COMPLETE arrives. + // However, the second time groupConstructionAndSerialize will be set to true so it won't be processed a third time + connection->groupConstructionAndSerialize==false + ) + { + // These messages will be held by the plugin and returned when the download is complete + connection->groupConstructionAndSerialize=true; + RakAssert(connection->downloadGroup.Size()==0); + connection->downloadGroup.Push(packet, __FILE__, __LINE__); + return RR_STOP_PROCESSING; + } + + connection->groupConstructionAndSerialize=false; + RakNet::BitStream bsIn(packetData,packetDataLength,false); + bsIn.IgnoreBytes(packetDataOffset); + connection->DeserializeOnDownloadStarted(&bsIn); + return RR_CONTINUE_PROCESSING; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +PluginReceiveResult ReplicaManager3::OnDownloadComplete(Packet *packet, unsigned char *packetData, int packetDataLength, RakNetGUID senderGuid, unsigned char packetDataOffset, WorldId worldId) +{ + Connection_RM3 *connection = GetConnectionByGUID(senderGuid, worldId); + if (connection==0) + return RR_CONTINUE_PROCESSING; + + if (connection->groupConstructionAndSerialize==true && connection->downloadGroup.Size()>0) + { + // Push back buffered packets in front of this one + unsigned int i; + for (i=0; i < connection->downloadGroup.Size(); i++) + rakPeerInterface->PushBackPacket(connection->downloadGroup[i],false); + + // Push this one to be last too. It will be processed again, but the second time + // groupConstructionAndSerialize will be false and downloadGroup will be empty, so it will go past this block + connection->downloadGroup.Clear(__FILE__,__LINE__); + rakPeerInterface->PushBackPacket(packet,false); + + return RR_STOP_PROCESSING; + } + + RakNet::BitStream bsIn(packetData,packetDataLength,false); + bsIn.IgnoreBytes(packetDataOffset); + connection->gotDownloadComplete=true; + connection->DeserializeOnDownloadComplete(&bsIn); + return RR_CONTINUE_PROCESSING; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Replica3* ReplicaManager3::GetReplicaByNetworkID(NetworkID networkId, WorldId worldId) +{ + RM3World *world = worldsArray[worldId]; + + unsigned int i; + for (i=0; i < world->userReplicaList.Size(); i++) + { + if (world->userReplicaList[i]->GetNetworkID()==networkId) + return world->userReplicaList[i]; + } + return 0; +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + +void ReplicaManager3::BroadcastDestructionList(DataStructures::List &replicaListSource, const SystemAddress &exclusionAddress, WorldId worldId) +{ + RakNet::BitStream bsOut; + unsigned int i,j; + + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + RM3World *world = worldsArray[worldId]; + + DataStructures::List replicaList; + + for (i=0; i < replicaListSource.Size(); i++) + { + if (replicaListSource[i]==currentlyDeallocatingReplica) + continue; + replicaList.Push(replicaListSource[i], __FILE__, __LINE__); + } + + if (replicaList.Size()==0) + return; + + for (i=0; i < replicaList.Size(); i++) + { + if (replicaList[i]->deletingSystemGUID==UNASSIGNED_RAKNET_GUID) + replicaList[i]->deletingSystemGUID=GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); + } + + for (j=0; j < world->connectionList.Size(); j++) + { + if (world->connectionList[j]->GetSystemAddress()==exclusionAddress) + continue; + + bsOut.Reset(); + bsOut.Write((MessageID)ID_REPLICA_MANAGER_CONSTRUCTION); + bsOut.Write(worldId); + uint16_t cnt=0; + bsOut.Write(cnt); // No construction + cnt=(uint16_t) replicaList.Size(); + BitSize_t cntOffset=bsOut.GetWriteOffset();; + bsOut.Write(cnt); // Overwritten at send call + cnt=0; + + for (i=0; i < replicaList.Size(); i++) + { + if (world->connectionList[j]->HasReplicaConstructed(replicaList[i])==false) + continue; + cnt++; + + NetworkID networkId; + networkId=replicaList[i]->GetNetworkID(); + bsOut.Write(networkId); + BitSize_t offsetStart, offsetEnd; + offsetStart=bsOut.GetWriteOffset(); + bsOut.Write(offsetStart); + bsOut.Write(replicaList[i]->deletingSystemGUID); + replicaList[i]->SerializeDestruction(&bsOut, world->connectionList[j]); + bsOut.AlignWriteToByteBoundary(); + offsetEnd=bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(offsetStart); + bsOut.Write(offsetEnd); + bsOut.SetWriteOffset(offsetEnd); + } + + if (cnt>0) + { + BitSize_t curOffset=bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(cntOffset); + bsOut.Write(cnt); + bsOut.SetWriteOffset(curOffset); + rakPeerInterface->Send(&bsOut,defaultSendParameters.priority,defaultSendParameters.reliability,defaultSendParameters.orderingChannel,world->connectionList[j]->GetSystemAddress(),false, defaultSendParameters.sendReceipt); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + +void ReplicaManager3::BroadcastDestruction(Replica3 *replica, const SystemAddress &exclusionAddress) +{ + DataStructures::List replicaList; + replicaList.Push(replica, _FILE_AND_LINE_ ); + BroadcastDestructionList(replicaList,exclusionAddress); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Connection_RM3::Connection_RM3(const SystemAddress &_systemAddress, RakNetGUID _guid) +: systemAddress(_systemAddress), guid(_guid) +{ + isValidated=false; + isFirstConstruction=true; + groupConstructionAndSerialize=false; + gotDownloadComplete=false; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Connection_RM3::~Connection_RM3() +{ + unsigned int i; + for (i=0; i < constructedReplicaList.Size(); i++) + RakNet::OP_DELETE(constructedReplicaList[i], _FILE_AND_LINE_); + for (i=0; i < queryToConstructReplicaList.Size(); i++) + RakNet::OP_DELETE(queryToConstructReplicaList[i], _FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::GetConstructedReplicas(DataStructures::List &objectsTheyDoHave) +{ + objectsTheyDoHave.Clear(true,_FILE_AND_LINE_); + for (unsigned int idx=0; idx < constructedReplicaList.Size(); idx++) + { + objectsTheyDoHave.Push(constructedReplicaList[idx]->replica, _FILE_AND_LINE_ ); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool Connection_RM3::HasReplicaConstructed(RakNet::Replica3 *replica) +{ + bool objectExists; + constructedReplicaList.GetIndexFromKey(replica, &objectExists); + return objectExists; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void Connection_RM3::SendSerializeHeader(RakNet::Replica3 *replica, RakNet::Time timestamp, RakNet::BitStream *bs, WorldId worldId) +{ + bs->Reset(); + + if (timestamp!=0) + { + bs->Write((MessageID)ID_TIMESTAMP); + bs->Write(timestamp); + } + bs->Write((MessageID)ID_REPLICA_MANAGER_SERIALIZE); + bs->Write(worldId); + bs->Write(replica->GetNetworkID()); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void Connection_RM3::ClearDownloadGroup(RakPeerInterface *rakPeerInterface) +{ + unsigned int i; + for (i=0; i < downloadGroup.Size(); i++) + rakPeerInterface->DeallocatePacket(downloadGroup[i]); + downloadGroup.Clear(__FILE__,__LINE__); +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +SendSerializeIfChangedResult Connection_RM3::SendSerialize(RakNet::Replica3 *replica, bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakNet::BitStream serializationData[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakNet::Time timestamp, PRO sendParameters[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], RakPeerInterface *rakPeer, unsigned char worldId, RakNet::Time curTime) +{ + bool channelHasData; + BitSize_t sum=0; + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + if (indicesToSend[z]) + sum+=serializationData[z].GetNumberOfBitsUsed(); + } + + RakNet::BitStream out; + BitSize_t bitsPerChannel[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + + if (sum==0) + { + memset(bitsPerChannel, 0, sizeof(bitsPerChannel)); + replica->OnSerializeTransmission(&out, this, bitsPerChannel, curTime); + return SSICR_DID_NOT_SEND_DATA; + } + + RakAssert(replica->GetNetworkID()!=UNASSIGNED_NETWORK_ID); + + BitSize_t bitsUsed; + + int channelIndex; + PRO lastPro=sendParameters[0]; + + for (channelIndex=0; channelIndex < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; channelIndex++) + { + if (channelIndex==0) + { + SendSerializeHeader(replica, timestamp, &out, worldId); + } + else if (lastPro!=sendParameters[channelIndex]) + { + // Write out remainder + for (int channelIndex2=channelIndex; channelIndex2 < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; channelIndex2++) + { + bitsPerChannel[channelIndex2]=0; + out.Write(false); + } + + // Send remainder + replica->OnSerializeTransmission(&out, this, bitsPerChannel, curTime); + rakPeer->Send(&out,lastPro.priority,lastPro.reliability,lastPro.orderingChannel,systemAddress,false,lastPro.sendReceipt); + + // If no data left to send, quit out + bool anyData=false; + for (int channelIndex2=channelIndex; channelIndex2 < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; channelIndex2++) + { + if (serializationData[channelIndex2].GetNumberOfBitsUsed()>0) + { + anyData=true; + break; + } + } + if (anyData==false) + return SSICR_SENT_DATA; + + // Restart stream + SendSerializeHeader(replica, timestamp, &out, worldId); + + for (int channelIndex2=0; channelIndex2 < channelIndex; channelIndex2++) + { + bitsPerChannel[channelIndex2]=0; + out.Write(false); + } + lastPro=sendParameters[channelIndex]; + } + + bitsUsed=serializationData[channelIndex].GetNumberOfBitsUsed(); + channelHasData = indicesToSend[channelIndex]==true && bitsUsed>0; + out.Write(channelHasData); + if (channelHasData) + { + bitsPerChannel[channelIndex] = bitsUsed; + out.WriteCompressed(bitsUsed); + out.AlignWriteToByteBoundary(); + out.Write(serializationData[channelIndex]); + // Crap, forgot this line, was a huge bug in that I'd only send to the first 3 systems + serializationData[channelIndex].ResetReadPointer(); + } + else + { + bitsPerChannel[channelIndex] = 0; + } + } + replica->OnSerializeTransmission(&out, this, bitsPerChannel, curTime); + rakPeer->Send(&out,lastPro.priority,lastPro.reliability,lastPro.orderingChannel,systemAddress,false,lastPro.sendReceipt); + return SSICR_SENT_DATA; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +SendSerializeIfChangedResult Connection_RM3::SendSerializeIfChanged(LastSerializationResult *lsr, SerializeParameters *sp, RakNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager, RakNet::Time curTime) +{ + RakNet::Replica3 *replica = lsr->replica; + + if (replica->GetNetworkID()==UNASSIGNED_NETWORK_ID) + return SSICR_DID_NOT_SEND_DATA; + + RM3QuerySerializationResult rm3qsr = replica->QuerySerialization(this); + if (rm3qsr==RM3QSR_NEVER_CALL_SERIALIZE) + { + // Never again for this connection and replica pair + OnNeverSerialize(lsr, replicaManager); + return SSICR_NEVER_SERIALIZE; + } + + if (rm3qsr==RM3QSR_DO_NOT_CALL_SERIALIZE) + return SSICR_DID_NOT_SEND_DATA; + + if (replica->forceSendUntilNextUpdate) + { + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + if (replica->lastSentSerialization.indicesToSend[z]) + sp->bitsWrittenSoFar+=replica->lastSentSerialization.bitStream[z].GetNumberOfBitsUsed(); + } + return SendSerialize(replica, replica->lastSentSerialization.indicesToSend, replica->lastSentSerialization.bitStream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); + } + + for (int i=0; i < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; i++) + { + sp->outputBitstream[i].Reset(); + if (lsr->lastSerializationResultBS) + sp->lastSentBitstream[i]=&lsr->lastSerializationResultBS->bitStream[i]; + else + sp->lastSentBitstream[i]=&replica->lastSentSerialization.bitStream[i]; + } + + RM3SerializationResult serializationResult = replica->Serialize(sp); + + if (serializationResult==RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION) + { + // Never again for this connection and replica pair + OnNeverSerialize(lsr, replicaManager); + return SSICR_NEVER_SERIALIZE; + } + + if (serializationResult==RM3SR_DO_NOT_SERIALIZE) + { + // Don't serialize this tick only + return SSICR_DID_NOT_SEND_DATA; + } + + // This is necessary in case the user in the Serialize() function for some reason read the bitstream they also wrote + // WIthout this code, the Write calls to another bitstream would not write the entire bitstream + BitSize_t sum=0; + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + sp->outputBitstream[z].ResetReadPointer(); + sum+=sp->outputBitstream[z].GetNumberOfBitsUsed(); + } + + if (sum==0) + { + // Don't serialize this tick only + return SSICR_DID_NOT_SEND_DATA; + } + + if (serializationResult==RM3SR_SERIALIZED_ALWAYS) + { + bool allIndices[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); + allIndices[z]=true; + + lsr->AllocBS(); + lsr->lastSerializationResultBS->bitStream[z].Reset(); + lsr->lastSerializationResultBS->bitStream[z].Write(&sp->outputBitstream[z]); + sp->outputBitstream[z].ResetReadPointer(); + } + return SendSerialize(replica, allIndices, sp->outputBitstream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); + } + + if (serializationResult==RM3SR_SERIALIZED_ALWAYS_IDENTICALLY) + { + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + replica->lastSentSerialization.indicesToSend[z]=sp->outputBitstream[z].GetNumberOfBitsUsed()>0; + sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); + replica->lastSentSerialization.bitStream[z].Reset(); + replica->lastSentSerialization.bitStream[z].Write(&sp->outputBitstream[z]); + sp->outputBitstream[z].ResetReadPointer(); + replica->forceSendUntilNextUpdate=true; + } + return SendSerialize(replica, replica->lastSentSerialization.indicesToSend, sp->outputBitstream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); + } + + bool indicesToSend[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + if (serializationResult==RM3SR_BROADCAST_IDENTICALLY || serializationResult==RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION) + { + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + if (sp->outputBitstream[z].GetNumberOfBitsUsed() > 0 && + (serializationResult==RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION || + ((sp->outputBitstream[z].GetNumberOfBitsUsed()!=replica->lastSentSerialization.bitStream[z].GetNumberOfBitsUsed() || + memcmp(sp->outputBitstream[z].GetData(), replica->lastSentSerialization.bitStream[z].GetData(), sp->outputBitstream[z].GetNumberOfBytesUsed())!=0)))) + { + indicesToSend[z]=true; + replica->lastSentSerialization.indicesToSend[z]=true; + sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); + replica->lastSentSerialization.bitStream[z].Reset(); + replica->lastSentSerialization.bitStream[z].Write(&sp->outputBitstream[z]); + sp->outputBitstream[z].ResetReadPointer(); + replica->forceSendUntilNextUpdate=true; + } + else + { + indicesToSend[z]=false; + replica->lastSentSerialization.indicesToSend[z]=false; + } + } + } + else + { + lsr->AllocBS(); + + // RM3SR_SERIALIZED_UNIQUELY + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + if (sp->outputBitstream[z].GetNumberOfBitsUsed() > 0 && + (sp->outputBitstream[z].GetNumberOfBitsUsed()!=lsr->lastSerializationResultBS->bitStream[z].GetNumberOfBitsUsed() || + memcmp(sp->outputBitstream[z].GetData(), lsr->lastSerializationResultBS->bitStream[z].GetData(), sp->outputBitstream[z].GetNumberOfBytesUsed())!=0) + ) + { + indicesToSend[z]=true; + sp->bitsWrittenSoFar+=sp->outputBitstream[z].GetNumberOfBitsUsed(); + lsr->lastSerializationResultBS->bitStream[z].Reset(); + lsr->lastSerializationResultBS->bitStream[z].Write(&sp->outputBitstream[z]); + sp->outputBitstream[z].ResetReadPointer(); + } + else + { + indicesToSend[z]=false; + } + } + } + + + if (serializationResult==RM3SR_BROADCAST_IDENTICALLY || serializationResult==RM3SR_BROADCAST_IDENTICALLY_FORCE_SERIALIZATION) + replica->forceSendUntilNextUpdate=true; + + // Send out the data + return SendSerialize(replica, indicesToSend, sp->outputBitstream, sp->messageTimestamp, sp->pro, rakPeer, worldId, curTime); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +void Connection_RM3::OnLocalReference(Replica3* replica3, ReplicaManager3 *replicaManager) +{ + ConstructionMode constructionMode = QueryConstructionMode(); + RakAssert(constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); + RakAssert(replica3); + (void) replicaManager; + (void) constructionMode; + +#ifdef _DEBUG + for (unsigned int i=0; i < queryToConstructReplicaList.Size(); i++) + { + if (queryToConstructReplicaList[i]->replica==replica3) + { + RakAssert("replica added twice to queryToConstructReplicaList" && 0); + } + } + + if (constructedReplicaList.HasData(replica3)==true) + { + RakAssert("replica added to queryToConstructReplicaList when already in constructedReplicaList" && 0); + } +#endif + + LastSerializationResult* lsr=RakNet::OP_NEW(_FILE_AND_LINE_); + lsr->replica=replica3; + queryToConstructReplicaList.Push(lsr,_FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnDereference(Replica3* replica3, ReplicaManager3 *replicaManager) +{ + ValidateLists(replicaManager); + + if (replica3->GetNetworkIDManager() == 0) + return; + + LastSerializationResult* lsr=0; + unsigned int idx; + + bool objectExists; + idx=constructedReplicaList.GetIndexFromKey(replica3, &objectExists); + if (objectExists) + { + lsr=constructedReplicaList[idx]; + constructedReplicaList.RemoveAtIndex(idx); + } + + for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) + { + if (queryToConstructReplicaList[idx]->replica==replica3) + { + lsr=queryToConstructReplicaList[idx]; + queryToConstructReplicaList.RemoveAtIndex(idx); + break; + } + } + + for (idx=0; idx < queryToSerializeReplicaList.Size(); idx++) + { + if (queryToSerializeReplicaList[idx]->replica==replica3) + { + lsr=queryToSerializeReplicaList[idx]; + queryToSerializeReplicaList.RemoveAtIndex(idx); + break; + } + } + + for (idx=0; idx < queryToDestructReplicaList.Size(); idx++) + { + if (queryToDestructReplicaList[idx]->replica==replica3) + { + lsr=queryToDestructReplicaList[idx]; + queryToDestructReplicaList.RemoveAtIndex(idx); + break; + } + } + + ValidateLists(replicaManager); + + if (lsr) + RakNet::OP_DELETE(lsr,_FILE_AND_LINE_); + + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnDownloadFromThisSystem(Replica3* replica3, ReplicaManager3 *replicaManager) +{ + RakAssert(replica3); + + ValidateLists(replicaManager); + LastSerializationResult* lsr=RakNet::OP_NEW(_FILE_AND_LINE_); + lsr->replica=replica3; + + ConstructionMode constructionMode = QueryConstructionMode(); + if (constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) + { + unsigned int j; + for (j=0; j < queryToConstructReplicaList.Size(); j++) + { + if (queryToConstructReplicaList[j]->replica==replica3 ) + { + queryToConstructReplicaList.RemoveAtIndex(j); + break; + } + } + + queryToDestructReplicaList.Push(lsr,_FILE_AND_LINE_); + } + + if (constructedReplicaList.Insert(lsr->replica, lsr, true, _FILE_AND_LINE_) != (unsigned) -1) + { + //assert(queryToSerializeReplicaList.GetIndexOf(replica3)==(unsigned int)-1); + queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); + } + + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnDownloadFromOtherSystem(Replica3* replica3, ReplicaManager3 *replicaManager) +{ + ConstructionMode constructionMode = QueryConstructionMode(); + if (constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) + { + unsigned int j; + for (j=0; j < queryToConstructReplicaList.Size(); j++) + { + if (queryToConstructReplicaList[j]->replica==replica3 ) + { + return; + } + } + + OnLocalReference(replica3, replicaManager); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnNeverConstruct(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager) +{ + ConstructionMode constructionMode = QueryConstructionMode(); + RakAssert(constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); + (void) constructionMode; + + ValidateLists(replicaManager); + LastSerializationResult* lsr = queryToConstructReplicaList[queryToConstructIdx]; + queryToConstructReplicaList.RemoveAtIndex(queryToConstructIdx); + RakNet::OP_DELETE(lsr,_FILE_AND_LINE_); + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnConstructToThisConnection(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager) +{ + ConstructionMode constructionMode = QueryConstructionMode(); + RakAssert(constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); + (void) constructionMode; + + ValidateLists(replicaManager); + LastSerializationResult* lsr = queryToConstructReplicaList[queryToConstructIdx]; + queryToConstructReplicaList.RemoveAtIndex(queryToConstructIdx); + //assert(constructedReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); + constructedReplicaList.Insert(lsr->replica,lsr,true,_FILE_AND_LINE_); + //assert(queryToDestructReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); + queryToDestructReplicaList.Push(lsr,_FILE_AND_LINE_); + //assert(queryToSerializeReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); + queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnConstructToThisConnection(Replica3 *replica, ReplicaManager3 *replicaManager) +{ + RakAssert(replica); + RakAssert(QueryConstructionMode()==QUERY_CONNECTION_FOR_REPLICA_LIST); + (void) replicaManager; + + LastSerializationResult* lsr=RakNet::OP_NEW(_FILE_AND_LINE_); + lsr->replica=replica; + constructedReplicaList.Insert(replica,lsr,true,_FILE_AND_LINE_); + queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnNeverSerialize(LastSerializationResult *lsr, ReplicaManager3 *replicaManager) +{ + ValidateLists(replicaManager); + + unsigned int j; + for (j=0; j < queryToSerializeReplicaList.Size(); j++) + { + if (queryToSerializeReplicaList[j]==lsr ) + { + queryToSerializeReplicaList.RemoveAtIndex(j); + break; + } + } + + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnReplicaAlreadyExists(unsigned int queryToConstructIdx, ReplicaManager3 *replicaManager) +{ + ConstructionMode constructionMode = QueryConstructionMode(); + RakAssert(constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); + (void) constructionMode; + + ValidateLists(replicaManager); + LastSerializationResult* lsr = queryToConstructReplicaList[queryToConstructIdx]; + queryToConstructReplicaList.RemoveAtIndex(queryToConstructIdx); + //assert(constructedReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); + constructedReplicaList.Insert(lsr->replica,lsr,true,_FILE_AND_LINE_); + //assert(queryToDestructReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); + queryToDestructReplicaList.Push(lsr,_FILE_AND_LINE_); + //assert(queryToSerializeReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); + queryToSerializeReplicaList.Push(lsr,_FILE_AND_LINE_); + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnDownloadExisting(Replica3* replica3, ReplicaManager3 *replicaManager) +{ + ValidateLists(replicaManager); + + ConstructionMode constructionMode = QueryConstructionMode(); + if (constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION) + { + unsigned int idx; + for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) + { + if (queryToConstructReplicaList[idx]->replica==replica3) + { + OnConstructToThisConnection(idx, replicaManager); + return; + } + } + } + else + { + OnConstructToThisConnection(replica3, replicaManager); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnSendDestructionFromQuery(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager) +{ + ConstructionMode constructionMode = QueryConstructionMode(); + RakAssert(constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION || constructionMode==QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION); + (void) constructionMode; + + ValidateLists(replicaManager); + LastSerializationResult* lsr = queryToDestructReplicaList[queryToDestructIdx]; + queryToDestructReplicaList.RemoveAtIndex(queryToDestructIdx); + unsigned int j; + for (j=0; j < queryToSerializeReplicaList.Size(); j++) + { + if (queryToSerializeReplicaList[j]->replica==lsr->replica ) + { + queryToSerializeReplicaList.RemoveAtIndex(j); + break; + } + } + for (j=0; j < constructedReplicaList.Size(); j++) + { + if (constructedReplicaList[j]->replica==lsr->replica ) + { + constructedReplicaList.RemoveAtIndex(j); + break; + } + } + //assert(queryToConstructReplicaList.GetIndexOf(lsr->replica)==(unsigned int)-1); + queryToConstructReplicaList.Push(lsr,_FILE_AND_LINE_); + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::OnDoNotQueryDestruction(unsigned int queryToDestructIdx, ReplicaManager3 *replicaManager) +{ + ValidateLists(replicaManager); + queryToDestructReplicaList.RemoveAtIndex(queryToDestructIdx); + ValidateLists(replicaManager); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::ValidateLists(ReplicaManager3 *replicaManager) const +{ + (void) replicaManager; + /* +#ifdef _DEBUG + // Each object should exist only once in either constructedReplicaList or queryToConstructReplicaList + // replicaPointer from LastSerializationResult should be same among all lists + unsigned int idx, idx2; + for (idx=0; idx < constructedReplicaList.Size(); idx++) + { + idx2=queryToConstructReplicaList.GetIndexOf(constructedReplicaList[idx]->replica); + if (idx2!=(unsigned int)-1) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } + + for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) + { + idx2=constructedReplicaList.GetIndexOf(queryToConstructReplicaList[idx]->replica); + if (idx2!=(unsigned int)-1) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } + + LastSerializationResult *lsr, *lsr2; + for (idx=0; idx < constructedReplicaList.Size(); idx++) + { + lsr=constructedReplicaList[idx]; + + idx2=queryToSerializeReplicaList.GetIndexOf(lsr->replica); + if (idx2!=(unsigned int)-1) + { + lsr2=queryToSerializeReplicaList[idx2]; + if (lsr2!=lsr) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } + + idx2=queryToDestructReplicaList.GetIndexOf(lsr->replica); + if (idx2!=(unsigned int)-1) + { + lsr2=queryToDestructReplicaList[idx2]; + if (lsr2!=lsr) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } + } + for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) + { + lsr=queryToConstructReplicaList[idx]; + + idx2=queryToSerializeReplicaList.GetIndexOf(lsr->replica); + if (idx2!=(unsigned int)-1) + { + lsr2=queryToSerializeReplicaList[idx2]; + if (lsr2!=lsr) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } + + idx2=queryToDestructReplicaList.GetIndexOf(lsr->replica); + if (idx2!=(unsigned int)-1) + { + lsr2=queryToDestructReplicaList[idx2]; + if (lsr2!=lsr) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } + } + + // Verify pointer integrity + for (idx=0; idx < constructedReplicaList.Size(); idx++) + { + if (constructedReplicaList[idx]->replica->replicaManager!=replicaManager) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } + + // Verify pointer integrity + for (idx=0; idx < queryToConstructReplicaList.Size(); idx++) + { + if (queryToConstructReplicaList[idx]->replica->replicaManager!=replicaManager) + { + int a=5; + assert(a==0); + int *b=0; + *b=5; + } + } +#endif + */ +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::SendConstruction(DataStructures::List &newObjects, DataStructures::List &deletedObjects, PRO sendParameters, RakNet::RakPeerInterface *rakPeer, unsigned char worldId, ReplicaManager3 *replicaManager3) +{ + if (newObjects.Size()==0 && deletedObjects.Size()==0) + return; + + // All construction and destruction takes place in the same network message + // Otherwise, if objects rely on each other being created the same tick to be valid, this won't always be true + // DataStructures::List serializedObjects; + BitSize_t offsetStart, offsetStart2, offsetEnd; + unsigned int newListIndex, oldListIndex; + RakNet::BitStream bsOut; + NetworkID networkId; + if (isFirstConstruction) + { + bsOut.Write((MessageID)ID_REPLICA_MANAGER_DOWNLOAD_STARTED); + bsOut.Write(worldId); + SerializeOnDownloadStarted(&bsOut); + rakPeer->Send(&bsOut,sendParameters.priority,RELIABLE_ORDERED,sendParameters.orderingChannel,systemAddress,false,sendParameters.sendReceipt); + } + + // LastSerializationResult* lsr; + bsOut.Reset(); + bsOut.Write((MessageID)ID_REPLICA_MANAGER_CONSTRUCTION); + bsOut.Write(worldId); + uint16_t objectSize = (uint16_t) newObjects.Size(); + bsOut.Write(objectSize); + + // Construction + for (newListIndex=0; newListIndex < newObjects.Size(); newListIndex++) + { + offsetStart=bsOut.GetWriteOffset(); + bsOut.Write(offsetStart); // overwritten to point to the end of the stream + networkId=newObjects[newListIndex]->GetNetworkID(); + bsOut.Write(networkId); + + RM3ConstructionState cs = newObjects[newListIndex]->QueryConstruction(this, replicaManager3); + bool actuallyCreateObject = cs==RM3CS_SEND_CONSTRUCTION; + bsOut.Write(actuallyCreateObject); + bsOut.AlignWriteToByteBoundary(); + + if (actuallyCreateObject) + { + // Actually create the object + bsOut.Write(newObjects[newListIndex]->creatingSystemGUID); + offsetStart2=bsOut.GetWriteOffset(); + bsOut.Write(offsetStart2); // overwritten to point to after the call to WriteAllocationID + bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy + newObjects[newListIndex]->WriteAllocationID(this, &bsOut); + bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy + offsetEnd=bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(offsetStart2); + bsOut.Write(offsetEnd); + bsOut.SetWriteOffset(offsetEnd); + newObjects[newListIndex]->SerializeConstruction(&bsOut, this); + } + else + { + newObjects[newListIndex]->SerializeConstructionExisting(&bsOut, this); + } + + bsOut.AlignWriteToByteBoundary(); + offsetEnd=bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(offsetStart); + bsOut.Write(offsetEnd); + bsOut.SetWriteOffset(offsetEnd); + } + + RakNet::BitStream bsOut2; + for (newListIndex=0; newListIndex < newObjects.Size(); newListIndex++) + { + bsOut2.Reset(); + RM3ConstructionState cs = newObjects[newListIndex]->QueryConstruction(this, replicaManager3); + if (cs==RM3CS_SEND_CONSTRUCTION) + { + newObjects[newListIndex]->PostSerializeConstruction(&bsOut2, this); + } + else + { + RakAssert(cs==RM3CS_ALREADY_EXISTS_REMOTELY); + newObjects[newListIndex]->PostSerializeConstructionExisting(&bsOut2, this); + } + if (bsOut2.GetNumberOfBitsUsed()>0) + { + bsOut.Write(true); + bsOut.AlignWriteToByteBoundary(); + offsetStart=bsOut.GetWriteOffset(); + bsOut.Write(offsetStart); // overwritten to point to the end of the stream + networkId=newObjects[newListIndex]->GetNetworkID(); + bsOut.Write(networkId); + bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy + bsOut.Write(&bsOut2); + bsOut.AlignWriteToByteBoundary(); // Give the user an aligned bitStream in case they use memcpy + offsetEnd=bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(offsetStart); + bsOut.Write(offsetEnd); + bsOut.SetWriteOffset(offsetEnd); + } + else + bsOut.Write(false); + } + bsOut.AlignWriteToByteBoundary(); + + // Destruction + objectSize = (uint16_t) deletedObjects.Size(); + bsOut.Write(objectSize); + for (oldListIndex=0; oldListIndex < deletedObjects.Size(); oldListIndex++) + { + networkId=deletedObjects[oldListIndex]->GetNetworkID(); + bsOut.Write(networkId); + offsetStart=bsOut.GetWriteOffset(); + bsOut.Write(offsetStart); + deletedObjects[oldListIndex]->deletingSystemGUID=rakPeer->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); + bsOut.Write(deletedObjects[oldListIndex]->deletingSystemGUID); + deletedObjects[oldListIndex]->SerializeDestruction(&bsOut, this); + bsOut.AlignWriteToByteBoundary(); + offsetEnd=bsOut.GetWriteOffset(); + bsOut.SetWriteOffset(offsetStart); + bsOut.Write(offsetEnd); + bsOut.SetWriteOffset(offsetEnd); + } + rakPeer->Send(&bsOut,sendParameters.priority,RELIABLE_ORDERED,sendParameters.orderingChannel,systemAddress,false,sendParameters.sendReceipt); + + // TODO - shouldn't this be part of construction? + + // Initial Download serialize to a new system + // Immediately send serialize after construction if the replica object already has saved data + // If the object was serialized identically, and does not change later on, then the new connection never gets the data + SerializeParameters sp; + sp.whenLastSerialized=0; + RakNet::BitStream emptyBs; + for (int index=0; index < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; index++) + { + sp.lastSentBitstream[index]=&emptyBs; + sp.pro[index]=sendParameters; + sp.pro[index].reliability=RELIABLE_ORDERED; + } + + sp.bitsWrittenSoFar=0; +// RakNet::Time t = RakNet::GetTimeMS(); + for (newListIndex=0; newListIndex < newObjects.Size(); newListIndex++) + { + sp.destinationConnection=this; + sp.messageTimestamp=0; + RakNet::Replica3 *replica = newObjects[newListIndex]; + // 8/22/09 Forgot ResetWritePointer + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + sp.outputBitstream[z].ResetWritePointer(); + } + + RM3SerializationResult res = replica->Serialize(&sp); + if (res!=RM3SR_NEVER_SERIALIZE_FOR_THIS_CONNECTION && + res!=RM3SR_DO_NOT_SERIALIZE && + res!=RM3SR_SERIALIZED_UNIQUELY) + { + bool allIndices[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS]; + for (int z=0; z < RM3_NUM_OUTPUT_BITSTREAM_CHANNELS; z++) + { + sp.bitsWrittenSoFar+=sp.outputBitstream[z].GetNumberOfBitsUsed(); + allIndices[z]=true; + } + SendSerialize(replica, allIndices, sp.outputBitstream, sp.messageTimestamp, sp.pro, rakPeer, worldId, GetTime()); +/// newObjects[newListIndex]->whenLastSerialized=t; + + } + // else wait for construction request accepted before serializing + } + + if (isFirstConstruction) + { + bsOut.Reset(); + bsOut.Write((MessageID)ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE); + bsOut.Write(worldId); + SerializeOnDownloadComplete(&bsOut); + rakPeer->Send(&bsOut,sendParameters.priority,RELIABLE_ORDERED,sendParameters.orderingChannel,systemAddress,false,sendParameters.sendReceipt); + } + + isFirstConstruction=false; + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Connection_RM3::SendValidation(RakNet::RakPeerInterface *rakPeer, WorldId worldId) +{ + // Hijack to mean sendValidation + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_REPLICA_MANAGER_SCOPE_CHANGE); + bsOut.Write(worldId); + rakPeer->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,systemAddress,false); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Replica3::Replica3() +{ + creatingSystemGUID=UNASSIGNED_RAKNET_GUID; + deletingSystemGUID=UNASSIGNED_RAKNET_GUID; + replicaManager=0; + forceSendUntilNextUpdate=false; + lsr=0; + referenceIndex = (uint32_t)-1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +Replica3::~Replica3() +{ + if (replicaManager) + { + replicaManager->Dereference(this); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void Replica3::BroadcastDestruction(void) +{ + replicaManager->BroadcastDestruction(this,UNASSIGNED_SYSTEM_ADDRESS); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RakNetGUID Replica3::GetCreatingSystemGUID(void) const +{ + return creatingSystemGUID; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3ConstructionState Replica3::QueryConstruction_ClientConstruction(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer) +{ + (void) destinationConnection; + if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) + return RM3CS_SEND_CONSTRUCTION; + // Send back to the owner client too, because they couldn't assign the network ID + if (isThisTheServer) + return RM3CS_SEND_CONSTRUCTION; + return RM3CS_NEVER_CONSTRUCT; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool Replica3::QueryRemoteConstruction_ClientConstruction(RakNet::Connection_RM3 *sourceConnection, bool isThisTheServer) +{ + (void) sourceConnection; + (void) isThisTheServer; + + // OK to create + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3ConstructionState Replica3::QueryConstruction_ServerConstruction(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer) +{ + (void) destinationConnection; + + if (isThisTheServer) + return RM3CS_SEND_CONSTRUCTION; + return RM3CS_NEVER_CONSTRUCT; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool Replica3::QueryRemoteConstruction_ServerConstruction(RakNet::Connection_RM3 *sourceConnection, bool isThisTheServer) +{ + (void) sourceConnection; + if (isThisTheServer) + return false; + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3ConstructionState Replica3::QueryConstruction_PeerToPeer(RakNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode) +{ + (void) destinationConnection; + + if (p2pMode==R3P2PM_SINGLE_OWNER) + { + // We send to all, others do nothing + if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) + return RM3CS_SEND_CONSTRUCTION; + + // RM3CS_NEVER_CONSTRUCT will not send the object, and will not Serialize() it + return RM3CS_NEVER_CONSTRUCT; + } + else if (p2pMode==R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE) + { + return RM3CS_SEND_CONSTRUCTION; + } + else if (p2pMode==R3P2PM_STATIC_OBJECT_CURRENTLY_AUTHORITATIVE) + { + return RM3CS_ALREADY_EXISTS_REMOTELY; + } + else if (p2pMode==R3P2PM_STATIC_OBJECT_NOT_CURRENTLY_AUTHORITATIVE) + { + return RM3CS_ALREADY_EXISTS_REMOTELY_DO_NOT_CONSTRUCT; + } + else + { + RakAssert(p2pMode==R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE); + + // RM3CS_ALREADY_EXISTS_REMOTELY will not send the object, but WILL call QuerySerialization() and Serialize() on it. + return RM3CS_ALREADY_EXISTS_REMOTELY; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool Replica3::QueryRemoteConstruction_PeerToPeer(RakNet::Connection_RM3 *sourceConnection) +{ + (void) sourceConnection; + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3QuerySerializationResult Replica3::QuerySerialization_ClientSerializable(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer) +{ + // Owner client sends to all + if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) + return RM3QSR_CALL_SERIALIZE; + // Server sends to all but owner client + if (isThisTheServer && destinationConnection->GetRakNetGUID()!=creatingSystemGUID) + return RM3QSR_CALL_SERIALIZE; + // Remote clients do not send + return RM3QSR_NEVER_CALL_SERIALIZE; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3QuerySerializationResult Replica3::QuerySerialization_ServerSerializable(RakNet::Connection_RM3 *destinationConnection, bool isThisTheServer) +{ + (void) destinationConnection; + // Server sends to all + if (isThisTheServer) + return RM3QSR_CALL_SERIALIZE; + + // Clients do not send + return RM3QSR_NEVER_CALL_SERIALIZE; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3QuerySerializationResult Replica3::QuerySerialization_PeerToPeer(RakNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode) +{ + (void) destinationConnection; + + if (p2pMode==R3P2PM_SINGLE_OWNER) + { + // Owner peer sends to all + if (creatingSystemGUID==replicaManager->GetRakPeerInterface()->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS)) + return RM3QSR_CALL_SERIALIZE; + + // Remote peers do not send + return RM3QSR_NEVER_CALL_SERIALIZE; + } + else if (p2pMode==R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE) + { + return RM3QSR_CALL_SERIALIZE; + } + else if (p2pMode==R3P2PM_STATIC_OBJECT_CURRENTLY_AUTHORITATIVE) + { + return RM3QSR_CALL_SERIALIZE; + } + else if (p2pMode==R3P2PM_STATIC_OBJECT_NOT_CURRENTLY_AUTHORITATIVE) + { + return RM3QSR_DO_NOT_CALL_SERIALIZE; + } + else + { + RakAssert(p2pMode==R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE); + return RM3QSR_DO_NOT_CALL_SERIALIZE; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3ActionOnPopConnection Replica3::QueryActionOnPopConnection_Client(RakNet::Connection_RM3 *droppedConnection) const +{ + (void) droppedConnection; + return RM3AOPC_DELETE_REPLICA; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3ActionOnPopConnection Replica3::QueryActionOnPopConnection_Server(RakNet::Connection_RM3 *droppedConnection) const +{ + (void) droppedConnection; + return RM3AOPC_DELETE_REPLICA_AND_BROADCAST_DESTRUCTION; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RM3ActionOnPopConnection Replica3::QueryActionOnPopConnection_PeerToPeer(RakNet::Connection_RM3 *droppedConnection) const +{ + (void) droppedConnection; + return RM3AOPC_DELETE_REPLICA; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/Router2.cpp b/src/raknet/Router2.cpp new file mode 100644 index 0000000..065b19d --- /dev/null +++ b/src/raknet/Router2.cpp @@ -0,0 +1,1368 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_Router2==1 && _RAKNET_SUPPORT_UDPForwarder==1 + +#include "include/raknet/Router2.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/RakNetTime.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/DS_OrderedList.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/FormatString.hpp" +#include "include/raknet/SocketDefines.hpp" + +using namespace RakNet; + +#ifndef INVALID_SOCKET +#define INVALID_SOCKET -1 +#endif + +/* +Algorithm: + +1. Sender calls ConnectInternal(). A ConnnectRequest structure is allocated and stored in the connectionRequests list, containing a list of every system we are connected to. ID_ROUTER_2_QUERY_FORWARDING is sent to all connected systems. + +2. Upon the router getting ID_ROUTER_2_QUERY_FORWARDING, ID_ROUTER_2_REPLY_FORWARDING is sent to the sender indicating if that router is connected to the endpoint, along with the ping from the router to the endpoint. + +3. Upon the sender getting ID_ROUTER_2_REPLY_FORWARDING, the connection request structure is looked up in Router2::UpdateForwarding. The ping is stored in that structure. Once all systems have replied, the system continues to the next state. If every system in step 1 has been exhausted, and routing has occured at least once, then ID_CONNECTION_LOST is returned. If every system in step 1 has been exhausted and routing has never occured, then ID_ROUTER_2_FORWARDING_NO_PATH is returned. Otherwise, the router with the lowest ping is chosen, and RequestForwarding() is called with that system, which sends ID_ROUTER_2_REQUEST_FORWARDING to the router. + +4. When the router gets ID_ROUTER_2_REQUEST_FORWARDING, a MiniPunchRequest structure is allocated and stored in the miniPunchesInProgress list. The function SendOOBMessages() sends ID_ROUTER_2_REPLY_TO_SENDER_PORT from the routing sockets to both the sender and endpoint. It also sends ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT through the regular RakNet connection. + +5. The sender and endpoint should get ID_ROUTER_2_REPLY_TO_SENDER_PORT and/or ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT depending on what type of router they have. If ID_ROUTER_2_REPLY_TO_SENDER_PORT arrives, then this will reply back to the routing socket directly. If ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT arrives, then the reply port is modified to be the port specified by the router system. In both cases, ID_ROUTER_2_MINI_PUNCH_REPLY is sent. As the router has already setup the forwarding, ID_ROUTER_2_MINI_PUNCH_REPLY will actually arrive to the endpoint from the sender, and from the sender to the endpoint. + +6. When ID_ROUTER_2_MINI_PUNCH_REPLY arrives, ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE will be sent to the router. This is to tell the router that the forwarding has succeeded. + +7. When ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE arrives on the router, the router will find the two systems in the miniPunchesInProgress list, which was added in step 4 (See OnMiniPunchReplyBounce()). gotReplyFromSource or gotReplyFromEndpoint will be set to true, depending on the sender. When both gotReplyFromSource and gotReplyFromEndpoint have replied, then ID_ROUTER_2_REROUTE is sent to the endpoint, and ID_ROUTER_2_FORWARDING_ESTABLISHED is sent to the sender. + +8. When the endpoint gets ID_ROUTER_2_REROUTE, the system address is updated for the guid of the sender using RakPeer::ChangeSystemAddress(). This happens in OnRerouted(). + +9. When the sender gets ID_ROUTER_2_FORWARDING_ESTABLISHED, then in OnForwardingSuccess() the endpoint is removed from the connectionRequest list and moved to the forwardedConnectionList. + +10. In OnClosedConnection(), for the sender, if the closed connection is the endpoint, then the endpoint is removed from the forwardedConnectionList (this is a graceful disconnect). If the connection was instead lost to the router, then ConnectInternal() gets called, which goes back to step 1. If instead this was a connection requset in progress, then UpdateForwarding() gets called, which goes back to step 3. + +11. When the user connects the endpoint and sender, then the sender will get ID_CONNECTION_REQUEST_ACCEPTED. The sender will look up the endpoint in the forwardedConnectionList, and send ID_ROUTER_2_INCREASE_TIMEOUT to the endpoint. This message will call SetTimeoutTime() on the endpoint, so that if the router disconnects, enough time is available for the reroute to complete. +*/ + +#define MIN_MINIPUNCH_TIMEOUT 5000 + + + + +void Router2DebugInterface::ShowFailure(const char *message) +{ + printf("%s", message); +} +void Router2DebugInterface::ShowDiagnostic(const char *message) +{ + printf("%s", message); +} + +enum Router2MessageIdentifiers +{ + ID_ROUTER_2_QUERY_FORWARDING, + ID_ROUTER_2_REPLY_FORWARDING, + ID_ROUTER_2_REQUEST_FORWARDING, + ID_ROUTER_2_INCREASE_TIMEOUT, +}; +Router2::ConnnectRequest::ConnnectRequest() +{ + +} +Router2::ConnnectRequest::~ConnnectRequest() +{ + +} + +STATIC_FACTORY_DEFINITIONS(Router2,Router2); + +Router2::Router2() +{ + udpForwarder=0; + maximumForwardingRequests=0; + debugInterface=0; + socketFamily=AF_INET; +} +Router2::~Router2() +{ + ClearAll(); + + if (udpForwarder) + { + udpForwarder->Shutdown(); + RakNet::OP_DELETE(udpForwarder,_FILE_AND_LINE_); + } +} +void Router2::ClearMinipunches(void) +{ + miniPunchesInProgressMutex.Lock(); + miniPunchesInProgress.Clear(false,_FILE_AND_LINE_); + miniPunchesInProgressMutex.Unlock(); +} +void Router2::ClearConnectionRequests(void) +{ + connectionRequestsMutex.Lock(); + for (unsigned int i=0; i < connectionRequests.Size(); i++) + { + RakNet::OP_DELETE(connectionRequests[i],_FILE_AND_LINE_); + } + connectionRequests.Clear(false,_FILE_AND_LINE_); + connectionRequestsMutex.Unlock(); +} +bool Router2::ConnectInternal(RakNetGUID endpointGuid, bool returnConnectionLostOnFailure) +{ + int largestPing = GetLargestPingAmongConnectedSystems(); + if (largestPing<0) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2: ConnectInternal(%I64d) failed at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); + + // Not connected to anyone + return false; + } + + // ALready in progress? + connectionRequestsMutex.Lock(); + if (GetConnectionRequestIndex(endpointGuid)!=(unsigned int)-1) + { + connectionRequestsMutex.Unlock(); + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2: ConnectInternal(%I64d) failed at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); + + return false; + } + connectionRequestsMutex.Unlock(); + + // StoreRequest(endpointGuid, Largest(ping*2), systemsSentTo). Set state REQUEST_STATE_QUERY_FORWARDING + Router2::ConnnectRequest *cr = RakNet::OP_NEW(_FILE_AND_LINE_); + DataStructures::List addresses; + DataStructures::List guids; + rakPeerInterface->GetSystemList(addresses, guids); + if (guids.Size()==0) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i\n", _FILE_AND_LINE_)); + + return false; + } + cr->requestState=R2RS_REQUEST_STATE_QUERY_FORWARDING; + cr->pingTimeout=RakNet::GetTimeMS()+largestPing*2+1000; + cr->endpointGuid=endpointGuid; + cr->returnConnectionLostOnFailure=returnConnectionLostOnFailure; + for (unsigned int i=0; i < guids.Size(); i++) + { + ConnectionRequestSystem crs; + if (guids[i]!=endpointGuid) + { + crs.guid=guids[i]; + crs.pingToEndpoint=-1; + cr->connectionRequestSystemsMutex.Lock(); + cr->connectionRequestSystems.Push(crs,_FILE_AND_LINE_); + cr->connectionRequestSystemsMutex.Unlock(); + + // Broadcast(ID_ROUTER_2_QUERY_FORWARDING, endpointGuid); + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); + bsOut.Write((unsigned char) ID_ROUTER_2_QUERY_FORWARDING); + bsOut.Write(endpointGuid); + uint32_t pack_id = rakPeerInterface->Send(&bsOut,MEDIUM_PRIORITY,RELIABLE_ORDERED,0,crs.guid,false); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Router2::ConnectInternal: at %s:%i, pack_id = %d", __FILE__, __LINE__,pack_id)); + } + + } + else + { + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Router2::ConnectInternal: at %s:%i [else ..].: %I64d==%I64d", __FILE__, __LINE__, + guids[i].g,endpointGuid.g)); + } + } + } + connectionRequestsMutex.Lock(); + connectionRequests.Push(cr,_FILE_AND_LINE_); + connectionRequestsMutex.Unlock(); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Broadcasting ID_ROUTER_2_QUERY_FORWARDING to %I64d at %s:%i\n", endpointGuid.g , __FILE__, __LINE__)); + } + + return true; +} +void Router2::SetSocketFamily(unsigned short _socketFamily) +{ + socketFamily=_socketFamily; +} +void Router2::EstablishRouting(RakNetGUID endpointGuid) +{ + ConnectionState cs = rakPeerInterface->GetConnectionState(endpointGuid); + if (cs!=IS_DISCONNECTED && cs!=IS_NOT_CONNECTED) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i " + "(already connected to the %I64d)\n", __FILE__, __LINE__, endpointGuid.g )); + return; + } + + ConnectInternal(endpointGuid,false); +} +void Router2::SetMaximumForwardingRequests(int max) +{ + if (max>0 && maximumForwardingRequests<=0) + { + udpForwarder = RakNet::OP_NEW(_FILE_AND_LINE_); + udpForwarder->Startup(); + } + else if (max<=0 && maximumForwardingRequests>0) + { + udpForwarder->Shutdown(); + RakNet::OP_DELETE(udpForwarder,_FILE_AND_LINE_); + udpForwarder=0; + } + + maximumForwardingRequests=max; +} +PluginReceiveResult Router2::OnReceive(Packet *packet) +{ + SystemAddress sa; + RakNet::BitStream bs(packet->data,packet->length,false); + if (packet->data[0]==ID_ROUTER_2_INTERNAL) + { + switch (packet->data[1]) + { + case ID_ROUTER_2_QUERY_FORWARDING: + { + OnQueryForwarding(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case ID_ROUTER_2_REPLY_FORWARDING: + { + OnQueryForwardingReply(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case ID_ROUTER_2_REQUEST_FORWARDING: + { + + if (debugInterface) + { + char buff[512]; + char buff2[32]; + packet->systemAddress.ToString(true,buff2); + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REQUEST_FORWARDING on ip %s from %I64d, ", + buff2,packet->guid.g)); + } + + OnRequestForwarding(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case ID_ROUTER_2_INCREASE_TIMEOUT: + { + /// The routed system wants more time to stay alive on no communication, in case the router drops or crashes + rakPeerInterface->SetTimeoutTime(rakPeerInterface->GetTimeoutTime(packet->systemAddress)+10000, packet->systemAddress); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + } + else if (packet->data[0]==ID_OUT_OF_BAND_INTERNAL && packet->length>=2) + { + switch (packet->data[1]) + { + case ID_ROUTER_2_REPLY_TO_SENDER_PORT: + { + RakNet::BitStream bsOut; + bsOut.Write(packet->guid); + SendOOBFromRakNetPort(ID_ROUTER_2_MINI_PUNCH_REPLY, &bsOut, packet->systemAddress); + + if (debugInterface) + { + char buff[512]; + char buff2[32]; + sa.ToString(false,buff2); + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_TO_SENDER_PORT %i on address %s, replying with ID_ROUTER_2_MINI_PUNCH_REPLY at %s:%i\n", sa.GetPort(), buff2, _FILE_AND_LINE_)); + +// packet->systemAddress.ToString(true,buff2); +// debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_TO_SENDER_PORT on address %s (%I64d), " +// "replying with ID_ROUTER_2_MINI_PUNCH_REPLY at %s:%i\n", buff2,packet->guid.g, __FILE__, __LINE__)); + } + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT: + { + RakNet::BitStream bsOut; + bsOut.Write(packet->guid); + bs.IgnoreBytes(2); + sa=packet->systemAddress; + unsigned short port; + bs.Read(port); + sa.SetPortHostOrder(port); + RakAssert(sa.GetPort()!=0); + SendOOBFromRakNetPort(ID_ROUTER_2_MINI_PUNCH_REPLY, &bsOut, sa); + + if (debugInterface) + { + char buff[512]; + char buff2[32]; + sa.ToString(false,buff2); + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT %i on address %s, " + "replying with ID_ROUTER_2_MINI_PUNCH_REPLY at %s:%i\n", sa.GetPort(), buff2, __FILE__, __LINE__)); + } + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case ID_ROUTER_2_MINI_PUNCH_REPLY: + OnMiniPunchReply(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE: + OnMiniPunchReplyBounce(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + else if (packet->data[0]==ID_ROUTER_2_FORWARDING_ESTABLISHED) + { +// printf("Got ID_ROUTER_2_FORWARDING_ESTABLISHED\n"); + if (OnForwardingSuccess(packet)==false) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + else if (packet->data[0]==ID_ROUTER_2_REROUTED) + { + OnRerouted(packet); + } + else if (packet->data[0]==ID_CONNECTION_REQUEST_ACCEPTED) + { + unsigned int forwardingIndex; + forwardedConnectionListMutex.Lock(); + for (forwardingIndex=0; forwardingIndex < forwardedConnectionList.Size(); forwardingIndex++) + { + if (forwardedConnectionList[forwardingIndex].endpointGuid==packet->guid && forwardedConnectionList[forwardingIndex].weInitiatedForwarding) + break; + } + + if (forwardingIndexSend(&bsOut,HIGH_PRIORITY,RELIABLE,0,packet->guid,false); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_CONNECTION_REQUEST_ACCEPTED, " + "sending ID_ROUTER_2_INCREASE_TIMEOUT to the %I64d at %s:%i\n", packet->guid.g, __FILE__, __LINE__)); + } + + // Also take longer ourselves + rakPeerInterface->SetTimeoutTime(rakPeerInterface->GetTimeoutTime(packet->systemAddress)+10000, packet->systemAddress); + } + else { + // ~Gwynn: Fix for Receive hanging up problem on Windows XP + // See http://blog.delphi-jedi.net/2008/04/23/the-case-of-the-unexplained-dead-lock-in-a-single-thread/ for details + forwardedConnectionListMutex.Unlock(); + } + } + else if (packet->data[0]==ID_ROUTER_2_FORWARDING_NO_PATH) + { + if (packet->wasGeneratedLocally==false) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + return RR_CONTINUE_PROCESSING; +} +void Router2::Update(void) +{ + RakNet::TimeMS curTime = RakNet::GetTimeMS(); + unsigned int connectionRequestIndex=0; + connectionRequestsMutex.Lock(); + while (connectionRequestIndex < connectionRequests.Size()) + { + ConnnectRequest* connectionRequest = connectionRequests[connectionRequestIndex]; + + // pingTimeout is only used with R2RS_REQUEST_STATE_QUERY_FORWARDING + if (connectionRequest->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING && + connectionRequest->pingTimeout < curTime) + { + bool anyRemoved=false; + unsigned int connectionRequestGuidIndex=0; + connectionRequest->connectionRequestSystemsMutex.Lock(); + while (connectionRequestGuidIndex < connectionRequest->connectionRequestSystems.Size()) + { + if (connectionRequest->connectionRequestSystems[connectionRequestGuidIndex].pingToEndpoint<0) + { + anyRemoved=true; + connectionRequest->connectionRequestSystems.RemoveAtIndexFast(connectionRequestGuidIndex); + } + else + { + connectionRequestGuidIndex++; + } + } + connectionRequest->connectionRequestSystemsMutex.Unlock(); + + if (anyRemoved) + { + if (connectionRequestIndex!=(unsigned int)-1) + { + // connectionRequestsMutex should be locked before calling this function + if (UpdateForwarding(connectionRequest)==false) + { + RemoveConnectionRequest(connectionRequestIndex); + } + else + { + connectionRequestIndex++; + } + } + else + { + connectionRequestIndex++; + } + } + else + { + connectionRequestIndex++; + } + } + else + { + connectionRequestIndex++; + } + } + connectionRequestsMutex.Unlock(); + + unsigned int i=0; + miniPunchesInProgressMutex.Lock(); + while (i < miniPunchesInProgress.Size()) + { + if (miniPunchesInProgress[i].timeoutminiPunchesInProgress[i].nextAction) + { + miniPunchesInProgress[i].nextAction=curTime+100; + SendOOBMessages(&miniPunchesInProgress[i]); + } + else + i++; + } + miniPunchesInProgressMutex.Unlock(); + +} +void Router2::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + + + unsigned int forwardedConnectionIndex=0; + forwardedConnectionListMutex.Lock(); + while (forwardedConnectionIndexShowDiagnostic(FormatStringTS(buff,"Closed connection to the %I64d, removing forwarding from list at %s:%i\n", rakNetGUID.g, __FILE__, __LINE__)); + } + + // No longer need forwarding + forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); + } + else if (forwardedConnectionList[forwardedConnectionIndex].intermediaryGuid==rakNetGUID && forwardedConnectionList[forwardedConnectionIndex].weInitiatedForwarding) + { + // Lost connection to intermediary. Restart process to connect to endpoint. If failed, push ID_CONNECTION_LOST. Also remove connection request if it already is in the list, to restart it + connectionRequestsMutex.Lock(); + unsigned int pos = GetConnectionRequestIndex(forwardedConnectionList[forwardedConnectionIndex].endpointGuid); + if((unsigned int)-1 != pos) {RakNet::OP_DELETE(connectionRequests[pos], __FILE__, __LINE__); connectionRequests.RemoveAtIndexFast(pos);} + connectionRequestsMutex.Unlock(); + + ConnectInternal(forwardedConnectionList[forwardedConnectionIndex].endpointGuid, true); + + forwardedConnectionIndex++; + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Closed connection %I64d, restarting forwarding at %s:%i\n",rakNetGUID.g, __FILE__, __LINE__)); + } + + // This should not be removed - the connection is still forwarded, but perhaps through another system +// forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); + } + else + forwardedConnectionIndex++; + } + forwardedConnectionListMutex.Unlock(); + + unsigned int connectionRequestIndex=0; + connectionRequestsMutex.Lock(); + while (connectionRequestIndex < connectionRequests.Size()) + { + ConnnectRequest *cr = connectionRequests[connectionRequestIndex]; + cr->connectionRequestSystemsMutex.Lock(); + unsigned int connectionRequestGuidIndex = cr->GetGuidIndex(rakNetGUID); + if (connectionRequestGuidIndex!=(unsigned int)-1) + { + cr->connectionRequestSystems.RemoveAtIndexFast(connectionRequestGuidIndex); + cr->connectionRequestSystemsMutex.Unlock(); + if (UpdateForwarding(cr)==false) // If returns false, no connection request systems left + { + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Aborted connection to the %I64d, aborted forwarding at %s:%i\n", rakNetGUID.g, __FILE__, __LINE__)); + } + + RemoveConnectionRequest(connectionRequestIndex); + } + else // Else a system in the connection request list dropped. If cr->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING then we are still waiting for other systems to respond. + { + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Aborted connection attempt to %I64d, restarting forwarding to %I64d at %s:%i\n", rakNetGUID.g,cr->endpointGuid.g,__FILE__, __LINE__)); + } +// if(volatile bool is_my_fix_a_truth = true) { // A system in the list of potential systems to try routing to dropped. There is no need to restart the whole process. +// connectionRequestsMutex.Lock(); +// connectionRequests.RemoveAtIndexFast(connectionRequestIndex); +// connectionRequestsMutex.Unlock(); +// +// if(false == ConnectInternal(cr->endpointGuid,cr->returnConnectionLostOnFailure)) +// if (debugInterface) +// { +// char buff[512]; +// debugInterface->ShowDiagnostic(FormatStringTS(buff,"ConnectInternal(cr->endpointGuid,cr->returnConnectionLostOnFailure) is false. at %s:%i\n", __FILE__, __LINE__)); +// } +// } + + connectionRequestIndex++; + } + } + else + { + cr->connectionRequestSystemsMutex.Unlock(); + connectionRequestIndex++; + } + } + connectionRequestsMutex.Unlock(); + + + unsigned int i=0; + miniPunchesInProgressMutex.Lock(); + while (i < miniPunchesInProgress.Size()) + { + if (miniPunchesInProgress[i].sourceGuid==rakNetGUID || miniPunchesInProgress[i].endpointGuid==rakNetGUID) + { + if (miniPunchesInProgress[i].sourceGuid!=rakNetGUID) + { + SendFailureOnCannotForward(miniPunchesInProgress[i].sourceGuid, miniPunchesInProgress[i].endpointGuid); + } + miniPunchesInProgress.RemoveAtIndexFast(i); + } + else + i++; + } + miniPunchesInProgressMutex.Unlock(); +} +void Router2::OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason) +{ + (void) failedConnectionAttemptReason; + (void) packet; + + unsigned int forwardedConnectionIndex=0; + forwardedConnectionListMutex.Lock(); + while (forwardedConnectionIndexsystemAddress) + { + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Failed connection attempt to forwarded system (%I64d : %s) at %s:%i\n", + forwardedConnectionList[forwardedConnectionIndex].endpointGuid.g, packet->systemAddress.ToString(true), __FILE__, __LINE__)); + } + + packet->guid=forwardedConnectionList[forwardedConnectionIndex].endpointGuid; + forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); + } + else + forwardedConnectionIndex++; + } + forwardedConnectionListMutex.Unlock(); +} +void Router2::OnRakPeerShutdown(void) +{ + ClearAll(); +} +// connectionRequestsMutex should already be locked +bool Router2::UpdateForwarding(ConnnectRequest* connectionRequest) +{ + connectionRequest->connectionRequestSystemsMutex.Lock(); + + // RAKNET_DEBUG_PRINTF(__FUNCTION__": connectionRequest->connectionRequestSystems.Size = %d", connectionRequest->connectionRequestSystems.Size()); + + if (connectionRequest->connectionRequestSystems.Size()==0) + { + connectionRequest->connectionRequestSystemsMutex.Unlock(); + + // printf("Router2 failed at %s:%i\n", __FILE__, __LINE__); + if (connectionRequest->returnConnectionLostOnFailure) { + ReturnToUser(ID_CONNECTION_LOST, connectionRequest->endpointGuid, UNASSIGNED_SYSTEM_ADDRESS, true); // This is a connection which was previously established. Rerouting is not possible. +// bool sendDisconnectionNotification = false; +// rakPeerInterface->CloseConnection(rakPeerInterface->GetSystemAddressFromGuid(connectionRequest->endpointGuid), sendDisconnectionNotification); +// RAKNET_DEBUG_PRINTF(__FUNCTION__": call rakPeerInterface->CloseConnection(%I64d)" , connectionRequest->endpointGuid.g); + } + else + ReturnToUser(ID_ROUTER_2_FORWARDING_NO_PATH, connectionRequest->endpointGuid, UNASSIGNED_SYSTEM_ADDRESS, false); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Forwarding failed, no remaining systems at %s:%i\n", _FILE_AND_LINE_)); + } + + forwardedConnectionListMutex.Lock(); + + for (unsigned int forwardedConnectionIndex=0; forwardedConnectionIndex < forwardedConnectionList.Size(); forwardedConnectionIndex++) + { + if (forwardedConnectionList[forwardedConnectionIndex].endpointGuid==connectionRequest->endpointGuid && forwardedConnectionList[forwardedConnectionIndex].weInitiatedForwarding) + { + forwardedConnectionList.RemoveAtIndexFast(forwardedConnectionIndex); + break; + } + } + forwardedConnectionListMutex.Unlock(); + + return false; + } + connectionRequest->connectionRequestSystemsMutex.Unlock(); + + if (connectionRequest->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING) + { + connectionRequest->connectionRequestSystemsMutex.Lock(); + + for (unsigned int i=0; i < connectionRequest->connectionRequestSystems.Size(); i++) + { + if (connectionRequest->connectionRequestSystems[i].pingToEndpoint<0) + { + connectionRequest->connectionRequestSystemsMutex.Unlock(); + return true; // Forward query still in progress, just return + } + } + connectionRequest->connectionRequestSystemsMutex.Unlock(); + + RequestForwarding(connectionRequest); + } +// else if (connectionRequest->requestState==REQUEST_STATE_REQUEST_FORWARDING) +// { +// RequestForwarding(connectionRequestIndex); +// } + + return true; +} +// connectionRequestsMutex should already be locked +void Router2::RemoveConnectionRequest(unsigned int connectionRequestIndex) +{ + RakNet::OP_DELETE(connectionRequests[connectionRequestIndex],_FILE_AND_LINE_); + connectionRequests.RemoveAtIndexFast(connectionRequestIndex); +} +int ConnectionRequestSystemComp( const Router2::ConnectionRequestSystem & key, const Router2::ConnectionRequestSystem &data ) +{ + if (key.pingToEndpoint * (key.usedForwardingEntries+1) < data.pingToEndpoint * (data.usedForwardingEntries+1)) + return -1; + if (key.pingToEndpoint * (key.usedForwardingEntries+1) == data.pingToEndpoint * (data.usedForwardingEntries+1)) + return 1; + if (key.guid < data.guid) + return -1; + if (key.guid > data.guid) + return -1; + return 0; +} +// connectionRequestsMutex should already be locked +void Router2::RequestForwarding(ConnnectRequest* connectionRequest) +{ + RakAssert(connectionRequest->requestState==R2RS_REQUEST_STATE_QUERY_FORWARDING); + connectionRequest->requestState=REQUEST_STATE_REQUEST_FORWARDING; + + if (connectionRequest->GetGuidIndex(connectionRequest->lastRequestedForwardingSystem)!=(unsigned int)-1) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i\n", _FILE_AND_LINE_)); + return; + } + + // Prioritize systems to request forwarding + DataStructures::OrderedList commandList; + unsigned int connectionRequestGuidIndex; + connectionRequest->connectionRequestSystemsMutex.Lock(); + for (connectionRequestGuidIndex=0; connectionRequestGuidIndex < connectionRequest->connectionRequestSystems.Size(); connectionRequestGuidIndex++) + { + RakAssert(connectionRequest->connectionRequestSystems[connectionRequestGuidIndex].pingToEndpoint>=0); + commandList.Insert(connectionRequest->connectionRequestSystems[connectionRequestGuidIndex], + connectionRequest->connectionRequestSystems[connectionRequestGuidIndex], + true, + _FILE_AND_LINE_); + } + connectionRequest->connectionRequestSystemsMutex.Unlock(); + + connectionRequest->lastRequestedForwardingSystem=commandList[0].guid; + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); + bsOut.Write((unsigned char) ID_ROUTER_2_REQUEST_FORWARDING); + bsOut.Write(connectionRequest->endpointGuid); + rakPeerInterface->Send(&bsOut,MEDIUM_PRIORITY,RELIABLE_ORDERED,0,connectionRequest->lastRequestedForwardingSystem,false); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_REQUEST_FORWARDING " + "(connectionRequest->lastRequestedForwardingSystem = %I64d, connectionRequest->endpointGuid = %I64d) at %s:%i\n", + connectionRequest->lastRequestedForwardingSystem.g,connectionRequest->endpointGuid.g, __FILE__, __LINE__)); + } +} +void Router2::SendFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid) +{ + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); + bsOut.Write((unsigned char) ID_ROUTER_2_REPLY_FORWARDING); + bsOut.Write(endpointGuid); + bsOut.Write(false); + rakPeerInterface->Send(&bsOut,MEDIUM_PRIORITY,RELIABLE_ORDERED,0,sourceGuid,false); +} +int Router2::ReturnFailureOnCannotForward(RakNetGUID sourceGuid, RakNetGUID endpointGuid) +{ + // If the number of systems we are currently forwarding>=maxForwarding, return ID_ROUTER_2_REPLY_FORWARDING,endpointGuid,false + if (udpForwarder==0 || udpForwarder->GetUsedForwardEntries()/2>maximumForwardingRequests) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d -> %I64d) at %s:%i\n", + sourceGuid.g, endpointGuid.g,__FILE__, __LINE__)); + SendFailureOnCannotForward(sourceGuid,endpointGuid); + return -1; + } + + // We cannot forward connections which are themselves forwarded. Return fail in that case + forwardedConnectionListMutex.Lock(); + for (unsigned int i=0; i < forwardedConnectionList.Size(); i++) + { + if ((forwardedConnectionList[i].endpointGuid==endpointGuid) + || (forwardedConnectionList[i].endpointGuid==sourceGuid)) // sourceGuid is here so you do not respond to routing requests from systems you are already routing through. + { + forwardedConnectionListMutex.Unlock(); + + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i\n", __FILE__, __LINE__)); + SendFailureOnCannotForward(sourceGuid,endpointGuid); + return -1; + } + } + forwardedConnectionListMutex.Unlock(); + + int pingToEndpoint; + pingToEndpoint = rakPeerInterface->GetAveragePing(endpointGuid); + if (pingToEndpoint==-1) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d -> %I64d) at %s:%i\n", + sourceGuid.g, endpointGuid.g,__FILE__, __LINE__)); + + SendFailureOnCannotForward(sourceGuid,endpointGuid); + return -1; + } + return pingToEndpoint; +} +void Router2::OnQueryForwarding(Packet *packet) +{ + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); + RakNetGUID endpointGuid; + // Read endpointGuid + bs.Read(endpointGuid); + + int pingToEndpoint = ReturnFailureOnCannotForward(packet->guid, endpointGuid); + if (pingToEndpoint==-1) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d) at %s:%i\n", packet->guid.g, __FILE__, __LINE__)); + return; + } + + // If we are connected to endpointGuid, reply ID_ROUTER_2_REPLY_FORWARDING,endpointGuid,true,ping,numCurrentlyForwarding + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_ROUTER_2_INTERNAL); + bsOut.Write((unsigned char) ID_ROUTER_2_REPLY_FORWARDING); + bsOut.Write(endpointGuid); + bsOut.Write(true); + bsOut.Write((unsigned short) pingToEndpoint); + bsOut.Write((unsigned short) udpForwarder->GetUsedForwardEntries()/2); + rakPeerInterface->Send(&bsOut,MEDIUM_PRIORITY,RELIABLE_ORDERED,0,packet->guid,false); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_REPLY_FORWARDING to the %I64d at %s:%i\n", packet->guid.g, __FILE__, __LINE__)); + } +} +void Router2::OnQueryForwardingReply(Packet *packet) +{ + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); + RakNetGUID endpointGuid; + bs.Read(endpointGuid); + // Find endpointGuid among stored requests + bool canForward=false; + bs.Read(canForward); + + + connectionRequestsMutex.Lock(); + unsigned int connectionRequestIndex = GetConnectionRequestIndex(endpointGuid); + if (connectionRequestIndex==(unsigned int)-1) + { + connectionRequestsMutex.Unlock(); + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d) at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); + return; + } + + connectionRequests[connectionRequestIndex]->connectionRequestSystemsMutex.Lock(); + unsigned int connectionRequestGuidIndex = connectionRequests[connectionRequestIndex]->GetGuidIndex(packet->guid); + if (connectionRequestGuidIndex==(unsigned int)-1) + { + connectionRequests[connectionRequestIndex]->connectionRequestSystemsMutex.Unlock(); + connectionRequestsMutex.Unlock(); + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (%I64d) at %s:%i\n", endpointGuid.g, __FILE__, __LINE__)); + return; + } + + if (debugInterface) + { + char buff[512]; + char buff2[512]; + packet->systemAddress.ToString(true,buff2); + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REPLY_FORWARDING on address %s(%I64d -> %I64d) canForward=%i at %s:%i\n", + buff2, packet->guid.g, endpointGuid.g, canForward, __FILE__, __LINE__)); + } + + if (canForward) + { + unsigned short pingToEndpoint; + unsigned short usedEntries; + bs.Read(pingToEndpoint); + bs.Read(usedEntries); + connectionRequests[connectionRequestIndex]->connectionRequestSystems[connectionRequestGuidIndex].usedForwardingEntries=usedEntries; + connectionRequests[connectionRequestIndex]->connectionRequestSystems[connectionRequestGuidIndex].pingToEndpoint=rakPeerInterface->GetAveragePing(packet->guid)+pingToEndpoint; + } + else + { + connectionRequests[connectionRequestIndex]->connectionRequestSystems.RemoveAtIndex(connectionRequestGuidIndex); + } + connectionRequests[connectionRequestIndex]->connectionRequestSystemsMutex.Unlock(); + + if (UpdateForwarding(connectionRequests[connectionRequestIndex])==false) + { + RemoveConnectionRequest(connectionRequestIndex); + } + connectionRequestsMutex.Unlock(); +} +void Router2::SendForwardingSuccess(MessageID messageId, RakNetGUID sourceGuid, RakNetGUID endpointGuid, unsigned short sourceToDstPort) +{ + RakNet::BitStream bsOut; + bsOut.Write(messageId); + bsOut.Write(endpointGuid); + bsOut.Write(sourceToDstPort); + rakPeerInterface->Send(&bsOut,MEDIUM_PRIORITY,RELIABLE_ORDERED,0,sourceGuid,false); + + if (debugInterface) + { + char buff[512]; + if (messageId==ID_ROUTER_2_FORWARDING_ESTABLISHED) + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_FORWARDING_ESTABLISHED at %s:%i\n", _FILE_AND_LINE_ )); + else + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_REROUTED at %s:%i\n", _FILE_AND_LINE_ )); + } +} +void Router2::SendOOBFromRakNetPort(OutOfBandIdentifiers oob, BitStream *extraData, SystemAddress sa) +{ + RakNet::BitStream oobBs; + oobBs.Write((unsigned char)oob); + if (extraData) + { + extraData->ResetReadPointer(); + oobBs.Write(*extraData); + } + char ipAddressString[32]; + sa.ToString(false, ipAddressString); + rakPeerInterface->SendOutOfBand((const char*) ipAddressString,sa.GetPort(),(const char*) oobBs.GetData(),oobBs.GetNumberOfBytesUsed()); +} +void Router2::SendOOBFromSpecifiedSocket(OutOfBandIdentifiers oob, SystemAddress sa, __UDPSOCKET__ socket) +{ + RakNet::BitStream bs; + rakPeerInterface->WriteOutOfBandHeader(&bs); + bs.Write((unsigned char) oob); + // SocketLayer::SendTo_PC( socket, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), sa, __FILE__, __LINE__ ); + + + if (sa.address.addr4.sin_family==AF_INET) + { + sendto__( socket, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), 0, ( const sockaddr* ) & sa.address.addr4, sizeof( sockaddr_in ) ); + } + else + { + #if RAKNET_SUPPORT_IPV6==1 + sendto__( socket, (const char*) bs.GetData(), bs.GetNumberOfBytesUsed(), 0, ( const sockaddr* ) & sa.address.addr6, sizeof( sockaddr_in6 ) ); + #endif + } + + + + + + + + + + + + +} +void Router2::SendOOBMessages(Router2::MiniPunchRequest *mpr) +{ + // Mini NAT punch + // Send from srcToDestPort to packet->systemAddress (source). If the message arrives, the remote system should reply. + SendOOBFromSpecifiedSocket(ID_ROUTER_2_REPLY_TO_SENDER_PORT, mpr->sourceAddress, mpr->forwardingSocket); + + // Send from destToSourcePort to endpointSystemAddress (destination). If the message arrives, the remote system should reply. + SendOOBFromSpecifiedSocket(ID_ROUTER_2_REPLY_TO_SENDER_PORT, mpr->endpointAddress, mpr->forwardingSocket); + + + if (debugInterface) { + char buff [512]; + + char buff2[128]; + + mpr->sourceAddress .ToString(true,buff2); + + debugInterface->ShowDiagnostic(FormatStringTS(buff,"call SendOOBFromSpecifiedSocket(...,%s,...)", buff2)); + + mpr->endpointAddress .ToString(true,buff2); + + debugInterface->ShowDiagnostic(FormatStringTS(buff,"call SendOOBFromSpecifiedSocket(...,%s,...)", buff2)); + } + + // Tell source to send to forwardingPort + RakNet::BitStream extraData; + extraData.Write(mpr->forwardingPort); + RakAssert(mpr->forwardingPort!=0); + SendOOBFromRakNetPort(ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, &extraData, mpr->sourceAddress); + + // Tell destination to send to forwardingPort + extraData.Reset(); + extraData.Write(mpr->forwardingPort); + RakAssert(mpr->forwardingPort); + SendOOBFromRakNetPort(ID_ROUTER_2_REPLY_TO_SPECIFIED_PORT, &extraData, mpr->endpointAddress); +} +void Router2::OnRequestForwarding(Packet *packet) +{ + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); + RakNetGUID endpointGuid; + bs.Read(endpointGuid); + + int pingToEndpoint = ReturnFailureOnCannotForward(packet->guid, endpointGuid); + if (pingToEndpoint==-1) + { + char buff[512]; + if (debugInterface) debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed (packet->guid =%I64d, endpointGuid = %I64d) at %s:%i\n", + packet->guid.g, endpointGuid.g, __FILE__, __LINE__)); + return; + } + + unsigned short forwardingPort=0; + __UDPSOCKET__ forwardingSocket=INVALID_SOCKET; + SystemAddress endpointSystemAddress = rakPeerInterface->GetSystemAddressFromGuid(endpointGuid); + UDPForwarderResult result = udpForwarder->StartForwarding( + packet->systemAddress, endpointSystemAddress, 30000, 0, socketFamily, + &forwardingPort, &forwardingSocket); + + if (result==UDPFORWARDER_FORWARDING_ALREADY_EXISTS) + { + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REQUEST_FORWARDING, result=UDPFORWARDER_FORWARDING_ALREADY_EXISTS " + "(packet->guid =%I64d, endpointGuid = %I64d) at %s:%i\n", + packet->guid.g, endpointGuid.g,__FILE__, __LINE__)); + } + + SendForwardingSuccess(ID_ROUTER_2_FORWARDING_ESTABLISHED, packet->guid, endpointGuid, forwardingPort); + } + else if (result==UDPFORWARDER_NO_SOCKETS) + { + char buff[512]; + char buff2[64]; + char buff3[64]; + packet->systemAddress.ToString(true,buff2); + endpointSystemAddress.ToString(true,buff3); + if (debugInterface) + debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i with UDPFORWARDER_NO_SOCKETS, packet->systemAddress=%s, endpointSystemAddress=%s, forwardingPort=%i, forwardingSocket=%i\n", + __FILE__, __LINE__, buff2, buff3, forwardingPort, forwardingSocket)); + SendFailureOnCannotForward(packet->guid, endpointGuid); + } + else if (result==UDPFORWARDER_INVALID_PARAMETERS) + { + char buff[512]; + char buff2[64]; + char buff3[64]; + packet->systemAddress.ToString(true,buff2); + endpointSystemAddress.ToString(true,buff3); + if (debugInterface) + debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i with UDPFORWARDER_INVALID_PARAMETERS, packet->systemAddress=%s, endpointSystemAddress=%s, forwardingPort=%i, forwardingSocket=%i\n", + __FILE__, __LINE__, buff2, buff3, forwardingPort, forwardingSocket)); + SendFailureOnCannotForward(packet->guid, endpointGuid); + } + else if (result==UDPFORWARDER_BIND_FAILED) + { + char buff[512]; + char buff2[64]; + char buff3[64]; + packet->systemAddress.ToString(true,buff2); + endpointSystemAddress.ToString(true,buff3); + if (debugInterface) + debugInterface->ShowFailure(FormatStringTS(buff,"Router2 failed at %s:%i with UDPFORWARDER_BIND_FAILED, packet->systemAddress=%s, endpointSystemAddress=%s, forwardingPort=%i, forwardingSocket=%i\n", + __FILE__, __LINE__, buff2, buff3, forwardingPort, forwardingSocket)); + SendFailureOnCannotForward(packet->guid, endpointGuid); + } + else + { + if (debugInterface) + { + char buff2[32]; + char buff3[32]; + endpointSystemAddress.ToString(true,buff2); + packet->systemAddress.ToString(true,buff3); + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REQUEST_FORWARDING.\n" + "endpointAddress=%s\nsourceAddress=%s\nforwardingPort=%i\n " + "calling SendOOBMessages at %s:%i\n", buff2,buff3,forwardingPort,_FILE_AND_LINE_)); + } + + // Store the punch request + MiniPunchRequest miniPunchRequest; + miniPunchRequest.endpointAddress=endpointSystemAddress; + miniPunchRequest.endpointGuid=endpointGuid; + miniPunchRequest.gotReplyFromEndpoint=false; + miniPunchRequest.gotReplyFromSource=false; + miniPunchRequest.sourceGuid=packet->guid; + miniPunchRequest.sourceAddress=packet->systemAddress; + miniPunchRequest.forwardingPort=forwardingPort; + miniPunchRequest.forwardingSocket=forwardingSocket; + int ping1 = rakPeerInterface->GetAveragePing(packet->guid); + int ping2 = rakPeerInterface->GetAveragePing(endpointGuid); + if (ping1>ping2) + miniPunchRequest.timeout=RakNet::GetTimeMS() + ping1*8+300; + else + miniPunchRequest.timeout=RakNet::GetTimeMS() + ping2*8+300; + miniPunchRequest.nextAction=RakNet::GetTimeMS()+100; + SendOOBMessages(&miniPunchRequest); + miniPunchesInProgressMutex.Lock(); + miniPunchesInProgress.Push(miniPunchRequest,_FILE_AND_LINE_); + miniPunchesInProgressMutex.Unlock(); + } +} +void Router2::OnMiniPunchReplyBounce(Packet *packet) +{ + // Find stored punch request + unsigned int i=0; + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE from guid=%I64d (miniPunchesInProgress.Size() = %d)", + packet->guid.g, miniPunchesInProgress.Size())); + } + + miniPunchesInProgressMutex.Lock(); + while (i < miniPunchesInProgress.Size()) + { + if (miniPunchesInProgress[i].sourceGuid==packet->guid || miniPunchesInProgress[i].endpointGuid==packet->guid) + { + if (miniPunchesInProgress[i].sourceGuid==packet->guid) + miniPunchesInProgress[i].gotReplyFromSource=true; + if (miniPunchesInProgress[i].endpointGuid==packet->guid) + miniPunchesInProgress[i].gotReplyFromEndpoint=true; + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Processing ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE, gotReplyFromSource=%i gotReplyFromEndpoint=%i at %s:%i\n", miniPunchesInProgress[i].gotReplyFromSource, miniPunchesInProgress[i].gotReplyFromEndpoint, __FILE__, __LINE__)); + } + + if (miniPunchesInProgress[i].gotReplyFromEndpoint==true && + miniPunchesInProgress[i].gotReplyFromSource==true) + { + SendForwardingSuccess(ID_ROUTER_2_REROUTED, miniPunchesInProgress[i].endpointGuid, miniPunchesInProgress[i].sourceGuid, miniPunchesInProgress[i].forwardingPort); + SendForwardingSuccess(ID_ROUTER_2_FORWARDING_ESTABLISHED, miniPunchesInProgress[i].sourceGuid, miniPunchesInProgress[i].endpointGuid, miniPunchesInProgress[i].forwardingPort); + miniPunchesInProgress.RemoveAtIndexFast(i); + } + else + { + i++; + } + } + else + i++; + } + miniPunchesInProgressMutex.Unlock(); +} +void Router2::OnMiniPunchReply(Packet *packet) +{ + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID) + sizeof(unsigned char)); + RakNetGUID routerGuid; + bs.Read(routerGuid); + SendOOBFromRakNetPort(ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE, 0, rakPeerInterface->GetSystemAddressFromGuid(routerGuid)); + + if (debugInterface) + { + char buff[512]; + + char buff2[512]; + + rakPeerInterface->GetSystemAddressFromGuid(routerGuid).ToString(true,buff2); + + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Sending ID_ROUTER_2_MINI_PUNCH_REPLY_BOUNCE (%s) at %s:%i\n", buff2, __FILE__, __LINE__)); + } +} +void Router2::OnRerouted(Packet *packet) +{ + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID)); + RakNetGUID endpointGuid; + bs.Read(endpointGuid); + unsigned short sourceToDestPort; + bs.Read(sourceToDestPort); + + // Return rerouted notice + SystemAddress intermediaryAddress=packet->systemAddress; + intermediaryAddress.SetPortHostOrder(sourceToDestPort); + rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); + + unsigned int forwardingIndex; + forwardedConnectionListMutex.Lock(); + for (forwardingIndex=0; forwardingIndex < forwardedConnectionList.Size(); forwardingIndex++) + { + if (forwardedConnectionList[forwardingIndex].endpointGuid==endpointGuid) + break; + } + + if (forwardingIndexsystemAddress; + ref_fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); + ref_fc.intermediaryGuid = packet->guid; + + rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"FIX: Got ID_ROUTER_2_REROUTE, returning ID_ROUTER_2_REROUTED," + " Calling RakPeer::ChangeSystemAddress(%I64d, %s) at %s:%i\n",endpointGuid.g, intermediaryAddress.ToString(true), __FILE__, __LINE__)); + } + } + else + { + ForwardedConnection fc; + fc.endpointGuid=endpointGuid; + fc.intermediaryAddress=packet->systemAddress; + fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); + fc.intermediaryGuid=packet->guid; + fc.weInitiatedForwarding=false; + // add to forwarding list. This is only here to avoid reporting direct connections in Router2::ReturnFailureOnCannotForward + forwardedConnectionList.Push (fc,__FILE__, __LINE__); + forwardedConnectionListMutex.Unlock(); + + rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_REROUTE, returning ID_ROUTER_2_REROUTED, Calling RakPeer::ChangeSystemAddress at %s:%i\n", __FILE__, __LINE__)); + } + } + +} +bool Router2::OnForwardingSuccess(Packet *packet) +{ + RakNet::BitStream bs(packet->data, packet->length, false); + bs.IgnoreBytes(sizeof(MessageID)); + RakNetGUID endpointGuid; + bs.Read(endpointGuid); + unsigned short sourceToDestPort; + bs.Read(sourceToDestPort); + + unsigned int forwardingIndex; + forwardedConnectionListMutex.Lock(); + for (forwardingIndex=0; forwardingIndex < forwardedConnectionList.Size(); forwardingIndex++) + { + if (forwardedConnectionList[forwardingIndex].endpointGuid==endpointGuid) + break; + } + + if (forwardingIndexsystemAddress; + intermediaryAddress.SetPortHostOrder(sourceToDestPort); + rakPeerInterface->ChangeSystemAddress(endpointGuid, intermediaryAddress); + + //////////////////////////////////////////////////////////////////////////// + ForwardedConnection& ref_fc = forwardedConnectionList[forwardingIndex]; + ref_fc.intermediaryAddress = packet->systemAddress; + ref_fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); + ref_fc.intermediaryGuid = packet->guid; + //////////////////////////////////////////////////////////////////////////// + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got ID_ROUTER_2_FORWARDING_ESTABLISHED, returning ID_ROUTER_2_REROUTED, Calling RakPeer::ChangeSystemAddress at %s:%i\n", _FILE_AND_LINE_)); + } + + packet->data[0]=ID_ROUTER_2_REROUTED; + + forwardedConnectionListMutex.Unlock(); + return true; // Return packet to user + } + else + { + forwardedConnectionListMutex.Unlock(); + + // removeFrom connectionRequests; + ForwardedConnection fc; + connectionRequestsMutex.Lock(); + unsigned int connectionRequestIndex = GetConnectionRequestIndex(endpointGuid); + fc.returnConnectionLostOnFailure=connectionRequests[connectionRequestIndex]->returnConnectionLostOnFailure; + connectionRequests.RemoveAtIndexFast(connectionRequestIndex); + connectionRequestsMutex.Unlock(); + fc.endpointGuid=endpointGuid; + fc.intermediaryAddress=packet->systemAddress; + fc.intermediaryAddress.SetPortHostOrder(sourceToDestPort); + fc.intermediaryGuid=packet->guid; + fc.weInitiatedForwarding=true; + + // add to forwarding list + forwardedConnectionListMutex.Lock(); + forwardedConnectionList.Push (fc,_FILE_AND_LINE_); + forwardedConnectionListMutex.Unlock(); + + if (debugInterface) + { + char buff[512]; + debugInterface->ShowDiagnostic(FormatStringTS(buff,"Got and returning to user ID_ROUTER_2_FORWARDING_ESTABLISHED at %s:%i\n", _FILE_AND_LINE_)); + } + + } + return true; // Return packet to user +} +int Router2::GetLargestPingAmongConnectedSystems(void) const +{ + int avePing; + int largestPing=-1; + unsigned int maxPeers = rakPeerInterface->GetMaximumNumberOfPeers(); + if (maxPeers==0) + return 9999; + unsigned int index; + for (index=0; index < rakPeerInterface->GetMaximumNumberOfPeers(); index++) + { + RakNetGUID g = rakPeerInterface->GetGUIDFromIndex(index); + if (g!=UNASSIGNED_RAKNET_GUID) + { + avePing=rakPeerInterface->GetAveragePing(rakPeerInterface->GetGUIDFromIndex(index)); + if (avePing>largestPing) + largestPing=avePing; + } + } + return largestPing; +} + +unsigned int Router2::GetConnectionRequestIndex(RakNetGUID endpointGuid) +{ + unsigned int i; + for (i=0; i < connectionRequests.Size(); i++) + { + if (connectionRequests[i]->endpointGuid==endpointGuid) + return i; + } + return (unsigned int) -1; +} +unsigned int Router2::ConnnectRequest::GetGuidIndex(RakNetGUID guid) +{ + unsigned int i; + for (i=0; i < connectionRequestSystems.Size(); i++) + { + if (connectionRequestSystems[i].guid==guid) + return i; + } + return (unsigned int) -1; +} +void Router2::ReturnToUser(MessageID messageId, RakNetGUID endpointGuid, const SystemAddress &systemAddress, bool wasGeneratedLocally) +{ + Packet *p = AllocatePacketUnified(sizeof(MessageID)+sizeof(unsigned char)); + p->data[0]=messageId; + p->systemAddress=systemAddress; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=endpointGuid; + p->wasGeneratedLocally=wasGeneratedLocally; + rakPeerInterface->PushBackPacket(p, true); +} +void Router2::ClearForwardedConnections(void) +{ + forwardedConnectionListMutex.Lock(); + forwardedConnectionList.Clear(false,_FILE_AND_LINE_); + forwardedConnectionListMutex.Unlock(); +} +void Router2::ClearAll(void) +{ + ClearConnectionRequests(); + ClearMinipunches(); + ClearForwardedConnections(); +} +void Router2::SetDebugInterface(Router2DebugInterface *_debugInterface) +{ + debugInterface=_debugInterface; +} +Router2DebugInterface *Router2::GetDebugInterface(void) const +{ + return debugInterface; +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/SecureHandshake.cpp b/src/raknet/SecureHandshake.cpp new file mode 100644 index 0000000..534c7f3 --- /dev/null +++ b/src/raknet/SecureHandshake.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + +#include "include/raknet/NativeFeatureIncludes.hpp" + +#if LIBCAT_SECURITY==1 + +// If building a RakNet DLL, be sure to tweak the CAT_EXPORT macro meaning +#if !defined(_RAKNET_LIB) && defined(_RAKNET_DLL) +# define CAT_BUILD_DLL +#else +# define CAT_NEUTER_EXPORT +#endif + +#include "include/raknet/cat/src/port/EndianNeutral.cpp" +#include "include/raknet/cat/src/port/AlignedAlloc.cpp" +#include "include/raknet/cat/src/time/Clock.cpp" +#include "include/raknet/cat/src/threads/Mutex.cpp" +#include "include/raknet/cat/src/threads/Thread.cpp" +#include "include/raknet/cat/src/threads/WaitableFlag.cpp" +#include "include/raknet/cat/src/hash/MurmurHash2.cpp" +#include "include/raknet/cat/src/lang/Strings.cpp" + +#include "include/raknet/cat/src/math/BigRTL.cpp" +#include "include/raknet/cat/src/math/BigPseudoMersenne.cpp" +#include "include/raknet/cat/src/math/BigTwistedEdwards.cpp" + +#include "include/raknet/cat/src/crypt/SecureCompare.cpp" +#include "include/raknet/cat/src/crypt/cookie/CookieJar.cpp" +#include "include/raknet/cat/src/crypt/hash/HMAC_MD5.cpp" +#include "include/raknet/cat/src/crypt/privatekey/ChaCha.cpp" +#include "include/raknet/cat/src/crypt/hash/Skein.cpp" +#include "include/raknet/cat/src/crypt/hash/Skein256.cpp" +#include "include/raknet/cat/src/crypt/hash/Skein512.cpp" +#include "include/raknet/cat/src/crypt/pass/Passwords.cpp" + +#include "include/raknet/cat/src/crypt/rand/EntropyWindows.cpp" +#include "include/raknet/cat/src/crypt/rand/EntropyLinux.cpp" +#include "include/raknet/cat/src/crypt/rand/EntropyWindowsCE.cpp" +#include "include/raknet/cat/src/crypt/rand/EntropyGeneric.cpp" +#include "include/raknet/cat/src/crypt/rand/Fortuna.cpp" + +#include "include/raknet/cat/src/crypt/tunnel/KeyAgreement.cpp" +#include "include/raknet/cat/src/crypt/tunnel/AuthenticatedEncryption.cpp" +#include "include/raknet/cat/src/crypt/tunnel/KeyAgreementInitiator.cpp" +#include "include/raknet/cat/src/crypt/tunnel/KeyAgreementResponder.cpp" +#include "include/raknet/cat/src/crypt/tunnel/KeyMaker.cpp" + +#include "include/raknet/cat/src/crypt/tunnel/EasyHandshake.cpp" + +#endif // LIBCAT_SECURITY diff --git a/src/raknet/SendToThread.cpp b/src/raknet/SendToThread.cpp new file mode 100644 index 0000000..9488605 --- /dev/null +++ b/src/raknet/SendToThread.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/SendToThread.hpp" +#ifdef USE_THREADED_SEND +#include "include/raknet/RakThread.hpp" +#include "include/raknet/InternalPacket.hpp" +#include "include/raknet/GetTime.hpp" + +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 +#include "include/raknet/CCRakNetUDT.hpp" +#else +#include "include/raknet/CCRakNetSlidingWindow.hpp" +#endif + +using namespace RakNet; + +int SendToThread::refCount=0; +DataStructures::ThreadsafeAllocatingQueue SendToThread::objectQueue; +ThreadPool SendToThread::threadPool; + +SendToThread::SendToThreadBlock* SendToWorkerThread(SendToThread::SendToThreadBlock* input, bool *returnOutput, void* perThreadData) +{ + (void) perThreadData; + *returnOutput=false; +// RakNet::TimeUS *mostRecentTime=(RakNet::TimeUS *)input->data; +// *mostRecentTime=RakNet::GetTimeUS(); + SocketLayer::SendTo(input->s, input->data, input->dataWriteOffset, input->systemAddress, _FILE_AND_LINE_); + SendToThread::objectQueue.Push(input); + return 0; +} +SendToThread::SendToThread() +{ +} +SendToThread::~SendToThread() +{ + +} +void SendToThread::AddRef(void) +{ + if (++refCount==1) + { + threadPool.StartThreads(1,0); + } +} +void SendToThread::Deref(void) +{ + if (refCount>0) + { + if (--refCount==0) + { + threadPool.StopThreads(); + RakAssert(threadPool.NumThreadsWorking()==0); + + unsigned i; + SendToThreadBlock* info; + for (i=0; i < threadPool.InputSize(); i++) + { + info = threadPool.GetInputAtIndex(i); + objectQueue.Push(info); + } + threadPool.ClearInput(); + objectQueue.Clear(_FILE_AND_LINE_); + } + } +} +SendToThread::SendToThreadBlock* SendToThread::AllocateBlock(void) +{ + SendToThread::SendToThreadBlock *b; + b=objectQueue.Pop(); + if (b==0) + b=objectQueue.Allocate(_FILE_AND_LINE_); + return b; +} +void SendToThread::ProcessBlock(SendToThread::SendToThreadBlock* threadedSend) +{ + RakAssert(threadedSend->dataWriteOffset>0 && threadedSend->dataWriteOffset<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE); + threadPool.AddInput(SendToWorkerThread,threadedSend); +} +#endif diff --git a/src/raknet/SignaledEvent.cpp b/src/raknet/SignaledEvent.cpp new file mode 100644 index 0000000..fa02ba5 --- /dev/null +++ b/src/raknet/SignaledEvent.cpp @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/SignaledEvent.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakSleep.hpp" + +#if defined(__GNUC__) +#include +#include +#endif + +using namespace RakNet; + + + + + +SignaledEvent::SignaledEvent() +{ +#ifdef _WIN32 + eventList=INVALID_HANDLE_VALUE; + + +#else + isSignaled=false; +#endif +} +SignaledEvent::~SignaledEvent() +{ + // Intentionally do not close event, so it doesn't close twice on linux +} + +void SignaledEvent::InitEvent(void) +{ +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) + eventList=CreateEventEx(0, 0, 0, 0); +#elif defined(_WIN32) + eventList=CreateEvent(0, false, false, 0); + + + + + + + + + +#else + +#if !defined(ANDROID) + pthread_condattr_init( &condAttr ); + pthread_cond_init(&eventList, &condAttr); +#else + pthread_cond_init(&eventList, 0); +#endif + pthread_mutexattr_init( &mutexAttr ); + pthread_mutex_init(&hMutex, &mutexAttr); +#endif +} + +void SignaledEvent::CloseEvent(void) +{ +#ifdef _WIN32 + if (eventList!=INVALID_HANDLE_VALUE) + { + CloseHandle(eventList); + eventList=INVALID_HANDLE_VALUE; + } + + + + + + + + + +#else + pthread_cond_destroy(&eventList); + pthread_mutex_destroy(&hMutex); +#if !defined(ANDROID) + pthread_condattr_destroy( &condAttr ); +#endif + pthread_mutexattr_destroy( &mutexAttr ); +#endif +} + +void SignaledEvent::SetEvent(void) +{ +#ifdef _WIN32 + ::SetEvent(eventList); + + + + + + + + + + +#else + // Different from SetEvent which stays signaled. + // We have to record manually that the event was signaled + isSignaledMutex.Lock(); + isSignaled=true; + isSignaledMutex.Unlock(); + + // Unblock waiting threads + pthread_cond_broadcast(&eventList); +#endif +} + +void SignaledEvent::WaitOnEvent(int timeoutMs) +{ +#ifdef _WIN32 +// WaitForMultipleObjects( +// 2, +// eventList, +// false, +// timeoutMs); + WaitForSingleObjectEx(eventList,timeoutMs,FALSE); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#else + + // If was previously set signaled, just unset and return + isSignaledMutex.Lock(); + if (isSignaled==true) + { + isSignaled=false; + isSignaledMutex.Unlock(); + return; + } + isSignaledMutex.Unlock(); + + + + //struct timespec ts; + + // Else wait for SetEvent to be called + + + + + + + + + + + + + + + + + + struct timespec ts; + + int rc; + struct timeval tp; + rc = gettimeofday(&tp, NULL); + ts.tv_sec = tp.tv_sec; + ts.tv_nsec = tp.tv_usec * 1000; +// #endif + + while (timeoutMs > 30) + { + // Wait 30 milliseconds for the signal, then check again. + // This is in case we missed the signal between the top of this function and pthread_cond_timedwait, or after the end of the loop and pthread_cond_timedwait + ts.tv_nsec += 30*1000000; + if (ts.tv_nsec >= 1000000000) + { + ts.tv_nsec -= 1000000000; + ts.tv_sec++; + } + + // [SBC] added mutex lock/unlock around cond_timedwait. + // this prevents airplay from generating a whole much of errors. + // not sure how this works on other platforms since according to + // the docs you are suppost to hold the lock before you wait + // on the cond. + pthread_mutex_lock(&hMutex); + pthread_cond_timedwait(&eventList, &hMutex, &ts); + pthread_mutex_unlock(&hMutex); + + timeoutMs-=30; + + isSignaledMutex.Lock(); + if (isSignaled==true) + { + isSignaled=false; + isSignaledMutex.Unlock(); + return; + } + isSignaledMutex.Unlock(); + } + + // Wait the remaining time, and turn off the signal in case it was set + ts.tv_nsec += timeoutMs*1000000; + if (ts.tv_nsec >= 1000000000) + { + ts.tv_nsec -= 1000000000; + ts.tv_sec++; + } + + pthread_mutex_lock(&hMutex); + pthread_cond_timedwait(&eventList, &hMutex, &ts); + pthread_mutex_unlock(&hMutex); + + isSignaledMutex.Lock(); + isSignaled=false; + isSignaledMutex.Unlock(); + +#endif +} diff --git a/src/raknet/SimpleMutex.cpp b/src/raknet/SimpleMutex.cpp new file mode 100644 index 0000000..29a01fa --- /dev/null +++ b/src/raknet/SimpleMutex.cpp @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + + +#include "include/raknet/SimpleMutex.hpp" +#include "include/raknet/RakAssert.hpp" + +using namespace RakNet; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +SimpleMutex::SimpleMutex() //: isInitialized(false) +{ + + + + + + + + // Prior implementation of Initializing in Lock() was not threadsafe + Init(); +} + +SimpleMutex::~SimpleMutex() +{ +// if (isInitialized==false) +// return; +#ifdef _WIN32 + // CloseHandle(hMutex); + DeleteCriticalSection(&criticalSection); + + + + + + +#else + pthread_mutex_destroy(&hMutex); +#endif + + + + + + + +} + +#ifdef _WIN32 +#ifdef _DEBUG +#include +#endif +#endif + +void SimpleMutex::Lock(void) +{ +// if (isInitialized==false) +// Init(); + +#ifdef _WIN32 + /* + DWORD d = WaitForSingleObject(hMutex, INFINITE); + #ifdef _DEBUG + if (d==WAIT_FAILED) + { + LPVOID messageBuffer; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPTSTR) &messageBuffer, + 0, + NULL + ); + // Process any inserts in messageBuffer. + // ... + // Display the string. + //MessageBox( NULL, (LPCTSTR)messageBuffer, "Error", MB_OK | MB_ICONINFORMATION ); + RAKNET_DEBUG_PRINTF("SimpleMutex error: %s", messageBuffer); + // Free the buffer. + LocalFree( messageBuffer ); + + } + + RakAssert(d==WAIT_OBJECT_0); + */ + EnterCriticalSection(&criticalSection); + + + + + + +#else + int error = pthread_mutex_lock(&hMutex); + (void) error; + RakAssert(error==0); +#endif +} + +void SimpleMutex::Unlock(void) +{ +// if (isInitialized==false) +// return; +#ifdef _WIN32 + // ReleaseMutex(hMutex); + LeaveCriticalSection(&criticalSection); + + + + + + +#else + int error = pthread_mutex_unlock(&hMutex); + (void) error; + RakAssert(error==0); +#endif +} + +void SimpleMutex::Init(void) +{ +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) + InitializeCriticalSectionEx(&criticalSection,0,CRITICAL_SECTION_NO_DEBUG_INFO); +#elif defined(_WIN32) + // hMutex = CreateMutex(NULL, FALSE, 0); + // RakAssert(hMutex); + InitializeCriticalSection(&criticalSection); + + + + + + + + +#else + int error = pthread_mutex_init(&hMutex, 0); + (void) error; + RakAssert(error==0); +#endif +// isInitialized=true; +} diff --git a/src/raknet/SocketLayer.cpp b/src/raknet/SocketLayer.cpp new file mode 100644 index 0000000..ca95e52 --- /dev/null +++ b/src/raknet/SocketLayer.cpp @@ -0,0 +1,613 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// \brief SocketLayer class implementation +/// + + +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakNetTypes.hpp" +#include "include/raknet/RakPeer.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/LinuxStrings.hpp" +#include "include/raknet/SocketDefines.hpp" +#if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(__WIN32__) +#include +#endif + +using namespace RakNet; + +/* +#if defined(__native_client__) +using namespace pp; +#endif +*/ + +#if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 +#include "include/raknet/CCRakNetUDT.hpp" +#else +#include "include/raknet/CCRakNetSlidingWindow.hpp" +#endif + +//SocketLayerOverride *SocketLayer::slo=0; + +#ifdef _WIN32 +#else +#include // memcpy +#include +#include +#include +#include // error numbers +#include // RAKNET_DEBUG_PRINTF +#if !defined(ANDROID) +#include +#endif +#include +#include +#include +#include +#include + +#endif + + + + + + + + + + + + + +#if defined(_WIN32) +#include "include/raknet/WSAStartupSingleton.hpp" +#include "include/raknet/WindowsIncludes.hpp" + +#else +#include +#endif + +#include "include/raknet/RakSleep.hpp" +#include +#include "include/raknet/Itoa.hpp" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +namespace RakNet +{ + extern void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNet::TimeUS timeRead ); + //extern void ProcessNetworkPacket( const SystemAddress systemAddress, const char *data, const int length, RakPeer *rakPeer, RakNetSocket* rakNetSocket, RakNet::TimeUS timeRead ); +} + +#ifdef _DEBUG +#include +#endif + + + +// http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#ip4to6 +// http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#getaddrinfo + +#if RAKNET_SUPPORT_IPV6==1 +void PrepareAddrInfoHints(addrinfo *hints) +{ + memset(hints, 0, sizeof (addrinfo)); // make sure the struct is empty + hints->ai_socktype = SOCK_DGRAM; // UDP sockets + hints->ai_flags = AI_PASSIVE; // fill in my IP for me +} +#endif + +void SocketLayer::SetSocketOptions( __UDPSOCKET__ listenSocket, bool blockingSocket, bool setBroadcast) +{ +#ifdef __native_client__ + (void) listenSocket; +#else + int sock_opt = 1; + + // This doubles the max throughput rate + sock_opt=1024*256; + setsockopt__(listenSocket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + + // Immediate hard close. Don't linger the socket, or recreating the socket quickly on Vista fails. + // Fail with voice and xbox + + sock_opt=0; + setsockopt__(listenSocket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + + + + // This doesn't make much difference: 10% maybe + // Not supported on console 2 + sock_opt=1024*16; + setsockopt__(listenSocket, SOL_SOCKET, SO_SNDBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + + + if (blockingSocket==false) + { +#ifdef _WIN32 + unsigned long nonblocking = 1; + ioctlsocket__(listenSocket, FIONBIO, &nonblocking ); + + + +#else + fcntl( listenSocket, F_SETFL, O_NONBLOCK ); +#endif + } + if (setBroadcast) + { + // Note: Fails with VDP but not xbox + // Set broadcast capable + sock_opt=1; + if ( setsockopt__(listenSocket, SOL_SOCKET, SO_BROADCAST, ( char * ) & sock_opt, sizeof( sock_opt ) ) == -1 ) + { +#if defined(_WIN32) && defined(_DEBUG) +#if !defined(WINDOWS_PHONE_8) + DWORD dwIOError = GetLastError(); + // On Vista, can get WSAEACCESS (10013) + // See http://support.microsoft.com/kb/819124 + // http://blogs.msdn.com/wndp/archive/2007/03/19/winsock-so-exclusiveaddruse-on-vista.aspx + // http://msdn.microsoft.com/en-us/library/ms740621(VS.85).aspx + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "setsockopt__(SO_BROADCAST) failed:Error code - %d\n%s", dwIOError, messageBuffer ); + //Free the buffer. + LocalFree( messageBuffer ); +#endif +#endif + + } + + } + +#endif +} + + +RakNet::RakString SocketLayer::GetSubNetForSocketAndIp(__UDPSOCKET__ inSock, RakNet::RakString inIpString) +{ + RakNet::RakString netMaskString; + RakNet::RakString ipString; + + + + + +#if defined(WINDOWS_STORE_RT) + RakAssert("Not yet supported" && 0); + return ""; +#elif defined(_WIN32) + INTERFACE_INFO InterfaceList[20]; + unsigned long nBytesReturned; + if (WSAIoctl(inSock, SIO_GET_INTERFACE_LIST, 0, 0, &InterfaceList, + sizeof(InterfaceList), &nBytesReturned, 0, 0) == SOCKET_ERROR) { + return ""; + } + + int nNumInterfaces = nBytesReturned / sizeof(INTERFACE_INFO); + + for (int i = 0; i < nNumInterfaces; ++i) + { + sockaddr_in *pAddress; + pAddress = (sockaddr_in *) & (InterfaceList[i].iiAddress); + ipString=inet_ntoa(pAddress->sin_addr); + + if (inIpString==ipString) + { + pAddress = (sockaddr_in *) & (InterfaceList[i].iiNetmask); + netMaskString=inet_ntoa(pAddress->sin_addr); + return netMaskString; + } + } + return ""; +#else + + int fd,fd2; + fd2 = socket__(AF_INET, SOCK_DGRAM, 0); + + if(fd2 < 0) + { + return ""; + } + + struct ifconf ifc; + char buf[1999]; + ifc.ifc_len = sizeof(buf); + ifc.ifc_buf = buf; + if(ioctl(fd2, SIOCGIFCONF, &ifc) < 0) + { + return ""; + } + + struct ifreq *ifr; + ifr = ifc.ifc_req; + int intNum = ifc.ifc_len / sizeof(struct ifreq); + for(int i = 0; i < intNum; i++) + { + ipString=inet_ntoa(((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr); + + if (inIpString==ipString) + { + struct ifreq ifr2; + fd = socket__(AF_INET, SOCK_DGRAM, 0); + if(fd < 0) + { + return ""; + } + ifr2.ifr_addr.sa_family = AF_INET; + + strncpy(ifr2.ifr_name, ifr[i].ifr_name, IFNAMSIZ-1); + + ioctl(fd, SIOCGIFNETMASK, &ifr2); + + close(fd); + close(fd2); + netMaskString=inet_ntoa(((struct sockaddr_in *)&ifr2.ifr_addr)->sin_addr); + + return netMaskString; + } + } + + close(fd2); + return ""; + +#endif + +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#if defined(WINDOWS_STORE_RT) +void GetMyIP_WinRT( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) +{ + // Perhaps DatagramSocket.BindEndpointAsynch, use localHostName as an empty string, then query what it bound to? + RakAssert("Not yet supported" && 0); +} +#else +void GetMyIP_Win32( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) +{ + int idx=0; + idx=0; + char ac[ 80 ]; + if ( gethostname( ac, sizeof( ac ) ) == -1 ) + { + #if defined(_WIN32) && !defined(WINDOWS_PHONE_8) + DWORD dwIOError = GetLastError(); + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "gethostname failed:Error code - %d\n%s", dwIOError, messageBuffer ); + //Free the buffer. + LocalFree( messageBuffer ); + #endif + return ; + } + + +#if RAKNET_SUPPORT_IPV6==1 + struct addrinfo hints; + struct addrinfo *servinfo=0, *aip; // will point to the results + PrepareAddrInfoHints(&hints); + getaddrinfo(ac, "", &hints, &servinfo); + + for (idx=0, aip = servinfo; aip != NULL && idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS; aip = aip->ai_next, idx++) + { + if (aip->ai_family == AF_INET) + { + struct sockaddr_in *ipv4 = (struct sockaddr_in *)aip->ai_addr; + memcpy(&addresses[idx].address.addr4,ipv4,sizeof(sockaddr_in)); + } + else + { + struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)aip->ai_addr; + memcpy(&addresses[idx].address.addr4,ipv6,sizeof(sockaddr_in6)); + } + + } + + freeaddrinfo(servinfo); // free the linked-list +#else + struct hostent *phe = gethostbyname( ac ); + + if ( phe == 0 ) + { + #if defined(_WIN32) && !defined(WINDOWS_PHONE_8) + DWORD dwIOError = GetLastError(); + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "gethostbyname failed:Error code - %d\n%s", dwIOError, messageBuffer ); + + //Free the buffer. + LocalFree( messageBuffer ); + #endif + return ; + } + for ( idx = 0; idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS; ++idx ) + { + if (phe->h_addr_list[ idx ] == 0) + break; + + memcpy(&addresses[idx].address.addr4.sin_addr,phe->h_addr_list[ idx ],sizeof(struct in_addr)); + + } +#endif // else RAKNET_SUPPORT_IPV6==1 + + while (idx < MAXIMUM_NUMBER_OF_INTERNAL_IDS) + { + addresses[idx]=UNASSIGNED_SYSTEM_ADDRESS; + idx++; + } +} + +#endif + + +void SocketLayer::GetMyIP( SystemAddress addresses[MAXIMUM_NUMBER_OF_INTERNAL_IDS] ) +{ + + + + + + +#if defined(WINDOWS_STORE_RT) + GetMyIP_WinRT(addresses); +#elif defined(_WIN32) + GetMyIP_Win32(addresses); +#else +// GetMyIP_Linux(addresses); + GetMyIP_Win32(addresses); +#endif +} + + +/* +unsigned short SocketLayer::GetLocalPort(RakNetSocket *s) +{ + SystemAddress sa; + GetSystemAddress(s,&sa); + return sa.GetPort(); +} +*/ +unsigned short SocketLayer::GetLocalPort(__UDPSOCKET__ s) +{ + SystemAddress sa; + GetSystemAddress(s,&sa); + return sa.GetPort(); +} +void SocketLayer::GetSystemAddress_Old ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ) +{ +#if defined(__native_client__) + *systemAddressOut = UNASSIGNED_SYSTEM_ADDRESS; +#else + sockaddr_in sa; + memset(&sa,0,sizeof(sockaddr_in)); + socklen_t len = sizeof(sa); + if (getsockname__(s, (sockaddr*)&sa, &len)!=0) + { +#if defined(_WIN32) && defined(_DEBUG) && !defined(WINDOWS_PHONE_8) + DWORD dwIOError = GetLastError(); + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "getsockname failed:Error code - %d\n%s", dwIOError, messageBuffer ); + + //Free the buffer. + LocalFree( messageBuffer ); +#endif + *systemAddressOut = UNASSIGNED_SYSTEM_ADDRESS; + return; + } + + systemAddressOut->SetPortNetworkOrder(sa.sin_port); + systemAddressOut->address.addr4.sin_addr.s_addr=sa.sin_addr.s_addr; +#endif +} +/* +void SocketLayer::GetSystemAddress_Old ( RakNetSocket *s, SystemAddress *systemAddressOut ) +{ + return GetSystemAddress_Old(s->s, systemAddressOut); +} +*/ +void SocketLayer::GetSystemAddress ( __UDPSOCKET__ s, SystemAddress *systemAddressOut ) +{ +#if RAKNET_SUPPORT_IPV6!=1 + GetSystemAddress_Old(s, systemAddressOut); +#else + socklen_t slen; + sockaddr_storage ss; + slen = sizeof(ss); + + if (getsockname__(s, (struct sockaddr *)&ss, &slen)!=0) + { +#if defined(_WIN32) && defined(_DEBUG) + DWORD dwIOError = GetLastError(); + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "getsockname failed:Error code - %d\n%s", dwIOError, messageBuffer ); + + //Free the buffer. + LocalFree( messageBuffer ); +#endif + systemAddressOut->FromString(0); + return; + } + + if (ss.ss_family==AF_INET) + { + memcpy(&systemAddressOut->address.addr4,(sockaddr_in *)&ss,sizeof(sockaddr_in)); + systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr4.sin_port); + + uint32_t zero = 0; + if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) + systemAddressOut->SetToLoopback(4); + // systemAddressOut->address.addr4.sin_port=ntohs(systemAddressOut->address.addr4.sin_port); + } + else + { + memcpy(&systemAddressOut->address.addr6,(sockaddr_in6 *)&ss,sizeof(sockaddr_in6)); + systemAddressOut->debugPort=ntohs(systemAddressOut->address.addr6.sin6_port); + + char zero[16]; + memset(zero,0,sizeof(zero)); + if (memcmp(&systemAddressOut->address.addr4.sin_addr.s_addr, &zero, sizeof(zero))==0) + systemAddressOut->SetToLoopback(6); + + // systemAddressOut->address.addr6.sin6_port=ntohs(systemAddressOut->address.addr6.sin6_port); + } +#endif // #if RAKNET_SUPPORT_IPV6!=1 +} +/* +void SocketLayer::GetSystemAddress ( RakNetSocket *s, SystemAddress *systemAddressOut ) +{ + return GetSystemAddress(s->s, systemAddressOut); +} +*/ + +// void SocketLayer::SetSocketLayerOverride(SocketLayerOverride *_slo) +// { +// slo=_slo; +// } + +bool SocketLayer::GetFirstBindableIP(char firstBindable[128], int ipProto) +{ + SystemAddress ipList[ MAXIMUM_NUMBER_OF_INTERNAL_IDS ]; + SocketLayer::GetMyIP( ipList ); + + + if (ipProto==AF_UNSPEC) + + { + ipList[0].ToString(false,firstBindable); + return true; + } + + // Find the first valid host address + unsigned int l; + for (l=0; l < MAXIMUM_NUMBER_OF_INTERNAL_IDS; l++) + { + if (ipList[l]==UNASSIGNED_SYSTEM_ADDRESS) + break; + if (ipList[l].GetIPVersion()==4 && ipProto==AF_INET) + break; + if (ipList[l].GetIPVersion()==6 && ipProto==AF_INET6) + break; + } + + if (ipList[l]==UNASSIGNED_SYSTEM_ADDRESS || l==MAXIMUM_NUMBER_OF_INTERNAL_IDS) + return false; +// RAKNET_DEBUG_PRINTF("%i %i %i %i\n", +// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[0], +// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[1], +// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[2], +// ((char*)(&ipList[l].address.addr4.sin_addr.s_addr))[3] +// ); + ipList[l].ToString(false,firstBindable); + return true; + +} + + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif diff --git a/src/raknet/StatisticsHistory.cpp b/src/raknet/StatisticsHistory.cpp new file mode 100644 index 0000000..a24f5ff --- /dev/null +++ b/src/raknet/StatisticsHistory.cpp @@ -0,0 +1,827 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_StatisticsHistory==1 + +#include "include/raknet/StatisticsHistory.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/RakNetStatistics.hpp" +#include "include/raknet/RakPeerInterface.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(StatisticsHistory,StatisticsHistory); +STATIC_FACTORY_DEFINITIONS(StatisticsHistoryPlugin,StatisticsHistoryPlugin); + +int StatisticsHistory::TrackedObjectComp( const uint64_t &key, StatisticsHistory::TrackedObject* const &data ) +{ + if (key < data->trackedObjectData.objectId) + return -1; + if (key == data->trackedObjectData.objectId) + return 0; + return 1; +} + +int TimeAndValueQueueCompAsc( StatisticsHistory::TimeAndValueQueue* const &key, StatisticsHistory::TimeAndValueQueue* const &data ) +{ + if (key->sortValue < data->sortValue) + return -1; + if (key->sortValue > data->sortValue) + return 1; + if (key->key < data->key) + return -1; + if (key->key > data->key) + return 1; + return 0; +} + +int TimeAndValueQueueCompDesc( StatisticsHistory::TimeAndValueQueue* const &key, StatisticsHistory::TimeAndValueQueue* const &data ) +{ + if (key->sortValue > data->sortValue) + return -1; + if (key->sortValue < data->sortValue) + return 1; + if (key->key > data->key) + return -1; + if (key->key < data->key) + return 1; + return 0; +} +StatisticsHistory::TrackedObjectData::TrackedObjectData() {} +StatisticsHistory::TrackedObjectData::TrackedObjectData(uint64_t _objectId, int _objectType, void *_userData) +{ + objectId=_objectId; + objectType=_objectType; + userData=_userData; +} +StatisticsHistory::StatisticsHistory() {timeToTrack = 30000;} +StatisticsHistory::~StatisticsHistory() +{ + Clear(); +} +void StatisticsHistory::SetDefaultTimeToTrack(Time defaultTimeToTrack) {timeToTrack = defaultTimeToTrack;} +Time StatisticsHistory::GetDefaultTimeToTrack(void) const {return timeToTrack;} +bool StatisticsHistory::AddObject(TrackedObjectData tod) +{ + bool objectExists; + unsigned int idx = objects.GetIndexFromKey(tod.objectId, &objectExists); + if (objectExists) + return false; + TrackedObject *to = RakNet::OP_NEW(_FILE_AND_LINE_); + to->trackedObjectData=tod; + objects.InsertAtIndex(to,idx,_FILE_AND_LINE_); + return true; +} +bool StatisticsHistory::RemoveObject(uint64_t objectId, void **userData) +{ + unsigned int idx = GetObjectIndex(objectId); + if (idx == (unsigned int) -1) + return false; + if (userData) + *userData = objects[idx]->trackedObjectData.userData; + RemoveObjectAtIndex(idx); + return true; +} +void StatisticsHistory::RemoveObjectAtIndex(unsigned int index) +{ + TrackedObject *to = objects[index]; + objects.RemoveAtIndex(index); + RakNet::OP_DELETE(to, _FILE_AND_LINE_); +} +void StatisticsHistory::Clear(void) +{ + for (unsigned int idx=0; idx < objects.Size(); idx++) + { + RakNet::OP_DELETE(objects[idx], _FILE_AND_LINE_); + } + objects.Clear(false, _FILE_AND_LINE_); +} +unsigned int StatisticsHistory::GetObjectCount(void) const {return objects.Size();} +StatisticsHistory::TrackedObjectData * StatisticsHistory::GetObjectAtIndex(unsigned int index) const {return &objects[index]->trackedObjectData;} +bool StatisticsHistory::AddValueByObjectID(uint64_t objectId, RakString key, SHValueType val, Time curTime, bool combineEqualTimes) +{ + unsigned int idx = GetObjectIndex(objectId); + if (idx == (unsigned int) -1) + return false; + AddValueByIndex(idx, key, val, curTime, combineEqualTimes); + return true; +} +void StatisticsHistory::AddValueByIndex(unsigned int index, RakString key, SHValueType val, Time curTime, bool combineEqualTimes) +{ + TimeAndValueQueue *queue; + TrackedObject *to = objects[index]; + DataStructures::HashIndex hi = to->dataQueues.GetIndexOf(key); + if (hi.IsInvalid()) + { + queue = RakNet::OP_NEW(_FILE_AND_LINE_); + queue->key=key; + queue->timeToTrackValues = timeToTrack; + to->dataQueues.Push(key, queue, _FILE_AND_LINE_); + } + else + { + queue = to->dataQueues.ItemAtIndex(hi); + } + + TimeAndValue tav; + if (combineEqualTimes==true && queue->values.Size()>0 && queue->values.PeekTail().time==curTime) + { + tav = queue->values.PopTail(); + + queue->recentSum -= tav.val; + queue->recentSumOfSquares -= tav.val * tav.val; + queue->longTermSum -= tav.val; + queue->longTermCount = queue->longTermCount - 1; + } + else + { + tav.val=0.0; + tav.time=curTime; + } + + tav.val+=val; + queue->values.Push(tav, _FILE_AND_LINE_); + + queue->recentSum += tav.val; + queue->recentSumOfSquares += tav.val * tav.val; + queue->longTermSum += tav.val; + queue->longTermCount = queue->longTermCount + 1; + if (queue->longTermLowest > tav.val) + queue->longTermLowest = tav.val; + if (queue->longTermHighest < tav.val) + queue->longTermHighest = tav.val; +} +StatisticsHistory::SHErrorCode StatisticsHistory::GetHistoryForKey(uint64_t objectId, RakString key, StatisticsHistory::TimeAndValueQueue **values, Time curTime) const +{ + if (values == 0) + return SH_INVALID_PARAMETER; + + unsigned int idx = GetObjectIndex(objectId); + if (idx == (unsigned int) -1) + return SH_UKNOWN_OBJECT; + TrackedObject *to = objects[idx]; + DataStructures::HashIndex hi = to->dataQueues.GetIndexOf(key); + if (hi.IsInvalid()) + return SH_UKNOWN_KEY; + *values = to->dataQueues.ItemAtIndex(hi); + (*values)->CullExpiredValues(curTime); + return SH_OK; +} +bool StatisticsHistory::GetHistorySorted(uint64_t objectId, SHSortOperation sortType, DataStructures::List &values) const +{ + unsigned int idx = GetObjectIndex(objectId); + if (idx == (unsigned int) -1) + return false; + TrackedObject *to = objects[idx]; + DataStructures::List itemList; + DataStructures::List keyList; + to->dataQueues.GetAsList(itemList,keyList,_FILE_AND_LINE_); + Time curTime = GetTime(); + + DataStructures::OrderedList sortedQueues; + for (unsigned int i=0; i < itemList.Size(); i++) + { + TimeAndValueQueue *tavq = itemList[i]; + tavq->CullExpiredValues(curTime); + + if (sortType == SH_SORT_BY_RECENT_SUM_ASCENDING || sortType == SH_SORT_BY_RECENT_SUM_DESCENDING) + tavq->sortValue = tavq->GetRecentSum(); + else if (sortType == SH_SORT_BY_LONG_TERM_SUM_ASCENDING || sortType == SH_SORT_BY_LONG_TERM_SUM_DESCENDING) + tavq->sortValue = tavq->GetLongTermSum(); + else if (sortType == SH_SORT_BY_RECENT_SUM_OF_SQUARES_ASCENDING || sortType == SH_SORT_BY_RECENT_SUM_OF_SQUARES_DESCENDING) + tavq->sortValue = tavq->GetRecentSumOfSquares(); + else if (sortType == SH_SORT_BY_RECENT_AVERAGE_ASCENDING || sortType == SH_SORT_BY_RECENT_AVERAGE_DESCENDING) + tavq->sortValue = tavq->GetRecentAverage(); + else if (sortType == SH_SORT_BY_LONG_TERM_AVERAGE_ASCENDING || sortType == SH_SORT_BY_LONG_TERM_AVERAGE_DESCENDING) + tavq->sortValue = tavq->GetLongTermAverage(); + else if (sortType == SH_SORT_BY_RECENT_HIGHEST_ASCENDING || sortType == SH_SORT_BY_RECENT_HIGHEST_DESCENDING) + tavq->sortValue = tavq->GetRecentHighest(); + else if (sortType == SH_SORT_BY_RECENT_LOWEST_ASCENDING || sortType == SH_SORT_BY_RECENT_LOWEST_DESCENDING) + tavq->sortValue = tavq->GetRecentLowest(); + else if (sortType == SH_SORT_BY_LONG_TERM_HIGHEST_ASCENDING || sortType == SH_SORT_BY_LONG_TERM_HIGHEST_DESCENDING) + tavq->sortValue = tavq->GetLongTermHighest(); + else + tavq->sortValue = tavq->GetLongTermLowest(); + + if ( + sortType == SH_SORT_BY_RECENT_SUM_ASCENDING || + sortType == SH_SORT_BY_LONG_TERM_SUM_ASCENDING || + sortType == SH_SORT_BY_RECENT_SUM_OF_SQUARES_ASCENDING || + sortType == SH_SORT_BY_RECENT_AVERAGE_ASCENDING || + sortType == SH_SORT_BY_LONG_TERM_AVERAGE_ASCENDING || + sortType == SH_SORT_BY_RECENT_HIGHEST_ASCENDING || + sortType == SH_SORT_BY_RECENT_LOWEST_ASCENDING || + sortType == SH_SORT_BY_LONG_TERM_HIGHEST_ASCENDING || + sortType == SH_SORT_BY_LONG_TERM_LOWEST_ASCENDING) + sortedQueues.Insert(tavq, tavq, false, _FILE_AND_LINE_, TimeAndValueQueueCompAsc); + else + sortedQueues.Insert(tavq, tavq, false, _FILE_AND_LINE_, TimeAndValueQueueCompDesc); + } + + for (unsigned int i=0; i < sortedQueues.Size(); i++) + values.Push(sortedQueues[i], _FILE_AND_LINE_); + return true; +} +void StatisticsHistory::MergeAllObjectsOnKey(RakString key, TimeAndValueQueue *tavqOutput, SHDataCategory dataCategory) const +{ + tavqOutput->Clear(); + + Time curTime = GetTime(); + + // Find every object with this key + for (unsigned int idx=0; idx < objects.Size(); idx++) + { + TrackedObject *to = objects[idx]; + DataStructures::HashIndex hi = to->dataQueues.GetIndexOf(key); + if (hi.IsInvalid()==false) + { + TimeAndValueQueue *tavqInput = to->dataQueues.ItemAtIndex(hi); + tavqInput->CullExpiredValues(curTime); + TimeAndValueQueue::MergeSets(tavqOutput, dataCategory, tavqInput, dataCategory, tavqOutput); + } + } +} +void StatisticsHistory::GetUniqueKeyList(DataStructures::List &keys) +{ + keys.Clear(true, _FILE_AND_LINE_); + + for (unsigned int idx=0; idx < objects.Size(); idx++) + { + TrackedObject *to = objects[idx]; + DataStructures::List itemList; + DataStructures::List keyList; + to->dataQueues.GetAsList(itemList, keyList, _FILE_AND_LINE_); + for (unsigned int k=0; k < keyList.Size(); k++) + { + bool hasKey=false; + for (unsigned int j=0; j < keys.Size(); j++) + { + if (keys[j]==keyList[k]) + { + hasKey=true; + break; + } + } + + if (hasKey==false) + keys.Push(keyList[k], _FILE_AND_LINE_); + } + } +} +StatisticsHistory::TimeAndValueQueue::TimeAndValueQueue() +{ + Clear(); +} +StatisticsHistory::TimeAndValueQueue::~TimeAndValueQueue(){} +void StatisticsHistory::TimeAndValueQueue::SetTimeToTrackValues(Time t) +{ + timeToTrackValues = t; +} +Time StatisticsHistory::TimeAndValueQueue::GetTimeToTrackValues(void) const {return timeToTrackValues;} +SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentSum(void) const {return recentSum;} +SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentSumOfSquares(void) const {return recentSumOfSquares;} +SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermSum(void) const {return longTermSum;} +SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentAverage(void) const +{ + if (values.Size() > 0) + return recentSum / (SHValueType) values.Size(); + else + return 0; +} +SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentLowest(void) const +{ + SHValueType out = SH_TYPE_MAX; + for (unsigned int idx=0; idx < values.Size(); idx++) + { + if (values[idx].val < out) + out = values[idx].val; + } + return out; +} +SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentHighest(void) const +{ + SHValueType out = -SH_TYPE_MAX; + for (unsigned int idx=0; idx < values.Size(); idx++) + { + if (values[idx].val > out) + out = values[idx].val; + } + return out; +} +SHValueType StatisticsHistory::TimeAndValueQueue::GetRecentStandardDeviation(void) const +{ + if (values.Size()==0) + return 0; + + SHValueType recentMean= GetRecentAverage(); + SHValueType squareOfMean = recentMean * recentMean; + SHValueType meanOfSquares = GetRecentSumOfSquares() / (SHValueType) values.Size(); + return meanOfSquares - squareOfMean; +} +SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermAverage(void) const +{ + if (longTermCount == 0) + return 0; + return longTermSum / longTermCount; +} +SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermLowest(void) const {return longTermLowest;} +SHValueType StatisticsHistory::TimeAndValueQueue::GetLongTermHighest(void) const {return longTermHighest;} +Time StatisticsHistory::TimeAndValueQueue::GetTimeRange(void) const +{ + if (values.Size()<2) + return 0; + return values[values.Size()-1].time - values[0].time; +} +SHValueType StatisticsHistory::TimeAndValueQueue::GetSumSinceTime(Time t) const +{ + SHValueType sum = 0; + for (int i=values.Size(); i > 0; --i) + { + if (values[i-1].time>=t) + sum+=values[i-1].val; + } + return sum; +} +void StatisticsHistory::TimeAndValueQueue::MergeSets( const TimeAndValueQueue *lhs, SHDataCategory lhsDataCategory, const TimeAndValueQueue *rhs, SHDataCategory rhsDataCategory, TimeAndValueQueue *output ) +{ + // Two ways to merge: + // 1. Treat rhs as just more data points. + // 1A. Sums are just added. If two values have the same time, just put in queue twice + // 1B. longTermLowest and longTermHighest are the lowest and highest of the two sets + // + // 2. Add by time. If time for the other set is missing, calculate slope to extrapolate + // 2A. Have to recalculate recentSum, recentSumOfSquares. + // 2B. longTermSum, longTermCount, longTermLowest, longTermHighest are unknown + + if (lhs!=output) + { + output->key = lhs->key; + output->timeToTrackValues = lhs->timeToTrackValues; + } + else + { + output->key = rhs->key; + output->timeToTrackValues = rhs->timeToTrackValues; + } + + unsigned int lhsIndex, rhsIndex; + lhsIndex=0; + rhsIndex=0; + + // I use local valuesOutput in case lhs==output || rhs==output + DataStructures::Queue valuesOutput; + + if (lhsDataCategory==StatisticsHistory::DC_DISCRETE && rhsDataCategory==StatisticsHistory::DC_DISCRETE) + { + while (rhsIndex < rhs->values.Size() && lhsIndex < lhs->values.Size()) + { + if (rhs->values[rhsIndex].time < lhs->values[lhsIndex].time) + { + valuesOutput.Push(rhs->values[rhsIndex], _FILE_AND_LINE_ ); + rhsIndex++; + } + else if (rhs->values[rhsIndex].time > lhs->values[lhsIndex].time) + { + valuesOutput.Push(lhs->values[rhsIndex], _FILE_AND_LINE_ ); + lhsIndex++; + } + else + { + valuesOutput.Push(rhs->values[rhsIndex], _FILE_AND_LINE_ ); + rhsIndex++; + valuesOutput.Push(lhs->values[rhsIndex], _FILE_AND_LINE_ ); + lhsIndex++; + } + } + + while (rhsIndex < rhs->values.Size()) + { + valuesOutput.Push(rhs->values[rhsIndex], _FILE_AND_LINE_ ); + rhsIndex++; + } + while (lhsIndex < lhs->values.Size()) + { + valuesOutput.Push(lhs->values[lhsIndex], _FILE_AND_LINE_ ); + lhsIndex++; + } + + output->recentSum = lhs->recentSum + rhs->recentSum; + output->recentSumOfSquares = lhs->recentSumOfSquares + rhs->recentSumOfSquares; + output->longTermSum = lhs->longTermSum + rhs->longTermSum; + output->longTermCount = lhs->longTermCount + rhs->longTermCount; + if (lhs->longTermLowest < rhs->longTermLowest) + output->longTermLowest = lhs->longTermLowest; + else + output->longTermLowest = rhs->longTermLowest; + if (lhs->longTermHighest > rhs->longTermHighest) + output->longTermHighest = lhs->longTermHighest; + else + output->longTermHighest = rhs->longTermHighest; + } + else + { + TimeAndValue lastTimeAndValueLhs, lastTimeAndValueRhs; + lastTimeAndValueLhs.time=0; + lastTimeAndValueLhs.val=0; + lastTimeAndValueRhs.time=0; + lastTimeAndValueRhs.val=0; + SHValueType lastSlopeLhs=0; + SHValueType lastSlopeRhs=0; + Time timeSinceOppositeValue; + + TimeAndValue newTimeAndValue; + + while (rhsIndex < rhs->values.Size() && lhsIndex < lhs->values.Size()) + { + if (rhs->values[rhsIndex].time < lhs->values[lhsIndex].time) + { + timeSinceOppositeValue = rhs->values[rhsIndex].time - lastTimeAndValueLhs.time; + newTimeAndValue.val = rhs->values[rhsIndex].val + lastTimeAndValueLhs.val + lastSlopeLhs * timeSinceOppositeValue; + newTimeAndValue.time = rhs->values[rhsIndex].time; + lastTimeAndValueRhs = rhs->values[rhsIndex]; + if (rhsIndex>0 && rhs->values[rhsIndex].time != rhs->values[rhsIndex-1].time && rhsDataCategory==StatisticsHistory::DC_CONTINUOUS) + lastSlopeRhs = (rhs->values[rhsIndex].val - rhs->values[rhsIndex-1].val) / (SHValueType) (rhs->values[rhsIndex].time - rhs->values[rhsIndex-1].time); + rhsIndex++; + } + else if (lhs->values[lhsIndex].time < rhs->values[rhsIndex].time) + { + timeSinceOppositeValue = lhs->values[lhsIndex].time - lastTimeAndValueRhs.time; + newTimeAndValue.val = lhs->values[lhsIndex].val + lastTimeAndValueRhs.val + lastSlopeRhs * timeSinceOppositeValue; + newTimeAndValue.time = lhs->values[lhsIndex].time; + lastTimeAndValueLhs = lhs->values[lhsIndex]; + if (lhsIndex>0 && lhs->values[lhsIndex].time != lhs->values[lhsIndex-1].time && lhsDataCategory==StatisticsHistory::DC_CONTINUOUS) + lastSlopeLhs = (lhs->values[lhsIndex].val - lhs->values[lhsIndex-1].val) / (SHValueType) (lhs->values[lhsIndex].time - lhs->values[lhsIndex-1].time); + lhsIndex++; + } + else + { + newTimeAndValue.val = lhs->values[lhsIndex].val + rhs->values[rhsIndex].val; + newTimeAndValue.time = lhs->values[lhsIndex].time; + lastTimeAndValueRhs = rhs->values[rhsIndex]; + lastTimeAndValueLhs = lhs->values[lhsIndex]; + if (rhsIndex>0 && rhs->values[rhsIndex].time != rhs->values[rhsIndex-1].time && rhsDataCategory==StatisticsHistory::DC_CONTINUOUS) + lastSlopeRhs = (rhs->values[rhsIndex].val - rhs->values[rhsIndex-1].val) / (SHValueType) (rhs->values[rhsIndex].time - rhs->values[rhsIndex-1].time); + if (lhsIndex>0 && lhs->values[lhsIndex].time != lhs->values[lhsIndex-1].time && lhsDataCategory==StatisticsHistory::DC_CONTINUOUS) + lastSlopeLhs = (lhs->values[lhsIndex].val - lhs->values[lhsIndex-1].val) / (SHValueType) (lhs->values[lhsIndex].time - lhs->values[lhsIndex-1].time); + lhsIndex++; + rhsIndex++; + } + + valuesOutput.Push(newTimeAndValue, _FILE_AND_LINE_ ); + } + + while (rhsIndex < rhs->values.Size()) + { + timeSinceOppositeValue = rhs->values[rhsIndex].time - lastTimeAndValueLhs.time; + newTimeAndValue.val = rhs->values[rhsIndex].val + lastTimeAndValueLhs.val + lastSlopeLhs * timeSinceOppositeValue; + newTimeAndValue.time = rhs->values[rhsIndex].time; + valuesOutput.Push(newTimeAndValue, _FILE_AND_LINE_ ); + rhsIndex++; + } + while (lhsIndex < lhs->values.Size()) + { + timeSinceOppositeValue = lhs->values[lhsIndex].time - lastTimeAndValueRhs.time; + newTimeAndValue.val = lhs->values[lhsIndex].val + lastTimeAndValueRhs.val + lastSlopeRhs * timeSinceOppositeValue; + newTimeAndValue.time = lhs->values[lhsIndex].time; + valuesOutput.Push(newTimeAndValue, _FILE_AND_LINE_ ); + lhsIndex++; + } + + output->recentSum = 0; + output->recentSumOfSquares = 0; + for (unsigned int i=0; i < valuesOutput.Size(); i++) + { + output->recentSum += valuesOutput[i].val; + output->recentSumOfSquares += valuesOutput[i].val * valuesOutput[i].val; + } + } + + output->values = valuesOutput; +} +void StatisticsHistory::TimeAndValueQueue::ResizeSampleSet( int maxSamples, DataStructures::Queue &histogram, SHDataCategory dataCategory, Time timeClipStart, Time timeClipEnd ) +{ + histogram.Clear(_FILE_AND_LINE_); + if (maxSamples==0) + return; + Time timeRange = GetTimeRange(); + if (timeRange==0) + return; + if (maxSamples==1) + { + StatisticsHistory::TimeAndValue tav; + tav.time = timeRange; + tav.val = GetRecentSum(); + histogram.Push(tav, _FILE_AND_LINE_); + return; + } + Time interval = timeRange / maxSamples; + if (interval==0) + interval=1; + unsigned int dataIndex; + Time timeBoundary; + StatisticsHistory::TimeAndValue currentSum; + Time currentTime; + SHValueType numSamples; + Time endTime; + + numSamples=0; + endTime = values[values.Size()-1].time; + dataIndex=0; + currentTime=values[0].time; + currentSum.val=0; + currentSum.time=values[0].time + interval / 2; + timeBoundary = values[0].time + interval; + while (timeBoundary <= endTime) + { + while (dataIndex < values.Size() && values[dataIndex].time <= timeBoundary) + { + currentSum.val += values[dataIndex].val; + dataIndex++; + numSamples++; + } + + if (dataCategory==DC_CONTINUOUS) + { + if (dataIndex > 0 && + dataIndex < values.Size() && + values[dataIndex-1].time < timeBoundary && + values[dataIndex].time > timeBoundary) + { + SHValueType interpolatedValue = Interpolate(values[dataIndex-1], values[dataIndex], timeBoundary); + currentSum.val+=interpolatedValue; + numSamples++; + } + + if (numSamples > 1) + { + currentSum.val /= numSamples; + } + } + + histogram.Push(currentSum, _FILE_AND_LINE_); + currentSum.time=timeBoundary + interval / 2; + timeBoundary += interval; + currentSum.val=0; + numSamples=0; + } + + + if ( timeClipStart!=0 && histogram.Size()>=1) + { + timeClipStart = histogram.Peek().time+timeClipStart; + if (histogram.PeekTail().time < timeClipStart) + { + histogram.Clear(_FILE_AND_LINE_); + } + else if (histogram.Size()>=2 && histogram.Peek().time < timeClipStart) + { + StatisticsHistory::TimeAndValue tav; + + do + { + tav = histogram.Pop(); + + if (histogram.Peek().time == timeClipStart) + { + break; + } + else if (histogram.Peek().time > timeClipStart) + { + StatisticsHistory::TimeAndValue tav2; + tav2.val = StatisticsHistory::TimeAndValueQueue::Interpolate(tav, histogram.Peek(), timeClipStart); + tav2.time=timeClipStart; + histogram.PushAtHead(tav2, 0, _FILE_AND_LINE_); + break; + } + } while (histogram.Size()>=2); + } + } + + if ( timeClipEnd!=0 && histogram.Size()>=1) + { + timeClipEnd = histogram.PeekTail().time-timeClipEnd; + if (histogram.Peek().time > timeClipEnd) + { + histogram.Clear(_FILE_AND_LINE_); + } + else if (histogram.Size()>=2 && histogram.PeekTail().time > timeClipEnd) + { + StatisticsHistory::TimeAndValue tav; + + do + { + tav = histogram.PopTail(); + + if (histogram.PeekTail().time == timeClipEnd) + { + break; + } + else if (histogram.PeekTail().time < timeClipEnd) + { + StatisticsHistory::TimeAndValue tav2; + tav2.val = StatisticsHistory::TimeAndValueQueue::Interpolate(tav, histogram.PeekTail(), timeClipEnd); + tav2.time=timeClipEnd; + histogram.Push(tav2, _FILE_AND_LINE_); + break; + } + } while (histogram.Size()>=2); + } + } +} +void StatisticsHistory::TimeAndValueQueue::CullExpiredValues(Time curTime) +{ + while (values.Size()) + { + StatisticsHistory::TimeAndValue tav = values.Peek(); + if (curTime - tav.time > timeToTrackValues) + { + recentSum -= tav.val; + recentSumOfSquares -= tav.val * tav.val; + values.Pop(); + } + else + { + break; + } + } +} +SHValueType StatisticsHistory::TimeAndValueQueue::Interpolate(StatisticsHistory::TimeAndValue t1, StatisticsHistory::TimeAndValue t2, Time time) +{ + if (t2.time==t1.time) + return (t1.val + t2.val) / 2; +// if (t2.time > t1.time) +// { + SHValueType slope = (t2.val - t1.val) / ((SHValueType) t2.time - (SHValueType) t1.time); + return t1.val + slope * ((SHValueType) time - (SHValueType) t1.time); +// } +// else +// { +// SHValueType slope = (t1.val - t2.val) / (SHValueType) (t1.time - t2.time); +// return t2.val + slope * (SHValueType) (time - t2.time); +// } +} +void StatisticsHistory::TimeAndValueQueue::Clear(void) +{ + recentSum = 0; + recentSumOfSquares = 0; + longTermSum = 0; + longTermCount = 0; + longTermLowest = SH_TYPE_MAX; + longTermHighest = -SH_TYPE_MAX; + values.Clear(_FILE_AND_LINE_); +} +StatisticsHistory::TimeAndValueQueue& StatisticsHistory::TimeAndValueQueue::operator = ( const TimeAndValueQueue& input ) +{ + values=input.values; + timeToTrackValues=input.timeToTrackValues; + key=input.key; + recentSum=input.recentSum; + recentSumOfSquares=input.recentSumOfSquares; + longTermSum=input.longTermSum; + longTermCount=input.longTermCount; + longTermLowest=input.longTermLowest; + longTermHighest=input.longTermHighest; + return *this; +} +StatisticsHistory::TrackedObject::TrackedObject() {} +StatisticsHistory::TrackedObject::~TrackedObject() +{ + DataStructures::List itemList; + DataStructures::List keyList; + for (unsigned int idx=0; idx < itemList.Size(); idx++) + RakNet::OP_DELETE(itemList[idx], _FILE_AND_LINE_); +} +unsigned int StatisticsHistory::GetObjectIndex(uint64_t objectId) const +{ + bool objectExists; + unsigned int idx = objects.GetIndexFromKey(objectId, &objectExists); + if (objectExists) + return idx; + return (unsigned int) -1; +} +StatisticsHistoryPlugin::StatisticsHistoryPlugin() +{ + addNewConnections = true; + removeLostConnections = true; + newConnectionsObjectType = 0; +} +StatisticsHistoryPlugin::~StatisticsHistoryPlugin() +{ +} +void StatisticsHistoryPlugin::SetTrackConnections(bool _addNewConnections, int _newConnectionsObjectType, bool _removeLostConnections) +{ + addNewConnections = _addNewConnections; + removeLostConnections = _removeLostConnections; + newConnectionsObjectType = _newConnectionsObjectType; +} +void StatisticsHistoryPlugin::Update(void) +{ + DataStructures::List addresses; + DataStructures::List guids; + DataStructures::List stats; + rakPeerInterface->GetStatisticsList(addresses, guids, stats); + + Time curTime = GetTime(); + for (unsigned int idx = 0; idx < guids.Size(); idx++) + { + unsigned int objectIndex = statistics.GetObjectIndex(guids[idx].g); + if (objectIndex!=(unsigned int)-1) + { + statistics.AddValueByIndex(objectIndex, + "RN_ACTUAL_BYTES_SENT", + (SHValueType) stats[idx].valueOverLastSecond[ACTUAL_BYTES_SENT], + curTime, false); + + statistics.AddValueByIndex(objectIndex, + "RN_USER_MESSAGE_BYTES_RESENT", + (SHValueType) stats[idx].valueOverLastSecond[USER_MESSAGE_BYTES_RESENT], + curTime, false); + + statistics.AddValueByIndex(objectIndex, + "RN_ACTUAL_BYTES_RECEIVED", + (SHValueType) stats[idx].valueOverLastSecond[ACTUAL_BYTES_RECEIVED], + curTime, false); + + statistics.AddValueByIndex(objectIndex, + "RN_USER_MESSAGE_BYTES_PUSHED", + (SHValueType) stats[idx].valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], + curTime, false); + + statistics.AddValueByIndex(objectIndex, + "RN_USER_MESSAGE_BYTES_RECEIVED_PROCESSED", + (SHValueType) stats[idx].valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], + curTime, false); + + statistics.AddValueByIndex(objectIndex, + "RN_lastPing", + (SHValueType) rakPeerInterface->GetLastPing(guids[idx]), + curTime, false); + + statistics.AddValueByIndex(objectIndex, + "RN_bytesInResendBuffer", + (SHValueType) stats[idx].bytesInResendBuffer, + curTime, false); + + statistics.AddValueByIndex(objectIndex, + "RN_packetlossLastSecond", + (SHValueType) stats[idx].packetlossLastSecond, + curTime, false); + } + + } + + /* + RakNetStatistics rns; + DataStructures::List addresses; + DataStructures::List guids; + rakPeerInterface->GetSystemList(addresses, guids); + for (unsigned int idx = 0; idx < guids.Size(); idx++) + { + rakPeerInterface->GetStatistics(remoteSystems[idx], &rns); + statistics.AddValue(); + + bool AddValue(uint64_t objectId, RakString key, SHValueType val, Time curTime); + + } + */ +} +/* +void StatisticsHistoryPlugin::OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) +{ + // Would have to use GetGuidFromSystemAddress for every send +} +void StatisticsHistoryPlugin::OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress) +{ +} +*/ +void StatisticsHistoryPlugin::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + + if (removeLostConnections) + { + statistics.RemoveObject(rakNetGUID.g, 0); + } +} +void StatisticsHistoryPlugin::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) systemAddress; + (void) isIncoming; + + if (addNewConnections) + { + statistics.AddObject(StatisticsHistory::TrackedObjectData(rakNetGUID.g, newConnectionsObjectType, 0)); + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +#endif // _RAKNET_SUPPORT_StatisticsHistory==1 diff --git a/src/raknet/StringCompressor.cpp b/src/raknet/StringCompressor.cpp new file mode 100644 index 0000000..e21759d --- /dev/null +++ b/src/raknet/StringCompressor.cpp @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +/// \file +/// + + + +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/DS_HuffmanEncodingTree.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/RakString.hpp" +#include "include/raknet/RakAssert.hpp" +#include + +#include + + + + + + + +using namespace RakNet; + +StringCompressor* StringCompressor::instance=0; +int StringCompressor::referenceCount=0; + +void StringCompressor::AddReference(void) +{ + if (++referenceCount==1) + { + instance = RakNet::OP_NEW( _FILE_AND_LINE_ ); + } +} +void StringCompressor::RemoveReference(void) +{ + RakAssert(referenceCount > 0); + + if (referenceCount > 0) + { + if (--referenceCount==0) + { + RakNet::OP_DELETE(instance, _FILE_AND_LINE_); + instance=0; + } + } +} + +StringCompressor* StringCompressor::Instance(void) +{ + return instance; +} + +unsigned int englishCharacterFrequencies[ 256 ] = +{ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 722, + 0, + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 11084, + 58, + 63, + 1, + 0, + 31, + 0, + 317, + 64, + 64, + 44, + 0, + 695, + 62, + 980, + 266, + 69, + 67, + 56, + 7, + 73, + 3, + 14, + 2, + 69, + 1, + 167, + 9, + 1, + 2, + 25, + 94, + 0, + 195, + 139, + 34, + 96, + 48, + 103, + 56, + 125, + 653, + 21, + 5, + 23, + 64, + 85, + 44, + 34, + 7, + 92, + 76, + 147, + 12, + 14, + 57, + 15, + 39, + 15, + 1, + 1, + 1, + 2, + 3, + 0, + 3611, + 845, + 1077, + 1884, + 5870, + 841, + 1057, + 2501, + 3212, + 164, + 531, + 2019, + 1330, + 3056, + 4037, + 848, + 47, + 2586, + 2919, + 4771, + 1707, + 535, + 1106, + 152, + 1243, + 100, + 0, + 2, + 0, + 10, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 +}; + +StringCompressor::StringCompressor() +{ + DataStructures::Map::IMPLEMENT_DEFAULT_COMPARISON(); + + // Make a default tree immediately, since this is used for RPC possibly from multiple threads at the same time + HuffmanEncodingTree *huffmanEncodingTree = RakNet::OP_NEW( _FILE_AND_LINE_ ); + huffmanEncodingTree->GenerateFromFrequencyTable( englishCharacterFrequencies ); + + huffmanEncodingTrees.Set(0, huffmanEncodingTree); +} +void StringCompressor::GenerateTreeFromStrings( unsigned char *input, unsigned inputLength, uint8_t languageId ) +{ + HuffmanEncodingTree *huffmanEncodingTree; + if (huffmanEncodingTrees.Has(languageId)) + { + huffmanEncodingTree = huffmanEncodingTrees.Get(languageId); + RakNet::OP_DELETE(huffmanEncodingTree, _FILE_AND_LINE_); + } + + unsigned index; + unsigned int frequencyTable[ 256 ]; + + if ( inputLength == 0 ) + return ; + + // Zero out the frequency table + memset( frequencyTable, 0, sizeof( frequencyTable ) ); + + // Generate the frequency table from the strings + for ( index = 0; index < inputLength; index++ ) + frequencyTable[ input[ index ] ] ++; + + // Build the tree + huffmanEncodingTree = RakNet::OP_NEW( _FILE_AND_LINE_ ); + huffmanEncodingTree->GenerateFromFrequencyTable( frequencyTable ); + huffmanEncodingTrees.Set(languageId, huffmanEncodingTree); +} + +StringCompressor::~StringCompressor() +{ + for (unsigned i=0; i < huffmanEncodingTrees.Size(); i++) + RakNet::OP_DELETE(huffmanEncodingTrees[i], _FILE_AND_LINE_); +} + +void StringCompressor::EncodeString( const char *input, int maxCharsToWrite, RakNet::BitStream *output, uint8_t languageId ) +{ + HuffmanEncodingTree *huffmanEncodingTree; + if (huffmanEncodingTrees.Has(languageId)==false) + return; + huffmanEncodingTree=huffmanEncodingTrees.Get(languageId); + + if ( input == 0 ) + { + output->WriteCompressed( (uint32_t) 0 ); + return ; + } + + RakNet::BitStream encodedBitStream; + + uint32_t stringBitLength; + + int charsToWrite; + + if ( maxCharsToWrite<=0 || ( int ) strlen( input ) < maxCharsToWrite ) + charsToWrite = ( int ) strlen( input ); + else + charsToWrite = maxCharsToWrite - 1; + + huffmanEncodingTree->EncodeArray( ( unsigned char* ) input, charsToWrite, &encodedBitStream ); + + stringBitLength = (uint32_t) encodedBitStream.GetNumberOfBitsUsed(); + + output->WriteCompressed( stringBitLength ); + + output->WriteBits( encodedBitStream.GetData(), stringBitLength ); +} + +bool StringCompressor::DecodeString( char *output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId ) +{ + HuffmanEncodingTree *huffmanEncodingTree; + if (huffmanEncodingTrees.Has(languageId)==false) + return false; + if (maxCharsToWrite<=0) + return false; + huffmanEncodingTree=huffmanEncodingTrees.Get(languageId); + + uint32_t stringBitLength; + int bytesInStream; + + output[ 0 ] = 0; + + if ( input->ReadCompressed( stringBitLength ) == false ) + return false; + + if ( (unsigned) input->GetNumberOfUnreadBits() < stringBitLength ) + return false; + + bytesInStream = huffmanEncodingTree->DecodeArray( input, stringBitLength, maxCharsToWrite, ( unsigned char* ) output ); + + if ( bytesInStream < maxCharsToWrite ) + output[ bytesInStream ] = 0; + else + output[ maxCharsToWrite - 1 ] = 0; + + return true; +} +#ifdef _CSTRING_COMPRESSOR +void StringCompressor::EncodeString( const CString &input, int maxCharsToWrite, RakNet::BitStream *output ) +{ + LPTSTR p = input; + EncodeString(p, maxCharsToWrite*sizeof(TCHAR), output, languageID); +} +bool StringCompressor::DecodeString( CString &output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId ) +{ + LPSTR p = output.GetBuffer(maxCharsToWrite*sizeof(TCHAR)); + DecodeString(p,maxCharsToWrite*sizeof(TCHAR), input, languageID); + output.ReleaseBuffer(0) + +} +#endif +#ifdef _STD_STRING_COMPRESSOR +void StringCompressor::EncodeString( const std::string &input, int maxCharsToWrite, RakNet::BitStream *output, uint8_t languageId ) +{ + EncodeString(input.c_str(), maxCharsToWrite, output, languageId); +} +bool StringCompressor::DecodeString( std::string *output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId ) +{ + if (maxCharsToWrite <= 0) + { + output->clear(); + return true; + } + + char *destinationBlock; + bool out; + +#if USE_ALLOCA==1 + if (maxCharsToWrite < MAX_ALLOCA_STACK_ALLOCATION) + { + destinationBlock = (char*) alloca(maxCharsToWrite); + out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); + *output=destinationBlock; + } + else +#endif + { + destinationBlock = (char*) rakMalloc_Ex( maxCharsToWrite, _FILE_AND_LINE_ ); + out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); + *output=destinationBlock; + rakFree_Ex(destinationBlock, _FILE_AND_LINE_ ); + } + + return out; +} +#endif +void StringCompressor::EncodeString( const RakString *input, int maxCharsToWrite, RakNet::BitStream *output, uint8_t languageId ) +{ + EncodeString(input->C_String(), maxCharsToWrite, output, languageId); +} +bool StringCompressor::DecodeString( RakString *output, int maxCharsToWrite, RakNet::BitStream *input, uint8_t languageId ) +{ + if (maxCharsToWrite <= 0) + { + output->Clear(); + return true; + } + + char *destinationBlock; + bool out; + +#if USE_ALLOCA==1 + if (maxCharsToWrite < MAX_ALLOCA_STACK_ALLOCATION) + { + destinationBlock = (char*) alloca(maxCharsToWrite); + out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); + *output=destinationBlock; + } + else +#endif + { + destinationBlock = (char*) rakMalloc_Ex( maxCharsToWrite, _FILE_AND_LINE_ ); + out=DecodeString(destinationBlock, maxCharsToWrite, input, languageId); + *output=destinationBlock; + rakFree_Ex(destinationBlock, _FILE_AND_LINE_ ); + } + + return out; +} diff --git a/src/raknet/StringTable.cpp b/src/raknet/StringTable.cpp new file mode 100644 index 0000000..92daae2 --- /dev/null +++ b/src/raknet/StringTable.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/StringTable.hpp" +#include +#include "include/raknet/RakAssert.hpp" +#include +#include "include/raknet/BitStream.hpp" +#include "include/raknet/StringCompressor.hpp" +using namespace RakNet; + +StringTable* StringTable::instance=0; +int StringTable::referenceCount=0; + + +int RakNet::StrAndBoolComp( char *const &key, const StrAndBool &data ) +{ + return strcmp(key,(const char*)data.str); +} + +StringTable::StringTable() +{ + +} + +StringTable::~StringTable() +{ + unsigned i; + for (i=0; i < orderedStringList.Size(); i++) + { + if (orderedStringList[i].b) + rakFree_Ex(orderedStringList[i].str, _FILE_AND_LINE_ ); + } +} + +void StringTable::AddReference(void) +{ + if (++referenceCount==1) + { + instance = RakNet::OP_NEW( _FILE_AND_LINE_ ); + } +} +void StringTable::RemoveReference(void) +{ + RakAssert(referenceCount > 0); + + if (referenceCount > 0) + { + if (--referenceCount==0) + { + RakNet::OP_DELETE(instance, _FILE_AND_LINE_); + instance=0; + } + } +} + +StringTable* StringTable::Instance(void) +{ + return instance; +} + +void StringTable::AddString(const char *str, bool copyString) +{ + StrAndBool sab; + sab.b=copyString; + if (copyString) + { + sab.str = (char*) rakMalloc_Ex( strlen(str)+1, _FILE_AND_LINE_ ); + strcpy(sab.str, str); + } + else + { + sab.str=(char*)str; + } + + // If it asserts inside here you are adding duplicate strings. + orderedStringList.Insert(sab.str,sab, true, _FILE_AND_LINE_); + + // If this assert hits you need to increase the range of StringTableType + RakAssert(orderedStringList.Size() < (StringTableType)-1); + +} +void StringTable::EncodeString( const char *input, int maxCharsToWrite, RakNet::BitStream *output ) +{ + unsigned index; + bool objectExists; + // This is fast because the list is kept ordered. + index=orderedStringList.GetIndexFromKey((char*)input, &objectExists); + if (objectExists) + { + output->Write(true); + output->Write((StringTableType)index); + } + else + { + LogStringNotFound(input); + output->Write(false); + StringCompressor::Instance()->EncodeString(input, maxCharsToWrite, output); + } +} + +bool StringTable::DecodeString( char *output, int maxCharsToWrite, RakNet::BitStream *input ) +{ + bool hasIndex=false; + RakAssert(maxCharsToWrite>0); + + if (maxCharsToWrite==0) + return false; + if (!input->Read(hasIndex)) + return false; + if (hasIndex==false) + { + StringCompressor::Instance()->DecodeString(output, maxCharsToWrite, input); + } + else + { + StringTableType index; + if (!input->Read(index)) + return false; + if (index >= orderedStringList.Size()) + { +#ifdef _DEBUG + // Critical error - got a string index out of range, which means AddString was called more times on the remote system than on this system. + // All systems must call AddString the same number of types, with the same strings in the same order. + RakAssert(0); +#endif + return false; + } + + strncpy(output, orderedStringList[index].str, maxCharsToWrite); + output[maxCharsToWrite-1]=0; + } + + return true; +} +void StringTable::LogStringNotFound(const char *strName) +{ + (void) strName; + +#ifdef _DEBUG + RAKNET_DEBUG_PRINTF("Efficiency Warning! Unregistered String %s sent to StringTable.\n", strName); +#endif +} diff --git a/src/raknet/SuperFastHash.cpp b/src/raknet/SuperFastHash.cpp new file mode 100644 index 0000000..a3abe22 --- /dev/null +++ b/src/raknet/SuperFastHash.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/SuperFastHash.hpp" +#include "include/raknet/NativeTypes.hpp" +#include + +#if !defined(_WIN32) +#include +#endif + +#undef get16bits + +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *) (d))) +#else +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif + +static const int INCREMENTAL_READ_BLOCK=65536; + +uint32_t SuperFastHash (const char * data, int length) +{ + // All this is necessary or the hash does not match SuperFastHashIncremental + int bytesRemaining=length; + unsigned int lastHash = length; + int offset=0; + while (bytesRemaining>=INCREMENTAL_READ_BLOCK) + { + lastHash=SuperFastHashIncremental (data+offset, INCREMENTAL_READ_BLOCK, lastHash ); + bytesRemaining-=INCREMENTAL_READ_BLOCK; + offset+=INCREMENTAL_READ_BLOCK; + } + if (bytesRemaining>0) + { + lastHash=SuperFastHashIncremental (data+offset, bytesRemaining, lastHash ); + } + return lastHash; + +// return SuperFastHashIncremental(data,len,len); +} +uint32_t SuperFastHashIncremental (const char * data, int len, unsigned int lastHash ) +{ + uint32_t hash = (uint32_t) lastHash; + uint32_t tmp; + int rem; + + if (len <= 0 || data == NULL) return 0; + + rem = len & 3; + len >>= 2; + + /* Main loop */ + for (;len > 0; len--) { + hash += get16bits (data); + tmp = (get16bits (data+2) << 11) ^ hash; + hash = (hash << 16) ^ tmp; + data += 2*sizeof (uint16_t); + hash += hash >> 11; + } + + /* Handle end cases */ + switch (rem) { + case 3: hash += get16bits (data); + hash ^= hash << 16; + hash ^= data[sizeof (uint16_t)] << 18; + hash += hash >> 11; + break; + case 2: hash += get16bits (data); + hash ^= hash << 11; + hash += hash >> 17; + break; + case 1: hash += *data; + hash ^= hash << 10; + hash += hash >> 1; + } + + /* Force "avalanching" of final 127 bits */ + hash ^= hash << 3; + hash += hash >> 5; + hash ^= hash << 4; + hash += hash >> 17; + hash ^= hash << 25; + hash += hash >> 6; + + return (uint32_t) hash; + +} + +uint32_t SuperFastHashFile (const char * filename) +{ + FILE *fp = fopen(filename, "rb"); + if (fp==0) + return 0; + uint32_t hash = SuperFastHashFilePtr(fp); + fclose(fp); + return hash; +} + +uint32_t SuperFastHashFilePtr (FILE *fp) +{ + fseek(fp, 0, SEEK_END); + int length = ftell(fp); + fseek(fp, 0, SEEK_SET); + int bytesRemaining=length; + unsigned int lastHash = length; + char readBlock[INCREMENTAL_READ_BLOCK]; + while (bytesRemaining>=(int) sizeof(readBlock)) + { + fread(readBlock, sizeof(readBlock), 1, fp); + lastHash=SuperFastHashIncremental (readBlock, (int) sizeof(readBlock), lastHash ); + bytesRemaining-=(int) sizeof(readBlock); + } + if (bytesRemaining>0) + { + fread(readBlock, bytesRemaining, 1, fp); + lastHash=SuperFastHashIncremental (readBlock, bytesRemaining, lastHash ); + } + return lastHash; +} diff --git a/src/raknet/TCPInterface.cpp b/src/raknet/TCPInterface.cpp new file mode 100644 index 0000000..915df42 --- /dev/null +++ b/src/raknet/TCPInterface.cpp @@ -0,0 +1,1439 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TCPInterface==1 + +/// \file +/// \brief A simple TCP based server allowing sends and receives. Can be connected to by a telnet client. +/// + + + +#include "include/raknet/TCPInterface.hpp" +#ifdef _WIN32 + #if !defined (WINDOWS_STORE_RT) + typedef int socklen_t; + #endif + + +#else +#include +#include +#include +#endif +#include +#include "include/raknet/RakAssert.hpp" +#include +#include "include/raknet/RakAssert.hpp" +#include "include/raknet/RakSleep.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/StringTable.hpp" +#include "include/raknet/Itoa.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/SocketDefines.hpp" +#if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(__WIN32__) +#include +#endif + +#ifdef _DO_PRINTF +#endif + +#ifdef _WIN32 +#include "include/raknet/WSAStartupSingleton.hpp" +#endif +namespace RakNet +{ +RAK_THREAD_DECLARATION(UpdateTCPInterfaceLoop); +RAK_THREAD_DECLARATION(ConnectionAttemptLoop); +} +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(TCPInterface,TCPInterface); + +TCPInterface::TCPInterface() +{ +#if !defined(WINDOWS_STORE_RT) + listenSocket=0; +#endif + remoteClients=0; + remoteClientsLength=0; + + StringCompressor::AddReference(); + RakNet::StringTable::AddReference(); + +#if OPEN_SSL_CLIENT_SUPPORT==1 + ctx=0; + meth=0; +#endif + +#ifdef _WIN32 + WSAStartupSingleton::AddRef(); +#endif +} +TCPInterface::~TCPInterface() +{ + Stop(); +#ifdef _WIN32 + WSAStartupSingleton::Deref(); +#endif + + RakNet::OP_DELETE_ARRAY(remoteClients,_FILE_AND_LINE_); + + StringCompressor::RemoveReference(); + RakNet::StringTable::RemoveReference(); +} +#if !defined(WINDOWS_STORE_RT) +bool TCPInterface::CreateListenSocket(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *bindAddress) +{ + (void) maxIncomingConnections; + (void) socketFamily; +#if RAKNET_SUPPORT_IPV6!=1 + listenSocket = socket__(AF_INET, SOCK_STREAM, 0); + if ((int)listenSocket ==-1) + return false; + + struct sockaddr_in serverAddress; + memset(&serverAddress,0,sizeof(sockaddr_in)); + serverAddress.sin_family = AF_INET; + if ( bindAddress && bindAddress[0] ) + { + + + + + + serverAddress.sin_addr.s_addr = inet_addr__(bindAddress ); + + } + else + serverAddress.sin_addr.s_addr = INADDR_ANY; + + serverAddress.sin_port = htons(port); + + SocketLayer::SetSocketOptions(listenSocket, false, false); + + if (bind__(listenSocket,(struct sockaddr *) &serverAddress,sizeof(serverAddress)) < 0) + return false; + + listen__(listenSocket, maxIncomingConnections); +#else + struct addrinfo hints; + memset(&hints, 0, sizeof (addrinfo)); // make sure the struct is empty + hints.ai_family = socketFamily; // don't care IPv4 or IPv6 + hints.ai_socktype = SOCK_STREAM; // TCP sockets + hints.ai_flags = AI_PASSIVE; // fill in my IP for me + struct addrinfo *servinfo=0, *aip; // will point to the results + char portStr[32]; + Itoa(port,portStr,10); + + getaddrinfo(0, portStr, &hints, &servinfo); + for (aip = servinfo; aip != NULL; aip = aip->ai_next) + { + // Open socket. The address type depends on what + // getaddrinfo() gave us. + listenSocket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol); + if (listenSocket != 0) + { + int ret = bind__( listenSocket, aip->ai_addr, (int) aip->ai_addrlen ); + if (ret>=0) + { + break; + } + else + { + closesocket__(listenSocket); + listenSocket=0; + } + } + } + + if (listenSocket==0) + return false; + + SocketLayer::SetSocketOptions(listenSocket, false, false); + + listen__(listenSocket, maxIncomingConnections); +#endif // #if RAKNET_SUPPORT_IPV6!=1 + + return true; +} +#endif + +#if defined(WINDOWS_STORE_RT) +bool TCPInterface::CreateListenSocket_WinStore8(unsigned short port, unsigned short maxIncomingConnections, unsigned short socketFamily, const char *bindAddress) +{ + listenSocket = WinRTCreateStreamSocket(AF_INET, SOCK_STREAM, 0); + return true; +} +#endif +bool TCPInterface::Start(unsigned short port, unsigned short maxIncomingConnections, unsigned short maxConnections, int _threadPriority, unsigned short socketFamily, const char *bindAddress) +{ +#ifdef __native_client__ + return false; +#else + (void) socketFamily; + + if (isStarted.GetValue()>0) + return false; + + threadPriority=_threadPriority; + + if (threadPriority==-99999) + { + + +#if defined(_WIN32) + threadPriority=0; + + +#else + threadPriority=1000; +#endif + } + + isStarted.Increment(); + if (maxConnections==0) + maxConnections=maxIncomingConnections; + if (maxConnections==0) + maxConnections=1; + remoteClientsLength=maxConnections; + remoteClients=RakNet::OP_NEW_ARRAY(maxConnections,_FILE_AND_LINE_); + + + listenSocket=0; + if (maxIncomingConnections>0) + { +#if defined(WINDOWS_STORE_RT) + CreateListenSocket_WinStore8(port, maxIncomingConnections, socketFamily, bindAddress); +#else + CreateListenSocket(port, maxIncomingConnections, socketFamily, bindAddress); +#endif + } + + + // Start the update thread + int errorCode; + + + + + + errorCode = RakNet::RakThread::Create(UpdateTCPInterfaceLoop, this, threadPriority); + + + if (errorCode!=0) + return false; + + while (threadRunning.GetValue()==0) + RakSleep(0); + + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + messageHandlerList[i]->OnRakPeerStartup(); + + return true; +#endif // __native_client__ +} +void TCPInterface::Stop(void) +{ + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + messageHandlerList[i]->OnRakPeerShutdown(); + +#ifndef __native_client__ + if (isStarted.GetValue()==0) + return; + +#if OPEN_SSL_CLIENT_SUPPORT==1 + for (i=0; i < remoteClientsLength; i++) + remoteClients[i].DisconnectSSL(); +#endif + + isStarted.Decrement(); + +#if !defined(WINDOWS_STORE_RT) + if (listenSocket!=0) +#endif + { +#ifdef _WIN32 + shutdown__(listenSocket, SD_BOTH); + +#else + shutdown__(listenSocket, SHUT_RDWR); +#endif + closesocket__(listenSocket); + } + + // Abort waiting connect calls + blockingSocketListMutex.Lock(); + for (i=0; i < blockingSocketList.Size(); i++) + { + closesocket__(blockingSocketList[i]); + } + blockingSocketListMutex.Unlock(); + + // Wait for the thread to stop + while ( threadRunning.GetValue()>0 ) + RakSleep(15); + + RakSleep(100); + + #if !defined(WINDOWS_STORE_RT) + listenSocket=0; + #endif + + // Stuff from here on to the end of the function is not threadsafe + for (i=0; i < (unsigned int) remoteClientsLength; i++) + { + closesocket__(remoteClients[i].socket); +#if OPEN_SSL_CLIENT_SUPPORT==1 + remoteClients[i].FreeSSL(); +#endif + } + remoteClientsLength=0; + RakNet::OP_DELETE_ARRAY(remoteClients,_FILE_AND_LINE_); + remoteClients=0; + + incomingMessages.Clear(_FILE_AND_LINE_); + newIncomingConnections.Clear(_FILE_AND_LINE_); + newRemoteClients.Clear(_FILE_AND_LINE_); + lostConnections.Clear(_FILE_AND_LINE_); + requestedCloseConnections.Clear(_FILE_AND_LINE_); + failedConnectionAttempts.Clear(_FILE_AND_LINE_); + completedConnectionAttempts.Clear(_FILE_AND_LINE_); + failedConnectionAttempts.Clear(_FILE_AND_LINE_); + for (i=0; i < headPush.Size(); i++) + DeallocatePacket(headPush[i]); + headPush.Clear(_FILE_AND_LINE_); + for (i=0; i < tailPush.Size(); i++) + DeallocatePacket(tailPush[i]); + tailPush.Clear(_FILE_AND_LINE_); + +#if OPEN_SSL_CLIENT_SUPPORT==1 + SSL_CTX_free (ctx); + startSSL.Clear(_FILE_AND_LINE_); + activeSSLConnections.Clear(false, _FILE_AND_LINE_); +#endif + + + + + +#endif // __native_client__ +} +SystemAddress TCPInterface::Connect(const char* host, unsigned short remotePort, bool block, unsigned short socketFamily, const char *bindAddress) +{ + if (threadRunning.GetValue()==0) + return UNASSIGNED_SYSTEM_ADDRESS; + + int newRemoteClientIndex=-1; + for (newRemoteClientIndex=0; newRemoteClientIndex < remoteClientsLength; newRemoteClientIndex++) + { + remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); + if (remoteClients[newRemoteClientIndex].isActive==false) + { + remoteClients[newRemoteClientIndex].SetActive(true); + remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); + break; + } + remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); + } + if (newRemoteClientIndex==-1) + return UNASSIGNED_SYSTEM_ADDRESS; + + if (block) + { + SystemAddress systemAddress; + systemAddress.FromString(host); + systemAddress.SetPortHostOrder(remotePort); + systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex; + char buffout[128]; + systemAddress.ToString(false,buffout); + + __TCPSOCKET__ sockfd = SocketConnect(buffout, remotePort, socketFamily, bindAddress); + // Windows RT TODO +#if !defined(WINDOWS_STORE_RT) + if (sockfd==0) +#endif + { + remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); + remoteClients[newRemoteClientIndex].SetActive(false); + remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); + + failedConnectionAttemptMutex.Lock(); + failedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ ); + failedConnectionAttemptMutex.Unlock(); + + return UNASSIGNED_SYSTEM_ADDRESS; + } + + remoteClients[newRemoteClientIndex].socket=sockfd; + remoteClients[newRemoteClientIndex].systemAddress=systemAddress; + + completedConnectionAttemptMutex.Lock(); + completedConnectionAttempts.Push(remoteClients[newRemoteClientIndex].systemAddress, _FILE_AND_LINE_ ); + completedConnectionAttemptMutex.Unlock(); + + return remoteClients[newRemoteClientIndex].systemAddress; + } + else + { + ThisPtrPlusSysAddr *s = RakNet::OP_NEW( _FILE_AND_LINE_ ); + s->systemAddress.FromStringExplicitPort(host,remotePort); + s->systemAddress.systemIndex=(SystemIndex) newRemoteClientIndex; + if (bindAddress) + strcpy(s->bindAddress, bindAddress); + else + s->bindAddress[0]=0; + s->tcpInterface=this; + s->socketFamily=socketFamily; + + // Start the connection thread + int errorCode; + + + + + errorCode = RakNet::RakThread::Create(ConnectionAttemptLoop, s, threadPriority); + + if (errorCode!=0) + { + RakNet::OP_DELETE(s, _FILE_AND_LINE_); + failedConnectionAttempts.Push(s->systemAddress, _FILE_AND_LINE_ ); + } + return UNASSIGNED_SYSTEM_ADDRESS; + } +} +#if OPEN_SSL_CLIENT_SUPPORT==1 +void TCPInterface::StartSSLClient(SystemAddress systemAddress) +{ + if (ctx==0) + { + sharedSslMutex.Lock(); + SSLeay_add_ssl_algorithms(); + meth = (SSL_METHOD*) SSLv23_client_method(); + SSL_load_error_strings(); + ctx = SSL_CTX_new (meth); + RakAssert(ctx!=0); + sharedSslMutex.Unlock(); + } + + SystemAddress *id = startSSL.Allocate( _FILE_AND_LINE_ ); + *id=systemAddress; + startSSL.Push(id); + unsigned index = activeSSLConnections.GetIndexOf(systemAddress); + if (index==(unsigned)-1) + activeSSLConnections.Insert(systemAddress,_FILE_AND_LINE_); +} +bool TCPInterface::IsSSLActive(SystemAddress systemAddress) +{ + return activeSSLConnections.GetIndexOf(systemAddress)!=-1; +} +#endif +void TCPInterface::Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast ) +{ + SendList( &data, &length, 1, systemAddress,broadcast ); +} +bool TCPInterface::SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ) +{ + if (isStarted.GetValue()==0) + return false; + if (data==0) + return false; + if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS && broadcast==false) + return false; + unsigned int totalLength=0; + int i; + for (i=0; i < numParameters; i++) + { + if (lengths[i]>0) + totalLength+=lengths[i]; + } + if (totalLength==0) + return false; + + if (broadcast) + { + // Send to all, possible exception system + for (i=0; i < remoteClientsLength; i++) + { + if (remoteClients[i].systemAddress!=systemAddress) + { + remoteClients[i].SendOrBuffer(data, lengths, numParameters); + } + } + } + else + { + // Send to this player + if (systemAddress.systemIndexUpdate(); + + Packet* outgoingPacket = ReceiveInt(); + + if (outgoingPacket) + { + PluginReceiveResult pluginResult; + for (i=0; i < messageHandlerList.Size(); i++) + { + pluginResult=messageHandlerList[i]->OnReceive(outgoingPacket); + if (pluginResult==RR_STOP_PROCESSING_AND_DEALLOCATE) + { + DeallocatePacket( outgoingPacket ); + outgoingPacket=0; // Will do the loop again and get another packet + break; // break out of the enclosing for + } + else if (pluginResult==RR_STOP_PROCESSING) + { + outgoingPacket=0; + break; + } + } + } + + + return outgoingPacket; +} +Packet* TCPInterface::ReceiveInt( void ) +{ + if (isStarted.GetValue()==0) + return 0; + if (headPush.IsEmpty()==false) + return headPush.Pop(); + Packet *p = incomingMessages.PopInaccurate(); + if (p) + return p; + if (tailPush.IsEmpty()==false) + return tailPush.Pop(); + return 0; +} + + +void TCPInterface::AttachPlugin( PluginInterface2 *plugin ) +{ + if (messageHandlerList.GetIndexOf(plugin)==MAX_UNSIGNED_LONG) + { + messageHandlerList.Insert(plugin, _FILE_AND_LINE_); + plugin->SetTCPInterface(this); + plugin->OnAttach(); + } +} +void TCPInterface::DetachPlugin( PluginInterface2 *plugin ) +{ + if (plugin==0) + return; + + unsigned int index; + index = messageHandlerList.GetIndexOf(plugin); + if (index!=MAX_UNSIGNED_LONG) + { + messageHandlerList[index]->OnDetach(); + // Unordered list so delete from end for speed + messageHandlerList[index]=messageHandlerList[messageHandlerList.Size()-1]; + messageHandlerList.RemoveFromEnd(); + plugin->SetTCPInterface(0); + } +} +void TCPInterface::CloseConnection( SystemAddress systemAddress ) +{ + if (isStarted.GetValue()==0) + return; + if (systemAddress==UNASSIGNED_SYSTEM_ADDRESS) + return; + + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + messageHandlerList[i]->OnClosedConnection(systemAddress, UNASSIGNED_RAKNET_GUID, LCR_CLOSED_BY_USER); + + if (systemAddress.systemIndexdeleteData) + { + rakFree_Ex(packet->data, _FILE_AND_LINE_ ); + incomingMessages.Deallocate(packet, _FILE_AND_LINE_); + } + else + { + // Came from userspace AllocatePacket + rakFree_Ex(packet->data, _FILE_AND_LINE_ ); + RakNet::OP_DELETE(packet, _FILE_AND_LINE_); + } +} +Packet* TCPInterface::AllocatePacket(unsigned dataSize) +{ + Packet*p = RakNet::OP_NEW(_FILE_AND_LINE_); + p->data=(unsigned char*) rakMalloc_Ex(dataSize,_FILE_AND_LINE_); + p->length=dataSize; + p->bitSize=BYTES_TO_BITS(dataSize); + p->deleteData=false; + p->guid=UNASSIGNED_RAKNET_GUID; + p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + p->systemAddress.systemIndex=(SystemIndex)-1; + return p; +} +void TCPInterface::PushBackPacket( Packet *packet, bool pushAtHead ) +{ + if (pushAtHead) + headPush.Push(packet, _FILE_AND_LINE_ ); + else + tailPush.Push(packet, _FILE_AND_LINE_ ); +} +bool TCPInterface::WasStarted(void) const +{ + return threadRunning.GetValue()>0; +} +SystemAddress TCPInterface::HasCompletedConnectionAttempt(void) +{ + SystemAddress sysAddr=UNASSIGNED_SYSTEM_ADDRESS; + completedConnectionAttemptMutex.Lock(); + if (completedConnectionAttempts.IsEmpty()==false) + sysAddr=completedConnectionAttempts.Pop(); + completedConnectionAttemptMutex.Unlock(); + + if (sysAddr!=UNASSIGNED_SYSTEM_ADDRESS) + { + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + messageHandlerList[i]->OnNewConnection(sysAddr, UNASSIGNED_RAKNET_GUID, true); + } + + return sysAddr; +} +SystemAddress TCPInterface::HasFailedConnectionAttempt(void) +{ + SystemAddress sysAddr=UNASSIGNED_SYSTEM_ADDRESS; + failedConnectionAttemptMutex.Lock(); + if (failedConnectionAttempts.IsEmpty()==false) + sysAddr=failedConnectionAttempts.Pop(); + failedConnectionAttemptMutex.Unlock(); + + if (sysAddr!=UNASSIGNED_SYSTEM_ADDRESS) + { + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + { + Packet p; + p.systemAddress=sysAddr; + p.data=0; + p.length=0; + p.bitSize=0; + messageHandlerList[i]->OnFailedConnectionAttempt(&p, FCAR_CONNECTION_ATTEMPT_FAILED); + } + } + + return sysAddr; +} +SystemAddress TCPInterface::HasNewIncomingConnection(void) +{ + SystemAddress *out, out2; + out = newIncomingConnections.PopInaccurate(); + if (out) + { + out2=*out; + newIncomingConnections.Deallocate(out, _FILE_AND_LINE_); + + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + messageHandlerList[i]->OnNewConnection(out2, UNASSIGNED_RAKNET_GUID, true); + + return *out; + } + else + { + return UNASSIGNED_SYSTEM_ADDRESS; + } +} +SystemAddress TCPInterface::HasLostConnection(void) +{ + SystemAddress *out, out2; + out = lostConnections.PopInaccurate(); + if (out) + { + out2=*out; + lostConnections.Deallocate(out, _FILE_AND_LINE_); + + unsigned int i; + for (i=0; i < messageHandlerList.Size(); i++) + messageHandlerList[i]->OnClosedConnection(out2, UNASSIGNED_RAKNET_GUID, LCR_DISCONNECTION_NOTIFICATION); + + return *out; + } + else + { + return UNASSIGNED_SYSTEM_ADDRESS; + } +} +void TCPInterface::GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const +{ + unsigned short systemCount=0; + unsigned short maxToWrite=*numberOfSystems; + for (int i=0; i < remoteClientsLength; i++) + { + if (remoteClients[i].isActive) + { + if (systemCount < maxToWrite) + remoteSystems[systemCount]=remoteClients[i].systemAddress; + systemCount++; + } + } + *numberOfSystems=systemCount; +} +unsigned short TCPInterface::GetConnectionCount(void) const +{ + unsigned short systemCount=0; + for (int i=0; i < remoteClientsLength; i++) + { + if (remoteClients[i].isActive) + systemCount++; + } + return systemCount; +} + +unsigned int TCPInterface::GetOutgoingDataBufferSize(SystemAddress systemAddress) const +{ + unsigned bytesWritten=0; + if (systemAddress.systemIndexh_addr, server->h_length); + + + + + + + + + + + blockingSocketListMutex.Lock(); + blockingSocketList.Insert(sockfd, _FILE_AND_LINE_); + blockingSocketListMutex.Unlock(); + + // This is blocking + connectResult = connect__( sockfd, ( struct sockaddr * ) &serverAddress, sizeof( struct sockaddr ) ); + +#else + + + struct addrinfo hints, *res; + int sockfd; + memset(&hints, 0, sizeof hints); + hints.ai_family = socketFamily; + hints.ai_socktype = SOCK_STREAM; + char portStr[32]; + Itoa(remotePort,portStr,10); + getaddrinfo(host, portStr, &hints, &res); + sockfd = socket__(res->ai_family, res->ai_socktype, res->ai_protocol); + blockingSocketListMutex.Lock(); + blockingSocketList.Insert(sockfd, _FILE_AND_LINE_); + blockingSocketListMutex.Unlock(); + connectResult=connect__(sockfd, res->ai_addr, res->ai_addrlen); + freeaddrinfo(res); // free the linked-list + +#endif // #if RAKNET_SUPPORT_IPV6!=1 + + if (connectResult==-1) + { + unsigned sockfdIndex; + blockingSocketListMutex.Lock(); + sockfdIndex=blockingSocketList.GetIndexOf(sockfd); + if (sockfdIndex!=(unsigned)-1) + blockingSocketList.RemoveAtIndexFast(sockfdIndex); + blockingSocketListMutex.Unlock(); + + closesocket__(sockfd); + return 0; + } + + return sockfd; +#endif // __native_client__ +} + +RAK_THREAD_DECLARATION(RakNet::ConnectionAttemptLoop) +{ + + + + TCPInterface::ThisPtrPlusSysAddr *s = (TCPInterface::ThisPtrPlusSysAddr *) arguments; + + + + SystemAddress systemAddress = s->systemAddress; + TCPInterface *tcpInterface = s->tcpInterface; + int newRemoteClientIndex=systemAddress.systemIndex; + unsigned short socketFamily = s->socketFamily; + RakNet::OP_DELETE(s, _FILE_AND_LINE_); + + char str1[64]; + systemAddress.ToString(false, str1); + __TCPSOCKET__ sockfd = tcpInterface->SocketConnect(str1, systemAddress.GetPort(), socketFamily, s->bindAddress); + if (sockfd==0) + { + tcpInterface->remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); + tcpInterface->remoteClients[newRemoteClientIndex].SetActive(false); + tcpInterface->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); + + tcpInterface->failedConnectionAttemptMutex.Lock(); + tcpInterface->failedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ ); + tcpInterface->failedConnectionAttemptMutex.Unlock(); + return 0; + } + + tcpInterface->remoteClients[newRemoteClientIndex].socket=sockfd; + tcpInterface->remoteClients[newRemoteClientIndex].systemAddress=systemAddress; + + // Notify user that the connection attempt has completed. + if (tcpInterface->threadRunning.GetValue()>0) + { + tcpInterface->completedConnectionAttemptMutex.Lock(); + tcpInterface->completedConnectionAttempts.Push(systemAddress, _FILE_AND_LINE_ ); + tcpInterface->completedConnectionAttemptMutex.Unlock(); + } + + + + + return 0; + +} + +RAK_THREAD_DECLARATION(RakNet::UpdateTCPInterfaceLoop) +{ + + + + TCPInterface * sts = ( TCPInterface * ) arguments; + + +// const int BUFF_SIZE=8096; + const unsigned int BUFF_SIZE=1048576; + //char data[ BUFF_SIZE ]; + char * data = (char*) rakMalloc_Ex(BUFF_SIZE,_FILE_AND_LINE_); + Packet *incomingMessage; + fd_set readFD, exceptionFD, writeFD; + sts->threadRunning.Increment(); + +#if RAKNET_SUPPORT_IPV6!=1 + sockaddr_in sockAddr; + int sockAddrSize = sizeof(sockAddr); +#else + struct sockaddr_storage sockAddr; + socklen_t sockAddrSize = sizeof(sockAddr); +#endif + + int len; + __TCPSOCKET__ newSock; + int selectResult; + + + timeval tv; + tv.tv_sec=0; + tv.tv_usec=30000; + + + while (sts->isStarted.GetValue()>0) + { +#if OPEN_SSL_CLIENT_SUPPORT==1 + SystemAddress *sslSystemAddress; + sslSystemAddress = sts->startSSL.PopInaccurate(); + if (sslSystemAddress) + { + if (sslSystemAddress->systemIndex>=0 && + sslSystemAddress->systemIndexremoteClientsLength && + sts->remoteClients[sslSystemAddress->systemIndex].systemAddress==*sslSystemAddress) + { + sts->remoteClients[sslSystemAddress->systemIndex].InitSSL(sts->ctx,sts->meth); + } + else + { + for (int i=0; i < sts->remoteClientsLength; i++) + { + sts->remoteClients[i].isActiveMutex.Lock(); + if (sts->remoteClients[i].isActive && sts->remoteClients[i].systemAddress==*sslSystemAddress) + { + if (sts->remoteClients[i].ssl==0) + sts->remoteClients[i].InitSSL(sts->ctx,sts->meth); + } + sts->remoteClients[i].isActiveMutex.Unlock(); + } + } + sts->startSSL.Deallocate(sslSystemAddress,_FILE_AND_LINE_); + } +#endif + + + __TCPSOCKET__ largestDescriptor=0; // see select__()'s first parameter's documentation under linux + + + // Linux' select__() implementation changes the timeout + + tv.tv_sec=0; + tv.tv_usec=30000; + + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + // Reset readFD, writeFD, and exceptionFD since select seems to clear it + FD_ZERO(&readFD); + FD_ZERO(&exceptionFD); + FD_ZERO(&writeFD); + largestDescriptor=0; + if (sts->listenSocket!=0) + { + FD_SET(sts->listenSocket, &readFD); + FD_SET(sts->listenSocket, &exceptionFD); + largestDescriptor = sts->listenSocket; // @see largestDescriptor def + } + + unsigned i; + for (i=0; i < (unsigned int) sts->remoteClientsLength; i++) + { + sts->remoteClients[i].isActiveMutex.Lock(); + if (sts->remoteClients[i].isActive) + { + // calling FD_ISSET with -1 as socket (that’s what 0 is set to) produces a bus error under Linux 64-Bit + __TCPSOCKET__ socketCopy = sts->remoteClients[i].socket; + if (socketCopy != 0) + { + FD_SET(socketCopy, &readFD); + FD_SET(socketCopy, &exceptionFD); + if (sts->remoteClients[i].outgoingData.GetBytesWritten()>0) + FD_SET(socketCopy, &writeFD); + if(socketCopy > largestDescriptor) // @see largestDescriptorDef + largestDescriptor = socketCopy; + } + } + sts->remoteClients[i].isActiveMutex.Unlock(); + } + +#ifdef _MSC_VER +#pragma warning( disable : 4244 ) // warning C4127: conditional expression is constant +#endif + + + selectResult=(int) select__(largestDescriptor+1, &readFD, &writeFD, &exceptionFD, &tv); + + + + + if (selectResult<=0) + break; + + if (sts->listenSocket!=0 && FD_ISSET(sts->listenSocket, &readFD)) + { + newSock = accept__(sts->listenSocket, (sockaddr*)&sockAddr, (socklen_t*)&sockAddrSize); + + if (newSock != 0) + { + int newRemoteClientIndex=-1; + for (newRemoteClientIndex=0; newRemoteClientIndex < sts->remoteClientsLength; newRemoteClientIndex++) + { + sts->remoteClients[newRemoteClientIndex].isActiveMutex.Lock(); + if (sts->remoteClients[newRemoteClientIndex].isActive==false) + { + sts->remoteClients[newRemoteClientIndex].socket=newSock; + +#if RAKNET_SUPPORT_IPV6!=1 + sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_addr.s_addr=sockAddr.sin_addr.s_addr; + sts->remoteClients[newRemoteClientIndex].systemAddress.SetPortNetworkOrder( sockAddr.sin_port); + sts->remoteClients[newRemoteClientIndex].systemAddress.systemIndex=newRemoteClientIndex; +#else + if (sockAddr.ss_family==AF_INET) + { + memcpy(&sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4,(sockaddr_in *)&sockAddr,sizeof(sockaddr_in)); + // sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_port=ntohs( sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr4.sin_port ); + } + else + { + memcpy(&sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6,(sockaddr_in6 *)&sockAddr,sizeof(sockaddr_in6)); + // sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6.sin6_port=ntohs( sts->remoteClients[newRemoteClientIndex].systemAddress.address.addr6.sin6_port ); + } + +#endif // #if RAKNET_SUPPORT_IPV6!=1 + sts->remoteClients[newRemoteClientIndex].SetActive(true); + sts->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); + + + SystemAddress *newConnectionSystemAddress=sts->newIncomingConnections.Allocate( _FILE_AND_LINE_ ); + *newConnectionSystemAddress=sts->remoteClients[newRemoteClientIndex].systemAddress; + sts->newIncomingConnections.Push(newConnectionSystemAddress); + + break; + } + sts->remoteClients[newRemoteClientIndex].isActiveMutex.Unlock(); + } + if (newRemoteClientIndex==-1) + { + closesocket__(sts->listenSocket); + } + } + else + { +#ifdef _DO_PRINTF + RAKNET_DEBUG_PRINTF("Error: connection failed\n"); +#endif + } + } + else if (sts->listenSocket!=0 && FD_ISSET(sts->listenSocket, &exceptionFD)) + { +#ifdef _DO_PRINTF + int err; + int errlen = sizeof(err); + getsockopt__(sts->listenSocket, SOL_SOCKET, SO_ERROR,(char*)&err, &errlen); + RAKNET_DEBUG_PRINTF("Socket error %s on listening socket\n", err); +#endif + } + + { + i=0; + while (i < (unsigned int) sts->remoteClientsLength) + { + if (sts->remoteClients[i].isActive==false) + { + i++; + continue; + } + // calling FD_ISSET with -1 as socket (that’s what 0 is set to) produces a bus error under Linux 64-Bit + __TCPSOCKET__ socketCopy = sts->remoteClients[i].socket; + if (socketCopy == 0) + { + i++; + continue; + } + + if (FD_ISSET(socketCopy, &exceptionFD)) + { +// #ifdef _DO_PRINTF +// if (sts->listenSocket!=-1) +// { +// int err; +// int errlen = sizeof(err); +// getsockopt__(sts->listenSocket, SOL_SOCKET, SO_ERROR,(char*)&err, &errlen); +// in_addr in; +// in.s_addr = sts->remoteClients[i].systemAddress.binaryAddress; +// RAKNET_DEBUG_PRINTF("Socket error %i on %s:%i\n", err,inet_ntoa( in ), sts->remoteClients[i].systemAddress.GetPort() ); +// } +// +// #endif + // Connection lost abruptly + SystemAddress *lostConnectionSystemAddress=sts->lostConnections.Allocate( _FILE_AND_LINE_ ); + *lostConnectionSystemAddress=sts->remoteClients[i].systemAddress; + sts->lostConnections.Push(lostConnectionSystemAddress); + sts->remoteClients[i].isActiveMutex.Lock(); + sts->remoteClients[i].SetActive(false); + sts->remoteClients[i].isActiveMutex.Unlock(); + } + else + { + if (FD_ISSET(socketCopy, &readFD)) + { + // if recv returns 0 this was a graceful close + len = sts->remoteClients[i].Recv(data,BUFF_SIZE); + + + // removeme +// data[len]=0; +// printf(data); + + if (len>0) + { + incomingMessage=sts->incomingMessages.Allocate( _FILE_AND_LINE_ ); + incomingMessage->data = (unsigned char*) rakMalloc_Ex( len+1, _FILE_AND_LINE_ ); + memcpy(incomingMessage->data, data, len); + incomingMessage->data[len]=0; // Null terminate this so we can print it out as regular strings. This is different from RakNet which does not do this. + // printf("RECV: %s\n",incomingMessage->data); + /* + if (1) + { + static FILE *fp=0; + if (fp==0) + { + fp = fopen("tcpRcv.txt", "wb"); + } + fwrite(data,1,len,fp); + } + */ + incomingMessage->length=len; + incomingMessage->deleteData=true; // actually means came from SPSC, rather than AllocatePacket + incomingMessage->systemAddress=sts->remoteClients[i].systemAddress; + sts->incomingMessages.Push(incomingMessage); + } + else + { + // Connection lost gracefully + SystemAddress *lostConnectionSystemAddress=sts->lostConnections.Allocate( _FILE_AND_LINE_ ); + *lostConnectionSystemAddress=sts->remoteClients[i].systemAddress; + sts->lostConnections.Push(lostConnectionSystemAddress); + sts->remoteClients[i].isActiveMutex.Lock(); + sts->remoteClients[i].SetActive(false); + sts->remoteClients[i].isActiveMutex.Unlock(); + continue; + } + } + if (FD_ISSET(socketCopy, &writeFD)) + { + RemoteClient *rc = &sts->remoteClients[i]; + unsigned int bytesInBuffer; + int bytesAvailable; + int bytesSent; + rc->outgoingDataMutex.Lock(); + bytesInBuffer=rc->outgoingData.GetBytesWritten(); + if (bytesInBuffer>0) + { + unsigned int contiguousLength; + char* contiguousBytesPointer = rc->outgoingData.PeekContiguousBytes(&contiguousLength); + if (contiguousLength < (unsigned int) BUFF_SIZE && contiguousLength BUFF_SIZE) + bytesAvailable=BUFF_SIZE; + else + bytesAvailable=bytesInBuffer; + rc->outgoingData.ReadBytes(data,bytesAvailable,true); + bytesSent=rc->Send(data,bytesAvailable); + } + else + { + bytesSent=rc->Send(contiguousBytesPointer,contiguousLength); + } + + if (bytesSent>0) + rc->outgoingData.IncrementReadOffset(bytesSent); + bytesInBuffer=rc->outgoingData.GetBytesWritten(); + } + rc->outgoingDataMutex.Unlock(); + } + + i++; // Nothing deleted so increment the index + } + } + } + } + + // Sleep 0 on Linux monopolizes the CPU + RakSleep(30); + } + sts->threadRunning.Decrement(); + + rakFree_Ex(data,_FILE_AND_LINE_); + + + + + return 0; + +} + +void RemoteClient::SetActive(bool a) +{ + if (isActive != a) + { + isActive=a; + Reset(); + if (isActive==false && socket!=0) + { + closesocket__(socket); + socket=0; + } + } +} +void RemoteClient::SendOrBuffer(const char **data, const unsigned int *lengths, const int numParameters) +{ + // True can save memory and buffer copies, but gives worse performance overall + // Do not use true for the XBOX, as it just locks up + const bool ALLOW_SEND_FROM_USER_THREAD=false; + + int parameterIndex; + if (isActive==false) + return; + parameterIndex=0; + for (; parameterIndex < numParameters; parameterIndex++) + { + outgoingDataMutex.Lock(); + if (ALLOW_SEND_FROM_USER_THREAD && outgoingData.GetBytesWritten()==0) + { + outgoingDataMutex.Unlock(); + int bytesSent = Send(data[parameterIndex],lengths[parameterIndex]); + if (bytesSent<(int) lengths[parameterIndex]) + { + // Push remainder + outgoingDataMutex.Lock(); + outgoingData.WriteBytes(data[parameterIndex]+bytesSent,lengths[parameterIndex]-bytesSent,_FILE_AND_LINE_); + outgoingDataMutex.Unlock(); + } + } + else + { + outgoingData.WriteBytes(data[parameterIndex],lengths[parameterIndex],_FILE_AND_LINE_); + outgoingDataMutex.Unlock(); + } + } +} +#if OPEN_SSL_CLIENT_SUPPORT==1 +bool RemoteClient::InitSSL(SSL_CTX* ctx, SSL_METHOD *meth) +{ + (void) meth; + + ssl = SSL_new (ctx); + RakAssert(ssl); + int res; + res = SSL_set_fd (ssl, socket); + if (res!=1) + { + printf("SSL_set_fd error: %s\n", ERR_reason_error_string(ERR_get_error())); + SSL_free(ssl); + ssl=0; + return false; + } + RakAssert(res==1); + res = SSL_connect (ssl); + if (res<0) + { + unsigned long err = ERR_get_error(); + printf("SSL_connect error: %s\n", ERR_reason_error_string(err)); + SSL_free(ssl); + ssl=0; + return false; + } + else if (res==0) + { + // The TLS/SSL handshake was not successful but was shut down controlled and by the specifications of the TLS/SSL protocol. Call SSL_get_error() with the return value ret to find out the reason. + int err = SSL_get_error(ssl, res); + switch (err) + { + case SSL_ERROR_NONE: + printf("SSL_ERROR_NONE\n"); + break; + case SSL_ERROR_ZERO_RETURN: + printf("SSL_ERROR_ZERO_RETURN\n"); + break; + case SSL_ERROR_WANT_READ: + printf("SSL_ERROR_WANT_READ\n"); + break; + case SSL_ERROR_WANT_WRITE: + printf("SSL_ERROR_WANT_WRITE\n"); + break; + case SSL_ERROR_WANT_CONNECT: + printf("SSL_ERROR_WANT_CONNECT\n"); + break; + case SSL_ERROR_WANT_ACCEPT: + printf("SSL_ERROR_WANT_ACCEPT\n"); + break; + case SSL_ERROR_WANT_X509_LOOKUP: + printf("SSL_ERROR_WANT_X509_LOOKUP\n"); + break; + case SSL_ERROR_SYSCALL: + { + // http://www.openssl.org/docs/ssl/SSL_get_error.html + char buff[1024]; + unsigned long ege = ERR_get_error(); + if (ege==0 && res==0) + printf("SSL_ERROR_SYSCALL EOF in violation of the protocol\n"); + else if (ege==0 && res==-1) + printf("SSL_ERROR_SYSCALL %s\n", strerror(errno)); + else + printf("SSL_ERROR_SYSCALL %s\n", ERR_error_string(ege, buff)); + } + break; + case SSL_ERROR_SSL: + printf("SSL_ERROR_SSL\n"); + break; + } + + } + + if (res!=1) + { + SSL_free(ssl); + ssl=0; + return false; + } + return true; +} +void RemoteClient::DisconnectSSL(void) +{ + if (ssl) + SSL_shutdown (ssl); /* send SSL/TLS close_notify */ +} +void RemoteClient::FreeSSL(void) +{ + if (ssl) + SSL_free (ssl); +} +int RemoteClient::Send(const char *data, unsigned int length) +{ + if (ssl) + return SSL_write (ssl, data, length); + else + return send__(socket, data, length, 0); +} +int RemoteClient::Recv(char *data, const int dataSize) +{ + if (ssl) + return SSL_read (ssl, data, dataSize); + else + return recv__(socket, data, dataSize, 0); +} +#else +int RemoteClient::Send(const char *data, unsigned int length) +{ +#ifdef __native_client__ + return -1; +#else + return send__(socket, data, length, 0); +#endif +} +int RemoteClient::Recv(char *data, const int dataSize) +{ +#ifdef __native_client__ + return -1; +#else + return recv__(socket, data, dataSize, 0); +#endif +} +#endif + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/TableSerializer.cpp b/src/raknet/TableSerializer.cpp new file mode 100644 index 0000000..2c3170d --- /dev/null +++ b/src/raknet/TableSerializer.cpp @@ -0,0 +1,330 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/TableSerializer.hpp" +#include "include/raknet/DS_Table.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/StringCompressor.hpp" +#include "include/raknet/RakAssert.hpp" + +using namespace RakNet; + +void TableSerializer::SerializeTable(DataStructures::Table *in, RakNet::BitStream *out) +{ + DataStructures::Page *cur = in->GetRows().GetListHead(); + const DataStructures::List &columns=in->GetColumns(); + SerializeColumns(in, out); + out->Write((unsigned)in->GetRows().Size()); + unsigned rowIndex; + while (cur) + { + for (rowIndex=0; rowIndex < (unsigned)cur->size; rowIndex++) + { + SerializeRow(cur->data[rowIndex], cur->keys[rowIndex], columns, out); + } + cur=cur->next; + } +} +void TableSerializer::SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out) +{ + const DataStructures::List &columns=in->GetColumns(); + out->Write((unsigned)columns.Size()); + unsigned i; + for (i=0; iEncodeString(columns[i].columnName, _TABLE_MAX_COLUMN_NAME_LENGTH, out); + out->Write((unsigned char)columns[i].columnType); + } +} +void TableSerializer::SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out, DataStructures::List &skipColumnIndices) +{ + const DataStructures::List &columns=in->GetColumns(); + out->Write((unsigned)columns.Size()-skipColumnIndices.Size()); + unsigned i; + for (i=0; iEncodeString(columns[i].columnName, _TABLE_MAX_COLUMN_NAME_LENGTH, out); + out->Write((unsigned char)columns[i].columnType); + } + } +} +bool TableSerializer::DeserializeTable(unsigned char *serializedTable, unsigned int dataLength, DataStructures::Table *out) +{ + RakNet::BitStream in((unsigned char*) serializedTable, dataLength, false); + return DeserializeTable(&in, out); +} +bool TableSerializer::DeserializeTable(RakNet::BitStream *in, DataStructures::Table *out) +{ + unsigned rowSize; + DeserializeColumns(in,out); + if (in->Read(rowSize)==false || rowSize>100000) + { + RakAssert(0); + return false; // Hacker crash prevention + } + + unsigned rowIndex; + for (rowIndex=0; rowIndex < rowSize; rowIndex++) + { + if (DeserializeRow(in, out)==false) + return false; + } + return true; +} +bool TableSerializer::DeserializeColumns(RakNet::BitStream *in, DataStructures::Table *out) +{ + unsigned columnSize; + unsigned char columnType; + char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]; + if (in->Read(columnSize)==false || columnSize > 10000) + return false; // Hacker crash prevention + + out->Clear(); + unsigned i; + for (i=0; iDecodeString(columnName, 32, in); + in->Read(columnType); + out->AddColumn(columnName, (DataStructures::Table::ColumnType)columnType); + } + return true; +} +void TableSerializer::SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out) +{ + unsigned cellIndex; + out->Write(keyIn); + unsigned int columnsSize = columns.Size(); + out->Write(columnsSize); + for (cellIndex=0; cellIndexWrite(cellIndex); + SerializeCell(out, in->cells[cellIndex], columns[cellIndex].columnType); + } +} +void TableSerializer::SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out, DataStructures::List &skipColumnIndices) +{ + unsigned cellIndex; + out->Write(keyIn); + unsigned int numEntries=0; + for (cellIndex=0; cellIndexWrite(numEntries); + + for (cellIndex=0; cellIndexWrite(cellIndex); + SerializeCell(out, in->cells[cellIndex], columns[cellIndex].columnType); + } + } +} +bool TableSerializer::DeserializeRow(RakNet::BitStream *in, DataStructures::Table *out) +{ + const DataStructures::List &columns=out->GetColumns(); + unsigned numEntries; + DataStructures::Table::Row *row; + unsigned key; + if (in->Read(key)==false) + return false; + row=out->AddRow(key); + unsigned int cnt; + in->Read(numEntries); + for (cnt=0; cntRead(cellIndex); + if (DeserializeCell(in, row->cells[cellIndex], columns[cellIndex].columnType)==false) + { + out->RemoveRow(key); + return false; + } + } + return true; +} +void TableSerializer::SerializeCell(RakNet::BitStream *out, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType) +{ + out->Write(cell->isEmpty); + if (cell->isEmpty==false) + { + if (columnType==DataStructures::Table::NUMERIC) + { + out->Write(cell->i); + } + else if (columnType==DataStructures::Table::STRING) + { + StringCompressor::Instance()->EncodeString(cell->c, 65535, out); + } + else if (columnType==DataStructures::Table::POINTER) + { + out->Write(cell->ptr); + } + else + { + // Binary + RakAssert(columnType==DataStructures::Table::BINARY); + RakAssert(cell->i>0); + unsigned binaryLength; + binaryLength=(unsigned)cell->i; + out->Write(binaryLength); + out->WriteAlignedBytes((const unsigned char*) cell->c, (const unsigned int) cell->i); + } + } +} +bool TableSerializer::DeserializeCell(RakNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType) +{ + bool isEmpty=false; + double value; + void *ptr; + char tempString[65535]; + cell->Clear(); + + if (in->Read(isEmpty)==false) + return false; + if (isEmpty==false) + { + if (columnType==DataStructures::Table::NUMERIC) + { + if (in->Read(value)==false) + return false; + cell->Set(value); + } + else if (columnType==DataStructures::Table::STRING) + { + if (StringCompressor::Instance()->DecodeString(tempString, 65535, in)==false) + return false; + cell->Set(tempString); + } + else if (columnType==DataStructures::Table::POINTER) + { + if (in->Read(ptr)==false) + return false; + cell->SetPtr(ptr); + } + else + { + unsigned binaryLength; + // Binary + RakAssert(columnType==DataStructures::Table::BINARY); + if (in->Read(binaryLength)==false || binaryLength > 10000000) + return false; // Sanity check to max binary cell of 10 megabytes + in->AlignReadToByteBoundary(); + if (BITS_TO_BYTES(in->GetNumberOfUnreadBits())<(BitSize_t)binaryLength) + return false; + cell->Set((char*) in->GetData()+BITS_TO_BYTES(in->GetReadOffset()), (int) binaryLength); + in->IgnoreBits(BYTES_TO_BITS((int) binaryLength)); + } + } + return true; +} +void TableSerializer::SerializeFilterQuery(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query) +{ + StringCompressor::Instance()->EncodeString(query->columnName,_TABLE_MAX_COLUMN_NAME_LENGTH,in,0); + in->WriteCompressed(query->columnIndex); + in->Write((unsigned char) query->operation); + in->Write(query->cellValue->isEmpty); + if (query->cellValue->isEmpty==false) + { + in->Write(query->cellValue->i); + in->WriteAlignedBytesSafe((const char*)query->cellValue->c,(const unsigned int)query->cellValue->i,10000000); // Sanity check to max binary cell of 10 megabytes + in->Write(query->cellValue->ptr); + + } +} +bool TableSerializer::DeserializeFilterQuery(RakNet::BitStream *out, DataStructures::Table::FilterQuery *query) +{ + bool b; + RakAssert(query->cellValue); + StringCompressor::Instance()->DecodeString(query->columnName,_TABLE_MAX_COLUMN_NAME_LENGTH,out,0); + out->ReadCompressed(query->columnIndex); + unsigned char op; + out->Read(op); + query->operation=(DataStructures::Table::FilterQueryType) op; + query->cellValue->Clear(); + b=out->Read(query->cellValue->isEmpty); + if (query->cellValue->isEmpty==false) + { + // HACK - cellValue->i is used for integer, character, and binary data. However, for character and binary c will be 0. So use that to determine if the data was integer or not. + out->Read(query->cellValue->i); + unsigned int inputLength; + out->ReadAlignedBytesSafeAlloc(&query->cellValue->c,inputLength,10000000); // Sanity check to max binary cell of 10 megabytes + if (query->cellValue->c) + query->cellValue->i=inputLength; + b=out->Read(query->cellValue->ptr); + } + return b; +} +void TableSerializer::SerializeFilterQueryList(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query, unsigned int numQueries, unsigned int maxQueries) +{ + (void) maxQueries; + in->Write((bool)(query && numQueries>0)); + if (query==0 || numQueries<=0) + return; + + RakAssert(numQueries<=maxQueries); + in->WriteCompressed(numQueries); + unsigned i; + for (i=0; i < numQueries; i++) + { + SerializeFilterQuery(in, query); + } +} +bool TableSerializer::DeserializeFilterQueryList(RakNet::BitStream *out, DataStructures::Table::FilterQuery **query, unsigned int *numQueries, unsigned int maxQueries, int allocateExtraQueries) +{ + bool b, anyQueries=false; + out->Read(anyQueries); + if (anyQueries==false) + { + if (allocateExtraQueries<=0) + *query=0; + else + *query=new DataStructures::Table::FilterQuery[allocateExtraQueries]; + + *numQueries=0; + return true; + } + b=out->ReadCompressed(*numQueries); + if (*numQueries>maxQueries) + { + RakAssert(0); + *numQueries=maxQueries; + } + if (*numQueries==0) + return b; + + *query=new DataStructures::Table::FilterQuery[*numQueries+allocateExtraQueries]; + DataStructures::Table::FilterQuery *queryPtr = *query; + + unsigned i; + for (i=0; i < *numQueries; i++) + { + queryPtr[i].cellValue=new DataStructures::Table::Cell; + b=DeserializeFilterQuery(out, queryPtr+i); + } + + return b; +} +void TableSerializer::DeallocateQueryList(DataStructures::Table::FilterQuery *query, unsigned int numQueries) +{ + if (query==0 || numQueries==0) + return; + + unsigned i; + for (i=0; i < numQueries; i++) + RakNet::OP_DELETE(query[i].cellValue, _FILE_AND_LINE_); + RakNet::OP_DELETE_ARRAY(query, _FILE_AND_LINE_); +} diff --git a/src/raknet/TeamBalancer.cpp b/src/raknet/TeamBalancer.cpp new file mode 100644 index 0000000..84a2cf5 --- /dev/null +++ b/src/raknet/TeamBalancer.cpp @@ -0,0 +1,885 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TeamBalancer==1 + +#include "include/raknet/TeamBalancer.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/Rand.hpp" + +using namespace RakNet; + +enum TeamBalancerOperations +{ + ID_STATUS_UPDATE_TO_NEW_HOST, + ID_CANCEL_TEAM_REQUEST, + ID_REQUEST_ANY_TEAM, + ID_REQUEST_SPECIFIC_TEAM +}; + +STATIC_FACTORY_DEFINITIONS(TeamBalancer,TeamBalancer); + +TeamBalancer::TeamBalancer() +{ + defaultAssigmentAlgorithm=SMALLEST_TEAM; + forceTeamsToBeEven=false; + lockTeams=false; + hostGuid=UNASSIGNED_RAKNET_GUID; +} +TeamBalancer::~TeamBalancer() +{ + +} +void TeamBalancer::SetTeamSizeLimit(TeamId team, unsigned short limit) +{ + teamLimits.Replace(limit,0,team,_FILE_AND_LINE_); + if (teamLimits.Size() > teamMemberCounts.Size()) + teamMemberCounts.Replace(0,0,teamLimits.Size()-1,_FILE_AND_LINE_); +} +void TeamBalancer::SetDefaultAssignmentAlgorithm(DefaultAssigmentAlgorithm daa) +{ + // Just update the default. Currently active teams are not affected. + defaultAssigmentAlgorithm=daa; +} +void TeamBalancer::SetForceEvenTeams(bool force) +{ + // Set flag to indicate that teams should be even. + forceTeamsToBeEven=force; + + // If teams are locked, just return. + if (lockTeams==true) + return; + + if (forceTeamsToBeEven==true) + { + // Run the even team algorithm + EvenTeams(); + } +} +void TeamBalancer::SetLockTeams(bool lock) +{ + if (lock==lockTeams) + return; + + // Set flag to indicate that teams can no longer be changed. + lockTeams=lock; + + // If lock is false, and teams were set to be forced as even, then run through the even team algorithm + if (lockTeams==false) + { + // Process even swaps + TeamId i,j; + for (i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i].requestedTeam!=UNASSIGNED_TEAM_ID) + { + for (j=i+1; j < teamMembers.Size(); j++) + { + if (teamMembers[j].requestedTeam==teamMembers[i].currentTeam && + teamMembers[i].requestedTeam==teamMembers[j].currentTeam) + { + SwapTeamMembersByRequest(i,j); + NotifyTeamAssigment(i); + NotifyTeamAssigment(j); + } + } + } + } + + if (forceTeamsToBeEven==true) + { + EvenTeams(); + } + else + { + // Process requested team changes + // Process movement while not full + for (i=0; i < teamMembers.Size(); i++) + { + TeamId requestedTeam = teamMembers[i].requestedTeam; + if (requestedTeam!=UNASSIGNED_TEAM_ID) + { + if (teamMemberCounts[requestedTeam]Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,hostGuid,false); +} +void TeamBalancer::CancelRequestSpecificTeam(NetworkID memberId) +{ + for (unsigned int i=0; i < myTeamMembers.Size(); i++) + { + if (myTeamMembers[i].memberId==memberId) + { + myTeamMembers[i].requestedTeam=UNASSIGNED_TEAM_ID; + + // Send packet to the host to remove our request flag. + BitStream bsOut; + bsOut.Write((MessageID)ID_TEAM_BALANCER_INTERNAL); + bsOut.Write((MessageID)ID_CANCEL_TEAM_REQUEST); + bsOut.Write(memberId); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,hostGuid,false); + + return; + } + } +} +void TeamBalancer::RequestAnyTeam(NetworkID memberId) +{ + bool foundMatch=false; + + for (unsigned int i=0; i < myTeamMembers.Size(); i++) + { + if (myTeamMembers[i].memberId==memberId) + { + foundMatch=true; + if (myTeamMembers[i].currentTeam!=UNASSIGNED_TEAM_ID) + return; + else + myTeamMembers[i].requestedTeam=UNASSIGNED_TEAM_ID; + break; + } + } + + if (foundMatch==false) + { + MyTeamMembers mtm; + mtm.currentTeam=UNASSIGNED_TEAM_ID; + mtm.memberId=memberId; + mtm.requestedTeam=UNASSIGNED_TEAM_ID; + myTeamMembers.Push(mtm, _FILE_AND_LINE_); + } + + // Else send to the current host that we need a team. + BitStream bsOut; + bsOut.Write((MessageID)ID_TEAM_BALANCER_INTERNAL); + bsOut.Write((MessageID)ID_REQUEST_ANY_TEAM); + bsOut.Write(memberId); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,hostGuid,false); +} +TeamId TeamBalancer::GetMyTeam(NetworkID memberId) const +{ + // Return team returned by last ID_TEAM_BALANCER_TEAM_ASSIGNED packet + for (unsigned int i=0; i < myTeamMembers.Size(); i++) + { + if (myTeamMembers[i].memberId==memberId) + { + return myTeamMembers[i].currentTeam; + } + } + + return UNASSIGNED_TEAM_ID; +} +void TeamBalancer::DeleteMember(NetworkID memberId) +{ + for (unsigned int i=0; i < myTeamMembers.Size(); i++) + { + if (myTeamMembers[i].memberId==memberId) + { + myTeamMembers.RemoveAtIndexFast(i); + break; + } + } + + for (unsigned int i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i].memberId==memberId) + { + RemoveTeamMember(i); + break; + } + } +} +PluginReceiveResult TeamBalancer::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_FCM2_NEW_HOST: + { + hostGuid=packet->guid; + + if (myTeamMembers.Size()>0) + { + BitStream bsOut; + bsOut.Write((MessageID)ID_TEAM_BALANCER_INTERNAL); + bsOut.Write((MessageID)ID_STATUS_UPDATE_TO_NEW_HOST); + + bsOut.WriteCasted(myTeamMembers.Size()); + for (unsigned int i=0; i < myTeamMembers.Size(); i++) + { + bsOut.Write(myTeamMembers[i].memberId); + bsOut.Write(myTeamMembers[i].currentTeam); + bsOut.Write(myTeamMembers[i].requestedTeam); + } + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,hostGuid,false); + } + } + break; + case ID_TEAM_BALANCER_INTERNAL: + { + if (packet->length>=2) + { + switch (packet->data[1]) + { + case ID_STATUS_UPDATE_TO_NEW_HOST: + OnStatusUpdateToNewHost(packet); + break; + case ID_CANCEL_TEAM_REQUEST: + OnCancelTeamRequest(packet); + break; + case ID_REQUEST_ANY_TEAM: + OnRequestAnyTeam(packet); + break; + case ID_REQUEST_SPECIFIC_TEAM: + OnRequestSpecificTeam(packet); + break; + } + } + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + + case ID_TEAM_BALANCER_TEAM_ASSIGNED: + { + return OnTeamAssigned(packet); + } + + case ID_TEAM_BALANCER_REQUESTED_TEAM_FULL: + { + return OnRequestedTeamChangePending(packet); + } + + case ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED: + { + return OnTeamsLocked(packet); + } + } + + // Got RequestSpecificTeam + // If teams are locked + // - If this user already has a team, return ID_TEAM_BALANCER_TEAMS_LOCKED + // - This user does not already have a team. Assign a team as if the user called RequestAnyTeam(), with a preference for the requested team. Return ID_TEAM_BALANCER_TEAM_ASSIGNED once the team has been assigned. + // If teams are not locked + // - If even team balancing is on, only assign this user if this would not cause teams to be unbalanced. If teams WOULD be unbalanced, then flag this user as wanting to join this team. Return ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING + // - If the destination team is full, flag this user as wanting to join this team. Return ID_TEAM_BALANCER_REQUESTED_TEAM_CHANGE_PENDING + // - Else, join this team. Return ID_TEAM_BALANCER_TEAM_ASSIGNED + + // Got RequestAnyTeam + // Put user on a team following the algorithm. No team is set as preferred. + + return RR_CONTINUE_PROCESSING; +} +void TeamBalancer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) systemAddress; + (void) lostConnectionReason; + + RemoveByGuid(rakNetGUID); +} +void TeamBalancer::OnAttach(void) +{ + hostGuid = rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); +} +void TeamBalancer::RemoveByGuid(RakNetGUID rakNetGUID) +{ + // If we are the host, and the closed connection has a team, and teams are not locked: + if (WeAreHost()) + { + unsigned int droppedMemberIndex=0; + while (droppedMemberIndex < teamMembers.Size()) + { + if (teamMembers[droppedMemberIndex].memberGuid==rakNetGUID) + { + TeamId droppedTeam = teamMembers[droppedMemberIndex].currentTeam; + RemoveTeamMember(droppedMemberIndex); + if (lockTeams==false) + { + if (forceTeamsToBeEven) + { + // - teams were forced to be even, then run the even team algorithm + EvenTeams(); + } + else + { + // - teams were NOT forced to be even, and the team the dropped player on was full, then move users wanting to join that team (if any) + if (teamMemberCounts[ droppedTeam ]==teamLimits[ droppedTeam ]-1) + { + MoveMemberThatWantsToJoinTeam(droppedTeam); + } + } + } + } + else + { + droppedMemberIndex++; + } + } + } +} +void TeamBalancer::OnStatusUpdateToNewHost(Packet *packet) +{ + if (WeAreHost()==false) + return; + + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + uint8_t requestedTeamChangeListSize; + bsIn.Read(requestedTeamChangeListSize); + TeamMember tm; + tm.memberGuid=packet->guid; + for (uint8_t i=0; i < requestedTeamChangeListSize; i++) + { + bsIn.Read(tm.memberId); + bsIn.Read(tm.currentTeam); + bsIn.Read(tm.requestedTeam); + + if (tm.currentTeam!=UNASSIGNED_TEAM_ID && tm.currentTeam>teamLimits.Size()) + { + RakAssert("Current team out of range in TeamBalancer::OnStatusUpdateToNewHost" && 0); + return; + } + + if (tm.requestedTeam!=UNASSIGNED_TEAM_ID && tm.requestedTeam>teamLimits.Size()) + { + RakAssert("Requested team out of range in TeamBalancer::OnStatusUpdateToNewHost" && 0); + return; + } + + if (tm.currentTeam==UNASSIGNED_TEAM_ID && tm.requestedTeam==UNASSIGNED_TEAM_ID) + return; + + unsigned int memberIndex = GetMemberIndex(tm.memberId, packet->guid); + if (memberIndex==(unsigned int) -1) + { + // Add this system (by GUID) to the list of members if he is not already there + // Also update his requested team flag. + // Do not process balancing on requested teams, since we don't necessarily have all data from all systems yet and hopefully the state during the host migration was stable. + if (tm.currentTeam==UNASSIGNED_TEAM_ID) + { + // Assign a default team, then add team member + if (tm.requestedTeam==UNASSIGNED_TEAM_ID) + { + // Assign a default team + tm.currentTeam=GetNextDefaultTeam(); + } + else + { + // Assign to requested team if possible. Otherwise, assign to a default team + if (TeamWouldBeOverpopulatedOnAddition(tm.requestedTeam, teamMembers.Size())==false) + { + tm.currentTeam=tm.requestedTeam; + } + else + { + tm.currentTeam=GetNextDefaultTeam(); + } + } + } + + if (tm.currentTeam==UNASSIGNED_TEAM_ID) + { + RakAssert("Too many members asking for teams!" && 0); + return; + } + NotifyTeamAssigment(AddTeamMember(tm)); + } + } +} +void TeamBalancer::OnCancelTeamRequest(Packet *packet) +{ + if (WeAreHost()==false) + return; + + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + NetworkID memberId; + bsIn.Read(memberId); + + unsigned int memberIndex = GetMemberIndex(memberId, packet->guid); + if (memberIndex!=(unsigned int)-1) + teamMembers[memberIndex].requestedTeam=UNASSIGNED_TEAM_ID; +} +void TeamBalancer::OnRequestAnyTeam(Packet *packet) +{ + if (WeAreHost()==false) + return; + + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + NetworkID memberId; + bsIn.Read(memberId); + + unsigned int memberIndex = GetMemberIndex(memberId, packet->guid); + if (memberIndex==(unsigned int)-1) + { + TeamMember tm; + tm.currentTeam=GetNextDefaultTeam(); + tm.requestedTeam=UNASSIGNED_TEAM_ID; + tm.memberGuid=packet->guid; + tm.memberId=memberId; + if (tm.currentTeam==UNASSIGNED_TEAM_ID) + { + RakAssert("Too many members asking for teams!" && 0); + return; + } + NotifyTeamAssigment(AddTeamMember(tm)); + } +} +void TeamBalancer::OnRequestSpecificTeam(Packet *packet) +{ + if (WeAreHost()==false) + return; + + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + TeamMember tm; + bsIn.Read(tm.memberId); + bsIn.Read(tm.requestedTeam); + + unsigned int memberIndex = GetMemberIndex(tm.memberId, packet->guid); + if (tm.requestedTeam==UNASSIGNED_TEAM_ID) + { + NotifyNoTeam(tm.memberId, packet->guid); + if (memberIndex != (unsigned int) -1) + RemoveTeamMember(memberIndex); + return; + } + + if (tm.requestedTeam>teamLimits.Size()) + { + RakAssert("Requested team out of range in TeamBalancer::OnRequestSpecificTeam" && 0); + return; + } + if (memberIndex==(unsigned int) -1) + { + tm.memberGuid=packet->guid; + + // Assign to requested team if possible. Otherwise, assign to a default team + if (TeamWouldBeOverpopulatedOnAddition(tm.requestedTeam, teamMembers.Size())==false) + { + tm.currentTeam=tm.requestedTeam; + tm.requestedTeam=UNASSIGNED_TEAM_ID; + } + else + { + tm.currentTeam=GetNextDefaultTeam(); + } + if (tm.currentTeam==UNASSIGNED_TEAM_ID) + { + RakAssert("Too many members asking for teams!" && 0); + return; + } + NotifyTeamAssigment(AddTeamMember(tm)); + } + else + { + teamMembers[memberIndex].requestedTeam=tm.requestedTeam; + TeamId oldTeamThisUserWasOn = teamMembers[memberIndex].currentTeam; + + if (lockTeams) + { + NotifyTeamsLocked(packet->guid, tm.requestedTeam); + return; + } + + // Assign to requested team if possible. Otherwise, assign to a default team + if (TeamsWouldBeEvenOnSwitch(tm.requestedTeam,oldTeamThisUserWasOn)==true) + { + SwitchMemberTeam(memberIndex,tm.requestedTeam); + NotifyTeamAssigment(memberIndex); + } + else + { + // If someone wants to join this user's old team, and we want to join their team, they can swap + unsigned int swappableMemberIndex; + for (swappableMemberIndex=0; swappableMemberIndex < teamMembers.Size(); swappableMemberIndex++) + { + if (teamMembers[swappableMemberIndex].currentTeam==tm.requestedTeam && teamMembers[swappableMemberIndex].requestedTeam==oldTeamThisUserWasOn) + break; + } + + if (swappableMemberIndex!=teamMembers.Size()) + { + SwapTeamMembersByRequest(memberIndex,swappableMemberIndex); + NotifyTeamAssigment(memberIndex); + NotifyTeamAssigment(swappableMemberIndex); + } + else + { + // Full or would not be even + NotifyTeamSwitchPending(packet->guid, tm.requestedTeam, tm.memberId); + } + } + } +} +unsigned int TeamBalancer::GetMemberIndex(NetworkID memberId, RakNetGUID guid) const +{ + for (unsigned int i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i].memberGuid==guid && teamMembers[i].memberId==memberId) + return i; + } + return (unsigned int) -1; +} +unsigned int TeamBalancer::AddTeamMember(const TeamMember &tm) +{ + if (tm.currentTeam>teamLimits.Size()) + { + RakAssert("TeamBalancer::AddTeamMember team index out of bounds" && 0); + return (unsigned int) -1; + } + + RakAssert(tm.currentTeam!=UNASSIGNED_TEAM_ID); + + teamMembers.Push(tm,_FILE_AND_LINE_); + if (teamMemberCounts.Size() overpopulatedTeams; + TeamId teamMemberCountsIndex; + unsigned int memberIndexToSwitch; + for (teamMemberCountsIndex=0; teamMemberCountsIndex0); + memberIndexToSwitch=GetMemberIndexToSwitchTeams(overpopulatedTeams,teamMemberCountsIndex); + RakAssert(memberIndexToSwitch!=(unsigned int)-1); + SwitchMemberTeam(memberIndexToSwitch,teamMemberCountsIndex); + // Tell this member he switched teams + NotifyTeamAssigment(memberIndexToSwitch); + } + } +} +unsigned int TeamBalancer::GetMemberIndexToSwitchTeams(const DataStructures::List &sourceTeamNumbers, TeamId targetTeamNumber) +{ + DataStructures::List preferredSwapIndices; + DataStructures::List potentialSwapIndices; + unsigned int i,j; + for (j=0; j < sourceTeamNumbers.Size(); j++) + { + RakAssert(sourceTeamNumbers[j]!=targetTeamNumber); + for (i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i].currentTeam==sourceTeamNumbers[j]) + { + if (teamMembers[i].requestedTeam==targetTeamNumber) + preferredSwapIndices.Push(i,_FILE_AND_LINE_); + else + potentialSwapIndices.Push(i,_FILE_AND_LINE_); + } + } + } + + if (preferredSwapIndices.Size()>0) + { + return preferredSwapIndices[ randomMT() % preferredSwapIndices.Size() ]; + } + else if (potentialSwapIndices.Size()>0) + { + return potentialSwapIndices[ randomMT() % potentialSwapIndices.Size() ]; + } + else + { + return (unsigned int) -1; + } +} +void TeamBalancer::SwitchMemberTeam(unsigned int teamMemberIndex, TeamId destinationTeam) +{ + teamMemberCounts[ teamMembers[teamMemberIndex].currentTeam ]=teamMemberCounts[ teamMembers[teamMemberIndex].currentTeam ]-1; + teamMemberCounts[ destinationTeam ]=teamMemberCounts[ destinationTeam ]+1; + teamMembers[teamMemberIndex].currentTeam=destinationTeam; + if (teamMembers[teamMemberIndex].requestedTeam==destinationTeam) + teamMembers[teamMemberIndex].requestedTeam=UNASSIGNED_TEAM_ID; +} +void TeamBalancer::GetOverpopulatedTeams(DataStructures::List &overpopulatedTeams, int maxTeamSize) +{ + overpopulatedTeams.Clear(true,_FILE_AND_LINE_); + for (TeamId i=0; i < teamMemberCounts.Size(); i++) + { + if (teamMemberCounts[i]>=maxTeamSize) + overpopulatedTeams.Push(i,_FILE_AND_LINE_); + } +} +void TeamBalancer::NotifyTeamAssigment(unsigned int teamMemberIndex) +{ + RakAssert(teamMemberIndex < teamMembers.Size()); + if (teamMemberIndex>=teamMembers.Size()) + return; + + BitStream bsOut; + bsOut.Write((MessageID)ID_TEAM_BALANCER_TEAM_ASSIGNED); + bsOut.Write(teamMembers[teamMemberIndex].currentTeam); + bsOut.Write(teamMembers[teamMemberIndex].memberId); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,teamMembers[teamMemberIndex].memberGuid,false); +} +bool TeamBalancer::WeAreHost(void) const +{ + return hostGuid==rakPeerInterface->GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS); +} +PluginReceiveResult TeamBalancer::OnTeamAssigned(Packet *packet) +{ + if (packet->guid!=hostGuid) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(1); + + MyTeamMembers mtm; + bsIn.Read(mtm.currentTeam); + bsIn.Read(mtm.memberId); + mtm.requestedTeam=UNASSIGNED_TEAM_ID; + + bool foundMatch=false; + for (unsigned int i=0; i < myTeamMembers.Size(); i++) + { + if (myTeamMembers[i].memberId==mtm.memberId) + { + foundMatch=true; + if (myTeamMembers[i].requestedTeam==mtm.currentTeam) + myTeamMembers[i].requestedTeam=UNASSIGNED_TEAM_ID; + myTeamMembers[i].currentTeam=mtm.currentTeam; + break; + } + } + + if (foundMatch==false) + { + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + return RR_CONTINUE_PROCESSING; +} +PluginReceiveResult TeamBalancer::OnRequestedTeamChangePending(Packet *packet) +{ + if (packet->guid!=hostGuid) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + + return RR_CONTINUE_PROCESSING; +} +PluginReceiveResult TeamBalancer::OnTeamsLocked(Packet *packet) +{ + if (packet->guid!=hostGuid) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + + return RR_CONTINUE_PROCESSING; +} +TeamId TeamBalancer::GetNextDefaultTeam(void) +{ + // Accounting for team balancing and team limits, get the team a player should be placed on + switch (defaultAssigmentAlgorithm) + { + case SMALLEST_TEAM: + { + return GetSmallestNonFullTeam(); + } + + case FILL_IN_ORDER: + { + return GetFirstNonFullTeam(); + } + + default: + { + RakAssert("TeamBalancer::GetNextDefaultTeam unknown algorithm enumeration" && 0); + return UNASSIGNED_TEAM_ID; + } + } +} +bool TeamBalancer::TeamWouldBeOverpopulatedOnAddition(TeamId teamId, unsigned int teamMemberSize) +{ + // Accounting for team balancing and team limits, would this team be overpopulated if a member was added to it? + if (teamMemberCounts[teamId]>=teamLimits[teamId]) + { + return true; + } + + if (forceTeamsToBeEven) + { + int allowedLimit = teamMemberSize/teamLimits.Size() + 1; + return teamMemberCounts[teamId]>=allowedLimit; + } + + return false; +} +bool TeamBalancer::TeamWouldBeUnderpopulatedOnLeave(TeamId teamId, unsigned int teamMemberSize) +{ + if (forceTeamsToBeEven) + { + unsigned int minMembersOnASingleTeam = (teamMemberSize-1)/teamLimits.Size(); + return teamMemberCounts[teamId]<=minMembersOnASingleTeam; + } + return false; +} +TeamId TeamBalancer::GetSmallestNonFullTeam(void) const +{ + TeamId idx; + unsigned long smallestTeamCount=MAX_UNSIGNED_LONG; + TeamId smallestTeamIndex = UNASSIGNED_TEAM_ID; + for (idx=0; idx < teamMemberCounts.Size(); idx++) + { + if (teamMemberCounts[idx] membersThatWantToJoinTheTeam; + for (TeamId i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i].requestedTeam==teamId) + membersThatWantToJoinTheTeam.Push(i,_FILE_AND_LINE_); + } + + if (membersThatWantToJoinTheTeam.Size()>0) + { + TeamId oldTeam; + unsigned int swappedMemberIndex = membersThatWantToJoinTheTeam[ randomMT() % membersThatWantToJoinTheTeam.Size() ]; + oldTeam=teamMembers[swappedMemberIndex].currentTeam; + SwitchMemberTeam(swappedMemberIndex,teamId); + NotifyTeamAssigment(swappedMemberIndex); + return oldTeam; + } + return UNASSIGNED_TEAM_ID; +} +void TeamBalancer::NotifyTeamsLocked(RakNetGUID target, TeamId requestedTeam) +{ + BitStream bsOut; + bsOut.Write((MessageID)ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED); + bsOut.Write(requestedTeam); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,target,false); +} +void TeamBalancer::NotifyTeamSwitchPending(RakNetGUID target, TeamId requestedTeam, NetworkID memberId) +{ + BitStream bsOut; + bsOut.Write((MessageID)ID_TEAM_BALANCER_REQUESTED_TEAM_FULL); + bsOut.Write(requestedTeam); + bsOut.Write(memberId); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,target,false); +} +void TeamBalancer::SwapTeamMembersByRequest(unsigned int memberIndex1, unsigned int memberIndex2) +{ + TeamId index1Team = teamMembers[memberIndex1].currentTeam; + teamMembers[memberIndex1].currentTeam=teamMembers[memberIndex2].currentTeam; + teamMembers[memberIndex2].currentTeam=index1Team; + teamMembers[memberIndex1].requestedTeam=UNASSIGNED_TEAM_ID; + teamMembers[memberIndex2].requestedTeam=UNASSIGNED_TEAM_ID; +} +void TeamBalancer::NotifyNoTeam(NetworkID memberId, RakNetGUID target) +{ + BitStream bsOut; + bsOut.Write((MessageID)ID_TEAM_BALANCER_TEAM_ASSIGNED); + bsOut.Write((unsigned char)UNASSIGNED_TEAM_ID); + bsOut.Write(memberId); + rakPeerInterface->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,target,false); +} +bool TeamBalancer::TeamsWouldBeEvenOnSwitch(TeamId t1, TeamId t2) +{ + RakAssert(teamMembers.Size()!=0); + return TeamWouldBeOverpopulatedOnAddition(t1, teamMembers.Size()-1)==false && + TeamWouldBeUnderpopulatedOnLeave(t2, teamMembers.Size()-1)==false; +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/TeamManager.cpp b/src/raknet/TeamManager.cpp new file mode 100644 index 0000000..19a9eeb --- /dev/null +++ b/src/raknet/TeamManager.cpp @@ -0,0 +1,2853 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TeamManager==1 + +#include "include/raknet/TeamManager.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/GetTime.hpp" + +using namespace RakNet; + + +enum TeamManagerOperations +{ + ID_RUN_UpdateListsToNoTeam, + ID_RUN_UpdateTeamsRequestedToAny, + ID_RUN_JoinAnyTeam, + ID_RUN_JoinRequestedTeam, + ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam, + ID_RUN_RemoveFromTeamsRequestedAndAddTeam, + ID_RUN_AddToRequestedTeams, + ID_RUN_LeaveTeam, + ID_RUN_SetMemberLimit, + ID_RUN_SetJoinPermissions, + ID_RUN_SetBalanceTeams, + ID_RUN_SetBalanceTeamsInitial, + ID_RUN_SerializeWorld, +}; + +STATIC_FACTORY_DEFINITIONS(TM_TeamMember,TM_TeamMember); +STATIC_FACTORY_DEFINITIONS(TM_Team,TM_Team); +STATIC_FACTORY_DEFINITIONS(TeamManager,TeamManager); + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +int TM_World::JoinRequestHelperComp(const TM_World::JoinRequestHelper &key, const TM_World::JoinRequestHelper &data) +{ + if (key.whenRequestMade < data.whenRequestMade) + return -1; + if (key.whenRequestMade > data.whenRequestMade) + return 1; + if (key.requestIndex < data.requestIndex) + return -1; + if (key.requestIndex > data.requestIndex) + return 1; + return 0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection::TeamSelection() {} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection::TeamSelection(JoinTeamType itt) : joinTeamType(itt) {} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection::TeamSelection(JoinTeamType itt, TM_Team *param) : joinTeamType(itt) {teamParameter.specificTeamToJoin=param;} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection::TeamSelection(JoinTeamType itt, NoTeamId param) : joinTeamType(itt) {teamParameter.noTeamSubcategory=param;} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection TeamSelection::AnyAvailable(void) {return TeamSelection(JOIN_ANY_AVAILABLE_TEAM);} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection TeamSelection::SpecificTeam(TM_Team *specificTeamToJoin) {return TeamSelection(JOIN_SPECIFIC_TEAM, specificTeamToJoin);} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection TeamSelection::NoTeam(NoTeamId noTeamSubcategory) {return TeamSelection(JOIN_NO_TEAM, noTeamSubcategory);} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_TeamMember::TM_TeamMember() +{ + networkId=0; + world=0; + joinTeamType=JOIN_NO_TEAM; + noTeamSubcategory=0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_TeamMember::~TM_TeamMember() +{ + if (world) + { + world->DereferenceTeamMember(this); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::RequestTeam(TeamSelection teamSelection) +{ + if (teamSelection.joinTeamType==JOIN_NO_TEAM) + { + // If joining no team: + // - If already no team, and no team category is the same, return false. + // - Execute JoinNoTeam() locally. Return ID_TEAM_BALANCER_TEAM_ASSIGNED locally. + // - If we are host, broadcast event. Done. + // - Send to remote host event to call JoinNoTeam() + // - remote Host executes JoinNoTeam() and broadcasts event. This may cause may cause rebalance if team balancing is on. + // - - JoinNoTeam(): Remove from all current and requested teams. Set no-team category. + + if (teams.Size()==0 && noTeamSubcategory==teamSelection.teamParameter.noTeamSubcategory) + { + // No change + return false; + } + + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_UpdateListsToNoTeam); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + bsOut.Write(teamSelection.teamParameter.noTeamSubcategory); + world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + + StoreLastTeams(); + + UpdateListsToNoTeam(teamSelection.teamParameter.noTeamSubcategory); + + world->GetTeamManager()->PushTeamAssigned(this); + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) + { + world->FillRequestedSlots(); + world->EnforceTeamBalance(teamSelection.teamParameter.noTeamSubcategory); + } + } + else if (teamSelection.joinTeamType==JOIN_ANY_AVAILABLE_TEAM) + { + // If joining any team + // Execute JoinAnyTeamCheck() + // - JoinAnyTeamCheck(): + // - - If already on a team, return false + // - - If any team is already in requested teams, return false. + // On local, call UpdateTeamsRequestedToAny(). Send event to also execute this to remote host + // If we are host, execute JoinAnyTeam(myguid). + // - JoinAnyTeam(requesterGuid): Attempt to join any team immediately. If fails, send to all except requestGuid UpdateTeamsRequestedToAny(). Else sends out new team, including to caller. + // On remote host, execute JoinAnyTeamCheck(). If fails, this was because you were added to a team simultaneously on host. This is OK, just ignore the call. + // Assuming JoinAnyTeamCheck() passed on remote host, call UpdateTeamsRequestedToAny() for this player. execute JoinAnyTeam(packet->guid). + + if (JoinAnyTeamCheck()==false) + return false; + + UpdateTeamsRequestedToAny(); + + // Send request to host to execute JoinAnyTeam() + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_JoinAnyTeam); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + world->GetTeamManager()->SendUnified(&bsOut,HIGH_PRIORITY, RELIABLE_ORDERED, 0, world->GetHost(), false); + } + else + { + RakAssert(teamSelection.joinTeamType==JOIN_SPECIFIC_TEAM); + + // If joining specific team + // Execute JoinSpecificTeamCheck() + // JoinSpecificTeamCheck(): + // - If already on specific team, return false + // - If specific team is in requested list, return false + // On local, call AddToRequestedTeams(). Send event to also execute this to remote host + // If we are host, execute JoinSpecificTeam(myguid) + // - JoinSpecificTeam(requesterGuid): Attempt to join specific team immediately. If fails, send to all except requesterGuid to execute AddSpecificToRequested(). Else sends out new team, including to caller. + // On remote host, execute JoinSpecificTeamCheck(). If fails, just ignore. + // Assuming JoinSpecificTeamCheck() passed on host, call AddSpecificToRequestedList(). Execute JoinSpecificTeam(packet->guid) + + if (JoinSpecificTeamCheck(teamSelection.teamParameter.specificTeamToJoin,false)==false) + return false; + + AddToRequestedTeams(teamSelection.teamParameter.specificTeamToJoin); + + // Send request to host to execute JoinRequestedTeam() + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_JoinRequestedTeam); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + bsOut.Write(teamSelection.teamParameter.specificTeamToJoin->GetNetworkID()); + bsOut.Write(false); + world->GetTeamManager()->SendUnified(&bsOut,HIGH_PRIORITY, RELIABLE_ORDERED, 0, world->GetHost(), false); + } + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::RequestTeamSwitch(TM_Team *teamToJoin, TM_Team *teamToLeave) +{ + if (SwitchSpecificTeamCheck(teamToJoin,teamToLeave,false)==false) + return false; + + AddToRequestedTeams(teamToJoin, teamToLeave); + + // Send request to host to execute JoinRequestedTeam() + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_JoinRequestedTeam); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + bsOut.Write(teamToJoin->GetNetworkID()); + bsOut.Write(true); + if (teamToLeave) + { + bsOut.Write(true); + bsOut.Write(teamToLeave->GetNetworkID()); + } + else + { + bsOut.Write(false); + } + world->GetTeamManager()->SendUnified(&bsOut,HIGH_PRIORITY, RELIABLE_ORDERED, 0, world->GetHost(), false); + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamSelection TM_TeamMember::GetRequestedTeam(void) const +{ + if (teamsRequested.Size()>0) + return TeamSelection::SpecificTeam(teamsRequested[0].requested); + else if (joinTeamType==JOIN_NO_TEAM) + return TeamSelection::NoTeam(noTeamSubcategory); + else + return TeamSelection::AnyAvailable(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::GetRequestedSpecificTeams(DataStructures::List &requestedTeams) const +{ + requestedTeams.Clear(true, _FILE_AND_LINE_); + for (unsigned int i=0; i < teamsRequested.Size(); i++) + requestedTeams.Push(teamsRequested[i].requested, _FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::HasRequestedTeam(TM_Team *team) const +{ + unsigned int i = GetRequestedTeamIndex(team); + if (i==(unsigned int)-1) + return false; + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_TeamMember::GetRequestedTeamIndex(TM_Team *team) const +{ + unsigned int i; + for (i=0; i < teamsRequested.Size(); i++) + { + if (teamsRequested[i].requested==team) + return i; + } + return (unsigned int) -1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_TeamMember::GetRequestedTeamCount(void) const +{ + return teamsRequested.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::CancelTeamRequest(TM_Team *specificTeamToCancel) +{ + if (RemoveFromRequestedTeams(specificTeamToCancel)==false) + return false; + + // Send request to host to execute JoinRequestedTeam() + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + if (specificTeamToCancel) + { + bsOut.Write(true); + bsOut.Write(specificTeamToCancel->GetNetworkID()); + } + else + { + bsOut.Write(false); + } + world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + + world->GetTeamManager()->PushBitStream(&bsOut); + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::LeaveTeam(TM_Team* team, NoTeamId _noTeamSubcategory) +{ + if (LeaveTeamCheck(team)==false) + return false; + + RemoveFromSpecificTeamInternal(team); + if (teams.Size()==0) + { + noTeamSubcategory=_noTeamSubcategory; + joinTeamType=JOIN_NO_TEAM; + } + + // Execute LeaveTeamCheck() + // - LeaveTeamCheck(): + // - - If not on this team, return false + // On local, call RemoteFromTeamsList(). Send event to also execute this to remote host + // If we are host, execute OnLeaveTeamEvent(myGuid) + // - OnLeaveTeamEvent(requesterGuid): + // - - If rebalancing is active, rebalance + // - - If someone else wants to join this team, let them. + // - - Send leave team event notification to all except requesterGuid- + // On remote host, execute LeaveTeamCheck(). If fails, ignore. + // On remote host, execute RemoteFromTeamsList() followed by OnLeaveTeamEvent(packet->guid) + + // Pattern: + // Execute local check, if fails return false + // Locally execute non-host guaranteed changes + // If local system is also host, execute host changes. Relay to all but local + // On remote host, execute check. If check passes, execute non-host changes, followed by host changes. Relay to all but sender. + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_LeaveTeam); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + bsOut.Write(team->GetNetworkID()); + bsOut.Write(noTeamSubcategory); + world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) + { + // Rebalance teams + world->FillRequestedSlots(); + world->EnforceTeamBalance(noTeamSubcategory); + } + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::LeaveAllTeams(NoTeamId noTeamSubcategory) +{ + return RequestTeam(TeamSelection::NoTeam(noTeamSubcategory)); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_Team* TM_TeamMember::GetCurrentTeam(void) const +{ + if (teams.Size()>0) + return teams[0]; + return 0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_TeamMember::GetCurrentTeamCount(void) const +{ + return teams.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_Team* TM_TeamMember::GetCurrentTeamByIndex(unsigned int index) +{ + return teams[index]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::GetCurrentTeams(DataStructures::List &_teams) const +{ + _teams=teams; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::GetLastTeams(DataStructures::List &_teams) const +{ + _teams=lastTeams; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::IsOnTeam(TM_Team *team) const +{ + unsigned int i; + for (i=0; i < teams.Size(); i++) + { + if (teams[i]==team) + return true; + } + return false; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +NetworkID TM_TeamMember::GetNetworkID(void) const +{ + return networkId; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_World* TM_TeamMember::GetTM_World(void) const +{ + return world; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::SerializeConstruction(BitStream *constructionBitstream) +{ + // Write requested teams + constructionBitstream->Write(world->GetWorldId()); + constructionBitstream->Write(networkId); + constructionBitstream->WriteCasted(teamsRequested.Size()); + for (unsigned int i=0; i < teamsRequested.Size(); i++) + { + constructionBitstream->Write(teamsRequested[i].isTeamSwitch); + if (teamsRequested[i].teamToLeave) + { + constructionBitstream->Write(true); + constructionBitstream->Write(teamsRequested[i].teamToLeave->GetNetworkID()); + } + else + { + constructionBitstream->Write(false); + } + if (teamsRequested[i].requested) + { + constructionBitstream->Write(true); + constructionBitstream->Write(teamsRequested[i].requested->GetNetworkID()); + } + else + { + constructionBitstream->Write(false); + } + } + + world->teamManager->EncodeTeamAssigned(constructionBitstream, this); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream) +{ + // Read requested teams + bool success; + uint16_t teamsRequestedSize; + + WorldId worldId; + constructionBitstream->Read(worldId); + TM_World *world = teamManager->GetWorldWithId(worldId); + RakAssert(world); + constructionBitstream->Read(networkId); + world->ReferenceTeamMember(this,networkId); + + success=constructionBitstream->Read(teamsRequestedSize); + for (unsigned int i=0; i < teamsRequestedSize; i++) + { + RequestedTeam rt; + rt.isTeamSwitch=false; + rt.requested=0; + rt.whenRequested=0; + constructionBitstream->Read(rt.isTeamSwitch); + bool hasTeamToLeave=false; + constructionBitstream->Read(hasTeamToLeave); + NetworkID teamToLeaveId; + if (hasTeamToLeave) + { + constructionBitstream->Read(teamToLeaveId); + rt.teamToLeave = world->GetTeamByNetworkID(teamToLeaveId); + RakAssert(rt.teamToLeave); + } + else + rt.teamToLeave=0; + bool hasTeamRequested=false; + success=constructionBitstream->Read(hasTeamRequested); + NetworkID teamRequestedId; + if (hasTeamRequested) + { + success=constructionBitstream->Read(teamRequestedId); + rt.requested = world->GetTeamByNetworkID(teamRequestedId); + RakAssert(rt.requested); + } + rt.whenRequested=RakNet::GetTime(); + rt.requestIndex=world->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests + if ( + (hasTeamToLeave==false || (hasTeamToLeave==true && rt.teamToLeave!=0)) && + (hasTeamRequested==false || (hasTeamRequested==true && rt.requested!=0)) + ) + { + teamsRequested.Push(rt, _FILE_AND_LINE_); + } + } + + + if (success) + world->teamManager->ProcessTeamAssigned(constructionBitstream); + return success; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void *TM_TeamMember::GetOwner(void) const +{ + return owner; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::SetOwner(void *o) +{ + owner=o; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +NoTeamId TM_TeamMember::GetNoTeamId(void) const +{ + return noTeamSubcategory; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_TeamMember::GetWorldIndex(void) const +{ + return world->GetTeamMemberIndex(this); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned long TM_TeamMember::ToUint32( const NetworkID &g ) +{ + return g & 0xFFFFFFFF; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::UpdateListsToNoTeam(NoTeamId nti) +{ + teamsRequested.Clear(true, _FILE_AND_LINE_ ); + for (unsigned int i=0; i < teams.Size(); i++) + { + teams[i]->RemoveFromTeamMemberList(this); + } + teams.Clear(true, _FILE_AND_LINE_ ); + noTeamSubcategory=nti; + joinTeamType=JOIN_NO_TEAM; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::JoinAnyTeamCheck(void) const +{ + // - - If already on a team, return false + if (teams.Size() > 0) + return false; + + // - - If any team is already in requested teams, return false. + if (teamsRequested.Size()==0 && joinTeamType==JOIN_ANY_AVAILABLE_TEAM) + return false; + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::JoinSpecificTeamCheck(TM_Team *specificTeamToJoin, bool ignoreRequested) const +{ + // - If already on specific team, return false + if (IsOnTeam(specificTeamToJoin)) + return false; + + if (ignoreRequested) + return true; + + unsigned int i; + for (i=0; i < teamsRequested.Size(); i++) + { + if (teamsRequested[i].requested==specificTeamToJoin) + { + if (teamsRequested[i].isTeamSwitch==true) + return true; // Turn off team switch + + // Same thing + return false; + } + } + + // Not in teams requested + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::SwitchSpecificTeamCheck(TM_Team *teamToJoin, TM_Team *teamToLeave, bool ignoreRequested) const +{ + RakAssert(teamToJoin!=0); + + // - If already on specific team, return false + if (IsOnTeam(teamToJoin)) + return false; + + if (teamToLeave!=0 && IsOnTeam(teamToLeave)==false) + return false; + + if (teamToJoin==teamToLeave) + return false; + + if (ignoreRequested) + return true; + + unsigned int i; + for (i=0; i < teamsRequested.Size(); i++) + { + if (teamsRequested[i].requested==teamToJoin) + { + if (teamsRequested[i].isTeamSwitch==false) + return true; // Different - leave team was off, turn on + + if (teamsRequested[i].teamToLeave==teamToLeave) + return false; // Same thing - leave all or a specific team + + // Change leave team + return true; + } + } + + // Not in teams requested + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::LeaveTeamCheck(TM_Team *team) const +{ + if (IsOnTeam(team)==false) + return false; + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::UpdateTeamsRequestedToAny(void) +{ + teamsRequested.Clear(true, _FILE_AND_LINE_); + joinTeamType=JOIN_ANY_AVAILABLE_TEAM; + whenJoinAnyRequested=RakNet::GetTime(); + joinAnyRequestIndex=world->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::UpdateTeamsRequestedToNone(void) +{ + teamsRequested.Clear(true, _FILE_AND_LINE_); + joinTeamType=JOIN_NO_TEAM; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::AddToRequestedTeams(TM_Team *teamToJoin) +{ + RemoveFromRequestedTeams(teamToJoin); + + RequestedTeam rt; + rt.isTeamSwitch=false; + rt.requested=teamToJoin; + rt.teamToLeave=0; + rt.whenRequested=RakNet::GetTime(); + rt.requestIndex=world->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests + teamsRequested.Push(rt, _FILE_AND_LINE_ ); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::AddToRequestedTeams(TM_Team *teamToJoin, TM_Team *teamToLeave) +{ + RemoveFromRequestedTeams(teamToJoin); + + RequestedTeam rt; + rt.isTeamSwitch=true; + rt.requested=teamToJoin; + rt.teamToLeave=teamToLeave; + rt.whenRequested=RakNet::GetTime(); + rt.requestIndex=world->teamRequestIndex++; // In case whenRequested is the same between two teams when sorting team requests + teamsRequested.Push(rt, _FILE_AND_LINE_ ); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_TeamMember::RemoveFromRequestedTeams(TM_Team *team) +{ + if (team==0) + { + teamsRequested.Clear(true, _FILE_AND_LINE_); + joinTeamType=JOIN_NO_TEAM; + return true; + } + else + { + unsigned int i; + for (i=0; i < teamsRequested.Size(); i++) + { + if (teamsRequested[i].requested==team) + { + teamsRequested.RemoveAtIndex(i); + if (teamsRequested.Size()==0) + { + joinTeamType=JOIN_NO_TEAM; + } + return true; + } + } + } + return false; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::AddToTeamList(TM_Team *team) +{ + team->teamMembers.Push(this, _FILE_AND_LINE_ ); + teams.Push(team, _FILE_AND_LINE_ ); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::RemoveFromSpecificTeamInternal(TM_Team *team) +{ + unsigned int i,j; + for (i=0; i < teams.Size(); i++) + { + if (teams[i]==team) + { + for (j=0; j < team->teamMembers.Size(); j++) + { + if (team->teamMembers[j]==this) + { + team->teamMembers.RemoveAtIndex(j); + break; + } + } + teams.RemoveAtIndex(i); + break; + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::RemoveFromAllTeamsInternal(void) +{ + TM_Team *team; + unsigned int i,j; + for (i=0; i < teams.Size(); i++) + { + team = teams[i]; + + for (j=0; j < team->teamMembers.Size(); j++) + { + if (team->teamMembers[j]==this) + { + team->teamMembers.RemoveAtIndex(j); + break; + } + } + } + teams.Clear(true, _FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_TeamMember::StoreLastTeams(void) +{ + lastTeams=teams; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_Team::TM_Team() +{ + ID=0; + world=0; + joinPermissions=ALLOW_JOIN_ANY_AVAILABLE_TEAM|ALLOW_JOIN_SPECIFIC_TEAM|ALLOW_JOIN_REBALANCING; + balancingApplies=true; + teamMemberLimit=65535; + owner=0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_Team::~TM_Team() +{ + if (world) + world->DereferenceTeam(this, 0); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_Team::SetMemberLimit(TeamMemberLimit _teamMemberLimit, NoTeamId noTeamId) +{ + if (teamMemberLimit==_teamMemberLimit) + return false; + + teamMemberLimit=_teamMemberLimit; + // Network this as request to host + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_SetMemberLimit); + bsOut.Write(world->GetWorldId()); + bsOut.Write(GetNetworkID()); + bsOut.Write(teamMemberLimit); + bsOut.Write(noTeamId); + world->GetTeamManager()->Send(&bsOut, world->GetHost(), false); + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamMemberLimit TM_Team::GetMemberLimit(void) const +{ + if (world->GetBalanceTeams()==false) + { + return teamMemberLimit; + } + else + { + TeamMemberLimit limitWithBalancing=world->GetBalancedTeamLimit(); + if (limitWithBalancing < teamMemberLimit) + return limitWithBalancing; + return teamMemberLimit; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamMemberLimit TM_Team::GetMemberLimitSetting(void) const +{ + return teamMemberLimit; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_Team::SetJoinPermissions(JoinPermissions _joinPermissions) +{ + if (joinPermissions==_joinPermissions) + return false; + + joinPermissions=_joinPermissions; + + // Network this as request to host + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_SetJoinPermissions); + bsOut.Write(world->GetWorldId()); + bsOut.Write(GetNetworkID()); + bsOut.Write(_joinPermissions); + world->GetTeamManager()->Send(&bsOut,world->GetHost(), false); + + return true; + + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +JoinPermissions TM_Team::GetJoinPermissions(void) const +{ + return joinPermissions; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_Team::LeaveTeam(TM_TeamMember* teamMember, NoTeamId noTeamSubcategory) +{ + teamMember->LeaveTeam(this, noTeamSubcategory); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_Team::GetBalancingApplies(void) const +{ + return balancingApplies; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_Team::GetTeamMembers(DataStructures::List &_teamMembers) const +{ + _teamMembers=teamMembers; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_Team::GetTeamMembersCount(void) const +{ + return teamMembers.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_TeamMember *TM_Team::GetTeamMemberByIndex(unsigned int index) const +{ + return teamMembers[index]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +NetworkID TM_Team::GetNetworkID(void) const +{ + return ID; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_World* TM_Team::GetTM_World(void) const +{ + return world; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_Team::SerializeConstruction(BitStream *constructionBitstream) +{ + // Do not need to serialize member lists, the team members do this + constructionBitstream->Write(world->GetWorldId()); + constructionBitstream->Write(ID); + constructionBitstream->Write(joinPermissions); + constructionBitstream->Write(balancingApplies); + constructionBitstream->Write(teamMemberLimit); + +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_Team::DeserializeConstruction(TeamManager *teamManager, BitStream *constructionBitstream) +{ + WorldId worldId; + constructionBitstream->Read(worldId); + TM_World *world = teamManager->GetWorldWithId(worldId); + RakAssert(world); + constructionBitstream->Read(ID); + constructionBitstream->Read(joinPermissions); + constructionBitstream->Read(balancingApplies); + bool b = constructionBitstream->Read(teamMemberLimit); + RakAssert(b); + if (b) + { + world->ReferenceTeam(this,ID,balancingApplies); + } + return b; +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned long TM_Team::ToUint32( const NetworkID &g ) +{ + return g & 0xFFFFFFFF; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void *TM_Team::GetOwner(void) const +{ + return owner; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + +unsigned int TM_Team::GetWorldIndex(void) const +{ + return world->GetTeamIndex(this); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_Team::SetOwner(void *o) +{ + owner=o; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_Team::RemoveFromTeamMemberList(TM_TeamMember *teamMember) +{ + unsigned int index = teamMembers.GetIndexOf(teamMember); + RakAssert(index != (unsigned int) -1); + teamMembers.RemoveAtIndex(index); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_Team::GetMemberWithRequestedSingleTeamSwitch(TM_Team *team) +{ + unsigned int i; + for (i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i]->GetCurrentTeamCount()==1) + { + unsigned int j = teamMembers[i]->GetRequestedTeamIndex(team); + if (j!=(unsigned int)-1) + { + if (teamMembers[i]->teamsRequested[j].isTeamSwitch && + (teamMembers[i]->teamsRequested[j].teamToLeave==0 || + teamMembers[i]->teamsRequested[j].teamToLeave==teamMembers[i]->teams[0]) + ) + return i; + } + } + } + return (unsigned int) -1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_World::TM_World() +{ + teamManager=0; + balanceTeamsIsActive=false; + hostGuid=UNASSIGNED_RAKNET_GUID; + worldId=0; + autoAddParticipants=true; + teamRequestIndex=0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_World::~TM_World() +{ + Clear(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamManager *TM_World::GetTeamManager(void) const +{ + return teamManager; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::AddParticipant(RakNetGUID rakNetGUID) +{ + participants.Push(rakNetGUID, _FILE_AND_LINE_ ); + + // Send to remote system status of balanceTeamsIsActive + + if (GetTeamManager()->GetMyGUIDUnified()==GetHost()) + { + // Actually just transmitting initial value of balanceTeamsIsActive + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_SetBalanceTeamsInitial); + bsOut.Write(GetWorldId()); + bsOut.Write(balanceTeamsIsActive); + teamManager->SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0,rakNetGUID, false); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::RemoveParticipant(RakNetGUID rakNetGUID) +{ + unsigned int i; + i = participants.GetIndexOf(rakNetGUID); + if (i!=(unsigned int)-1) + participants.RemoveAtIndex(i); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::SetAutoManageConnections(bool autoAdd) +{ + autoAddParticipants=autoAdd; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::GetParticipantList(DataStructures::List &participantList) +{ + participantList = participants; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::ReferenceTeam(TM_Team *team, NetworkID networkId, bool applyBalancing) +{ + unsigned int i; + for (i=0; i < teams.Size(); i++) + { + if (teams[i]==team) + return; + } + + team->ID=networkId; + team->balancingApplies=applyBalancing; + team->world=this; + + // Add this team to the list of teams + teams.Push(team, _FILE_AND_LINE_); + + teamsHash.Push(networkId,team,_FILE_AND_LINE_); + + // If autobalancing is on, and the team lock state supports it, then call EnforceTeamBalancing() + if (applyBalancing && balanceTeamsIsActive) + { + EnforceTeamBalance(0); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::DereferenceTeam(TM_Team *team, NoTeamId noTeamSubcategory) +{ + unsigned int i; + for (i=0; i < teams.Size(); i++) + { + if (teams[i]==team) + { + TM_Team *team = teams[i]; + while (team->teamMembers.Size()) + { + team->teamMembers[team->teamMembers.Size()-1]->LeaveTeam(team, noTeamSubcategory); + } + teams.RemoveAtIndex(i); + + teamsHash.Remove(team->GetNetworkID(),_FILE_AND_LINE_); + + break; + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_World::GetTeamCount(void) const +{ + return teams.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_Team *TM_World::GetTeamByIndex(unsigned int index) const +{ + return teams[index]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_Team *TM_World::GetTeamByNetworkID(NetworkID teamId) +{ + DataStructures::HashIndex hi = teamsHash.GetIndexOf(teamId); + if (hi.IsInvalid()) + return 0; + return teamsHash.ItemAtIndex(hi); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_World::GetTeamIndex(const TM_Team *team) const +{ + unsigned int i; + for (i=0; i < teams.Size(); i++) + { + if (teams[i]==team) + return i; + } + return (unsigned int) -1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::ReferenceTeamMember(TM_TeamMember *teamMember, NetworkID networkId) +{ + unsigned int i; + for (i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i]==teamMember) + return; + } + + teamMember->world=this; + teamMember->networkId=networkId; + + teamMembers.Push(teamMember, _FILE_AND_LINE_); + + teamMembersHash.Push(networkId,teamMember,_FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::DereferenceTeamMember(TM_TeamMember *teamMember) +{ + unsigned int i; + for (i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i]==teamMember) + { + teamMembers[i]->UpdateListsToNoTeam(0); + teamMembersHash.Remove(teamMembers[i]->GetNetworkID(),_FILE_AND_LINE_); + teamMembers.RemoveAtIndex(i); + break; + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_World::GetTeamMemberCount(void) const +{ + return teamMembers.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_TeamMember *TM_World::GetTeamMemberByIndex(unsigned int index) const +{ + return teamMembers[index]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +NetworkID TM_World::GetTeamMemberIDByIndex(unsigned int index) const +{ + return teamMembers[index]->GetNetworkID(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_TeamMember *TM_World::GetTeamMemberByNetworkID(NetworkID teamMemberId) +{ + DataStructures::HashIndex hi = teamMembersHash.GetIndexOf(teamMemberId); + if (hi.IsInvalid()) + return 0; + return teamMembersHash.ItemAtIndex(hi); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_World::GetTeamMemberIndex(const TM_TeamMember *teamMember) const +{ + unsigned int i; + for (i=0; i < teamMembers.Size(); i++) + { + if (teamMembers[i]==teamMember) + return i; + } + return (unsigned int) -1; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_World::SetBalanceTeams(bool balanceTeams, NoTeamId noTeamId) +{ + if (balanceTeams==balanceTeamsIsActive) + return false; + + balanceTeamsIsActive=balanceTeams; + + // Network this as request to host + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_SetBalanceTeams); + bsOut.Write(GetWorldId()); + bsOut.Write(balanceTeams); + bsOut.Write(noTeamId); + GetTeamManager()->SendUnified(&bsOut,HIGH_PRIORITY, RELIABLE_ORDERED, 0, GetHost(), false); + + return true; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TM_World::GetBalanceTeams(void) const +{ + return balanceTeamsIsActive; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::SetHost(RakNetGUID _hostGuid) +{ + if (hostGuid==_hostGuid) + return; + + RakAssert(_hostGuid!=UNASSIGNED_RAKNET_GUID); + + hostGuid=_hostGuid; + + if (GetHost()==GetTeamManager()->GetMyGUIDUnified()) + FillRequestedSlots(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +RakNetGUID TM_World::GetHost(void) const +{ + return hostGuid; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +WorldId TM_World::GetWorldId(void) const +{ + return worldId; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::Clear(void) +{ + for (unsigned int i=0; i < teams.Size(); i++) + { + teams[i]->world=0; + } + for (unsigned int i=0; i < teamMembers.Size(); i++) + { + teamMembers[i]->world=0; + } + participants.Clear(true, _FILE_AND_LINE_); + teams.Clear(true, _FILE_AND_LINE_); + teamMembers.Clear(true, _FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) systemAddress; + + RemoveParticipant(rakNetGUID); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + (void) isIncoming; + (void) systemAddress; + + if (autoAddParticipants) + AddParticipant(rakNetGUID); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::EnforceTeamBalance(NoTeamId noTeamId) +{ + // Host only function + RakAssert(GetHost()==GetTeamManager()->GetMyGUIDUnified()); + + KickExcessMembers(noTeamId); +} + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::KickExcessMembers(NoTeamId noTeamId) +{ + // Host only function + RakAssert(GetHost()==GetTeamManager()->GetMyGUIDUnified()); + + // For each team that applies balancing, if the team is overfull, put on a team that is not overfull if the team has ALLOW_JOIN_REBALANCING set + // If cannot move the player to another team, just take the player off the team and set to noTeamId if they have no team at that point + + TeamMemberLimit balancedTeamLimit; + if (balanceTeamsIsActive) + balancedTeamLimit = GetBalancedTeamLimit(); + else + balancedTeamLimit = (TeamMemberLimit) -1; + + TM_Team *team, *teamToJoin; + unsigned int i, teamIndex; + for (i=0; i < teams.Size(); i++) + { + team = teams[i]; + while (team->GetMemberLimitSetting() < team->GetTeamMembersCount() || + (balancedTeamLimit < team->GetTeamMembersCount() && team->GetBalancingApplies()) ) + { + TM_TeamMember *teamMember = team->teamMembers[team->teamMembers.Size()-1]; + + teamIndex = GetAvailableTeamIndexWithFewestMembers(balancedTeamLimit, ALLOW_JOIN_REBALANCING); + if (teamIndex == (unsigned int)-1) + { + // Move this member to no team + teamMember->LeaveTeam(team, noTeamId); + teamManager->PushTeamAssigned(teamMember); + } + else + { + teamToJoin = teams[teamIndex]; + + // Move this member + teamMember->StoreLastTeams(); + teamManager->RemoveFromTeamsRequestedAndAddTeam(teamMember, teamToJoin, true, team); + + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_RemoveFromTeamsRequestedAndAddTeam); + bsOut.Write(GetWorldId()); + bsOut.Write(teamMember->GetNetworkID()); + bsOut.Write(teamToJoin->GetNetworkID()); + bsOut.Write(true); + bsOut.Write(true); + bsOut.Write(team->GetNetworkID()); + BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + } + + } + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::FillRequestedSlots(void) +{ + // Host only function + RakAssert(GetHost()==GetTeamManager()->GetMyGUIDUnified()); + + + TeamMemberLimit balancedTeamLimit; + if (balanceTeamsIsActive) + balancedTeamLimit = GetBalancedTeamLimit(); + else + balancedTeamLimit = (TeamMemberLimit) -1; + + unsigned int teamIndex, indexIntoTeamsRequested = (unsigned int)-1; + TM_Team *team; + TM_TeamMember *teamMember; + DataStructures::OrderedList joinRequests; + GetSortedJoinRequests(joinRequests); + unsigned int joinRequestIndex; + + for (joinRequestIndex=0; joinRequestIndex < joinRequests.Size(); joinRequestIndex++) + { + teamMember = teamMembers[joinRequests[joinRequestIndex].teamMemberIndex]; + if (teamMember->teamsRequested.Size()==0) + { + if (teamMember->joinTeamType==JOIN_ANY_AVAILABLE_TEAM) + teamIndex = GetAvailableTeamIndexWithFewestMembers(balancedTeamLimit, ALLOW_JOIN_ANY_AVAILABLE_TEAM); + else + teamIndex=(unsigned int)-1; + } + else + { + indexIntoTeamsRequested = joinRequests[joinRequestIndex].indexIntoTeamsRequested; + + team = teamMember->teamsRequested[indexIntoTeamsRequested].requested; + if (team->GetTeamMembersCount() < balancedTeamLimit && + team->GetTeamMembersCount() < team->GetMemberLimitSetting() && + (ALLOW_JOIN_SPECIFIC_TEAM & team->GetJoinPermissions())!=0) + { + teamIndex=teams.GetIndexOf(team); + } + else + { + teamIndex=(unsigned int)-1; + } + } + + if (teamIndex != (unsigned int)-1) + { + team = teams[teamIndex]; + + if (teamMember->teamsRequested.Size()==0) + { + if (teamMember->joinTeamType==JOIN_ANY_AVAILABLE_TEAM) + { + // Join any + teamMember->StoreLastTeams(); + teamMember->UpdateTeamsRequestedToNone(); + teamMember->AddToTeamList(teams[teamIndex]); + teamManager->PushTeamAssigned(teamMember); + + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam); + bsOut.Write(GetWorldId()); + bsOut.Write(teamMember->GetNetworkID()); + bsOut.Write(team->GetNetworkID()); + BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + } + } + else + { + // Switch or join specific + DataStructures::List teamsWeAreLeaving; + bool isSwitch = teamMember->teamsRequested[indexIntoTeamsRequested].isTeamSwitch; + TM_Team *teamToLeave; + if (isSwitch) + { + teamToLeave=teamMember->teamsRequested[indexIntoTeamsRequested].teamToLeave; + if (teamToLeave) + { + if (teamMember->IsOnTeam(teamToLeave)) + { + teamsWeAreLeaving.Push(teamToLeave, _FILE_AND_LINE_); + } + else + { + teamToLeave=0; + isSwitch=false; + } + } + else + { + teamsWeAreLeaving=teamMember->teams; + } + } + else + teamToLeave=0; + + int teamJoined = JoinSpecificTeam(teamMember, team, isSwitch, teamToLeave, teamsWeAreLeaving); + + if (teamJoined==1) + { + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_RemoveFromTeamsRequestedAndAddTeam); + bsOut.Write(GetWorldId()); + bsOut.Write(teamMember->GetNetworkID()); + bsOut.Write(team->GetNetworkID()); + bsOut.Write(isSwitch); + if (teamToLeave!=0) + { + bsOut.Write(true); + bsOut.Write(teamToLeave->GetNetworkID()); + } + else + bsOut.Write(false); + BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + } + } + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TM_World::GetAvailableTeamIndexWithFewestMembers(TeamMemberLimit secondaryLimit, JoinPermissions joinPermissions) +{ + unsigned int teamIndex; + + unsigned int lowestTeamMembers = (unsigned int) -1; + unsigned int lowestIndex = (unsigned int) -1; + + for (teamIndex=0; teamIndex < teams.Size(); teamIndex++) + { + if (teams[teamIndex]->GetTeamMembersCount() < secondaryLimit && + teams[teamIndex]->GetTeamMembersCount() < teams[teamIndex]->GetMemberLimitSetting() && + teams[teamIndex]->GetTeamMembersCount() < lowestTeamMembers && + (joinPermissions & teams[teamIndex]->GetJoinPermissions())!=0) + { + lowestTeamMembers = teams[teamIndex]->GetTeamMembersCount(); + lowestIndex = teamIndex; + } + } + + return lowestIndex; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::GetSortedJoinRequests(DataStructures::OrderedList &joinRequests) +{ + unsigned int i; + + for (i=0; i < teamMembers.Size(); i++) + { + TM_TeamMember *teamMember = teamMembers[i]; + if (teamMember->teamsRequested.Size()==0) + { + if (teamMember->joinTeamType==JOIN_ANY_AVAILABLE_TEAM) + { + TM_World::JoinRequestHelper jrh; + jrh.whenRequestMade=teamMember->whenJoinAnyRequested; + jrh.teamMemberIndex=i; + jrh.requestIndex=teamMember->joinAnyRequestIndex; + joinRequests.Insert(jrh, jrh, true, _FILE_AND_LINE_); + } + } + else + { + unsigned int j; + for (j=0; j < teamMember->teamsRequested.Size(); j++) + { + TM_World::JoinRequestHelper jrh; + jrh.whenRequestMade=teamMember->teamsRequested[j].whenRequested; + jrh.teamMemberIndex=i; + jrh.indexIntoTeamsRequested=j; + jrh.requestIndex=teamMember->teamsRequested[j].requestIndex; + joinRequests.Insert(jrh, jrh, true, _FILE_AND_LINE_); + } + + } + } +} +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::BroadcastToParticipants(RakNet::BitStream *bsOut, RakNetGUID exclusionGuid) +{ + for (unsigned int i=0; i < participants.Size(); i++) + { + if (participants[i]==exclusionGuid) + continue; + teamManager->SendUnified(bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, participants[i], false); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TM_World::BroadcastToParticipants(unsigned char *data, const int length, RakNetGUID exclusionGuid) +{ + for (unsigned int i=0; i < participants.Size(); i++) + { + if (participants[i]==exclusionGuid) + continue; + teamManager->SendUnified((const char*) data, length, HIGH_PRIORITY, RELIABLE_ORDERED, 0, participants[i], false); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_Team* TM_World::JoinAnyTeam(TM_TeamMember *teamMember, int *resultCode) +{ + TeamMemberLimit balancedLimit = GetBalancedTeamLimit(); + + unsigned int idx = GetAvailableTeamIndexWithFewestMembers(balancedLimit, ALLOW_JOIN_ANY_AVAILABLE_TEAM); + if (idx == (unsigned int ) -1) + { + // If any team is joinable but full, return full. Otherwise return locked + for (idx=0; idx < teams.Size(); idx++) + { + if ((teams[idx]->GetTeamMembersCount() >= balancedLimit || + teams[idx]->GetTeamMembersCount() >= teams[idx]->GetMemberLimitSetting()) && + teams[idx]->GetMemberLimitSetting() != 0 && + (ALLOW_JOIN_ANY_AVAILABLE_TEAM & teams[idx]->GetJoinPermissions())!=0) + { + // Full + *resultCode=-2; + return teams[idx]; + } + } + + // Locked + *resultCode=-1; + return 0; + } + + TM_Team* lowestMemberTeam = teams[idx]; + + teamMember->StoreLastTeams(); + teamMember->UpdateTeamsRequestedToNone(); + teamMember->AddToTeamList(lowestMemberTeam); + teamManager->PushTeamAssigned(teamMember); + + *resultCode=1; + return lowestMemberTeam; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +int TM_World::JoinSpecificTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave, DataStructures::List &teamsWeAreLeaving) +{ + if (team->GetJoinPermissions() & ALLOW_JOIN_SPECIFIC_TEAM) + { + if (balanceTeamsIsActive==false || teamsWeAreLeaving.Size()==0) + { + if (team->GetMemberLimit() > team->GetTeamMembersCount()) + { + // Can join normally + teamMember->StoreLastTeams(); + teamManager->RemoveFromTeamsRequestedAndAddTeam(teamMember, team, isTeamSwitch, teamToLeave); + return 1; + } + else + { + // Full + return -2; + } + } + else + { + // Note: balanceTeamsIsActive==true && isTeamSwitch==true + + // Do limited team swap + // We must be on one team, target must be on one team, and we want to exchange teams + if (teamsWeAreLeaving.Size()==1) + { + unsigned int j = team->GetMemberWithRequestedSingleTeamSwitch(teamsWeAreLeaving[0]); + if (j!=(unsigned int)-1) + { + TM_TeamMember *swappingMember = team->teamMembers[j]; + teamMember->StoreLastTeams(); + swappingMember->StoreLastTeams(); + teamManager->RemoveFromTeamsRequestedAndAddTeam(teamMember, team, true, 0); + teamManager->RemoveFromTeamsRequestedAndAddTeam(swappingMember, teamsWeAreLeaving[0], true, 0); + + // Send ID_TEAM_BALANCER_TEAM_ASSIGNED to all, for swapped member + // Calling function sends ID_RUN_RemoveFromTeamsRequestedAndAddTeam which pushes ID_TEAM_BALANCER_TEAM_ASSIGNED for teamMember + RakNet::BitStream bitStream; + bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); + teamManager->EncodeTeamAssigned(&bitStream, swappingMember); + BroadcastToParticipants(&bitStream, UNASSIGNED_RAKNET_GUID); + + return 1; + } + } + + // Full + return -2; + } + } + else + { + // Locked + return -1; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamMemberLimit TM_World::GetBalancedTeamLimit(void) const +{ + if (teams.Size()==0) + return 0; + + if (balanceTeamsIsActive==false) + return (TeamMemberLimit) -1; + + unsigned int i; + bool additionalTeamsExcluded; + TeamMemberLimit balancedLimit; + unsigned int teamsCount=teams.Size(); + unsigned int membersCount=teamMembers.Size(); + DataStructures::List consideredTeams = teams; + + do + { + additionalTeamsExcluded=false; + balancedLimit = (TeamMemberLimit) ((membersCount+(teamsCount-1))/(teamsCount)); + i=0; + while (i < consideredTeams.Size()) + { + if (consideredTeams[i]->GetMemberLimitSetting() < balancedLimit) + { + additionalTeamsExcluded=true; + membersCount-=consideredTeams[i]->GetMemberLimitSetting(); + teamsCount--; + consideredTeams.RemoveAtIndexFast(i); + } + else + { + i++; + } + } + + } while (additionalTeamsExcluded==true && teamsCount>0); + + return balancedLimit; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamManager::TeamManager() +{ + for (unsigned int i=0; i < 255; i++) + worldsArray[i]=0; + autoAddParticipants=true; + topology=TM_PEER_TO_PEER; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TeamManager::~TeamManager() +{ + Clear(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_World* TeamManager::AddWorld(WorldId worldId) +{ + RakAssert(worldsArray[worldId]==0 && "World already in use"); + + TM_World *newWorld = RakNet::OP_NEW(_FILE_AND_LINE_); + newWorld->worldId=worldId; + newWorld->teamManager=this; + newWorld->hostGuid=GetMyGUIDUnified(); + worldsArray[worldId]=newWorld; + worldsList.Push(newWorld,_FILE_AND_LINE_); + return newWorld; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::RemoveWorld(WorldId worldId) +{ + RakAssert(worldsArray[worldId]!=0 && "World not in use"); + for (unsigned int i=0; i < worldsList.Size(); i++) + { + if (worldsList[i]==worldsArray[worldId]) + { + RakNet::OP_DELETE(worldsList[i],_FILE_AND_LINE_); + worldsList.RemoveAtIndexFast(i); + break; + } + } + worldsArray[worldId]=0; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +unsigned int TeamManager::GetWorldCount(void) const +{ + return worldsList.Size(); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_World* TeamManager::GetWorldAtIndex(unsigned int index) const +{ + return worldsList[index]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +TM_World* TeamManager::GetWorldWithId(WorldId worldId) const +{ + return worldsArray[worldId]; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::SetAutoManageConnections(bool autoAdd) +{ + autoAddParticipants=autoAdd; + + for (unsigned int i=0; i < worldsList.Size(); i++) + { + worldsList[i]->SetAutoManageConnections(autoAdd); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::SetTopology(TMTopology _topology) +{ + topology=_topology; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::EncodeTeamFull(RakNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team) +{ + bitStream->WriteCasted(ID_TEAM_BALANCER_REQUESTED_TEAM_FULL); + EncodeTeamFullOrLocked(bitStream, teamMember, team); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::DecomposeTeamFull(Packet *packet, + TM_World **world, TM_TeamMember **teamMember, TM_Team **team, + uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + DecomposeTeamFullOrLocked(&bsIn, world, teamMember, team, currentMembers, memberLimitIncludingBalancing, balancingIsActive, joinPermissions); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::EncodeTeamLocked(RakNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team) +{ + bitStream->WriteCasted(ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED); + EncodeTeamFullOrLocked(bitStream, teamMember, team); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::EncodeTeamFullOrLocked(RakNet::BitStream *bitStream, TM_TeamMember *teamMember, TM_Team *team) +{ + bitStream->Write(teamMember->world->GetWorldId()); + bitStream->Write(teamMember->GetNetworkID()); + bitStream->Write(team->GetNetworkID()); + bitStream->WriteCasted(team->GetTeamMembersCount()); + bitStream->Write(team->GetMemberLimit()); + bitStream->Write(team->GetBalancingApplies()); + bitStream->Write(team->GetJoinPermissions()); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::DecomposeTeamFullOrLocked(RakNet::BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, TM_Team **team, + uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions) +{ + WorldId worldId; + NetworkID teamMemberId; + NetworkID teamId; + + *teamMember=0; + *team=0; + *world=0; + + bsIn->Read(worldId); + bsIn->Read(teamMemberId); + bsIn->Read(teamId); + bsIn->Read(currentMembers); + bsIn->Read(memberLimitIncludingBalancing); + bsIn->Read(balancingIsActive); + bsIn->Read(joinPermissions); + + *world = GetWorldWithId(worldId); + if (*world) + { + *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); + *team = (*world)->GetTeamByNetworkID(teamId); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::DecomposeTeamLocked(Packet *packet, + TM_World **world, TM_TeamMember **teamMember, TM_Team **team, + uint16_t ¤tMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + DecomposeTeamFullOrLocked(&bsIn, world, teamMember, team, currentMembers, memberLimitIncludingBalancing, balancingIsActive, joinPermissions); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::EncodeTeamAssigned(RakNet::BitStream *bitStream, TM_TeamMember *teamMember) +{ + bitStream->Write(teamMember->world->GetWorldId()); + bitStream->Write(teamMember->GetNetworkID()); + bitStream->WriteCasted(teamMember->teams.Size()); + for (unsigned int i=0; i < teamMember->teams.Size(); i++) + { + bitStream->Write(teamMember->teams[i]->GetNetworkID()); + } + bitStream->Write(teamMember->noTeamSubcategory); + bitStream->Write(teamMember->joinTeamType); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::ProcessTeamAssigned(RakNet::BitStream *bsIn) +{ + TM_World *world; + TM_TeamMember *teamMember; + NoTeamId noTeamId; + JoinTeamType joinTeamType; + DataStructures::List newTeam; + DataStructures::List teamsLeft; + DataStructures::List teamsJoined; + DecodeTeamAssigned(bsIn, &world, &teamMember, noTeamId, joinTeamType, newTeam, teamsLeft, teamsJoined); + if (teamMember) + { + teamMember->StoreLastTeams(); + for (unsigned int i=0; i < teamsLeft.Size(); i++) + { + teamMember->RemoveFromSpecificTeamInternal(teamsLeft[i]); + } + for (unsigned int i=0; i < teamsJoined.Size(); i++) + { + if (teamMember->IsOnTeam(teamsJoined[i])==false) + { + teamMember->RemoveFromRequestedTeams(teamsJoined[i]); + teamMember->AddToTeamList(teamsJoined[i]); + } + } + teamMember->noTeamSubcategory=noTeamId; + teamMember->joinTeamType=joinTeamType; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::DecodeTeamAssigned(Packet *packet, TM_World **world, TM_TeamMember **teamMember) +{ + WorldId worldId; + NetworkID teamMemberId; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + bsIn.Read(worldId); + bsIn.Read(teamMemberId); + *world = GetWorldWithId(worldId); + if (*world) + { + *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); + } + else + { + *teamMember=0; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::DecodeTeamCancelled(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **teamCancelled) +{ + WorldId worldId; + NetworkID teamMemberId; + + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)); + bsIn.Read(worldId); + bsIn.Read(teamMemberId); + bool sp=false; + *world = GetWorldWithId(worldId); + if (*world) + { + *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); + } + else + { + *teamMember=0; + } + + bsIn.Read(sp); + if (sp) + { + NetworkID nid; + bsIn.Read(nid); + *teamCancelled = (*world)->GetTeamByNetworkID(nid); + } + else + { + *teamCancelled = 0; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::DecodeTeamAssigned(BitStream *bsIn, TM_World **world, TM_TeamMember **teamMember, NoTeamId &noTeamId, + JoinTeamType &joinTeamType, DataStructures::List &newTeam, + DataStructures::List &teamsLeft, DataStructures::List &teamsJoined + ) +{ + newTeam.Clear(true, _FILE_AND_LINE_); + teamsLeft.Clear(true, _FILE_AND_LINE_); + teamsJoined.Clear(true, _FILE_AND_LINE_); + + WorldId worldId; + NetworkID teamMemberId; + NetworkID teamId; + + bsIn->Read(worldId); + bsIn->Read(teamMemberId); + *world = GetWorldWithId(worldId); + if (*world) + { + *teamMember = (*world)->GetTeamMemberByNetworkID(teamMemberId); + uint16_t teamsCount; + bsIn->Read(teamsCount); + + for (unsigned int i=0; i < teamsCount; i++) + { + bsIn->Read(teamId); + TM_Team * team = (*world)->GetTeamByNetworkID(teamId); + RakAssert(team); + if (team) + newTeam.Push(team, _FILE_AND_LINE_); + // else probably didn't reference team first + } + + if (*teamMember) + { + for (unsigned int i=0; i < (*teamMember)->teams.Size(); i++) + { + TM_Team *team = (*teamMember)->teams[i]; + if (newTeam.GetIndexOf(team)==(unsigned int)-1) + teamsLeft.Push(team, _FILE_AND_LINE_); + } + } + + for (unsigned int i=0; i < newTeam.Size(); i++) + { + TM_Team *team = newTeam[i]; + if ((*teamMember)->teams.GetIndexOf(team)==(unsigned int)-1) + teamsJoined.Push(team, _FILE_AND_LINE_); + } + + bsIn->Read(noTeamId); + bsIn->Read(joinTeamType); + } + else + { + *teamMember=0; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::Clear(void) +{ + for (unsigned int i=0; i < worldsList.Size(); i++) + { + worldsArray[worldsList[i]->worldId]=0; + worldsList[i]->Clear(); + delete worldsList[i]; + } + worldsList.Clear(false, _FILE_AND_LINE_); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::Update(void) +{ +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +PluginReceiveResult TeamManager::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_FCM2_NEW_HOST: + { + unsigned int i; + for (i=0; i < worldsList.Size(); i++) + worldsList[i]->SetHost(packet->guid); + } + break; + case ID_TEAM_BALANCER_TEAM_ASSIGNED: + { + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + + ProcessTeamAssigned(&bsIn); + } + break; + case ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED: + { + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(1); + WorldId worldId; + bsIn.Read(worldId); + TM_World *world = GetWorldWithId(worldId); + if (world==0) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + bool validPacket = OnRemoveFromRequestedTeams(packet, world); + if (validPacket==false) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + break; + } + case ID_TEAM_BALANCER_INTERNAL: + { + if (packet->length>=2) + { + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2); + WorldId worldId; + bsIn.Read(worldId); + TM_World *world = GetWorldWithId(worldId); + if (world==0) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + + switch (packet->data[1]) + { + case ID_RUN_UpdateListsToNoTeam: + OnUpdateListsToNoTeam(packet, world); + break; + case ID_RUN_UpdateTeamsRequestedToAny: + OnUpdateTeamsRequestedToAny(packet, world); + break; + case ID_RUN_JoinAnyTeam: + OnJoinAnyTeam(packet, world); + break; + case ID_RUN_JoinRequestedTeam: + OnJoinRequestedTeam(packet, world); + break; + case ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam: + OnUpdateTeamsRequestedToNoneAndAddTeam(packet, world); + break; + case ID_RUN_RemoveFromTeamsRequestedAndAddTeam: + OnRemoveFromTeamsRequestedAndAddTeam(packet, world); + break; + case ID_RUN_AddToRequestedTeams: + OnAddToRequestedTeams(packet, world); + break; + case ID_RUN_LeaveTeam: + OnLeaveTeam(packet, world); + break; + case ID_RUN_SetMemberLimit: + OnSetMemberLimit(packet, world); + break; + case ID_RUN_SetJoinPermissions: + OnSetJoinPermissions(packet, world); + break; + case ID_RUN_SetBalanceTeams: + OnSetBalanceTeams(packet, world); + break; + case ID_RUN_SetBalanceTeamsInitial: + OnSetBalanceTeamsInitial(packet, world); + break; + } + } + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + + return RR_CONTINUE_PROCESSING; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + for (unsigned int i=0; i < worldsList.Size(); i++) + { + worldsList[i]->OnClosedConnection(systemAddress, rakNetGUID, lostConnectionReason); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming) +{ + for (unsigned int i=0; i < worldsList.Size(); i++) + { + worldsList[i]->OnNewConnection(systemAddress, rakNetGUID, isIncoming); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::Send( const RakNet::BitStream * bitStream, const AddressOrGUID systemIdentifier, bool broadcast ) +{ + SendUnified(bitStream,HIGH_PRIORITY, RELIABLE_ORDERED, 0, systemIdentifier, broadcast); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::RemoveFromTeamsRequestedAndAddTeam(TM_TeamMember *teamMember, TM_Team *team, bool isTeamSwitch, TM_Team *teamToLeave) +{ + teamMember->RemoveFromRequestedTeams(team); + if (isTeamSwitch) + { + if (teamToLeave==0) + { + // Leave all teams + teamMember->RemoveFromAllTeamsInternal(); + } + else + { + // Leave specific team if it exists + teamMember->RemoveFromSpecificTeamInternal(teamToLeave); + } + } + teamMember->AddToTeamList(team); + PushTeamAssigned(teamMember); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::PushTeamAssigned(TM_TeamMember *teamMember) +{ + // Push ID_TEAM_BALANCER_TEAM_ASSIGNED locally + RakNet::BitStream bitStream; + bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); + EncodeTeamAssigned(&bitStream, teamMember); + + PushBitStream(&bitStream); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::PushBitStream(RakNet::BitStream *bitStream) +{ + Packet *p = AllocatePacketUnified(bitStream->GetNumberOfBytesUsed()); + memcpy(p->data, bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); + p->systemAddress=UNASSIGNED_SYSTEM_ADDRESS; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=UNASSIGNED_RAKNET_GUID; + p->wasGeneratedLocally=true; + PushBackPacketUnified(p, true); +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnUpdateListsToNoTeam(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + NoTeamId noTeamId; + bsIn.Read(noTeamId); + if (teamMember) + { + teamMember->StoreLastTeams(); + teamMember->UpdateListsToNoTeam(noTeamId); + PushTeamAssigned(teamMember); + + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) + { + world->FillRequestedSlots(); + world->EnforceTeamBalance(noTeamId); + + if (topology==TM_CLIENT_SERVER) + { + // Relay + world->BroadcastToParticipants(packet->data, packet->length, packet->guid); + } + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnUpdateTeamsRequestedToAny(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + if (teamMember) + { + teamMember->UpdateTeamsRequestedToAny(); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnJoinAnyTeam(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + if (teamMember) + { + // This is a host-only operation + RakAssert(world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()); + + teamMember->UpdateTeamsRequestedToAny(); + + int resultCode; + TM_Team *newTeam = world->JoinAnyTeam(teamMember, &resultCode); + + if (resultCode==1) + { + // Broadcast packet - remote systems should clear requested teams to none, and add the team we joined. + // Broadcast includes non-host sender (all participants) + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_UpdateTeamsRequestedToNoneAndAddTeam); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + bsOut.Write(newTeam->GetNetworkID()); + world->BroadcastToParticipants(&bsOut, packet->guid); + + // Send to sender ID_TEAM_BALANCER_TEAM_ASSIGNED + if (packet->guid!=GetMyGUIDUnified()) + { + RakNet::BitStream bitStream; + bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); + EncodeTeamAssigned(&bitStream, teamMember); + SendUnified(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + } + } + else + { + // Relay packet to set requested teams to any + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_UpdateTeamsRequestedToAny); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + world->BroadcastToParticipants(&bsOut, packet->guid); + + bsOut.Reset(); + if (resultCode==-2) + { + EncodeTeamFull(&bsOut, teamMember, newTeam); + } + else if (resultCode==-1) + { + EncodeTeamLocked(&bsOut, teamMember, newTeam); + } + // SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + if (packet->guid!=GetMyGUIDUnified()) + PushBitStream(&bsOut); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnJoinRequestedTeam(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + NetworkID teamToJoinNetworkId; + bsIn.Read(teamToJoinNetworkId); + TM_Team *teamToJoin = world->GetTeamByNetworkID(teamToJoinNetworkId); + bool isTeamSwitch=false; + bool switchSpecificTeam=false; + NetworkID teamToLeaveNetworkId=UNASSIGNED_NETWORK_ID; + TM_Team *teamToLeave=0; + bsIn.Read(isTeamSwitch); + if (isTeamSwitch) + { + bsIn.Read(switchSpecificTeam); + if (switchSpecificTeam) + { + bsIn.Read(teamToLeaveNetworkId); + teamToLeave = world->GetTeamByNetworkID(teamToLeaveNetworkId); + if (teamToLeave==0) + isTeamSwitch=false; + } + } + if (teamToJoin && teamMember) + { + if (isTeamSwitch) + { + if (teamMember->SwitchSpecificTeamCheck(teamToJoin, teamToLeave, packet->guid==GetMyGUIDUnified())==false) + return; + + teamMember->AddToRequestedTeams(teamToJoin, teamToLeave); + } + else + { + if (teamMember->JoinSpecificTeamCheck(teamToJoin, packet->guid==GetMyGUIDUnified())==false) + return; + + teamMember->AddToRequestedTeams(teamToJoin); + } + + DataStructures::List teamsWeAreLeaving; + if (isTeamSwitch) + { + if (teamToLeave==0) + { + teamsWeAreLeaving=teamMember->teams; + } + else + { + if (teamMember->IsOnTeam(teamToLeave)) + teamsWeAreLeaving.Push(teamToLeave, _FILE_AND_LINE_); + } + + if (teamsWeAreLeaving.Size()==0) + isTeamSwitch=false; + } + + int resultCode = world->JoinSpecificTeam(teamMember, teamToJoin, isTeamSwitch, teamToLeave, teamsWeAreLeaving); + + if (resultCode==1) + { + // Broadcast packet - remote systems should remove from requested teams and add the team we joined. + // Broadcast includes non-host sender (all participants) + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_RemoveFromTeamsRequestedAndAddTeam); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + bsOut.Write(teamToJoin->GetNetworkID()); + bsOut.Write(isTeamSwitch); + if (isTeamSwitch) + { + bsOut.Write(switchSpecificTeam); + if (switchSpecificTeam) + bsOut.Write(teamToLeaveNetworkId); + } + world->BroadcastToParticipants(&bsOut, packet->guid); + + // Send to sender ID_TEAM_BALANCER_TEAM_ASSIGNED + if (packet->guid!=GetMyGUIDUnified()) + { + RakNet::BitStream bitStream; + bitStream.WriteCasted(ID_TEAM_BALANCER_TEAM_ASSIGNED); + EncodeTeamAssigned(&bitStream, teamMember); + SendUnified(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + } + } + else + { + // Relay packet to set requested teams to any + BitStream bsOut; + bsOut.WriteCasted(ID_TEAM_BALANCER_INTERNAL); + bsOut.WriteCasted(ID_RUN_AddToRequestedTeams); + bsOut.Write(world->GetWorldId()); + bsOut.Write(networkId); + bsOut.Write(teamToJoin->GetNetworkID()); + bsOut.Write(isTeamSwitch); + if (isTeamSwitch) + { + bsOut.Write(switchSpecificTeam); + if (switchSpecificTeam) + bsOut.Write(teamToLeaveNetworkId); + } + world->BroadcastToParticipants(&bsOut, packet->guid); + + bsOut.Reset(); + if (resultCode==-2) + { + EncodeTeamFull(&bsOut, teamMember, teamToJoin); + } + else if (resultCode==-1) + { + EncodeTeamLocked(&bsOut, teamMember, teamToJoin); + } + // SendUnified(&bsOut, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->guid, false); + + world->BroadcastToParticipants(&bsOut, UNASSIGNED_RAKNET_GUID); + if (packet->guid!=GetMyGUIDUnified()) + PushBitStream(&bsOut); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnUpdateTeamsRequestedToNoneAndAddTeam(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + NetworkID teamNetworkId; + bsIn.Read(teamNetworkId); + TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); + + if (team && teamMember) + { + teamMember->StoreLastTeams(); + teamMember->UpdateTeamsRequestedToNone(); + teamMember->AddToTeamList(team); + world->GetTeamManager()->PushTeamAssigned(teamMember); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnRemoveFromTeamsRequestedAndAddTeam(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + NetworkID teamNetworkId; + bsIn.Read(teamNetworkId); + bool isTeamSwitch=false, switchSpecificTeam=false; + NetworkID teamToLeaveNetworkId; + TM_Team *teamToLeave=0; + bsIn.Read(isTeamSwitch); + if (isTeamSwitch) + { + bsIn.Read(switchSpecificTeam); + if (switchSpecificTeam) + { + bsIn.Read(teamToLeaveNetworkId); + teamToLeave = world->GetTeamByNetworkID(teamToLeaveNetworkId); + } + } + + TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); + if (team && teamMember) + { + teamMember->StoreLastTeams(); + if (teamToLeave) + teamMember->RemoveFromSpecificTeamInternal(teamToLeave); + else if (isTeamSwitch==true && switchSpecificTeam==false) + teamMember->RemoveFromAllTeamsInternal(); + RemoveFromTeamsRequestedAndAddTeam(teamMember, team, false, 0); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnAddToRequestedTeams(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + NetworkID teamNetworkId; + bsIn.Read(teamNetworkId); + TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); + + bool isTeamSwitch=false; + bool switchSpecificTeam=false; + NetworkID teamToLeaveNetworkId=UNASSIGNED_NETWORK_ID; + TM_Team *teamToLeave=0; + bsIn.Read(isTeamSwitch); + if (isTeamSwitch) + { + bsIn.Read(switchSpecificTeam); + if (switchSpecificTeam) + { + bsIn.Read(teamToLeaveNetworkId); + teamToLeave = world->GetTeamByNetworkID(teamToLeaveNetworkId); + if (teamToLeave==0) + isTeamSwitch=false; + } + } + + if (team && teamMember) + { + if (isTeamSwitch) + teamMember->AddToRequestedTeams(team, teamToLeave); + else + teamMember->AddToRequestedTeams(team); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +bool TeamManager::OnRemoveFromRequestedTeams(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(1+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + bool hasSpecificTeam=false; + NetworkID teamNetworkId; + TM_Team *team; + bsIn.Read(hasSpecificTeam); + if (hasSpecificTeam) + { + bsIn.Read(teamNetworkId); + team = world->GetTeamByNetworkID(teamNetworkId); + if (team==0) + return false; + } + else + { + team=0; + } + + if (teamMember) + { + teamMember->RemoveFromRequestedTeams(team); + + // Relay as host + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified() && topology==TM_CLIENT_SERVER) + { + world->BroadcastToParticipants(packet->data, packet->length, packet->guid); + } + return true; + } + else + { + return false; + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnLeaveTeam(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID networkId; + bsIn.Read(networkId); + TM_TeamMember *teamMember = world->GetTeamMemberByNetworkID(networkId); + NetworkID teamNetworkId; + bsIn.Read(teamNetworkId); + TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); + NoTeamId noTeamId; + bsIn.Read(noTeamId); + + if (team && teamMember) + { + if (teamMember->LeaveTeamCheck(team)==false) + return; + + teamMember->StoreLastTeams(); + teamMember->RemoveFromSpecificTeamInternal(team); + if (teamMember->GetCurrentTeamCount()==0) + { + teamMember->noTeamSubcategory=noTeamId; + teamMember->joinTeamType=JOIN_NO_TEAM; + } + PushTeamAssigned(teamMember); + + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) + { + // Rebalance teams + world->FillRequestedSlots(); + world->EnforceTeamBalance(noTeamId); + + // Relay as host + if (topology==TM_CLIENT_SERVER) + world->BroadcastToParticipants(packet->data, packet->length, packet->guid); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnSetMemberLimit(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID teamNetworkId; + bsIn.Read(teamNetworkId); + TeamMemberLimit teamMemberLimit; + NoTeamId noTeamId; + bsIn.Read(teamMemberLimit); + bsIn.Read(noTeamId); + + TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); + if (team) + { + team->teamMemberLimit=teamMemberLimit; + + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) + { + if (packet->guid==GetMyGUIDUnified()) + world->BroadcastToParticipants(packet->data, packet->length, packet->guid); + else + world->BroadcastToParticipants(packet->data, packet->length, UNASSIGNED_RAKNET_GUID); + world->FillRequestedSlots(); + world->KickExcessMembers(noTeamId); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnSetJoinPermissions(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + NetworkID teamNetworkId; + bsIn.Read(teamNetworkId); + JoinPermissions joinPermissions; + bsIn.Read(joinPermissions); + + TM_Team *team = world->GetTeamByNetworkID(teamNetworkId); + if (team) + { + team->joinPermissions=joinPermissions; + + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) + { + if (packet->guid==GetMyGUIDUnified()) + world->BroadcastToParticipants(packet->data, packet->length, packet->guid); + else + world->BroadcastToParticipants(packet->data, packet->length, UNASSIGNED_RAKNET_GUID); + world->FillRequestedSlots(); + } + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnSetBalanceTeams(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + bool balanceTeams=false; + bsIn.Read(balanceTeams); + NoTeamId noTeamId; + bsIn.Read(noTeamId); + + world->balanceTeamsIsActive=balanceTeams; + if (world->GetHost()==world->GetTeamManager()->GetMyGUIDUnified()) + { + if (packet->guid==GetMyGUIDUnified()) + world->BroadcastToParticipants(packet->data, packet->length, packet->guid); + else + world->BroadcastToParticipants(packet->data, packet->length, UNASSIGNED_RAKNET_GUID); + + if (balanceTeams) + world->EnforceTeamBalance(noTeamId); + else + world->FillRequestedSlots(); + } +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +void TeamManager::OnSetBalanceTeamsInitial(Packet *packet, TM_World *world) +{ + BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(2+sizeof(WorldId)); + bool balanceTeams=false; + bsIn.Read(balanceTeams); + world->balanceTeamsIsActive=balanceTeams; +} + +// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +#endif // _RAKNET_SUPPORT_TeamManager==1 + diff --git a/src/raknet/TelnetTransport.cpp b/src/raknet/TelnetTransport.cpp new file mode 100644 index 0000000..805ec04 --- /dev/null +++ b/src/raknet/TelnetTransport.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TelnetTransport==1 && _RAKNET_SUPPORT_TCPInterface==1 + +#include "include/raknet/TelnetTransport.hpp" +#include "include/raknet/TCPInterface.hpp" +#include +#include +#include +#include "include/raknet/LinuxStrings.hpp" + +// #define _PRINTF_DEBUG + +#define ECHO_INPUT + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(TelnetTransport,TelnetTransport); + +TelnetTransport::TelnetTransport() +{ + tcpInterface=0; + sendSuffix=0; + sendPrefix=0; +} +TelnetTransport::~TelnetTransport() +{ + Stop(); + if (sendSuffix) + rakFree_Ex(sendSuffix, _FILE_AND_LINE_ ); + if (sendPrefix) + rakFree_Ex(sendPrefix, _FILE_AND_LINE_ ); +} +bool TelnetTransport::Start(unsigned short port, bool serverMode) +{ + (void) serverMode; + AutoAllocate(); + RakAssert(serverMode); + return tcpInterface->Start(port, 64); +} +void TelnetTransport::Stop(void) +{ + if (tcpInterface==0) return; + tcpInterface->Stop(); + unsigned i; + for (i=0; i < remoteClients.Size(); i++) + RakNet::OP_DELETE(remoteClients[i], _FILE_AND_LINE_); + remoteClients.Clear(false, _FILE_AND_LINE_); + RakNet::OP_DELETE(tcpInterface, _FILE_AND_LINE_); + tcpInterface=0; +} +void TelnetTransport::Send( SystemAddress systemAddress, const char *data,... ) +{ + if (tcpInterface==0) return; + + if (data==0 || data[0]==0) + return; + + char text[REMOTE_MAX_TEXT_INPUT]; + size_t prefixLength; + if (sendPrefix) + { + strcpy(text, sendPrefix); + prefixLength = strlen(sendPrefix); + } + else + { + text[0]=0; + prefixLength=0; + } + va_list ap; + va_start(ap, data); + _vsnprintf(text+prefixLength, REMOTE_MAX_TEXT_INPUT-prefixLength, data, ap); + va_end(ap); + text[REMOTE_MAX_TEXT_INPUT-1]=0; + + if (sendSuffix) + { + size_t length = strlen(text); + size_t availableChars = REMOTE_MAX_TEXT_INPUT-length-1; + strncat(text, sendSuffix, availableChars); + } + + tcpInterface->Send(text, (unsigned int) strlen(text), systemAddress, false); +} +void TelnetTransport::CloseConnection( SystemAddress systemAddress ) +{ + tcpInterface->CloseConnection(systemAddress); +} +Packet* TelnetTransport::Receive( void ) +{ + if (tcpInterface==0) return 0; + Packet *p = tcpInterface->Receive(); + if (p==0) + return 0; + + /* + if (p->data[0]==255) + { + unsigned i; + for (i=0; i < p->length; i++) + { + RAKNET_DEBUG_PRINTF("%i ", p->data[i]); + } + RAKNET_DEBUG_PRINTF("\n"); + tcpInterface->DeallocatePacket(p); + return 0; + } + */ + + // Get this guy's cursor buffer. This is real bullcrap that I have to do this. + unsigned i; + TelnetClient *remoteClient=0; + for (i=0; i < remoteClients.Size(); i++) + { + if (remoteClients[i]->systemAddress==p->systemAddress) + remoteClient=remoteClients[i]; + } + //RakAssert(remoteClient); + if (remoteClient==0) + { + tcpInterface->DeallocatePacket(p); + return 0; + } + + + if (p->length==3 && p->data[0]==27 && p->data[1]==91 && p->data[2]==65) + { + if (remoteClient->lastSentTextInput[0]) + { + // Up arrow, return last string + for (int i=0; remoteClient->textInput[i]; i++) + remoteClient->textInput[i]=8; + strcat(remoteClient->textInput, remoteClient->lastSentTextInput); + tcpInterface->Send((const char *)remoteClient->textInput, (unsigned int) strlen(remoteClient->textInput), p->systemAddress, false); + strcpy(remoteClient->textInput,remoteClient->lastSentTextInput); + remoteClient->cursorPosition=(unsigned int) strlen(remoteClient->textInput); + } + + return 0; + } + + + // 127 is delete - ignore that + // 9 is tab + // 27 is escape + if (p->data[0]>=127 || p->data[0]==9 || p->data[0]==27) + { + tcpInterface->DeallocatePacket(p); + return 0; + } + + // Hack - I don't know what the hell this is about but cursor keys send 3 characters at a time. I can block these + //Up=27,91,65 + //Down=27,91,66 + //Right=27,91,67 + //Left=27,91,68 + if (p->length==3 && p->data[0]==27 && p->data[1]==91 && p->data[2]>=65 && p->data[2]<=68) + { + tcpInterface->DeallocatePacket(p); + return 0; + } + + + + // Echo +#ifdef ECHO_INPUT + tcpInterface->Send((const char *)p->data, p->length, p->systemAddress, false); +#endif + + bool gotLine; + // Process each character in turn + for (i=0; i < p->length; i++) + { + +#ifdef ECHO_INPUT + if (p->data[i]==8) + { + char spaceThenBack[2]; + spaceThenBack[0]=' '; + spaceThenBack[1]=8; + tcpInterface->Send((const char *)spaceThenBack, 2, p->systemAddress, false); + } +#endif + + gotLine=ReassembleLine(remoteClient, p->data[i]); + if (gotLine && remoteClient->textInput[0]) + { + + Packet *reassembledLine = (Packet*) rakMalloc_Ex(sizeof(Packet), _FILE_AND_LINE_); + reassembledLine->length=(unsigned int) strlen(remoteClient->textInput); + memcpy(remoteClient->lastSentTextInput, remoteClient->textInput, reassembledLine->length+1); + RakAssert(reassembledLine->length < REMOTE_MAX_TEXT_INPUT); + reassembledLine->data= (unsigned char*) rakMalloc_Ex( reassembledLine->length+1, _FILE_AND_LINE_ ); + memcpy(reassembledLine->data, remoteClient->textInput, reassembledLine->length); +#ifdef _PRINTF_DEBUG + memset(remoteClient->textInput, 0, REMOTE_MAX_TEXT_INPUT); +#endif + reassembledLine->data[reassembledLine->length]=0; + reassembledLine->systemAddress=p->systemAddress; + tcpInterface->DeallocatePacket(p); + return reassembledLine; + } + } + + tcpInterface->DeallocatePacket(p); + return 0; +} +void TelnetTransport::DeallocatePacket( Packet *packet ) +{ + if (tcpInterface==0) return; + rakFree_Ex(packet->data, _FILE_AND_LINE_ ); + rakFree_Ex(packet, _FILE_AND_LINE_ ); +} +SystemAddress TelnetTransport::HasNewIncomingConnection(void) +{ + unsigned i; + SystemAddress newConnection; + newConnection = tcpInterface->HasNewIncomingConnection(); + // 03/16/06 Can't force the stupid windows telnet to use line mode or local echo so now I have to track all the remote players and their + // input buffer + if (newConnection != UNASSIGNED_SYSTEM_ADDRESS) + { + unsigned char command[10]; + // http://www.pcmicro.com/netfoss/RFC857.html + // IAC WON'T ECHO + command[0]=255; // IAC + //command[1]=253; // WON'T + command[1]=251; // WILL + command[2]=1; // ECHO + tcpInterface->Send((const char*)command, 3, newConnection, false); + + /* + // Tell the other side to use line mode + // http://www.faqs.org/rfcs/rfc1184.html + // IAC DO LINEMODE + // command[0]=255; // IAC + // command[1]=252; // DO + // command[2]=34; // LINEMODE + // tcpInterface->Send((const char*)command, 3, newConnection); + + */ + + TelnetClient *remoteClient=0; + for (i=0; i < remoteClients.Size(); i++) + { + if (remoteClients[i]->systemAddress==newConnection) + { + remoteClient=remoteClients[i]; + remoteClient->cursorPosition=0; + } + } + + if (remoteClient==0) + { + remoteClient=new TelnetClient; + remoteClient->lastSentTextInput[0]=0; + remoteClient->cursorPosition=0; + remoteClient->systemAddress=newConnection; +#ifdef _PRINTF_DEBUG + memset(remoteClient->textInput, 0, REMOTE_MAX_TEXT_INPUT); +#endif + } + + remoteClients.Insert(remoteClient, _FILE_AND_LINE_); + } + return newConnection; +} +SystemAddress TelnetTransport::HasLostConnection(void) +{ + SystemAddress systemAddress; + unsigned i; + systemAddress=tcpInterface->HasLostConnection(); + if (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) + { + for (i=0; i < remoteClients.Size(); i++) + { + if (remoteClients[i]->systemAddress==systemAddress) + { + RakNet::OP_DELETE(remoteClients[i], _FILE_AND_LINE_); + remoteClients[i]=remoteClients[remoteClients.Size()-1]; + remoteClients.RemoveFromEnd(); + } + } + } + return systemAddress; +} +CommandParserInterface* TelnetTransport::GetCommandParser(void) +{ + return 0; +} +void TelnetTransport::SetSendSuffix(const char *suffix) +{ + if (sendSuffix) + { + rakFree_Ex(sendSuffix, _FILE_AND_LINE_ ); + sendSuffix=0; + } + if (suffix) + { + sendSuffix = (char*) rakMalloc_Ex(strlen(suffix)+1, _FILE_AND_LINE_); + strcpy(sendSuffix, suffix); + } +} +void TelnetTransport::SetSendPrefix(const char *prefix) +{ + if (sendPrefix) + { + rakFree_Ex(sendPrefix, _FILE_AND_LINE_ ); + sendPrefix=0; + } + if (prefix) + { + sendPrefix = (char*) rakMalloc_Ex(strlen(prefix)+1, _FILE_AND_LINE_); + strcpy(sendPrefix, prefix); + } +} +void TelnetTransport::AutoAllocate(void) +{ + if (tcpInterface==0) + tcpInterface=new TCPInterface; +} +bool TelnetTransport::ReassembleLine(TelnetTransport::TelnetClient* remoteClient, unsigned char c) +{ + if (c=='\n') + { + remoteClient->textInput[remoteClient->cursorPosition]=0; + remoteClient->cursorPosition=0; +#ifdef _PRINTF_DEBUG + RAKNET_DEBUG_PRINTF("[Done] %s\n", remoteClient->textInput); +#endif + return true; + } + else if (c==8) // backspace + { + if (remoteClient->cursorPosition>0) + { + remoteClient->textInput[--remoteClient->cursorPosition]=0; +#ifdef _PRINTF_DEBUG + RAKNET_DEBUG_PRINTF("[Back] %s\n", remoteClient->textInput); +#endif + } + } + else if (c>=32 && c <127) + { + if (remoteClient->cursorPosition < REMOTE_MAX_TEXT_INPUT) + { + remoteClient->textInput[remoteClient->cursorPosition++]=c; +#ifdef _PRINTF_DEBUG + RAKNET_DEBUG_PRINTF("[Norm] %s\n", remoteClient->textInput); +#endif + } + } + return false; +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/ThreadsafePacketLogger.cpp b/src/raknet/ThreadsafePacketLogger.cpp new file mode 100644 index 0000000..0c64634 --- /dev/null +++ b/src/raknet/ThreadsafePacketLogger.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_PacketLogger==1 + +#include "include/raknet/ThreadsafePacketLogger.hpp" +#include + +using namespace RakNet; + +ThreadsafePacketLogger::ThreadsafePacketLogger() +{ + +} +ThreadsafePacketLogger::~ThreadsafePacketLogger() +{ + char **msg; + while ((msg = logMessages.ReadLock()) != 0) + { + rakFree_Ex((*msg), _FILE_AND_LINE_ ); + } +} +void ThreadsafePacketLogger::Update(void) +{ + char **msg; + while ((msg = logMessages.ReadLock()) != 0) + { + WriteLog(*msg); + rakFree_Ex((*msg), _FILE_AND_LINE_ ); + } +} +void ThreadsafePacketLogger::AddToLog(const char *str) +{ + char **msg = logMessages.WriteLock(); + *msg = (char*) rakMalloc_Ex( strlen(str)+1, _FILE_AND_LINE_ ); + strcpy(*msg, str); + logMessages.WriteUnlock(); +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/TwoWayAuthentication.cpp b/src/raknet/TwoWayAuthentication.cpp new file mode 100644 index 0000000..673325f --- /dev/null +++ b/src/raknet/TwoWayAuthentication.cpp @@ -0,0 +1,441 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_TwoWayAuthentication==1 + +#include "include/raknet/TwoWayAuthentication.hpp" +#include "include/raknet/Rand.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/RakPeerInterface.hpp" + +#if LIBCAT_SECURITY==1 +static const int HASH_BITS = 256; +static const int HASH_BYTES = HASH_BITS / 8; +static const int STRENGTHENING_FACTOR = 256; +#include +#endif + +using namespace RakNet; + +enum NegotiationIdentifiers +{ + ID_NONCE_REQUEST, + ID_NONCE_REPLY, + ID_HASHED_NONCE_AND_PASSWORD, +}; + +TwoWayAuthentication::NonceGenerator::NonceGenerator() {nextRequestId=0;} +TwoWayAuthentication::NonceGenerator::~NonceGenerator() +{ + Clear(); +} +void TwoWayAuthentication::NonceGenerator::GetNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short *requestId, RakNet::AddressOrGUID remoteSystem) +{ + TwoWayAuthentication::NonceAndRemoteSystemRequest *narsr = RakNet::OP_NEW(_FILE_AND_LINE_); + narsr->remoteSystem=remoteSystem; + GenerateNonce(narsr->nonce); + narsr->requestId=nextRequestId++; + *requestId=narsr->requestId; + memcpy(nonce,narsr->nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + narsr->whenGenerated=RakNet::GetTime(); + generatedNonces.Push(narsr,_FILE_AND_LINE_); +} +void TwoWayAuthentication::NonceGenerator::GenerateNonce(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]) +{ + fillBufferMT(nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); +} +bool TwoWayAuthentication::NonceGenerator::GetNonceById(char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], unsigned short requestId, RakNet::AddressOrGUID remoteSystem, bool popIfFound) +{ + unsigned int i; + for (i=0; i < generatedNonces.Size(); i++) + { + if (generatedNonces[i]->requestId==requestId) + { + if (remoteSystem==generatedNonces[i]->remoteSystem) + { + memcpy(nonce,generatedNonces[i]->nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + if (popIfFound) + { + RakNet::OP_DELETE(generatedNonces[i],_FILE_AND_LINE_); + generatedNonces.RemoveAtIndex(i); + } + return true; + } + else + { + return false; + } + } + } + return false; +} +void TwoWayAuthentication::NonceGenerator::Clear(void) +{ + unsigned int i; + for (i=0; i < generatedNonces.Size(); i++) + RakNet::OP_DELETE(generatedNonces[i],_FILE_AND_LINE_); + generatedNonces.Clear(true,_FILE_AND_LINE_); +} +void TwoWayAuthentication::NonceGenerator::ClearByAddress(RakNet::AddressOrGUID remoteSystem) +{ + unsigned int i=0; + while (i < generatedNonces.Size()) + { + if (generatedNonces[i]->remoteSystem==remoteSystem) + { + RakNet::OP_DELETE(generatedNonces[i],_FILE_AND_LINE_); + generatedNonces.RemoveAtIndex(i); + } + else + { + i++; + } + } +} +void TwoWayAuthentication::NonceGenerator::Update(RakNet::Time curTime) +{ + if (generatedNonces.Size()>0 && GreaterThan(curTime-5000, generatedNonces[0]->whenGenerated)) + { + RakNet::OP_DELETE(generatedNonces[0], _FILE_AND_LINE_); + generatedNonces.RemoveAtIndex(0); + } +} +TwoWayAuthentication::TwoWayAuthentication() +{ + whenLastTimeoutCheck=RakNet::GetTime(); + seedMT(RakNet::GetTimeMS()); +} +TwoWayAuthentication::~TwoWayAuthentication() +{ + Clear(); +} +bool TwoWayAuthentication::AddPassword(RakNet::RakString identifier, RakNet::RakString password) +{ + if (password.IsEmpty()) + return false; + + if (identifier.IsEmpty()) + return false; + + if (password==identifier) + return false; // Insecure + + if (passwords.GetIndexOf(identifier.C_String()).IsInvalid()==false) + return false; // This identifier already in use + + passwords.Push(identifier, password,_FILE_AND_LINE_); + return true; +} +bool TwoWayAuthentication::Challenge(RakNet::RakString identifier, AddressOrGUID remoteSystem) +{ + DataStructures::HashIndex skhi = passwords.GetIndexOf(identifier.C_String()); + if (skhi.IsInvalid()) + return false; + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_NEGOTIATION); + bsOut.Write((MessageID)ID_NONCE_REQUEST); + SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,remoteSystem,false); + + PendingChallenge pc; + pc.identifier=identifier; + pc.remoteSystem=remoteSystem; + pc.time=RakNet::GetTime(); + pc.sentHash=false; + outgoingChallenges.Push(pc,_FILE_AND_LINE_); + + return true; +} +void TwoWayAuthentication::Update(void) +{ + RakNet::Time curTime = RakNet::GetTime(); + nonceGenerator.Update(curTime); + if (GreaterThan(curTime - CHALLENGE_MINIMUM_TIMEOUT, whenLastTimeoutCheck)) + { + while (outgoingChallenges.Size() && GreaterThan(curTime - CHALLENGE_MINIMUM_TIMEOUT, outgoingChallenges.Peek().time)) + { + PendingChallenge pc = outgoingChallenges.Pop(); + + // Tell the user about the timeout + PushToUser(ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT, pc.identifier, pc.remoteSystem); + } + + whenLastTimeoutCheck=curTime+CHALLENGE_MINIMUM_TIMEOUT; + } +} +PluginReceiveResult TwoWayAuthentication::OnReceive(Packet *packet) +{ + switch (packet->data[0]) + { + case ID_TWO_WAY_AUTHENTICATION_NEGOTIATION: + { + if (packet->length>=sizeof(MessageID)*2) + { + switch (packet->data[sizeof(MessageID)]) + { + case ID_NONCE_REQUEST: + { + OnNonceRequest(packet); + } + break; + case ID_NONCE_REPLY: + { + OnNonceReply(packet); + } + break; + case ID_HASHED_NONCE_AND_PASSWORD: + { + return OnHashedNonceAndPassword(packet); + } + break; + } + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + case ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE: + case ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS: + { + if (packet->wasGeneratedLocally==false) + { + OnPasswordResult(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + else + break; + } + break; + // These should only be generated locally + case ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS: + case ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE: + case ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT: + if (packet->wasGeneratedLocally==false) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + break; + } + + return RR_CONTINUE_PROCESSING; +} +void TwoWayAuthentication::OnRakPeerShutdown(void) +{ + Clear(); +} +void TwoWayAuthentication::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + + // Remove from pending challenges + unsigned int i=0; + while (i < outgoingChallenges.Size()) + { + if ((rakNetGUID!=UNASSIGNED_RAKNET_GUID && outgoingChallenges[i].remoteSystem.rakNetGuid==rakNetGUID) || + (systemAddress!=UNASSIGNED_SYSTEM_ADDRESS && outgoingChallenges[i].remoteSystem.systemAddress==systemAddress)) + { + outgoingChallenges.RemoveAtIndex(i); + } + else + { + i++; + } + } + + if (rakNetGUID!=UNASSIGNED_RAKNET_GUID) + nonceGenerator.ClearByAddress(rakNetGUID); + else + nonceGenerator.ClearByAddress(systemAddress); +} +void TwoWayAuthentication::Clear(void) +{ + outgoingChallenges.Clear(_FILE_AND_LINE_); + passwords.Clear(_FILE_AND_LINE_); + nonceGenerator.Clear(); +} +void TwoWayAuthentication::PushToUser(MessageID messageId, RakNet::RakString password, RakNet::AddressOrGUID remoteSystem) +{ + RakNet::BitStream output; + output.Write(messageId); + if (password.IsEmpty()==false) + output.Write(password); + Packet *p = AllocatePacketUnified(output.GetNumberOfBytesUsed()); + p->systemAddress=remoteSystem.systemAddress; + p->systemAddress.systemIndex=(SystemIndex)-1; + p->guid=remoteSystem.rakNetGuid; + p->wasGeneratedLocally=true; + memcpy(p->data, output.GetData(), output.GetNumberOfBytesUsed()); + rakPeerInterface->PushBackPacket(p, true); +} +void TwoWayAuthentication::OnNonceRequest(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + char nonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; + unsigned short requestId; + nonceGenerator.GetNonce(nonce,&requestId,packet); + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_NEGOTIATION); + bsOut.Write((MessageID)ID_NONCE_REPLY); + bsOut.Write(requestId); + bsOut.WriteAlignedBytes((const unsigned char*) nonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet,false); +} +void TwoWayAuthentication::OnNonceReply(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + char thierNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; + unsigned short requestId; + bsIn.Read(requestId); + bsIn.ReadAlignedBytes((unsigned char *) thierNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + + // Lookup one of the negotiations for this guid/system address + AddressOrGUID aog(packet); + unsigned int i; + for (i=0; i < outgoingChallenges.Size(); i++) + { + if (outgoingChallenges[i].remoteSystem==aog && outgoingChallenges[i].sentHash==false) + { + outgoingChallenges[i].sentHash=true; + + // Get the password for this identifier + DataStructures::HashIndex skhi = passwords.GetIndexOf(outgoingChallenges[i].identifier.C_String()); + if (skhi.IsInvalid()==false) + { + RakNet::RakString password = passwords.ItemAtIndex(skhi); + + // Hash their nonce with password and reply + char hashedNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; + Hash(thierNonce, password, hashedNonceAndPw); + + // Send + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_NEGOTIATION); + bsOut.Write((MessageID)ID_HASHED_NONCE_AND_PASSWORD); + bsOut.Write(requestId); + bsOut.Write(outgoingChallenges[i].identifier); // Identifier helps the other system lookup the password quickly. + bsOut.WriteAlignedBytes((const unsigned char*) hashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); + SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet,false); + } + + return; + } + } +} +PluginReceiveResult TwoWayAuthentication::OnHashedNonceAndPassword(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*2); + + char remoteHashedNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; + unsigned short requestId; + bsIn.Read(requestId); + RakNet::RakString passwordIdentifier; + bsIn.Read(passwordIdentifier); + bsIn.ReadAlignedBytes((unsigned char *) remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); + + // Look up used nonce from requestId + char usedNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; + if (nonceGenerator.GetNonceById(usedNonce, requestId, packet, true)==false) + return RR_STOP_PROCESSING_AND_DEALLOCATE; + + DataStructures::HashIndex skhi = passwords.GetIndexOf(passwordIdentifier.C_String()); + if (skhi.IsInvalid()==false) + { + char hashedThisNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; + Hash(usedNonce, passwords.ItemAtIndex(skhi), hashedThisNonceAndPw); + if (memcmp(hashedThisNonceAndPw, remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH)==0) + { + // Pass + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS); + bsOut.WriteAlignedBytes((const unsigned char*) usedNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + bsOut.WriteAlignedBytes((const unsigned char*) remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); + bsOut.Write(passwordIdentifier); + SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet,false); + + // Incoming success, modify packet header to tell user + PushToUser(ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS, passwordIdentifier, packet); + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + + // Incoming failure, modify arrived packet header to tell user + packet->data[0]=(MessageID) ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE; + + RakNet::BitStream bsOut; + bsOut.Write((MessageID)ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE); + bsOut.WriteAlignedBytes((const unsigned char*) usedNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + bsOut.WriteAlignedBytes((const unsigned char*) remoteHashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); + bsOut.Write(passwordIdentifier); + SendUnified(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,packet,false); + + return RR_CONTINUE_PROCESSING; +} +void TwoWayAuthentication::OnPasswordResult(Packet *packet) +{ + RakNet::BitStream bsIn(packet->data, packet->length, false); + bsIn.IgnoreBytes(sizeof(MessageID)*1); + char usedNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH]; + bsIn.ReadAlignedBytes((unsigned char *)usedNonce,TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + char hashedNonceAndPw[HASHED_NONCE_AND_PW_LENGTH]; + bsIn.ReadAlignedBytes((unsigned char *)hashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH); + RakNet::RakString passwordIdentifier; + bsIn.Read(passwordIdentifier); + + DataStructures::HashIndex skhi = passwords.GetIndexOf(passwordIdentifier.C_String()); + if (skhi.IsInvalid()==false) + { + RakNet::RakString password = passwords.ItemAtIndex(skhi); + char testHash[HASHED_NONCE_AND_PW_LENGTH]; + Hash(usedNonce, password, testHash); + if (memcmp(testHash,hashedNonceAndPw,HASHED_NONCE_AND_PW_LENGTH)==0) + { + // Lookup the outgoing challenge and remove it from the list + unsigned int i; + AddressOrGUID aog(packet); + for (i=0; i < outgoingChallenges.Size(); i++) + { + if (outgoingChallenges[i].identifier==passwordIdentifier && + outgoingChallenges[i].remoteSystem==aog && + outgoingChallenges[i].sentHash==true) + { + outgoingChallenges.RemoveAtIndex(i); + + PushToUser(packet->data[0], passwordIdentifier, packet); + return; + } + } + } + } +} +void TwoWayAuthentication::Hash(char thierNonce[TWO_WAY_AUTHENTICATION_NONCE_LENGTH], RakNet::RakString password, char out[HASHED_NONCE_AND_PW_LENGTH]) +{ +#if LIBCAT_SECURITY==1 + cat::Skein hash; + if (!hash.BeginKey(HASH_BITS)) return; + hash.Crunch(thierNonce, TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + hash.Crunch(password.C_String(), (int) password.GetLength()); + hash.End(); + hash.Generate(out, HASH_BYTES, STRENGTHENING_FACTOR); +#else + CSHA1 sha1; + sha1.Update((unsigned char *) thierNonce, TWO_WAY_AUTHENTICATION_NONCE_LENGTH); + sha1.Update((unsigned char *) password.C_String(), (unsigned int) password.GetLength()); + sha1.Final(); + sha1.GetHash((unsigned char *) out); +#endif +} + +#endif diff --git a/src/raknet/UDPForwarder.cpp b/src/raknet/UDPForwarder.cpp new file mode 100644 index 0000000..ee08e08 --- /dev/null +++ b/src/raknet/UDPForwarder.cpp @@ -0,0 +1,643 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/UDPForwarder.hpp" + +#if _RAKNET_SUPPORT_UDPForwarder==1 + +#include "include/raknet/GetTime.hpp" +#include "include/raknet/MTUSize.hpp" +#include "include/raknet/SocketLayer.hpp" +#include "include/raknet/WSAStartupSingleton.hpp" +#include "include/raknet/RakSleep.hpp" +#include "include/raknet/DS_OrderedList.hpp" +#include "include/raknet/LinuxStrings.hpp" +#include "include/raknet/SocketDefines.hpp" +#include "include/raknet/VitaIncludes.hpp" +#include + +#ifndef INVALID_SOCKET +#define INVALID_SOCKET -1 +#endif + +using namespace RakNet; +static const unsigned short DEFAULT_MAX_FORWARD_ENTRIES=64; + +namespace RakNet +{ + RAK_THREAD_DECLARATION(UpdateUDPForwarderGlobal); +} + +UDPForwarder::ForwardEntry::ForwardEntry() +{ + socket=INVALID_SOCKET; + timeLastDatagramForwarded=RakNet::GetTimeMS(); + addr1Confirmed=UNASSIGNED_SYSTEM_ADDRESS; + addr2Confirmed=UNASSIGNED_SYSTEM_ADDRESS; +} +UDPForwarder::ForwardEntry::~ForwardEntry() { + if (socket!=INVALID_SOCKET) + closesocket__(socket); +} + +UDPForwarder::UDPForwarder() +{ +#ifdef _WIN32 + WSAStartupSingleton::AddRef(); +#endif + + maxForwardEntries=DEFAULT_MAX_FORWARD_ENTRIES; + nextInputId=0; + startForwardingInput.SetPageSize(sizeof(StartForwardingInputStruct)*16); + stopForwardingCommands.SetPageSize(sizeof(StopForwardingStruct)*16); +} +UDPForwarder::~UDPForwarder() +{ + Shutdown(); + +#ifdef _WIN32 + WSAStartupSingleton::Deref(); +#endif +} +void UDPForwarder::Startup(void) +{ + if (isRunning.GetValue()>0) + return; + + isRunning.Increment(); + + int errorCode; + + + + errorCode = RakNet::RakThread::Create(UpdateUDPForwarderGlobal, this); + + if ( errorCode != 0 ) + { + RakAssert(0); + return; + } + + while (threadRunning.GetValue()==0) + RakSleep(30); +} +void UDPForwarder::Shutdown(void) +{ + if (isRunning.GetValue()==0) + return; + isRunning.Decrement(); + + while (threadRunning.GetValue()>0) + RakSleep(30); + + unsigned int j; + for (j=0; j < forwardListNotUpdated.Size(); j++) + RakNet::OP_DELETE(forwardListNotUpdated[j],_FILE_AND_LINE_); + forwardListNotUpdated.Clear(false, _FILE_AND_LINE_); +} +void UDPForwarder::SetMaxForwardEntries(unsigned short maxEntries) +{ + RakAssert(maxEntries>0 && maxEntries<65535/2); + maxForwardEntries=maxEntries; +} +int UDPForwarder::GetMaxForwardEntries(void) const +{ + return maxForwardEntries; +} +int UDPForwarder::GetUsedForwardEntries(void) const +{ + return (int) forwardListNotUpdated.Size(); +} +UDPForwarderResult UDPForwarder::StartForwarding(SystemAddress source, SystemAddress destination, RakNet::TimeMS timeoutOnNoDataMS, const char *forceHostAddress, unsigned short socketFamily, + unsigned short *forwardingPort, __UDPSOCKET__ *forwardingSocket) +{ + // Invalid parameters? + if (timeoutOnNoDataMS == 0 || timeoutOnNoDataMS > UDP_FORWARDER_MAXIMUM_TIMEOUT || source==UNASSIGNED_SYSTEM_ADDRESS || destination==UNASSIGNED_SYSTEM_ADDRESS) + return UDPFORWARDER_INVALID_PARAMETERS; + + if (isRunning.GetValue()==0) + return UDPFORWARDER_NOT_RUNNING; + + (void) socketFamily; + + unsigned int inputId = nextInputId++; + + StartForwardingInputStruct *sfis; + sfis = startForwardingInput.Allocate(_FILE_AND_LINE_); + sfis->source=source; + sfis->destination=destination; + sfis->timeoutOnNoDataMS=timeoutOnNoDataMS; + RakAssert(timeoutOnNoDataMS!=0); + if (forceHostAddress && forceHostAddress[0]) + sfis->forceHostAddress=forceHostAddress; + sfis->socketFamily=socketFamily; + sfis->inputId=inputId; + startForwardingInput.Push(sfis); + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + RakSleep(0); + startForwardingOutputMutex.Lock(); + for (unsigned int i=0; i < startForwardingOutput.Size(); i++) + { + if (startForwardingOutput[i].inputId==inputId) + { + if (startForwardingOutput[i].result==UDPFORWARDER_SUCCESS) + { + if (forwardingPort) + *forwardingPort = startForwardingOutput[i].forwardingPort; + if (forwardingSocket) + *forwardingSocket = startForwardingOutput[i].forwardingSocket; + } + UDPForwarderResult res = startForwardingOutput[i].result; + startForwardingOutput.RemoveAtIndex(i); + startForwardingOutputMutex.Unlock(); + return res; + } + } + startForwardingOutputMutex.Unlock(); + } + + return UDPFORWARDER_RESULT_COUNT; +} +void UDPForwarder::StopForwarding(SystemAddress source, SystemAddress destination) +{ + StopForwardingStruct *sfs; + sfs = stopForwardingCommands.Allocate(_FILE_AND_LINE_); + sfs->destination=destination; + sfs->source=source; + stopForwardingCommands.Push(sfs); +} +void UDPForwarder::RecvFrom(RakNet::TimeMS curTime, ForwardEntry *forwardEntry) +{ +#ifndef __native_client__ + char data[ MAXIMUM_MTU_SIZE ]; + +#if RAKNET_SUPPORT_IPV6==1 + sockaddr_storage their_addr; + memset(&their_addr,0,sizeof(their_addr)); + sockaddr* sockAddrPtr; + socklen_t sockLen; + socklen_t* socketlenPtr=(socklen_t*) &sockLen; + sockaddr_in *sockAddrIn; + sockaddr_in6 *sockAddrIn6; + sockLen=sizeof(their_addr); + sockAddrPtr=(sockaddr*) &their_addr; +#else + sockaddr_in sockAddrIn; + memset(&sockAddrIn,0,sizeof(sockaddr_in)); + socklen_t len2; + len2 = sizeof( sockAddrIn ); + sockAddrIn.sin_family = AF_INET; +#endif + +#if defined(__GNUC__) + #if defined(MSG_DONTWAIT) + const int flag=MSG_DONTWAIT; + #else + const int flag=0x40; + #endif +#else + const int flag=0; +#endif + + int receivedDataLen, len=0; + //unsigned short portnum=0; + +#if RAKNET_SUPPORT_IPV6==1 + receivedDataLen = recvfrom__( forwardEntry->socket, data, MAXIMUM_MTU_SIZE, flag, sockAddrPtr, socketlenPtr ); +#else + receivedDataLen = recvfrom__( forwardEntry->socket, data, MAXIMUM_MTU_SIZE, flag, ( sockaddr* ) & sockAddrIn, ( socklen_t* ) & len2 ); +#endif + + if (receivedDataLen<0) + { +#if defined(_WIN32) && defined(_DEBUG) && !defined(WINDOWS_PHONE_8) && !defined(WINDOWS_STORE_RT) + DWORD dwIOError = WSAGetLastError(); + + if (dwIOError!=WSAECONNRESET && dwIOError!=WSAEINTR && dwIOError!=WSAETIMEDOUT && dwIOError!=WSAEWOULDBLOCK) + { + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "recvfrom failed:Error code - %d\n%s", dwIOError, messageBuffer ); + + //Free the buffer. + LocalFree( messageBuffer ); + } +#else + if (errno!=EAGAIN + && errno!=0 +#if defined(__GNUC__) + && errno!=EWOULDBLOCK +#endif + ) + { + printf("errno=%i\n", errno); + } +#endif + + + } + + if (receivedDataLen<=0) + return; + + SystemAddress receivedAddr; +#if RAKNET_SUPPORT_IPV6==1 + if (their_addr.ss_family==AF_INET) + { + sockAddrIn=(sockaddr_in *)&their_addr; + sockAddrIn6=0; + memcpy(&receivedAddr.address.addr4,sockAddrIn,sizeof(sockaddr_in)); + } + else + { + sockAddrIn=0; + sockAddrIn6=(sockaddr_in6 *)&their_addr; + memcpy(&receivedAddr.address.addr6,sockAddrIn6,sizeof(sockaddr_in6)); + } +#else + memcpy(&receivedAddr.address.addr4,&sockAddrIn,sizeof(sockaddr_in)); +#endif + //portnum=receivedAddr.GetPort(); + + SystemAddress forwardTarget; + + bool confirmed1 = forwardEntry->addr1Confirmed!=UNASSIGNED_SYSTEM_ADDRESS; + bool confirmed2 = forwardEntry->addr2Confirmed!=UNASSIGNED_SYSTEM_ADDRESS; + bool matchConfirmed1 = + confirmed1 && + forwardEntry->addr1Confirmed==receivedAddr; + bool matchConfirmed2 = + confirmed2 && + forwardEntry->addr2Confirmed==receivedAddr; + bool matchUnconfirmed1 = forwardEntry->addr1Unconfirmed.EqualsExcludingPort(receivedAddr); + bool matchUnconfirmed2 = forwardEntry->addr2Unconfirmed.EqualsExcludingPort(receivedAddr); + + if (matchConfirmed1==true || (matchConfirmed2==false && confirmed1==false && matchUnconfirmed1==true)) + { + // Forward to addr2 + if (forwardEntry->addr1Confirmed==UNASSIGNED_SYSTEM_ADDRESS) + { + forwardEntry->addr1Confirmed=receivedAddr; + } + if (forwardEntry->addr2Confirmed!=UNASSIGNED_SYSTEM_ADDRESS) + forwardTarget=forwardEntry->addr2Confirmed; + else + forwardTarget=forwardEntry->addr2Unconfirmed; + } + else if (matchConfirmed2==true || (confirmed2==false && matchUnconfirmed2==true)) + { + // Forward to addr1 + if (forwardEntry->addr2Confirmed==UNASSIGNED_SYSTEM_ADDRESS) + { + forwardEntry->addr2Confirmed=receivedAddr; + } + if (forwardEntry->addr1Confirmed!=UNASSIGNED_SYSTEM_ADDRESS) + forwardTarget=forwardEntry->addr1Confirmed; + else + forwardTarget=forwardEntry->addr1Unconfirmed; + } + else + { + return; + } + + // Forward to dest + len=0; +// sockaddr_in saOut; +// saOut.sin_port = forwardTarget.GetPortNetworkOrder(); // User port +// saOut.sin_addr.s_addr = forwardTarget.address.addr4.sin_addr.s_addr; +// saOut.sin_family = AF_INET; + do + { + + + +#if RAKNET_SUPPORT_IPV6==1 + if (forwardTarget.address.addr4.sin_family==AF_INET) + { + do + { + len = sendto__( forwardEntry->socket, data, receivedDataLen, 0, ( const sockaddr* ) & forwardTarget.address.addr4, sizeof( sockaddr_in ) ); + } + while ( len == 0 ); + } + else + { + do + { + len = sendto__( forwardEntry->socket, data, receivedDataLen, 0, ( const sockaddr* ) & forwardTarget.address.addr6, sizeof( sockaddr_in6 ) ); + } + while ( len == 0 ); + } +#else + do + { + len = sendto__( forwardEntry->socket, data, receivedDataLen, 0, ( const sockaddr* ) & forwardTarget.address.addr4, sizeof( sockaddr_in ) ); + } + while ( len == 0 ); +#endif + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + } + while ( len == 0 ); + + forwardEntry->timeLastDatagramForwarded=curTime; +#endif // __native_client__ +} +void UDPForwarder::UpdateUDPForwarder(void) +{ + /* +#if !defined(SN_TARGET_PSP2) + timeval tv; + tv.tv_sec=0; + tv.tv_usec=0; +#endif + */ + + RakNet::TimeMS curTime = RakNet::GetTimeMS(); + + StartForwardingInputStruct *sfis; + StartForwardingOutputStruct sfos; + sfos.forwardingSocket=INVALID_SOCKET; + sfos.forwardingPort=0; + sfos.inputId=0; + sfos.result=UDPFORWARDER_RESULT_COUNT; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + sfis = startForwardingInput.Pop(); + if (sfis==0) + break; + + if (GetUsedForwardEntries()>maxForwardEntries) + { + sfos.result=UDPFORWARDER_NO_SOCKETS; + } + else + { + sfos.result=UDPFORWARDER_RESULT_COUNT; + + for (unsigned int i=0; i < forwardListNotUpdated.Size(); i++) + { + if ( + (forwardListNotUpdated[i]->addr1Unconfirmed==sfis->source && + forwardListNotUpdated[i]->addr2Unconfirmed==sfis->destination) + || + (forwardListNotUpdated[i]->addr1Unconfirmed==sfis->destination && + forwardListNotUpdated[i]->addr2Unconfirmed==sfis->source) + ) + { + ForwardEntry *fe = forwardListNotUpdated[i]; + sfos.forwardingPort = SocketLayer::GetLocalPort ( fe->socket ); + sfos.forwardingSocket=fe->socket; + sfos.result=UDPFORWARDER_FORWARDING_ALREADY_EXISTS; + break; + } + } + + if (sfos.result==UDPFORWARDER_RESULT_COUNT) + { + int sock_opt; + sockaddr_in listenerSocketAddress; + listenerSocketAddress.sin_port = 0; + ForwardEntry *fe = RakNet::OP_NEW(_FILE_AND_LINE_); + fe->addr1Unconfirmed=sfis->source; + fe->addr2Unconfirmed=sfis->destination; + fe->timeoutOnNoDataMS=sfis->timeoutOnNoDataMS; + +#if RAKNET_SUPPORT_IPV6!=1 + fe->socket = socket__( AF_INET, SOCK_DGRAM, 0 ); + listenerSocketAddress.sin_family = AF_INET; + if (sfis->forceHostAddress.IsEmpty()==false) + { + + + + + + listenerSocketAddress.sin_addr.s_addr = inet_addr__( sfis->forceHostAddress.C_String() ); + + } + else + { + listenerSocketAddress.sin_addr.s_addr = INADDR_ANY; + } + int ret = bind__( fe->socket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) ); + if (ret==-1) + { + RakNet::OP_DELETE(fe,_FILE_AND_LINE_); + sfos.result=UDPFORWARDER_BIND_FAILED; + } + else + { + sfos.result=UDPFORWARDER_SUCCESS; + } + +#else // RAKNET_SUPPORT_IPV6==1 + struct addrinfo hints; + memset(&hints, 0, sizeof (addrinfo)); // make sure the struct is empty + hints.ai_family = sfis->socketFamily; + hints.ai_socktype = SOCK_DGRAM; // UDP sockets + hints.ai_flags = AI_PASSIVE; // fill in my IP for me + struct addrinfo *servinfo=0, *aip; // will point to the results + + if (sfis->forceHostAddress.IsEmpty() || sfis->forceHostAddress=="UNASSIGNED_SYSTEM_ADDRESS") + getaddrinfo(0, "0", &hints, &servinfo); + else + getaddrinfo(sfis->forceHostAddress.C_String(), "0", &hints, &servinfo); + + for (aip = servinfo; aip != NULL; aip = aip->ai_next) + { + // Open socket. The address type depends on what + // getaddrinfo() gave us. + fe->socket = socket__(aip->ai_family, aip->ai_socktype, aip->ai_protocol); + if (fe->socket != INVALID_SOCKET) + { + int ret = bind__( fe->socket, aip->ai_addr, (int) aip->ai_addrlen ); + if (ret>=0) + { + break; + } + else + { + closesocket__(fe->socket); + fe->socket=INVALID_SOCKET; + } + } + } + + if (fe->socket==INVALID_SOCKET) + sfos.result=UDPFORWARDER_BIND_FAILED; + else + sfos.result=UDPFORWARDER_SUCCESS; +#endif // RAKNET_SUPPORT_IPV6==1 + + if (sfos.result==UDPFORWARDER_SUCCESS) + { + sfos.forwardingPort = SocketLayer::GetLocalPort ( fe->socket ); + sfos.forwardingSocket=fe->socket; + + sock_opt=1024*256; + setsockopt__(fe->socket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) ); + sock_opt=0; + setsockopt__(fe->socket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) ); +#ifdef _WIN32 + unsigned long nonblocking = 1; + ioctlsocket__( fe->socket, FIONBIO, &nonblocking ); + + + +#else + fcntl( fe->socket, F_SETFL, O_NONBLOCK ); +#endif + + forwardListNotUpdated.Insert(fe,_FILE_AND_LINE_); + } + } + } + + // Push result + sfos.inputId=sfis->inputId; + startForwardingOutputMutex.Lock(); + startForwardingOutput.Push(sfos,_FILE_AND_LINE_); + startForwardingOutputMutex.Unlock(); + + startForwardingInput.Deallocate(sfis, _FILE_AND_LINE_); + } + + StopForwardingStruct *sfs; + +#ifdef _MSC_VER +#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant +#endif + while (1) + { + sfs = stopForwardingCommands.Pop(); + if (sfs==0) + break; + + ForwardEntry *fe; + for (unsigned int i=0; i < forwardListNotUpdated.Size(); i++) + { + if ( + (forwardListNotUpdated[i]->addr1Unconfirmed==sfs->source && + forwardListNotUpdated[i]->addr2Unconfirmed==sfs->destination) + || + (forwardListNotUpdated[i]->addr1Unconfirmed==sfs->destination && + forwardListNotUpdated[i]->addr2Unconfirmed==sfs->source) + ) + { + fe = forwardListNotUpdated[i]; + forwardListNotUpdated.RemoveAtIndexFast(i); + RakNet::OP_DELETE(fe, _FILE_AND_LINE_); + break; + } + } + + stopForwardingCommands.Deallocate(sfs, _FILE_AND_LINE_); + } + + unsigned int i; + + i=0; + while (i < forwardListNotUpdated.Size()) + { + if (curTime > forwardListNotUpdated[i]->timeLastDatagramForwarded && // Account for timestamp wrap + curTime > forwardListNotUpdated[i]->timeLastDatagramForwarded+forwardListNotUpdated[i]->timeoutOnNoDataMS) + { + RakNet::OP_DELETE(forwardListNotUpdated[i],_FILE_AND_LINE_); + forwardListNotUpdated.RemoveAtIndex(i); + } + else + i++; + } + + ForwardEntry *forwardEntry; + for (i=0; i < forwardListNotUpdated.Size(); i++) + { + forwardEntry = forwardListNotUpdated[i]; + RecvFrom(curTime, forwardEntry); + } +} + +namespace RakNet { +RAK_THREAD_DECLARATION(UpdateUDPForwarderGlobal) +{ + + + + UDPForwarder * udpForwarder = ( UDPForwarder * ) arguments; + + + udpForwarder->threadRunning.Increment(); + while (udpForwarder->isRunning.GetValue()>0) + { + udpForwarder->UpdateUDPForwarder(); + + // 12/1/2010 Do not change from 0 + // See http://www.jenkinssoftware.com/forum/index.php?topic=4033.0;topicseen + // Avoid 100% reported CPU usage + if (udpForwarder->forwardListNotUpdated.Size()==0) + RakSleep(30); + else + RakSleep(0); + } + udpForwarder->threadRunning.Decrement(); + + + + + return 0; + + +} + +} // namespace RakNet + +#endif // #if _RAKNET_SUPPORT_FileOperations==1 diff --git a/src/raknet/UDPProxyClient.cpp b/src/raknet/UDPProxyClient.cpp new file mode 100644 index 0000000..1402126 --- /dev/null +++ b/src/raknet/UDPProxyClient.cpp @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_UDPProxyClient==1 + +#include "include/raknet/UDPProxyClient.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/UDPProxyCommon.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/GetTime.hpp" + +using namespace RakNet; +static const int DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR=1000; + +// bool operator<( const DataStructures::MLKeyRef &inputKey, const UDPProxyClient::ServerWithPing &cls ) {return inputKey.Get().serverAddress < cls.serverAddress;} +// bool operator>( const DataStructures::MLKeyRef &inputKey, const UDPProxyClient::ServerWithPing &cls ) {return inputKey.Get().serverAddress > cls.serverAddress;} +// bool operator==( const DataStructures::MLKeyRef &inputKey, const UDPProxyClient::ServerWithPing &cls ) {return inputKey.Get().serverAddress == cls.serverAddress;} + +STATIC_FACTORY_DEFINITIONS(UDPProxyClient,UDPProxyClient); + +UDPProxyClient::UDPProxyClient() +{ + resultHandler=0; +} +UDPProxyClient::~UDPProxyClient() +{ + Clear(); +} +void UDPProxyClient::SetResultHandler(UDPProxyClientResultHandler *rh) +{ + resultHandler=rh; +} +bool UDPProxyClient::RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, RakNetGUID targetGuid, RakNet::TimeMS timeoutOnNoDataMS, RakNet::BitStream *serverSelectionBitstream) +{ + // Return false if not connected + ConnectionState cs = rakPeerInterface->GetConnectionState(proxyCoordinator); + if (cs!=IS_CONNECTED) + return false; + + // Pretty much a bug not to set the result handler, as otherwise you won't know if the operation succeeed or not + RakAssert(resultHandler!=0); + if (resultHandler==0) + return false; + + BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR); + outgoingBs.Write(sourceAddress); + outgoingBs.Write(false); + outgoingBs.Write(targetGuid); + outgoingBs.Write(timeoutOnNoDataMS); + if (serverSelectionBitstream && serverSelectionBitstream->GetNumberOfBitsUsed()>0) + { + outgoingBs.Write(true); + outgoingBs.Write(serverSelectionBitstream); + } + else + { + outgoingBs.Write(false); + } + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, proxyCoordinator, false); + + return true; +} +bool UDPProxyClient::RequestForwarding(SystemAddress proxyCoordinator, SystemAddress sourceAddress, SystemAddress targetAddressAsSeenFromCoordinator, RakNet::TimeMS timeoutOnNoDataMS, RakNet::BitStream *serverSelectionBitstream) +{ + // Return false if not connected + ConnectionState cs = rakPeerInterface->GetConnectionState(proxyCoordinator); + if (cs!=IS_CONNECTED) + return false; + + // Pretty much a bug not to set the result handler, as otherwise you won't know if the operation succeeed or not + RakAssert(resultHandler!=0); + if (resultHandler==0) + return false; + + BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR); + outgoingBs.Write(sourceAddress); + outgoingBs.Write(true); + outgoingBs.Write(targetAddressAsSeenFromCoordinator); + outgoingBs.Write(timeoutOnNoDataMS); + if (serverSelectionBitstream && serverSelectionBitstream->GetNumberOfBitsUsed()>0) + { + outgoingBs.Write(true); + outgoingBs.Write(serverSelectionBitstream); + } + else + { + outgoingBs.Write(false); + } + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, proxyCoordinator, false); + + return true; +} +void UDPProxyClient::Update(void) +{ + unsigned int idx1=0; + while (idx1 < pingServerGroups.Size()) + { + PingServerGroup *psg = pingServerGroups[idx1]; + + if (psg->serversToPing.Size() > 0 && + RakNet::GetTimeMS() > psg->startPingTime+DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR) + { + // If they didn't reply within DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR, just give up on them + psg->SendPingedServersToCoordinator(rakPeerInterface); + + RakNet::OP_DELETE(psg,_FILE_AND_LINE_); + pingServerGroups.RemoveAtIndex(idx1); + } + else + idx1++; + } + +} +PluginReceiveResult UDPProxyClient::OnReceive(Packet *packet) +{ + if (packet->data[0]==ID_UNCONNECTED_PONG) + { + unsigned int idx1, idx2; + PingServerGroup *psg; + for (idx1=0; idx1 < pingServerGroups.Size(); idx1++) + { + psg = pingServerGroups[idx1]; + for (idx2=0; idx2 < psg->serversToPing.Size(); idx2++) + { + if (psg->serversToPing[idx2].serverAddress==packet->systemAddress) + { + RakNet::BitStream bsIn(packet->data,packet->length,false); + bsIn.IgnoreBytes(sizeof(MessageID)); + RakNet::TimeMS sentTime; + bsIn.Read(sentTime); + RakNet::TimeMS curTime=RakNet::GetTimeMS(); + int ping; + if (curTime>sentTime) + ping=(int) (curTime-sentTime); + else + ping=0; + psg->serversToPing[idx2].ping=(unsigned short) ping; + + // If all servers to ping are now pinged, reply to coordinator + if (psg->AreAllServersPinged()) + { + psg->SendPingedServersToCoordinator(rakPeerInterface); + RakNet::OP_DELETE(psg,_FILE_AND_LINE_); + pingServerGroups.RemoveAtIndex(idx1); + } + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + + } + } + else if (packet->data[0]==ID_UDP_PROXY_GENERAL && packet->length>1) + { + switch (packet->data[1]) + { + case ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT: + { + OnPingServers(packet); + } + break; + case ID_UDP_PROXY_FORWARDING_SUCCEEDED: + case ID_UDP_PROXY_ALL_SERVERS_BUSY: + case ID_UDP_PROXY_IN_PROGRESS: + case ID_UDP_PROXY_NO_SERVERS_ONLINE: + case ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR: + case ID_UDP_PROXY_FORWARDING_NOTIFICATION: + { + RakNetGUID targetGuid; + SystemAddress senderAddress, targetAddress; + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(sizeof(MessageID)*2); + incomingBs.Read(senderAddress); + incomingBs.Read(targetAddress); + incomingBs.Read(targetGuid); + + switch (packet->data[1]) + { + case ID_UDP_PROXY_FORWARDING_NOTIFICATION: + case ID_UDP_PROXY_FORWARDING_SUCCEEDED: + case ID_UDP_PROXY_IN_PROGRESS: + { + unsigned short forwardingPort; + RakNet::RakString serverIP; + incomingBs.Read(serverIP); + incomingBs.Read(forwardingPort); + if (packet->data[1]==ID_UDP_PROXY_FORWARDING_SUCCEEDED) + { + if (resultHandler) + resultHandler->OnForwardingSuccess(serverIP.C_String(), forwardingPort, packet->systemAddress, senderAddress, targetAddress, targetGuid, this); + } + else if (packet->data[1]==ID_UDP_PROXY_IN_PROGRESS) + { + if (resultHandler) + resultHandler->OnForwardingInProgress(serverIP.C_String(), forwardingPort, packet->systemAddress, senderAddress, targetAddress, targetGuid, this); + } + else + { + // Send a datagram to the proxy, so if we are behind a router, that router adds an entry to the routing table. + // Otherwise the router would block the incoming datagrams from source + // It doesn't matter if the message actually arrives as long as it goes through the router + rakPeerInterface->Ping(serverIP.C_String(), forwardingPort, false); + + if (resultHandler) + resultHandler->OnForwardingNotification(serverIP.C_String(), forwardingPort, packet->systemAddress, senderAddress, targetAddress, targetGuid, this); + } + } + break; + case ID_UDP_PROXY_ALL_SERVERS_BUSY: + if (resultHandler) + resultHandler->OnAllServersBusy(packet->systemAddress, senderAddress, targetAddress, targetGuid, this); + break; + case ID_UDP_PROXY_NO_SERVERS_ONLINE: + if (resultHandler) + resultHandler->OnNoServersOnline(packet->systemAddress, senderAddress, targetAddress, targetGuid, this); + break; + case ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR: + { + if (resultHandler) + resultHandler->OnRecipientNotConnected(packet->systemAddress, senderAddress, targetAddress, targetGuid, this); + break; + } + } + + } + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + return RR_CONTINUE_PROCESSING; +} +void UDPProxyClient::OnRakPeerShutdown(void) +{ + Clear(); +} +void UDPProxyClient::OnPingServers(Packet *packet) +{ + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(2); + + PingServerGroup *psg = RakNet::OP_NEW(_FILE_AND_LINE_); + + ServerWithPing swp; + incomingBs.Read(psg->sata.senderClientAddress); + incomingBs.Read(psg->sata.targetClientAddress); + psg->startPingTime=RakNet::GetTimeMS(); + psg->coordinatorAddressForPings=packet->systemAddress; + unsigned short serverListSize; + incomingBs.Read(serverListSize); + SystemAddress serverAddress; + unsigned short serverListIndex; + char ipStr[64]; + for (serverListIndex=0; serverListIndexserversToPing.Push(swp, _FILE_AND_LINE_ ); + swp.serverAddress.ToString(false,ipStr); + rakPeerInterface->Ping(ipStr,swp.serverAddress.GetPort(),false,0); + } + pingServerGroups.Push(psg,_FILE_AND_LINE_); +} + +bool UDPProxyClient::PingServerGroup::AreAllServersPinged(void) const +{ + unsigned int serversToPingIndex; + for (serversToPingIndex=0; serversToPingIndex < serversToPing.Size(); serversToPingIndex++) + { + if (serversToPing[serversToPingIndex].ping==DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR) + return false; + } + return true; +} + +void UDPProxyClient::PingServerGroup::SendPingedServersToCoordinator(RakPeerInterface *rakPeerInterface) +{ + BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR); + outgoingBs.Write(sata.senderClientAddress); + outgoingBs.Write(sata.targetClientAddress); + unsigned short serversToPingSize = (unsigned short) serversToPing.Size(); + outgoingBs.Write(serversToPingSize); + unsigned int serversToPingIndex; + for (serversToPingIndex=0; serversToPingIndex < serversToPingSize; serversToPingIndex++) + { + outgoingBs.Write(serversToPing[serversToPingIndex].serverAddress); + outgoingBs.Write(serversToPing[serversToPingIndex].ping); + } + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, coordinatorAddressForPings, false); +} +void UDPProxyClient::Clear(void) +{ + for (unsigned int i=0; i < pingServerGroups.Size(); i++) + RakNet::OP_DELETE(pingServerGroups[i],_FILE_AND_LINE_); + pingServerGroups.Clear(false, _FILE_AND_LINE_); +} + + +#endif // _RAKNET_SUPPORT_* + diff --git a/src/raknet/UDPProxyCoordinator.cpp b/src/raknet/UDPProxyCoordinator.cpp new file mode 100644 index 0000000..e1f68b8 --- /dev/null +++ b/src/raknet/UDPProxyCoordinator.cpp @@ -0,0 +1,568 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_UDPProxyCoordinator==1 && _RAKNET_SUPPORT_UDPForwarder==1 + +#include "include/raknet/UDPProxyCoordinator.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/UDPProxyCommon.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" +#include "include/raknet/Rand.hpp" +#include "include/raknet/GetTime.hpp" +#include "include/raknet/UDPForwarder.hpp" + +// Larger than the client version +static const int DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME=2000; +static const int DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR=DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME+1000; + +using namespace RakNet; + +// bool operator<( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ServerWithPing &cls ) {return inputKey.Get() < cls.ping;} +// bool operator>( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ServerWithPing &cls ) {return inputKey.Get() > cls.ping;} +// bool operator==( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ServerWithPing &cls ) {return inputKey.Get() == cls.ping;} + +int UDPProxyCoordinator::ServerWithPingComp( const unsigned short &key, const UDPProxyCoordinator::ServerWithPing &data ) +{ + if (key < data.ping) + return -1; + if (key > data.ping) + return 1; + return 0; +} + +int UDPProxyCoordinator::ForwardingRequestComp( const SenderAndTargetAddress &key, ForwardingRequest* const &data) +{ + if (key.senderClientAddress < data->sata.senderClientAddress ) + return -1; + if (key.senderClientAddress > data->sata.senderClientAddress ) + return -1; + if (key.targetClientAddress < data->sata.targetClientAddress ) + return -1; + if (key.targetClientAddress > data->sata.targetClientAddress ) + return 1; + return 0; +} +// +// bool operator<( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ForwardingRequest *cls ) +// { +// return inputKey.Get().senderClientAddress < cls->sata.senderClientAddress || +// (inputKey.Get().senderClientAddress == cls->sata.senderClientAddress && inputKey.Get().targetClientAddress < cls->sata.targetClientAddress); +// } +// bool operator>( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ForwardingRequest *cls ) +// { +// return inputKey.Get().senderClientAddress > cls->sata.senderClientAddress || +// (inputKey.Get().senderClientAddress == cls->sata.senderClientAddress && inputKey.Get().targetClientAddress > cls->sata.targetClientAddress); +// } +// bool operator==( const DataStructures::MLKeyRef &inputKey, const UDPProxyCoordinator::ForwardingRequest *cls ) +// { +// return inputKey.Get().senderClientAddress == cls->sata.senderClientAddress && inputKey.Get().targetClientAddress == cls->sata.targetClientAddress; +// } + +STATIC_FACTORY_DEFINITIONS(UDPProxyCoordinator,UDPProxyCoordinator); + +UDPProxyCoordinator::UDPProxyCoordinator() +{ + +} +UDPProxyCoordinator::~UDPProxyCoordinator() +{ + Clear(); +} +void UDPProxyCoordinator::SetRemoteLoginPassword(RakNet::RakString password) +{ + remoteLoginPassword=password; +} +void UDPProxyCoordinator::Update(void) +{ + unsigned int idx; + RakNet::TimeMS curTime = RakNet::GetTimeMS(); + ForwardingRequest *fw; + idx=0; + while (idx < forwardingRequestList.Size()) + { + fw=forwardingRequestList[idx]; + if (fw->timeRequestedPings!=0 && + curTime > fw->timeRequestedPings + DEFAULT_UNRESPONSIVE_PING_TIME_COORDINATOR) + { + fw->OrderRemainingServersToTry(); + fw->timeRequestedPings=0; + TryNextServer(fw->sata, fw); + idx++; + } + else if (fw->timeoutAfterSuccess!=0 && + curTime > fw->timeoutAfterSuccess) + { + // Forwarding request succeeded, we waited a bit to prevent duplicates. Can forget about the entry now. + RakNet::OP_DELETE(fw,_FILE_AND_LINE_); + forwardingRequestList.RemoveAtIndex(idx); + } + else + idx++; + } +} +PluginReceiveResult UDPProxyCoordinator::OnReceive(Packet *packet) +{ + if (packet->data[0]==ID_UDP_PROXY_GENERAL && packet->length>1) + { + switch (packet->data[1]) + { + case ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR: + OnForwardingRequestFromClientToCoordinator(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR: + OnLoginRequestFromServerToCoordinator(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR: + OnForwardingReplyFromServerToCoordinator(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + case ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR: + OnPingServersReplyFromClientToCoordinator(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + return RR_CONTINUE_PROCESSING; +} +void UDPProxyCoordinator::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) rakNetGUID; + + unsigned int idx, idx2; + + idx=0; + while (idx < forwardingRequestList.Size()) + { + if (forwardingRequestList[idx]->requestingAddress==systemAddress) + { + // Guy disconnected before the attempt completed + RakNet::OP_DELETE(forwardingRequestList[idx], _FILE_AND_LINE_); + forwardingRequestList.RemoveAtIndex(idx ); + } + else + idx++; + } + + idx = serverList.GetIndexOf(systemAddress); + if (idx!=(unsigned int)-1) + { + ForwardingRequest *fw; + // For each pending client for this server, choose from remaining servers. + for (idx2=0; idx2 < forwardingRequestList.Size(); idx2++) + { + fw = forwardingRequestList[idx2]; + if (fw->currentlyAttemptedServerAddress==systemAddress) + { + // Try the next server + TryNextServer(fw->sata, fw); + } + } + + // Remove dead server + serverList.RemoveAtIndexFast(idx); + } +} +void UDPProxyCoordinator::OnForwardingRequestFromClientToCoordinator(Packet *packet) +{ + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(2); + SystemAddress sourceAddress; + incomingBs.Read(sourceAddress); + if (sourceAddress==UNASSIGNED_SYSTEM_ADDRESS) + sourceAddress=packet->systemAddress; + SystemAddress targetAddress; + RakNetGUID targetGuid; + bool usesAddress=false; + incomingBs.Read(usesAddress); + if (usesAddress) + { + incomingBs.Read(targetAddress); + targetGuid=rakPeerInterface->GetGuidFromSystemAddress(targetAddress); + } + else + { + incomingBs.Read(targetGuid); + targetAddress=rakPeerInterface->GetSystemAddressFromGuid(targetGuid); + } + ForwardingRequest *fw = RakNet::OP_NEW(_FILE_AND_LINE_); + fw->timeoutAfterSuccess=0; + incomingBs.Read(fw->timeoutOnNoDataMS); + bool hasServerSelectionBitstream=false; + incomingBs.Read(hasServerSelectionBitstream); + if (hasServerSelectionBitstream) + incomingBs.Read(&(fw->serverSelectionBitstream)); + + RakNet::BitStream outgoingBs; + SenderAndTargetAddress sata; + sata.senderClientAddress=sourceAddress; + sata.targetClientAddress=targetAddress; + sata.targetClientGuid=targetGuid; + sata.senderClientGuid=rakPeerInterface->GetGuidFromSystemAddress(sourceAddress); + SenderAndTargetAddress sataReversed; + sataReversed.senderClientAddress=targetAddress; + sataReversed.targetClientAddress=sourceAddress; + sataReversed.senderClientGuid=sata.targetClientGuid; + sataReversed.targetClientGuid=sata.senderClientGuid; + + unsigned int insertionIndex; + bool objectExists1, objectExists2; + insertionIndex=forwardingRequestList.GetIndexFromKey(sata, &objectExists1); + forwardingRequestList.GetIndexFromKey(sataReversed, &objectExists2); + + if (objectExists1 || objectExists2) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_IN_PROGRESS); + outgoingBs.Write(sata.senderClientAddress); + outgoingBs.Write(targetAddress); + outgoingBs.Write(targetGuid); + // Request in progress, not completed + unsigned short forwardingPort=0; + RakString serverPublicIp; + outgoingBs.Write(serverPublicIp); + outgoingBs.Write(forwardingPort); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); + RakNet::OP_DELETE(fw, _FILE_AND_LINE_); + return; + } + + if (serverList.Size()==0) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_NO_SERVERS_ONLINE); + outgoingBs.Write(sata.senderClientAddress); + outgoingBs.Write(targetAddress); + outgoingBs.Write(targetGuid); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); + RakNet::OP_DELETE(fw, _FILE_AND_LINE_); + return; + } + + if (rakPeerInterface->GetConnectionState(targetAddress)!=IS_CONNECTED && usesAddress==false) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR); + outgoingBs.Write(sata.senderClientAddress); + outgoingBs.Write(targetAddress); + outgoingBs.Write(targetGuid); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); + RakNet::OP_DELETE(fw, _FILE_AND_LINE_); + return; + } + + fw->sata=sata; + fw->requestingAddress=packet->systemAddress; + + if (serverList.Size()>1) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT); + outgoingBs.Write(sourceAddress); + outgoingBs.Write(targetAddress); + outgoingBs.Write(targetGuid); + unsigned short serverListSize = (unsigned short) serverList.Size(); + outgoingBs.Write(serverListSize); + unsigned int idx; + for (idx=0; idx < serverList.Size(); idx++) + outgoingBs.Write(serverList[idx]); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, sourceAddress, false); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, targetAddress, false); + fw->timeRequestedPings=RakNet::GetTimeMS(); + unsigned int copyIndex; + for (copyIndex=0; copyIndex < serverList.Size(); copyIndex++) + fw->remainingServersToTry.Push(serverList[copyIndex], _FILE_AND_LINE_ ); + forwardingRequestList.InsertAtIndex(fw, insertionIndex, _FILE_AND_LINE_ ); + } + else + { + fw->timeRequestedPings=0; + fw->currentlyAttemptedServerAddress=serverList[0]; + forwardingRequestList.InsertAtIndex(fw, insertionIndex, _FILE_AND_LINE_ ); + SendForwardingRequest(sourceAddress, targetAddress, fw->currentlyAttemptedServerAddress, fw->timeoutOnNoDataMS); + } +} + +void UDPProxyCoordinator::SendForwardingRequest(SystemAddress sourceAddress, SystemAddress targetAddress, SystemAddress serverAddress, RakNet::TimeMS timeoutOnNoDataMS) +{ + RakNet::BitStream outgoingBs; + // Send request to desired server + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER); + outgoingBs.Write(sourceAddress); + outgoingBs.Write(targetAddress); + outgoingBs.Write(timeoutOnNoDataMS); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, serverAddress, false); +} +void UDPProxyCoordinator::OnLoginRequestFromServerToCoordinator(Packet *packet) +{ + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(2); + RakNet::RakString password; + incomingBs.Read(password); + RakNet::BitStream outgoingBs; + + if (remoteLoginPassword.IsEmpty()) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER); + outgoingBs.Write(password); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); + return; + } + + if (remoteLoginPassword!=password) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER); + outgoingBs.Write(password); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); + return; + } + + unsigned int insertionIndex; + insertionIndex=serverList.GetIndexOf(packet->systemAddress); + if (insertionIndex!=(unsigned int)-1) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER); + outgoingBs.Write(password); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); + return; + } + serverList.Push(packet->systemAddress, _FILE_AND_LINE_ ); + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER); + outgoingBs.Write(password); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); +} +void UDPProxyCoordinator::OnForwardingReplyFromServerToCoordinator(Packet *packet) +{ + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(2); + SenderAndTargetAddress sata; + incomingBs.Read(sata.senderClientAddress); + incomingBs.Read(sata.targetClientAddress); + bool objectExists; + unsigned int index = forwardingRequestList.GetIndexFromKey(sata, &objectExists); + if (objectExists==false) + { + // The guy disconnected before the request finished + return; + } + ForwardingRequest *fw = forwardingRequestList[index]; + sata.senderClientGuid = fw->sata.senderClientGuid; + sata.targetClientGuid = fw->sata.targetClientGuid; + + RakString serverPublicIp; + incomingBs.Read(serverPublicIp); + + if (serverPublicIp.IsEmpty()) + { + char serverIP[64]; + packet->systemAddress.ToString(false,serverIP); + serverPublicIp=serverIP; + } + + UDPForwarderResult success; + unsigned char c; + incomingBs.Read(c); + success=(UDPForwarderResult)c; + + unsigned short forwardingPort; + incomingBs.Read(forwardingPort); + + RakNet::BitStream outgoingBs; + if (success==UDPFORWARDER_SUCCESS) + { + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_SUCCEEDED); + outgoingBs.Write(sata.senderClientAddress); + outgoingBs.Write(sata.targetClientAddress); + outgoingBs.Write(sata.targetClientGuid); + outgoingBs.Write(serverPublicIp); + outgoingBs.Write(forwardingPort); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, fw->requestingAddress, false); + + outgoingBs.Reset(); + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_NOTIFICATION); + outgoingBs.Write(sata.senderClientAddress); + outgoingBs.Write(sata.targetClientAddress); + outgoingBs.Write(sata.targetClientGuid); + outgoingBs.Write(serverPublicIp); + outgoingBs.Write(forwardingPort); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, sata.targetClientAddress, false); + + // 05/18/09 Keep the entry around for some time after success, so duplicates are reported if attempting forwarding from the target system before notification of success + fw->timeoutAfterSuccess=RakNet::GetTimeMS()+fw->timeoutOnNoDataMS; + // forwardingRequestList.RemoveAtIndex(index); + // RakNet::OP_DELETE(fw,_FILE_AND_LINE_); + + return; + } + else if (success==UDPFORWARDER_NO_SOCKETS) + { + // Try next server + TryNextServer(sata, fw); + } + else + { + RakAssert(success==UDPFORWARDER_FORWARDING_ALREADY_EXISTS); + + // Return in progress + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_IN_PROGRESS); + outgoingBs.Write(sata.senderClientAddress); + outgoingBs.Write(sata.targetClientAddress); + outgoingBs.Write(sata.targetClientGuid); + outgoingBs.Write(serverPublicIp); + outgoingBs.Write(forwardingPort); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, fw->requestingAddress, false); + forwardingRequestList.RemoveAtIndex(index); + RakNet::OP_DELETE(fw,_FILE_AND_LINE_); + } +} +void UDPProxyCoordinator::OnPingServersReplyFromClientToCoordinator(Packet *packet) +{ + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(2); + unsigned short serversToPingSize; + SystemAddress serverAddress; + SenderAndTargetAddress sata; + incomingBs.Read(sata.senderClientAddress); + incomingBs.Read(sata.targetClientAddress); + bool objectExists; + unsigned int index = forwardingRequestList.GetIndexFromKey(sata, &objectExists); + if (objectExists==false) + return; + unsigned short idx; + ServerWithPing swp; + ForwardingRequest *fw = forwardingRequestList[index]; + if (fw->timeRequestedPings==0) + return; + + incomingBs.Read(serversToPingSize); + if (packet->systemAddress==sata.senderClientAddress) + { + for (idx=0; idx < serversToPingSize; idx++) + { + incomingBs.Read(swp.serverAddress); + incomingBs.Read(swp.ping); + unsigned int index2; + for (index2=0; index2 < fw->sourceServerPings.Size(); index2++) + { + if (fw->sourceServerPings[index2].ping >= swp.ping ) + break; + } + fw->sourceServerPings.Insert(swp, index2, _FILE_AND_LINE_); + } + } + else + { + for (idx=0; idx < serversToPingSize; idx++) + { + incomingBs.Read(swp.serverAddress); + incomingBs.Read(swp.ping); + + unsigned int index2; + for (index2=0; index2 < fw->targetServerPings.Size(); index2++) + { + if (fw->targetServerPings[index2].ping >= swp.ping ) + break; + } + fw->sourceServerPings.Insert(swp, index2, _FILE_AND_LINE_); + } + } + + // Both systems have to give us pings to progress here. Otherwise will timeout in Update() + if (fw->sourceServerPings.Size()>0 && + fw->targetServerPings.Size()>0) + { + fw->OrderRemainingServersToTry(); + fw->timeRequestedPings=0; + TryNextServer(fw->sata, fw); + } +} +void UDPProxyCoordinator::TryNextServer(SenderAndTargetAddress sata, ForwardingRequest *fw) +{ + bool pickedGoodServer=false; + while(fw->remainingServersToTry.Size()>0) + { + fw->currentlyAttemptedServerAddress=fw->remainingServersToTry.Pop(); + if (serverList.GetIndexOf(fw->currentlyAttemptedServerAddress)!=(unsigned int)-1) + { + pickedGoodServer=true; + break; + } + } + + if (pickedGoodServer==false) + { + SendAllBusy(sata.senderClientAddress, sata.targetClientAddress, sata.targetClientGuid, fw->requestingAddress); + forwardingRequestList.Remove(sata); + RakNet::OP_DELETE(fw,_FILE_AND_LINE_); + return; + } + + SendForwardingRequest(sata.senderClientAddress, sata.targetClientAddress, fw->currentlyAttemptedServerAddress, fw->timeoutOnNoDataMS); +} +void UDPProxyCoordinator::SendAllBusy(SystemAddress senderClientAddress, SystemAddress targetClientAddress, RakNetGUID targetClientGuid, SystemAddress requestingAddress) +{ + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_ALL_SERVERS_BUSY); + outgoingBs.Write(senderClientAddress); + outgoingBs.Write(targetClientAddress); + outgoingBs.Write(targetClientGuid); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, requestingAddress, false); +} +void UDPProxyCoordinator::Clear(void) +{ + serverList.Clear(true, _FILE_AND_LINE_); + for (unsigned int i=0; i < forwardingRequestList.Size(); i++) + { + RakNet::OP_DELETE(forwardingRequestList[i],_FILE_AND_LINE_); + } + forwardingRequestList.Clear(false, _FILE_AND_LINE_); +} +void UDPProxyCoordinator::ForwardingRequest::OrderRemainingServersToTry(void) +{ + //DataStructures::Multilist swpList; + DataStructures::OrderedList swpList; + // swpList.SetSortOrder(true); + + if (sourceServerPings.Size()==0 && targetServerPings.Size()==0) + return; + + unsigned int idx; + UDPProxyCoordinator::ServerWithPing swp; + for (idx=0; idx < remainingServersToTry.Size(); idx++) + { + swp.serverAddress=remainingServersToTry[idx]; + swp.ping=0; + if (sourceServerPings.Size()) + swp.ping+=(unsigned short) (sourceServerPings[idx].ping); + else + swp.ping+=(unsigned short) (DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME); + if (targetServerPings.Size()) + swp.ping+=(unsigned short) (targetServerPings[idx].ping); + else + swp.ping+=(unsigned short) (DEFAULT_CLIENT_UNRESPONSIVE_PING_TIME); + swpList.Insert(swp.ping, swp, false, _FILE_AND_LINE_); + } + remainingServersToTry.Clear(_FILE_AND_LINE_ ); + for (idx=0; idx < swpList.Size(); idx++) + { + remainingServersToTry.Push(swpList[idx].serverAddress, _FILE_AND_LINE_ ); + } +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/UDPProxyServer.cpp b/src/raknet/UDPProxyServer.cpp new file mode 100644 index 0000000..93c5e60 --- /dev/null +++ b/src/raknet/UDPProxyServer.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/NativeFeatureIncludes.hpp" +#if _RAKNET_SUPPORT_UDPProxyServer==1 && _RAKNET_SUPPORT_UDPForwarder==1 + +#include "include/raknet/UDPProxyServer.hpp" +#include "include/raknet/BitStream.hpp" +#include "include/raknet/UDPProxyCommon.hpp" +#include "include/raknet/RakPeerInterface.hpp" +#include "include/raknet/MessageIdentifiers.hpp" + +using namespace RakNet; + +STATIC_FACTORY_DEFINITIONS(UDPProxyServer,UDPProxyServer); + +UDPProxyServer::UDPProxyServer() +{ + resultHandler=0; + socketFamily=AF_INET; +} +UDPProxyServer::~UDPProxyServer() +{ + +} +void UDPProxyServer::SetSocketFamily(unsigned short _socketFamily) +{ + socketFamily=_socketFamily; +} +void UDPProxyServer::SetResultHandler(UDPProxyServerResultHandler *rh) +{ + resultHandler=rh; +} +bool UDPProxyServer::LoginToCoordinator(RakNet::RakString password, SystemAddress coordinatorAddress) +{ + unsigned int insertionIndex; + bool objectExists; + insertionIndex=loggingInCoordinators.GetIndexFromKey(coordinatorAddress,&objectExists); + if (objectExists==true) + return false; + loggedInCoordinators.GetIndexFromKey(coordinatorAddress,&objectExists); + if (objectExists==true) + return false; + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR); + outgoingBs.Write(password); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, coordinatorAddress, false); + loggingInCoordinators.InsertAtIndex(coordinatorAddress, insertionIndex, _FILE_AND_LINE_ ); + return true; +} +void UDPProxyServer::SetServerPublicIP(RakString ip) +{ + serverPublicIp = ip; +} +void UDPProxyServer::Update(void) +{ +} +PluginReceiveResult UDPProxyServer::OnReceive(Packet *packet) +{ + // Make sure incoming messages from from UDPProxyCoordinator + + if (packet->data[0]==ID_UDP_PROXY_GENERAL && packet->length>1) + { + bool objectExists; + + switch (packet->data[1]) + { + case ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER: + if (loggedInCoordinators.GetIndexFromKey(packet->systemAddress, &objectExists)!=(unsigned int)-1) + { + OnForwardingRequestFromCoordinatorToServer(packet); + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + break; + case ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER: + case ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER: + case ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER: + case ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER: + { + unsigned int removalIndex = loggingInCoordinators.GetIndexFromKey(packet->systemAddress, &objectExists); + if (objectExists) + { + loggingInCoordinators.RemoveAtIndex(removalIndex); + + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(2); + RakNet::RakString password; + incomingBs.Read(password); + switch (packet->data[1]) + { + case ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER: + if (resultHandler) + resultHandler->OnNoPasswordSet(password, this); + break; + case ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER: + if (resultHandler) + resultHandler->OnWrongPassword(password, this); + break; + case ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER: + if (resultHandler) + resultHandler->OnAlreadyLoggedIn(password, this); + break; + case ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER: + // RakAssert(loggedInCoordinators.GetIndexOf(packet->systemAddress)==(unsigned int)-1); + loggedInCoordinators.Insert(packet->systemAddress, packet->systemAddress, true, _FILE_AND_LINE_); + if (resultHandler) + resultHandler->OnLoginSuccess(password, this); + break; + } + } + + + return RR_STOP_PROCESSING_AND_DEALLOCATE; + } + } + } + return RR_CONTINUE_PROCESSING; +} +void UDPProxyServer::OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason ) +{ + (void) lostConnectionReason; + (void) rakNetGUID; + + loggingInCoordinators.RemoveIfExists(systemAddress); + loggedInCoordinators.RemoveIfExists(systemAddress); +} +void UDPProxyServer::OnRakPeerStartup(void) +{ + udpForwarder.Startup(); +} +void UDPProxyServer::OnRakPeerShutdown(void) +{ + udpForwarder.Shutdown(); + loggingInCoordinators.Clear(true,_FILE_AND_LINE_); + loggedInCoordinators.Clear(true,_FILE_AND_LINE_); +} +void UDPProxyServer::OnAttach(void) +{ + if (rakPeerInterface->IsActive()) + OnRakPeerStartup(); +} +void UDPProxyServer::OnDetach(void) +{ + OnRakPeerShutdown(); +} +void UDPProxyServer::OnForwardingRequestFromCoordinatorToServer(Packet *packet) +{ + SystemAddress sourceAddress, targetAddress; + RakNet::BitStream incomingBs(packet->data, packet->length, false); + incomingBs.IgnoreBytes(2); + incomingBs.Read(sourceAddress); + incomingBs.Read(targetAddress); + RakNet::TimeMS timeoutOnNoDataMS; + incomingBs.Read(timeoutOnNoDataMS); + RakAssert(timeoutOnNoDataMS > 0 && timeoutOnNoDataMS <= UDP_FORWARDER_MAXIMUM_TIMEOUT); + + unsigned short forwardingPort=0; + UDPForwarderResult success = udpForwarder.StartForwarding(sourceAddress, targetAddress, timeoutOnNoDataMS, 0, socketFamily, &forwardingPort, 0); + RakNet::BitStream outgoingBs; + outgoingBs.Write((MessageID)ID_UDP_PROXY_GENERAL); + outgoingBs.Write((MessageID)ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR); + outgoingBs.Write(sourceAddress); + outgoingBs.Write(targetAddress); + outgoingBs.Write(serverPublicIp); + outgoingBs.Write((unsigned char) success); + outgoingBs.Write(forwardingPort); + rakPeerInterface->Send(&outgoingBs, MEDIUM_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, false); +} + +#endif // _RAKNET_SUPPORT_* diff --git a/src/raknet/VariableDeltaSerializer.cpp b/src/raknet/VariableDeltaSerializer.cpp new file mode 100644 index 0000000..fd4f3cc --- /dev/null +++ b/src/raknet/VariableDeltaSerializer.cpp @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/VariableDeltaSerializer.hpp" + +using namespace RakNet; + +VariableDeltaSerializer::VariableDeltaSerializer() {didComparisonThisTick=false;} +VariableDeltaSerializer::~VariableDeltaSerializer() {RemoveRemoteSystemVariableHistory();} + +VariableDeltaSerializer::SerializationContext::SerializationContext() {variableHistoryIdentical=0; variableHistoryUnique=0;} +VariableDeltaSerializer::SerializationContext::~SerializationContext() {} + +void VariableDeltaSerializer::OnMessageReceipt(RakNetGUID guid, uint32_t receiptId, bool messageArrived) +{ + // Module? + if (messageArrived) + FreeVarsAssociatedWithReceipt(guid, receiptId); + else + DirtyAndFreeVarsAssociatedWithReceipt(guid, receiptId); + +} + +void VariableDeltaSerializer::BeginUnreliableAckedSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream, uint32_t _sendReceipt) +{ + RakAssert(_guid!=UNASSIGNED_RAKNET_GUID); + context->anyVariablesWritten=false; + context->guid=_guid; + context->bitStream=_bitStream; + if (context->variableHistoryUnique==0) + context->variableHistoryUnique=StartVariableHistoryWrite(_guid); + context->variableHistory=context->variableHistoryUnique; + context->sendReceipt=_sendReceipt; + context->changedVariables = AllocChangedVariablesList(); + context->newSystemSend=false; + context->serializationMode=UNRELIABLE_WITH_ACK_RECEIPT; +} + +void VariableDeltaSerializer::BeginUniqueSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream) +{ + RakAssert(_guid!=UNASSIGNED_RAKNET_GUID); + context->anyVariablesWritten=false; + context->guid=_guid; + context->bitStream=_bitStream; + if (context->variableHistoryUnique==0) + context->variableHistoryUnique=StartVariableHistoryWrite(_guid); + context->variableHistory=context->variableHistoryUnique; + context->newSystemSend=false; + + context->serializationMode=RELIABLE; +} + + +void VariableDeltaSerializer::BeginIdenticalSerialize(SerializationContext *context, bool _isFirstSendToRemoteSystem, BitStream *_bitStream) +{ + context->anyVariablesWritten=false; + context->guid=UNASSIGNED_RAKNET_GUID; + context->bitStream=_bitStream; + context->serializationMode=RELIABLE; + if (context->variableHistoryIdentical==0) + context->variableHistoryIdentical=StartVariableHistoryWrite(UNASSIGNED_RAKNET_GUID); + context->variableHistory=context->variableHistoryIdentical; + context->newSystemSend=_isFirstSendToRemoteSystem; +} + +void VariableDeltaSerializer::EndSerialize(SerializationContext *context) +{ + if (context->serializationMode==UNRELIABLE_WITH_ACK_RECEIPT) + { + if (context->anyVariablesWritten==false) + { + context->bitStream->Reset(); + FreeChangedVariablesList(context->changedVariables); + return; + } + + StoreChangedVariablesList(context->variableHistory, context->changedVariables, context->sendReceipt); + } + else + { + if (context->variableHistoryIdentical) + { + if (didComparisonThisTick==false) + { + didComparisonThisTick=true; + identicalSerializationBs.Reset(); + + if (context->anyVariablesWritten==false) + { + context->bitStream->Reset(); + return; + } + + identicalSerializationBs.Write(context->bitStream); + context->bitStream->ResetReadPointer(); + } + else + { + context->bitStream->Write(&identicalSerializationBs); + identicalSerializationBs.ResetReadPointer(); + } + } + else if (context->anyVariablesWritten==false) + { + context->bitStream->Reset(); + return; + } + } +} + +void VariableDeltaSerializer::BeginDeserialize(DeserializationContext *context, BitStream *_bitStream) +{ + context->bitStream=_bitStream; +} + +void VariableDeltaSerializer::EndDeserialize(DeserializationContext *context) +{ + (void) context; +} + +void VariableDeltaSerializer::AddRemoteSystemVariableHistory(RakNetGUID guid) +{ + (void) guid; +} + +void VariableDeltaSerializer::RemoveRemoteSystemVariableHistory(RakNetGUID guid) +{ + unsigned int idx,idx2; + idx = GetVarsWrittenPerRemoteSystemListIndex(guid); + if (idx==(unsigned int)-1) + return; + + if (remoteSystemVariableHistoryList[idx]->guid==guid) + { + // Memory pool doesn't call destructor + for (idx2=0; idx2 < remoteSystemVariableHistoryList[idx]->updatedVariablesHistory.Size(); idx2++) + { + FreeChangedVariablesList(remoteSystemVariableHistoryList[idx]->updatedVariablesHistory[idx2]); + } + + delete remoteSystemVariableHistoryList[idx]; + remoteSystemVariableHistoryList.RemoveAtIndexFast(idx); + return; + } +} + +int RakNet::VariableDeltaSerializer::UpdatedVariablesListPtrComp( const uint32_t &key, ChangedVariablesList* const &data ) +{ + if (keysendReceipt) + return -1; + if (key==data->sendReceipt) + return 0; + return 1; +} + +void VariableDeltaSerializer::FreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId) +{ + unsigned int idx, idx2; + idx = GetVarsWrittenPerRemoteSystemListIndex(guid); + if (idx==(unsigned int)-1) + return; + + RemoteSystemVariableHistory* vprs = remoteSystemVariableHistoryList[idx]; + bool objectExists; + idx2=vprs->updatedVariablesHistory.GetIndexFromKey(receiptId,&objectExists); + if (objectExists) + { + // Free this history node + FreeChangedVariablesList(vprs->updatedVariablesHistory[idx2]); + vprs->updatedVariablesHistory.RemoveAtIndex(idx2); + } +} + +void VariableDeltaSerializer::DirtyAndFreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId) +{ + unsigned int idx, idx2; + idx = GetVarsWrittenPerRemoteSystemListIndex(guid); + if (idx==(unsigned int)-1) + return; + + RemoteSystemVariableHistory* vprs = remoteSystemVariableHistoryList[idx]; + bool objectExists; + idx2=vprs->updatedVariablesHistory.GetIndexFromKey(receiptId,&objectExists); + if (objectExists) + { + // 'Dirty' all variables sent this update, meaning they will be resent the next time Serialize() is called + vprs->variableListDeltaTracker.FlagDirtyFromBitArray(vprs->updatedVariablesHistory[idx2]->bitField); + + // Free this history node + FreeChangedVariablesList(vprs->updatedVariablesHistory[idx2]); + vprs->updatedVariablesHistory.RemoveAtIndex(idx2); + } +} +unsigned int VariableDeltaSerializer::GetVarsWrittenPerRemoteSystemListIndex(RakNetGUID guid) +{ + unsigned int idx; + for (idx=0; idx < remoteSystemVariableHistoryList.Size(); idx++) + { + if (remoteSystemVariableHistoryList[idx]->guid==guid) + return idx; + } + return (unsigned int) -1; +} +void VariableDeltaSerializer::RemoveRemoteSystemVariableHistory(void) +{ + unsigned int idx,idx2; + for (idx=0; idx < remoteSystemVariableHistoryList.Size(); idx++) + { + for (idx2=0; idx2 < remoteSystemVariableHistoryList[idx]->updatedVariablesHistory.Size(); idx2++) + { + FreeChangedVariablesList(remoteSystemVariableHistoryList[idx]->updatedVariablesHistory[idx2]); + } + + delete remoteSystemVariableHistoryList[idx]; + } + remoteSystemVariableHistoryList.Clear(false,_FILE_AND_LINE_); +} + +VariableDeltaSerializer::RemoteSystemVariableHistory* VariableDeltaSerializer::GetRemoteSystemVariableHistory(RakNetGUID guid) +{ + unsigned int rshli = GetRemoteSystemHistoryListIndex(guid); + return remoteSystemVariableHistoryList[rshli]; +} + +VariableDeltaSerializer::ChangedVariablesList *VariableDeltaSerializer::AllocChangedVariablesList(void) +{ + VariableDeltaSerializer::ChangedVariablesList *p = updatedVariablesMemoryPool.Allocate(_FILE_AND_LINE_); + p->bitWriteIndex=0; + p->bitField[0]=0; + return p; +} +void VariableDeltaSerializer::FreeChangedVariablesList(ChangedVariablesList *changedVariables) +{ + updatedVariablesMemoryPool.Release(changedVariables, _FILE_AND_LINE_); +} +void VariableDeltaSerializer::StoreChangedVariablesList(RemoteSystemVariableHistory *variableHistory, ChangedVariablesList *changedVariables, uint32_t sendReceipt) +{ + changedVariables->sendReceipt=sendReceipt; + variableHistory->updatedVariablesHistory.Insert(changedVariables->sendReceipt,changedVariables,true,_FILE_AND_LINE_); +} + +VariableDeltaSerializer::RemoteSystemVariableHistory *VariableDeltaSerializer::StartVariableHistoryWrite(RakNetGUID guid) +{ + RemoteSystemVariableHistory *variableHistory; + + unsigned int rshli = GetRemoteSystemHistoryListIndex(guid); + if (rshli==(unsigned int) -1) + { + variableHistory = new RemoteSystemVariableHistory; + variableHistory->guid=guid; + remoteSystemVariableHistoryList.Push(variableHistory,_FILE_AND_LINE_); + } + else + { + variableHistory=remoteSystemVariableHistoryList[rshli]; + } + + variableHistory->variableListDeltaTracker.StartWrite(); + return variableHistory; +} +unsigned int VariableDeltaSerializer::GetRemoteSystemHistoryListIndex(RakNetGUID guid) +{ + // Find the variable tracker for the target system + unsigned int idx; + for (idx=0; idx < remoteSystemVariableHistoryList.Size(); idx++) + { + if (remoteSystemVariableHistoryList[idx]->guid==guid) + { + return idx; + } + } + return (unsigned int) -1; +} + +void VariableDeltaSerializer::OnPreSerializeTick(void) +{ + didComparisonThisTick=false; +} diff --git a/src/raknet/VariableListDeltaTracker.cpp b/src/raknet/VariableListDeltaTracker.cpp new file mode 100644 index 0000000..3d115e5 --- /dev/null +++ b/src/raknet/VariableListDeltaTracker.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/VariableListDeltaTracker.hpp" + +using namespace RakNet; + +VariableListDeltaTracker::VariableListDeltaTracker() {nextWriteIndex=0;} +VariableListDeltaTracker::~VariableListDeltaTracker() +{ + unsigned int i; + for (i=0; i < variableList.Size(); i++) + rakFree_Ex(variableList[i].lastData,_FILE_AND_LINE_); +} + +// Call before using a series of WriteVar +void VariableListDeltaTracker::StartWrite(void) {nextWriteIndex=0;} + +void VariableListDeltaTracker::FlagDirtyFromBitArray(unsigned char *bArray) +{ + unsigned short readOffset=0; + for (readOffset=0; readOffset < variableList.Size(); readOffset++) + { + bool result = ( bArray[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) !=0; + + if (result==true) + variableList[readOffset].isDirty=true; + } +} +VariableListDeltaTracker::VariableLastValueNode::VariableLastValueNode() +{ + lastData=0; +} +VariableListDeltaTracker::VariableLastValueNode::VariableLastValueNode(const unsigned char *data, int _byteLength) +{ + lastData=(char*) rakMalloc_Ex(_byteLength,_FILE_AND_LINE_); + memcpy(lastData,data,_byteLength); + byteLength=_byteLength; + isDirty=false; +} +VariableListDeltaTracker::VariableLastValueNode::~VariableLastValueNode() +{ +} diff --git a/src/raknet/VariadicSQLParser.cpp b/src/raknet/VariadicSQLParser.cpp new file mode 100644 index 0000000..aeb096b --- /dev/null +++ b/src/raknet/VariadicSQLParser.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/VariadicSQLParser.hpp" +#include "include/raknet/BitStream.hpp" +#include + +using namespace VariadicSQLParser; + +struct TypeMapping +{ + char inputType; + const char *type; +}; +const int NUM_TYPE_MAPPINGS=7; +TypeMapping typeMappings[NUM_TYPE_MAPPINGS] = +{ + {'i', "int"}, + {'d', "int"}, + {'s', "text"}, + {'b', "bool"}, + {'f', "numeric"}, + {'g', "double precision"}, + {'a', "bytea"}, +}; +unsigned int GetTypeMappingIndex(char c) +{ + unsigned int i; + for (i=0; i < (unsigned int) NUM_TYPE_MAPPINGS; i++ ) + if (typeMappings[i].inputType==c) + return i; + return (unsigned int)-1; +} +const char* VariadicSQLParser::GetTypeMappingAtIndex(int i) +{ + return typeMappings[i].type; +} +void VariadicSQLParser::GetTypeMappingIndices( const char *format, DataStructures::List &indices ) +{ + bool previousCharWasPercentSign; + unsigned int i; + unsigned int typeMappingIndex; + indices.Clear(false, _FILE_AND_LINE_); + unsigned int len = (unsigned int) strlen(format); + previousCharWasPercentSign=false; + for (i=0; i < len; i++) + { + if (previousCharWasPercentSign==true ) + { + typeMappingIndex = GetTypeMappingIndex(format[i]); + if (typeMappingIndex!=(unsigned int) -1) + { + IndexAndType iat; + iat.strIndex=i-1; + iat.typeMappingIndex=typeMappingIndex; + indices.Insert(iat, _FILE_AND_LINE_ ); + } + } + + previousCharWasPercentSign=format[i]=='%'; + } +} +void VariadicSQLParser::ExtractArguments( va_list argptr, const DataStructures::List &indices, char ***argumentBinary, int **argumentLengths ) +{ + if (indices.Size()==0) + return; + + unsigned int i; + *argumentBinary=RakNet::OP_NEW_ARRAY(indices.Size(), _FILE_AND_LINE_); + *argumentLengths=RakNet::OP_NEW_ARRAY(indices.Size(), _FILE_AND_LINE_); + + char **paramData=*argumentBinary; + int *paramLength=*argumentLengths; + + int variadicArgIndex; + for (variadicArgIndex=0, i=0; i < indices.Size(); i++, variadicArgIndex++) + { + switch (typeMappings[indices[i].typeMappingIndex].inputType) + { + case 'i': + case 'd': + { + int val = va_arg( argptr, int ); + paramLength[i]=sizeof(val); + paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); + memcpy(paramData[i], &val, paramLength[i]); + if (RakNet::BitStream::IsNetworkOrder()==false) RakNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); + } + break; + case 's': + { + char* val = va_arg( argptr, char* ); + paramLength[i]=(int) strlen(val); + paramData[i]=(char*) rakMalloc_Ex(paramLength[i]+1, _FILE_AND_LINE_); + memcpy(paramData[i], val, paramLength[i]+1); + } + break; + case 'b': + { + bool val = (va_arg( argptr, int )!=0); + paramLength[i]=sizeof(val); + paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); + memcpy(paramData[i], &val, paramLength[i]); + if (RakNet::BitStream::IsNetworkOrder()==false) RakNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); + } + break; + /* + case 'f': + { + // On MSVC at least, this only works with double as the 2nd param + float val = (float) va_arg( argptr, double ); + //float val = va_arg( argptr, float ); + paramLength[i]=sizeof(val); + paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); + memcpy(paramData[i], &val, paramLength[i]); + if (RakNet::BitStream::IsNetworkOrder()==false) RakNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); + } + break; + */ + // On MSVC at least, this only works with double as the 2nd param + case 'f': + case 'g': + { + double val = va_arg( argptr, double ); + paramLength[i]=sizeof(val); + paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); + memcpy(paramData[i], &val, paramLength[i]); + if (RakNet::BitStream::IsNetworkOrder()==false) RakNet::BitStream::ReverseBytesInPlace((unsigned char*) paramData[i], paramLength[i]); + } + break; + case 'a': + { + char* val = va_arg( argptr, char* ); + paramLength[i]=va_arg( argptr, unsigned int ); + paramData[i]=(char*) rakMalloc_Ex(paramLength[i], _FILE_AND_LINE_); + memcpy(paramData[i], val, paramLength[i]); + } + break; + } + } + +} +void VariadicSQLParser::FreeArguments(const DataStructures::List &indices, char **argumentBinary, int *argumentLengths) +{ + if (indices.Size()==0) + return; + + unsigned int i; + for (i=0; i < indices.Size(); i++) + rakFree_Ex(argumentBinary[i],_FILE_AND_LINE_); + RakNet::OP_DELETE_ARRAY(argumentBinary,_FILE_AND_LINE_); + RakNet::OP_DELETE_ARRAY(argumentLengths,_FILE_AND_LINE_); +} diff --git a/src/raknet/VitaIncludes.cpp b/src/raknet/VitaIncludes.cpp new file mode 100644 index 0000000..62881c4 --- /dev/null +++ b/src/raknet/VitaIncludes.cpp @@ -0,0 +1,165 @@ +#include "include/raknet/EmptyHeader.hpp" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/raknet/WSAStartupSingleton.cpp b/src/raknet/WSAStartupSingleton.cpp new file mode 100644 index 0000000..9ded5de --- /dev/null +++ b/src/raknet/WSAStartupSingleton.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#include "include/raknet/WSAStartupSingleton.hpp" + + + + + +#if defined(_WIN32) && !defined(WINDOWS_STORE_RT) +#include +#include + + + + + +#endif +#include "include/raknet/RakNetDefines.hpp" +#include + +int WSAStartupSingleton::refCount=0; + +WSAStartupSingleton::WSAStartupSingleton() {} +WSAStartupSingleton::~WSAStartupSingleton() {} +void WSAStartupSingleton::AddRef(void) +{ +#if defined(_WIN32) && !defined(WINDOWS_STORE_RT) + + refCount++; + + if (refCount!=1) + return; + + + + + + WSADATA winsockInfo; + if ( WSAStartup( MAKEWORD( 2, 2 ), &winsockInfo ) != 0 ) + { +#if defined(_DEBUG) && !defined(WINDOWS_PHONE_8) + DWORD dwIOError = GetLastError(); + LPVOID messageBuffer; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // Default language + ( LPTSTR ) & messageBuffer, 0, NULL ); + // something has gone wrong here... + RAKNET_DEBUG_PRINTF( "WSAStartup failed:Error code - %d\n%s", dwIOError, messageBuffer ); + //Free the buffer. + LocalFree( messageBuffer ); +#endif + } + +#endif +} +void WSAStartupSingleton::Deref(void) +{ +#if defined(_WIN32) && !defined(WINDOWS_STORE_RT) + if (refCount==0) + return; + + if (refCount>1) + { + refCount--; + return; + } + + WSACleanup(); + + + + + + + refCount=0; +#endif +} diff --git a/src/raknet/_FindFirst.cpp b/src/raknet/_FindFirst.cpp new file mode 100644 index 0000000..da909ce --- /dev/null +++ b/src/raknet/_FindFirst.cpp @@ -0,0 +1,159 @@ +/** +* Original file by the_viking, fixed by R√yenmulo Fernandes, fixed by Emmanuel Nars +* Should emulate windows finddata structure +*/ +#if (defined(__GNUC__) || defined(__GCCXML__)) && !defined(_WIN32) +#include "include/raknet/_FindFirst.hpp" +#include "include/raknet/DS_List.hpp" + +#include + +#include + + +static DataStructures::List< _findinfo_t* > fileInfo; + +#include "include/raknet/RakMemoryOverride.hpp" +#include "include/raknet/RakAssert.hpp" + +/** +* _findfirst - equivalent +*/ +long _findfirst(const char *name, _finddata_t *f) +{ + RakNet::RakString nameCopy = name; + RakNet::RakString filter; + + // This is linux only, so don't bother with '\' + const char* lastSep = strrchr(name,'/'); + if(!lastSep) + { + // filter pattern only is given, search current directory. + filter = nameCopy; + nameCopy = "."; + } else + { + // strip filter pattern from directory name, leave + // trailing '/' intact. + filter = lastSep+1; + unsigned sepIndex = lastSep - name; + nameCopy.Erase(sepIndex+1, nameCopy.GetLength() - sepIndex-1); + } + + DIR* dir = opendir(nameCopy); + + if(!dir) return -1; + + _findinfo_t* fi = RakNet::OP_NEW<_findinfo_t>( _FILE_AND_LINE_ ); + fi->filter = filter; + fi->dirName = nameCopy; // we need to remember this for stat() + fi->openedDir = dir; + fileInfo.Insert(fi, _FILE_AND_LINE_); + + long ret = fileInfo.Size()-1; + + // Retrieve the first file. We cannot rely on the first item + // being '.' + if (_findnext(ret, f) == -1) return -1; + else return ret; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +int _findnext(long h, _finddata_t *f) +{ + RakAssert(h >= 0 && h < (long)fileInfo.Size()); + if (h < 0 || h >= (long)fileInfo.Size()) return -1; + + _findinfo_t* fi = fileInfo[h]; + + while(true) + { + dirent* entry = readdir(fi->openedDir); + if(entry == 0) return -1; + + // Only report stuff matching our filter + if (fnmatch(fi->filter, entry->d_name, FNM_PATHNAME) != 0) continue; + + // To reliably determine the entry's type, we must do + // a stat... don't rely on entry->d_type, as this + // might be unavailable! + struct stat filestat; + RakNet::RakString fullPath = fi->dirName + entry->d_name; + if (stat(fullPath, &filestat) != 0) + { + RAKNET_DEBUG_PRINTF("Cannot stat %s\n", fullPath.C_String()); + continue; + } + + if (S_ISREG(filestat.st_mode)) + { + f->attrib = _A_NORMAL; + } else if (S_ISDIR(filestat.st_mode)) + { + f->attrib = _A_SUBDIR; + } else continue; // We are interested in files and + // directories only. Links currently + // are not supported. + + f->size = filestat.st_size; + strncpy(f->name, entry->d_name, STRING_BUFFER_SIZE); + + return 0; + } + + return -1; +} + + + + + +/** + * _findclose - equivalent + */ +int _findclose(long h) +{ + if (h==-1) return 0; + + if (h < 0 || h >= (long)fileInfo.Size()) + { + RakAssert(false); + return -1; + } + + _findinfo_t* fi = fileInfo[h]; + closedir(fi->openedDir); + fileInfo.RemoveAtIndex(h); + RakNet::OP_DELETE(fi, _FILE_AND_LINE_); + return 0; +} +#endif diff --git a/src/raknet/gettimeofday.cpp b/src/raknet/gettimeofday.cpp new file mode 100644 index 0000000..76572b6 --- /dev/null +++ b/src/raknet/gettimeofday.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2014, Oculus VR, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ + +#if defined(_WIN32) && !defined(__GNUC__) &&!defined(__GCCXML__) + +#include "include/raknet/gettimeofday.hpp" + +// From http://www.openasthra.com/c-tidbits/gettimeofday-function-for-windows/ + +#include "include/raknet/WindowsIncludes.hpp" + +#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) + #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 +#else + #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL +#endif + +int gettimeofday(struct timeval *tv, struct timezone *tz) +{ +#if defined(WINDOWS_PHONE_8) || defined(WINDOWS_STORE_RT) + // _tzset not supported + (void) tv; + (void) tz; +#else + + FILETIME ft; + unsigned __int64 tmpres = 0; + static int tzflag; + + if (NULL != tv) + { + GetSystemTimeAsFileTime(&ft); + + tmpres |= ft.dwHighDateTime; + tmpres <<= 32; + tmpres |= ft.dwLowDateTime; + + /*converting file time to unix epoch*/ + tmpres /= 10; /*convert into microseconds*/ + tmpres -= DELTA_EPOCH_IN_MICROSECS; + tv->tv_sec = (long)(tmpres / 1000000UL); + tv->tv_usec = (long)(tmpres % 1000000UL); + } + + if (NULL != tz) + { + if (!tzflag) + { + _tzset(); + tzflag++; + } + tz->tz_minuteswest = _timezone / 60; + tz->tz_dsttime = _daylight; + } + +#endif + + return 0; +} + +#endif + diff --git a/src/utils/BitReader.cpp b/src/utils/BitReader.cpp new file mode 100644 index 0000000..b71883e --- /dev/null +++ b/src/utils/BitReader.cpp @@ -0,0 +1,208 @@ +#include "include/utils/BitReader.hpp" +#include + +unsigned char BitReader::getBitsFromByte(unsigned char byte, unsigned int count){ + + return BitReader::getBitsFromByte(byte,0,count); + +} + +unsigned char BitReader::getBitsFromByte(unsigned char byte, unsigned int index, unsigned int count){ + + if(count==0||byte==0){ + return 0; + } + + if(index>=8||count>8){ + return byte; + } + + unsigned int maxRange=(8-index); + + if(count>maxRange){ + + count=maxRange; + + } + + unsigned char mask=(unsigned char)((1<<(maxRange))-1); + + return (byte&mask)>>((maxRange-count)); + +} + +BitReader::BitReader(const char* dataArray, unsigned int arrayLength){ + + if(dataArray!=nullptr){ + + this->array=new char[arrayLength]; + + this->arrlen=arrayLength; + + memcpy(this->array, dataArray, arrayLength); + + }else{ + + this->array=nullptr; + + this->arrlen=0; + + } + + this->page=0; + + this->currentBitCursor=0; + +} + +BitReader::~BitReader(){ + + delete[] this->array; + +} + +unsigned long long int BitReader::getBitIndex(){ + + return (((unsigned long long int)(this->page==this->arrlen?(this->page-1):this->page))*8)+this->currentBitCursor; + +} + +unsigned int BitReader::getBitIndexOfCurrentByte(){ + + return this->currentBitCursor; + +} + +unsigned int BitReader::getByteIndex(){ + + return this->page==this->arrlen?(this->page-1):this->page; + +} + +void BitReader::setBitIndex(unsigned long long int index){ + + unsigned long long int maxAcceptableIndex=(this->arrlen*8); + + if(indexpage=index/8; + + this->currentBitCursor=index%8; + + } + +} + +void BitReader::setBitIndexOfCurrentByte(unsigned int index){ + + if(index<8){ + + this->currentBitCursor=index; + + } + +} + +void BitReader::setByteIndex(unsigned int index){ + + if(indexarrlen){ + + this->page=index; + + } + +} + +unsigned int BitReader::isEOA(){ + + if(page==this->arrlen&&this->currentBitCursor==7){ + + return true; + + }else{ + + return false; + + } + +} + +char* BitReader::getFixedDepthBitsFromArray(unsigned int bitDepth, unsigned int count){ + + if(bitDepth>8||bitDepth==0||this->arrlen==0){ + + return nullptr; + + } + + unsigned int leftSpace=((this->arrlen-this->page)*8)-(this->currentBitCursor); + + unsigned long long int maxReadableCount=leftSpace/bitDepth+(leftSpace%bitDepth!=0); + + if(count>maxReadableCount){ + + return nullptr; + + } + + char* result=new char[count]; + + for(unsigned int i=0;igetBitsFromArray(bitDepth); + + } + + return result; + +} + +unsigned char BitReader::getBitsFromArray(unsigned int count){ + + if(this->array==nullptr||count==0||count>8){ + + return 0; + + } + + if(this->isEOA()){ + + return 0; + + } + + unsigned char result=BitReader::getBitsFromByte(this->array[this->page],this->currentBitCursor,count); + + this->currentBitCursor=this->currentBitCursor+count; + + if(this->currentBitCursor>=8){ + + this->page++; + + if(this->page==this->arrlen){ + + this->currentBitCursor=7; + + }else{ + + unsigned int leftBits=(this->currentBitCursor-8); + + if(leftBits!=0){ + + result=(result<array[page],0,leftBits)); + + this->currentBitCursor=leftBits; + + }else{ + + this->currentBitCursor=0; + + } + + } + + } + + return result; + +} diff --git a/src/utils/CRC.cpp b/src/utils/CRC.cpp new file mode 100644 index 0000000..73a80ba --- /dev/null +++ b/src/utils/CRC.cpp @@ -0,0 +1,54 @@ +#include "include/utils/CRC.hpp" + +const unsigned int CRC::CRC32_POLYNOMIAL=0xEDB88320; +const unsigned int CRC::CRC32_POLYNOMIAL_DRF=0x7FFF0109; + +const unsigned int CRC::CRC_MODE_DEFAULT=0x66CCFF00; +const unsigned int CRC::CRC_MODE_DRF=0x2196F300; + +CRC::CRC(unsigned int mode){ + + if(this->crc32_table==0){ + this->crc32_table=new unsigned int[256]; + }else{ + return; + } + for (unsigned int i = 0,c=0; i < 256; i++,c=i) { + for (unsigned int k = 0; k < 8; k++) { + if ((c & 1) != 0) { + c = (mode==CRC::CRC_MODE_DEFAULT?CRC::CRC32_POLYNOMIAL:CRC::CRC32_POLYNOMIAL_DRF) ^ (c >> 1); + } else { + c = c >> 1; + } + } + this->crc32_table[i] = c; + } + +} + +CRC::~CRC(){ + + delete crc32_table; + +} + +unsigned int CRC::update_crc32(const unsigned char* data, unsigned int dataLength, unsigned int old_crc32){ + + if(data==0||dataLength==0){ + return 0; + } + + unsigned int tempCRC32=old_crc32; + + for (unsigned int i=0; icrc32_table[(tempCRC32^data[i])&0xFF]^(tempCRC32>>8); + } + return tempCRC32; +} + +unsigned int CRC::getCRC32(const unsigned char* data,unsigned int dataLength){ + + return (this->update_crc32(data,dataLength,0xFFFFFFFF))^0xFFFFFFFF; + +} + diff --git a/src/utils/EndianUtils.cpp b/src/utils/EndianUtils.cpp new file mode 100644 index 0000000..209228a --- /dev/null +++ b/src/utils/EndianUtils.cpp @@ -0,0 +1,66 @@ +#include "include/utils/EndianUtils.hpp" +#include + +unsigned int EndianUtils::isLittleEndian(){ + + unsigned int endianTest=1; + return ((unsigned char*)&endianTest)[0]; + +} + +unsigned long long EndianUtils::reverseBytes(unsigned long long arg, unsigned int dataSize){ + + if(dataSize==0||dataSize>sizeof(unsigned long long)){ + std::runtime_error error("IllegalArgumentException: Bad data length."); + throw error; + } + + if(dataSize==1){ + return arg; + } + + unsigned long long result=0; + + for(unsigned int i=0,i3=dataSize-1;i + +FileReader::FileReader(const char* filePath){ + + this->fd=fopen(filePath,"rb"); + if(this->fd==0){ + std::runtime_error error("IOException: cannot open file."); + throw error; + } + fseek(this->fd,SEEK_SET,SEEK_END); + this->length=ftell(this->fd); + fseek(this->fd,0,SEEK_SET); + +} + +FileReader::~FileReader(){ + + if(this->fd!=0){ + + fclose(this->fd); + + } + +} + +void FileReader::readFully(char* buffer,unsigned int length){ + + if( length==0 || length > this->length-ftell(this->fd) ){ + printf("ftell: %lu\n",ftell(this->fd)); + std::runtime_error error("IOException: not enough data read!"); + throw error; + } + + unsigned long long int readBytes=0; + + for(;readBytesfd); + + if(ferror(this->fd)){ + + break; + + } + + readBytes=readBytes+byteCount; + + } + + if(readBytes!=length){ + std::runtime_error error("IOException: unexpected end of stream!"); + throw error; + } + +} + +unsigned int FileReader::read(char * buffer, unsigned int length){ + + return fread(buffer,1,length,this->fd); + +} + +unsigned int FileReader::isEOF(){ + + return feof(this->fd); + +} + +void FileReader::reset(){ + + fseek(this->fd,0,SEEK_SET); + +} + +void FileReader::seekTo(unsigned int offset){ + + if(offset>this->length){ + std::runtime_error error("IOException: offset larger than file length!"); + throw error; + } + fseek(this->fd,offset,SEEK_SET); +} + +unsigned int FileReader::getFileLength(){ + + return this->length; + +} diff --git a/src/utils/FileWriter.cpp b/src/utils/FileWriter.cpp new file mode 100644 index 0000000..398ab08 --- /dev/null +++ b/src/utils/FileWriter.cpp @@ -0,0 +1,53 @@ +#include "include/utils/FileWriter.hpp" +#include + +FileWriter::FileWriter(const char* filePath){ + + this->fd=fopen(filePath,"wb"); + if(this->fd==0){ + std::runtime_error error("IOException: cannot create file."); + throw error; + } +} + +FileWriter::~FileWriter(){ + + if(this->fd!=0){ + + fclose(this->fd); + + } + +} + +void FileWriter::write(const char* buffer,unsigned int length){ + + unsigned int byteCount=fwrite(buffer,1,length,this->fd); + if(byteCount!=length){ + std::runtime_error error("IOException: write error!"); + throw error; + } + +} + +void FileWriter::reset(){ + + fseek(this->fd,0,SEEK_SET); + +} + +void FileWriter::seekTo(unsigned int offset){ + + fseek(this->fd,offset,SEEK_SET); + +} + +unsigned int FileWriter::getCurrentFileSize(){ + + unsigned int currentIndex=ftell(this->fd); + fseek(this->fd,SEEK_SET,SEEK_END); + unsigned int fileEnd=ftell(this->fd); + fseek(this->fd,currentIndex,SEEK_END); + return fileEnd; + +} diff --git a/src/utils/GzipUtils.cpp b/src/utils/GzipUtils.cpp new file mode 100644 index 0000000..37361c5 --- /dev/null +++ b/src/utils/GzipUtils.cpp @@ -0,0 +1,224 @@ +#include "include/utils/GzipUtils.hpp" +#include "include/zlib/zlib.h" +#include +#include +#include "include/utils/Integer.hpp" + +unsigned char* GzipUtils::compressData(const unsigned char* data, unsigned long dataLength, unsigned long* resultLength){ + + if(dataLength<=0||data==nullptr||resultLength==nullptr){ + + return 0; + + } + + z_streamp stream=new z_stream; + + stream->next_in=(Bytef*)data; + stream->avail_in=dataLength; + stream->total_out = 0; + stream->zalloc = Z_NULL; + stream->zfree = Z_NULL; + stream->opaque= Z_NULL; + + unsigned int step=1; + unsigned int startSize=(dataLength*step); + + unsigned char* result=new unsigned char[startSize]; + + stream->avail_out=startSize; + stream->next_out=result; + + int ret=deflateInit2(stream,Z_BEST_COMPRESSION, Z_DEFLATED, MAX_WBITS+16, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); + + if(ret!=Z_OK){ + + delete stream; + + return nullptr; + + } + + unsigned long tempResultLength=startSize; + + for(;;){ + + int ret=deflate(stream, Z_FINISH); + + if(ret==Z_STREAM_END){ + + deflateEnd(stream); + + *resultLength=stream->total_out; + + result=(unsigned char*)realloc(result,stream->total_out); + + delete stream; + + return result; + + }else if(ret==Z_OK){ + + step=step<<1; + + tempResultLength=(step*dataLength); + + result=(unsigned char*)realloc(result,tempResultLength); + + stream->avail_out=tempResultLength-(stream->total_out); + stream->next_out=result+stream->total_out; + + }else{ + + deflateEnd(stream); + + delete stream; + + delete result; + + return nullptr; + + } + + } + +} + +unsigned char* GzipUtils::decompressData(const unsigned char* data, unsigned long dataLength, unsigned long* resultLength){ + + if(dataLength<=0||data==nullptr||resultLength==nullptr){ + + return nullptr; + + } + + z_streamp stream=new z_stream; + + stream->next_in=(Bytef*)data; + stream->avail_in=dataLength; + stream->total_out = 0; + stream->zalloc = Z_NULL; + stream->zfree = Z_NULL; + stream->opaque= Z_NULL; + + unsigned int step=4; + unsigned int startSize=(dataLength*step); + + unsigned char* result=new unsigned char[startSize]; + + stream->avail_out=startSize; + stream->next_out=result; + + int ret=inflateInit2(stream,MAX_WBITS+16); + + if(ret!=Z_OK){ + + delete stream; + + return nullptr; + + } + + unsigned long tempResultLength=startSize; + + for(;;){ + + int ret=inflate(stream,Z_FINISH); + + if(ret==Z_STREAM_END){ + + inflateEnd(stream); + + *resultLength=stream->total_out; + + result=(unsigned char*)realloc(result,stream->total_out); + + delete stream; + + return result; + + }else if(ret==Z_OK){ + + step=step<<1; + + tempResultLength=(step*dataLength); + + result=(unsigned char*)realloc(result,tempResultLength); + + stream->avail_out=tempResultLength-(stream->total_out); + stream->next_out=result+stream->total_out; + + }else{ + + inflateEnd(stream); + + delete stream; + + delete result; + + return nullptr; + + } + + } + +} + +int GzipUtils::decompressData(const unsigned char* data, unsigned long dataLength, unsigned char* resultBuffer, unsigned long resultBufferSize, unsigned long* resultLength){ + + if(dataLength==0||data==nullptr||resultLength==nullptr||resultBuffer==nullptr||resultBufferSize==0){ + + return -1; + + } + + z_streamp stream=new z_stream; + + stream->next_in=(Bytef*)data; + stream->avail_in=dataLength; + stream->total_out = 0; + stream->zalloc = Z_NULL; + stream->zfree = Z_NULL; + stream->opaque= Z_NULL; + + stream->next_out=resultBuffer; + stream->avail_out=resultBufferSize; + + int ret=inflateInit2(stream, MAX_WBITS+16); + + if(ret!=Z_OK){ + + delete stream; + + return ret; + + } + + int inflate_ret=inflate(stream,Z_FINISH); + + int status=0; + + if(inflate_ret==Z_STREAM_END){ + + status=Z_OK; + + *resultLength=stream->total_out; + + }else if(inflate_ret==Z_OK){ + + status=Z_BUF_ERROR; + + }else{ + + status=inflate_ret; + + } + + inflateEnd(stream); + + delete stream; + + return ret; + + +} diff --git a/src/utils/HeaderChecker.cpp b/src/utils/HeaderChecker.cpp new file mode 100644 index 0000000..2f18d5c --- /dev/null +++ b/src/utils/HeaderChecker.cpp @@ -0,0 +1,12 @@ +#include "include/utils/HeaderChecker.hpp" +#include + +const unsigned char HeaderChecker::HEADER_DRF[HeaderChecker::HEADER_DRF_LENGTH]={0xff,'D','R','F'}; + +const unsigned char HeaderChecker::HEADER_PNG[]={0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A}; + +unsigned char HeaderChecker::checkHeader(const unsigned char* imgHeader, unsigned int headerLength, const unsigned char* targetHeader){ + + return memcmp(imgHeader,targetHeader,headerLength); + +} diff --git a/src/utils/Integer.cpp b/src/utils/Integer.cpp new file mode 100644 index 0000000..38719bd --- /dev/null +++ b/src/utils/Integer.cpp @@ -0,0 +1,361 @@ +#include "include/utils/Integer.hpp" +#include "include/utils/EndianUtils.hpp" +#include + +const char Integer::hexChars[17]="0123456789abcdef"; + +int Integer::getIntegerLength(const long long int arg){ + + int length=arg<0; + + long long int arg_copied=arg; + + for(;arg_copied!=0;length++){ + + arg_copied=arg_copied/10; + + } + + return length; + +} + +long long int Integer::parseInteger(const char * istr){ + + if(istr==nullptr){ + + return 0; + + } + + unsigned int max_length=strlen(istr); + + if(max_length==0||max_length>20){ + + return 0; + + } + + max_length--; + + unsigned char is_negative=istr[0]=='-'; + + long long int result=0; + + unsigned long long int level=1; + + for(int i=max_length;i>=is_negative;i--){ + + if(!(istr[i]>='0'&&istr[i]<='9')){ + + break; + + } + + if(!is_negative){ + + result=result+((istr[i]-'0')*level); + + }else{ + + result=result-((istr[i]-'0')*level); + + } + + level=level*10; + + } + + return result; + +} + +long long int Integer::parseHex(const char* str){ + + if(str==nullptr){ + + return 0; + + } + + unsigned int str_len=strlen(str); + + if(str_len==0){ + + return 0; + + } + + if(str_len>HEX_MAX_LENGTH){ + + return 0; + + } + + unsigned int startIndex=0; + + if(str_len<=HEX_MAX_LENGTH){ + + if(memcmp(str,"0x",2)==0||memcmp(str,"0X",2)==0){ + + startIndex=2; + + } + + } + + unsigned long long int result=0; + + for(unsigned int i=startIndex;i='0')&&(str[i]<='9')){ + + charVal=(str[i]-'0'); + + }else if((str[i]>='a')&&(str[i]<='f')){ + + charVal=((str[i]-'a')+10); + + }else if((str[i]>='A')&&(str[i]<='F')){ + + charVal=((str[i]-'A')+10); + + } + + unsigned int shiftCount=(str_len-i); + + shiftCount=(shiftCount==0?0:(shiftCount-1)); + + //halfByte; + shiftCount=shiftCount*4; + + result=result+(charVal<<(shiftCount)); + + } + + return result; + +} + +char* Integer::toString(const long long arg){ + + char* result=new char[INTEGER_MAX_LENGTH+1]; + + if(Integer::toString(arg,result,INTEGER_MAX_LENGTH+1)==0){ + + return result; + + }else{ + + delete result; + + return nullptr; + + } + +} + +int Integer::toString(const long long int arg, char* buffer, const unsigned int buffer_size){ + + if(buffer==nullptr||buffer_size==0){ + + return -1; + + } + + if(arg<10){ + + if(buffer_size>=2){ + + buffer[0]='0'+arg; + buffer[1]=0; + + return 0; + + }else{ + + return -1; + + } + + } + + unsigned char is_negative=arg<0; + + unsigned int arg_length=0; + + unsigned long long int level=1; + + long long int arg_copied=arg; + + while(arg_copied!=0){ + + arg_copied=arg_copied/10; + level=level*10; + arg_length++; + + } + + level=level/10; + + if(buffer_size<(is_negative+arg_length+1)){ + + return -1; + + } + + buffer[is_negative+arg_length]=0; + + arg_copied=arg; + + if(is_negative){ + + buffer[0]='-'; + arg_copied=arg_copied*(-1); + + } + + for(unsigned int i=is_negative;level!=0;i++){ + + unsigned char num=(arg_copied/level); + + buffer[i]=num+'0'; + + arg_copied=arg_copied-(num*level); + + level=level/10; + + } + + return 0; + +} + +char* Integer::toHexString(unsigned long long int arg){ + + return Integer::toHexString(arg,0); + +} + +char* Integer::toHexString(unsigned long long int arg, unsigned int format){ + + char* result=new char[HEX_MAX_LENGTH+1]; + + if(Integer::toHexString(arg, format, result, HEX_MAX_LENGTH+1)==0){ + + return result; + + }else{ + + delete result; + + return nullptr; + + } + +} + +int Integer::toHexString(const unsigned long long int arg, const unsigned int format, char* buffer, const unsigned int bufferSize){ + + if(buffer==nullptr||bufferSize==0){ + + return -1; + + } + + unsigned int startIndex=0; + + if(format){ + + if(bufferSize<2){ + + return -1; + + } + + memcpy(buffer,"0x",2); + + startIndex=2; + + } + + if(arg<=15){ + + if(bufferSize<(startIndex+2)){ + + return -1; + + } + + buffer[startIndex]=Integer::hexChars[arg]; + + buffer[startIndex+1]=0; + + return 0; + + } + + unsigned long long int arg_copied=arg; + + if(EndianUtils::isLittleEndian()){ + + arg_copied=EndianUtils::reverseBytes((unsigned long long int)arg_copied); + + } + + unsigned int isStarted=0; + + unsigned int resultCursor=startIndex; + + for(unsigned int i=0;i<8;i++){ + + unsigned char byteVal=((unsigned char*)&arg_copied)[i]; + + if(isStarted==0){ + + if(byteVal!=0){ + + if(bufferSize<(((8-i)*2)+startIndex+1)){ + + return -1; + + } + + isStarted=1; + + if((byteVal>>4)==0){ + + buffer[resultCursor]=Integer::hexChars[(byteVal&0x0F)]; + + resultCursor++; + + continue; + + } + + } + + } + + if(isStarted){ + + buffer[resultCursor]=Integer::hexChars[(byteVal>>4)]; + + resultCursor++; + + buffer[resultCursor]=Integer::hexChars[(byteVal&0x0F)]; + + resultCursor++; + + } + + } + + buffer[resultCursor]=0; + + return 0; + + +} diff --git a/src/utils/LineReader.cpp b/src/utils/LineReader.cpp new file mode 100644 index 0000000..46d262a --- /dev/null +++ b/src/utils/LineReader.cpp @@ -0,0 +1,142 @@ +#include "include/utils/LineReader.hpp" +#include +#include + +char* LineReader::getLine(const char* data, const unsigned int data_length, const unsigned int lineNum, unsigned int withLineBreak){ + + char currentChar; + unsigned int index=0; + char* result=0; + + for(unsigned int cursor=0,currentLineNum=0;;cursor++){ + + currentChar=data[cursor]; + + if(currentChar=='\n'||cursor==data_length){ + + if(currentLineNumfileHandle=0; + + std::runtime_error error("Invaild file path or file is not accessible!"); + throw error; + + } + + this->fileHandle=tmpFileHandle; + +} + +unsigned char* LineReader::getLine(unsigned int lineNum,unsigned int withLineBreak){ + + int currentChar; + + unsigned int index=0; + + unsigned char* result=nullptr; + + for(unsigned int cursor=0,currentLineNum=0;;cursor++){ + + currentChar=fgetc(this->fileHandle); + + if(currentChar=='\n'||currentChar==-1){ + + if(currentLineNumfileHandle,index,SEEK_SET); + + fread(result,(memSize-(1+(withLineBreak?1:0))),1,this->fileHandle); + + result[memSize-1]=0; + + if(withLineBreak){ + + result[memSize-2]='\n'; + + } + + break; + + } + } + } + + fseek(this->fileHandle,0,SEEK_SET); + return result; + +} + +unsigned char* LineReader::getLine(unsigned int lineNum){ + return this->getLine(lineNum,0); +} + +LineReader::~LineReader(){ + + if(this->fileHandle!=0){ + fclose(this->fileHandle); + } + +} diff --git a/src/utils/Obfuscator.cpp b/src/utils/Obfuscator.cpp new file mode 100644 index 0000000..ac30c8c --- /dev/null +++ b/src/utils/Obfuscator.cpp @@ -0,0 +1,114 @@ +#include "include/utils/Obfuscator.hpp" +#include "include/utils/CRC.hpp" +#include "include/utils/EndianUtils.hpp" +#include +#include +#include + +#define OBFUSCATE_KEY_LENGTH 8 +#define CRC32_LENGTH 4 + +unsigned char* Obfuscator::encode(unsigned char* data, unsigned int dataLength, unsigned int* resultLength){ + + if(data==nullptr||dataLength==0||resultLength==nullptr){ + return nullptr; + } + + unsigned int seed_offset=0; + + unsigned char* obfuscate_key=new unsigned char[OBFUSCATE_KEY_LENGTH]; + + struct timespec spec; + + clock_gettime(CLOCK_REALTIME, &spec); + + for(unsigned int i=0;igetCRC32(result,dataLength+OBFUSCATE_KEY_LENGTH); + + crc32=EndianUtils::isLittleEndian()?EndianUtils::reverseBytes((unsigned int)crc32):crc32; + + delete crc32_instance; + + memcpy(crc32_start,&crc32,sizeof(unsigned int)); + + *resultLength=result_length; + + delete obfuscate_key; + + return result; + +} + + +unsigned char* Obfuscator::decode(unsigned char* data, unsigned int dataLength, unsigned int* resultLength){ + + if(data==nullptr||dataLength<(1+OBFUSCATE_KEY_LENGTH+CRC32_LENGTH)||resultLength==nullptr){ + + return nullptr; + + } + + const unsigned char* crc32_start=&data[dataLength-CRC32_LENGTH]; + + CRC* crc32_instance=new CRC(CRC::CRC_MODE_DRF); + + unsigned int data_crc32; + + memcpy(&data_crc32,crc32_start,CRC32_LENGTH); + + data_crc32=EndianUtils::toNativeEndian((unsigned int)data_crc32); + + unsigned int crc32=crc32_instance->getCRC32(data,dataLength-(CRC32_LENGTH)); + + delete crc32_instance; + + if(crc32!=data_crc32){ + + return nullptr; + + } + + const unsigned int result_length=dataLength-(OBFUSCATE_KEY_LENGTH+CRC32_LENGTH); + + const unsigned char* obfuscate_key_start=&data[dataLength-(OBFUSCATE_KEY_LENGTH+CRC32_LENGTH)]; + + unsigned char* result=new unsigned char[result_length]; + + for(unsigned int i=0;i +#include + +unsigned char* ZLibUtils::compressData(const unsigned char* data,unsigned long dataLength,unsigned long* resultLength){ + + if(dataLength<=0||data==nullptr||resultLength==nullptr){ + + return 0; + + } + + unsigned long bufferSize=compressBound(dataLength); + + unsigned char* buffer=new unsigned char[bufferSize]; + + unsigned long tempResultLength=0; + + tempResultLength=bufferSize; + + int result=compress2((Bytef*)buffer,(uLongf*)tempResultLength,(const Bytef*)data,(uLongf)dataLength,Z_BEST_COMPRESSION); + + if(result!=Z_OK){ + + delete buffer; + + return nullptr; + + } + + *resultLength=tempResultLength; + + buffer=(unsigned char*)(realloc(buffer, tempResultLength)); + + return buffer; + +} + +unsigned char* ZLibUtils::decompressData(const unsigned char* data,unsigned long dataLength,unsigned long* resultLength){ + + if(dataLength==0||data==nullptr||resultLength==nullptr){ + return nullptr; + } + + unsigned int step=4; + unsigned int startSize=(dataLength*step); + + unsigned char* result=new unsigned char[startSize]; + unsigned long tempResultLength=startSize; + + for(;;){ + + int decompressResult=uncompress((Bytef*)result,(uLongf*)&tempResultLength,(const Bytef*)data,(uLongf)dataLength); + + if(decompressResult==Z_OK){ + + *resultLength=tempResultLength; + result=(unsigned char*)(realloc(result,*resultLength)); + + break; + + }else if(decompressResult==Z_BUF_ERROR){ + + step=step<<1; + + tempResultLength=(dataLength*step); + + result=(unsigned char*)(realloc(result,tempResultLength)); + + continue; + + }else{ + + delete result; + + result=nullptr; + break; + + } + } + + return result; + +} + +int ZLibUtils::decompressData(const unsigned char* data,unsigned long dataLength,unsigned char* resultBuffer,unsigned long resultBufferSize,unsigned long* resultLength){ + + if(dataLength==0||data==nullptr||resultLength==nullptr||resultBuffer==nullptr||resultBufferSize==0){ + + return -1; + + } + + unsigned long tempResultLength=resultBufferSize; + + int decompressResult=uncompress((Bytef*)resultBuffer,(uLongf*)&tempResultLength,(const Bytef*)data,(uLongf)dataLength); + + if(decompressResult==Z_OK){ + + *resultLength=tempResultLength; + + return 0; + + }else{ + + return decompressResult; + + } +} diff --git a/src/zlib/adler32.c b/src/zlib/adler32.c new file mode 100644 index 0000000..321de86 --- /dev/null +++ b/src/zlib/adler32.c @@ -0,0 +1,186 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2011, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "include/zlib/zutil.h" + +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + +#define BASE 65521U /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ +#ifdef NO_DIVIDE +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD(a) \ + do { \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32_z(adler, buf, len) + uLong adler; + const Bytef *buf; + z_size_t len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD28(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + return adler32_z(adler, buf, len); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + + /* the derivation of this formula is left as an exercise for the reader */ + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/src/zlib/compress.c b/src/zlib/compress.c new file mode 100644 index 0000000..973880a --- /dev/null +++ b/src/zlib/compress.c @@ -0,0 +1,86 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "include/zlib/zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + const uInt max = (uInt)-1; + uLong left; + + left = *destLen; + *destLen = 0; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + stream.next_out = dest; + stream.avail_out = 0; + stream.next_in = (z_const Bytef *)source; + stream.avail_in = 0; + + do { + if (stream.avail_out == 0) { + stream.avail_out = left > (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen; + sourceLen -= stream.avail_in; + } + err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH); + } while (err == Z_OK); + + *destLen = stream.total_out; + deflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/src/zlib/crc32.c b/src/zlib/crc32.c new file mode 100644 index 0000000..717b5bb --- /dev/null +++ b/src/zlib/crc32.c @@ -0,0 +1,442 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "include/zlib/zutil.h" /* for STDC and FAR definitions */ + +/* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif +#ifdef BYFOUR + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, z_size_t)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, z_size_t)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local z_crc_t FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const z_crc_t FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + z_crc_t c; + int n, k; + z_crc_t poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (z_crc_t)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = ZSWAP32(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = ZSWAP32(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const z_crc_t FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const z_crc_t FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "include/zlib/crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const z_crc_t FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32_z(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + z_crc_t endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + return crc32_z(crc, buf, len); +} + +#ifdef BYFOUR + +/* + This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit + integer pointer type. This violates the strict aliasing rule, where a + compiler can assume, for optimization purposes, that two pointers to + fundamentally different types won't ever point to the same memory. This can + manifest as a problem only if one of the pointers is written to. This code + only reads from those pointers. So long as this code remains isolated in + this compilation unit, there won't be a problem. For this reason, this code + should not be copied and pasted into a compilation unit in which other code + writes to the buffer that is passed to these routines. + */ + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = (z_crc_t)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *buf4++; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + z_size_t len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = ZSWAP32((z_crc_t)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(ZSWAP32(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/src/zlib/deflate.c b/src/zlib/deflate.c new file mode 100644 index 0000000..4a64661 --- /dev/null +++ b/src/zlib/deflate.c @@ -0,0 +1,2163 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://tools.ietf.org/html/rfc1951 + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "include/zlib/deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local int deflateStateCheck OF((z_streamp strm)); +local void slide_hash OF((deflate_state *s)); +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV +# pragma message("Assembler code may have bugs -- use at your own risk") + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef ZLIB_DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0)) + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to UPDATE_HASH are made with consecutive input + * characters, so that a running hash key can be computed from the previous + * key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to INSERT_STRING are made with consecutive input + * characters and the first MIN_MATCH bytes of str are valid (except for + * the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* =========================================================================== + * Slide the hash table when sliding the window down (could be avoided with 32 + * bit values at the expense of memory usage). We slide even when level == 0 to + * keep the hash table consistent if we switch back to level > 0 later. + */ +local void slide_hash(s) + deflate_state *s; +{ + unsigned n, m; + Posf *p; + uInt wsize = s->w_size; + + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + } while (--n); + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m - wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif +} + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + s->status = INIT_STATE; /* to pass state test in deflateReset() */ + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = (uInt)windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = (uInt)memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= + * Check for a valid deflate stream state. Return 0 if ok, 1 if not. + */ +local int deflateStateCheck (strm) + z_streamp strm; +{ + deflate_state *s; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + s = strm->state; + if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE && +#ifdef GZIP + s->status != GZIP_STATE && +#endif + s->status != EXTRA_STATE && + s->status != NAME_STATE && + s->status != COMMENT_STATE && + s->status != HCRC_STATE && + s->status != BUSY_STATE && + s->status != FINISH_STATE)) + return 1; + return 0; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt str, n; + int wrap; + unsigned avail; + z_const unsigned char *next; + + if (deflateStateCheck(strm) || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; + } + + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (z_const Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); + } + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength) + z_streamp strm; + Bytef *dictionary; + uInt *dictLength; +{ + deflate_state *s; + uInt len; + + if (deflateStateCheck(strm)) + return Z_STREAM_ERROR; + s = strm->state; + len = s->strstart + s->lookahead; + if (len > s->w_size) + len = s->w_size; + if (dictionary != Z_NULL && len) + zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len); + if (dictLength != Z_NULL) + *dictLength = len; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateResetKeep (strm) + z_streamp strm; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = +#ifdef GZIP + s->wrap == 2 ? GZIP_STATE : +#endif + s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (deflateStateCheck(strm) || strm->state->wrap != 2) + return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + deflate_state *s; + int put; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + s->high_water) { + /* Flush the last buffer: */ + int err = deflate(strm, Z_BLOCK); + if (err == Z_STREAM_ERROR) + return err; + if (strm->avail_out == 0) + return Z_BUF_ERROR; + } + if (s->level != level) { + if (s->level == 0 && s->matches != 0) { + if (s->matches == 1) + slide_hash(s); + else + CLEAR_HASH(s); + s->matches = 0; + } + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = (uInt)good_length; + s->max_lazy_match = (uInt)max_lazy; + s->nice_match = nice_length; + s->max_chain_length = (uInt)max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (deflateStateCheck(strm)) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; +#ifdef GZIP + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + Bytef *str; + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; +#endif + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output, except for + * some deflate_stored() output, goes through this function so some + * applications may wish to modify it to avoid allocating a large + * strm->next_out buffer and copying into it. (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len; + deflate_state *s = strm->state; + + _tr_flush_bits(s); + len = s->pending; + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, s->pending_out, len); + strm->next_out += len; + s->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; + } +} + +/* =========================================================================== + * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1]. + */ +#define HCRC_UPDATE(beg) \ + do { \ + if (s->gzhead->hcrc && s->pending > (beg)) \ + strm->adler = crc32(strm->adler, s->pending_buf + (beg), \ + s->pending - (beg)); \ + } while (0) + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->avail_in != 0 && strm->next_in == Z_NULL) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + old_flush = s->last_flush; + s->last_flush = flush; + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Write the header */ + if (s->status == INIT_STATE) { + /* zlib header */ + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#ifdef GZIP + if (s->status == GZIP_STATE) { + /* gzip header */ + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex; + while (s->pending + left > s->pending_buf_size) { + uInt copy = s->pending_buf_size - s->pending; + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, copy); + s->pending = s->pending_buf_size; + HCRC_UPDATE(beg); + s->gzindex += copy; + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + left -= copy; + } + zmemcpy(s->pending_buf + s->pending, + s->gzhead->extra + s->gzindex, left); + s->pending += left; + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + s->gzindex = 0; + } + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + ulg beg = s->pending; /* start of bytes to update crc */ + int val; + do { + if (s->pending == s->pending_buf_size) { + HCRC_UPDATE(beg); + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + beg = 0; + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + HCRC_UPDATE(beg); + } + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) { + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + } + s->status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s->pending != 0) { + s->last_flush = -1; + return Z_OK; + } + } +#endif + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->level == 0 ? deflate_stored(s, flush) : + s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (deflateStateCheck(strm)) return Z_STREAM_ERROR; + + status = strm->state->status; + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (deflateStateCheck(source) || dest == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local unsigned read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, buf, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, buf, len); + } +#endif + strm->next_in += len; + strm->total_in += len; + + return len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->insert = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = (int)s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef ZLIB_DEBUG + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* ZLIB_DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + unsigned n; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + slide_hash(s); + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* Maximum stored block length in deflate format (not including header). */ +#define MAX_STORED 65535 + +/* Minimum of a and b. */ +#define MIN(a, b) ((a) > (b) ? (b) : (a)) + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * + * In case deflateParams() is used to later switch to a non-zero compression + * level, s->matches (otherwise unused when storing) keeps track of the number + * of hash table slides to perform. If s->matches is 1, then one hash table + * slide will be done when switching. If s->matches is 2, the maximum value + * allowed here, then the hash table will be cleared, since two or more slides + * is the same as a clear. + * + * deflate_stored() is written to minimize the number of times an input byte is + * copied. It is most efficient with large input and output buffers, which + * maximizes the opportunites to have a single copy from next_in to next_out. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Smallest worthy block size when not flushing or finishing. By default + * this is 32K. This can be as small as 507 bytes for memLevel == 1. For + * large input and output buffers, the stored block size will be larger. + */ + unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size); + + /* Copy as many min_block or larger stored blocks directly to next_out as + * possible. If flushing, copy the remaining available input to next_out as + * stored blocks, if there is enough space. + */ + unsigned len, left, have, last = 0; + unsigned used = s->strm->avail_in; + do { + /* Set len to the maximum size block that we can copy directly with the + * available input data and output space. Set left to how much of that + * would be copied from what's left in the window. + */ + len = MAX_STORED; /* maximum deflate stored block length */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + if (s->strm->avail_out < have) /* need room for header */ + break; + /* maximum stored block length that will fit in avail_out: */ + have = s->strm->avail_out - have; + left = s->strstart - s->block_start; /* bytes left in window */ + if (len > (ulg)left + s->strm->avail_in) + len = left + s->strm->avail_in; /* limit len to the input */ + if (len > have) + len = have; /* limit len to the output */ + + /* If the stored block would be less than min_block in length, or if + * unable to copy all of the available input when flushing, then try + * copying to the window and the pending buffer instead. Also don't + * write an empty block when flushing -- deflate() does that. + */ + if (len < min_block && ((len == 0 && flush != Z_FINISH) || + flush == Z_NO_FLUSH || + len != left + s->strm->avail_in)) + break; + + /* Make a dummy stored block in pending to get the header bytes, + * including any pending bits. This also updates the debugging counts. + */ + last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0; + _tr_stored_block(s, (char *)0, 0L, last); + + /* Replace the lengths in the dummy stored block with len. */ + s->pending_buf[s->pending - 4] = len; + s->pending_buf[s->pending - 3] = len >> 8; + s->pending_buf[s->pending - 2] = ~len; + s->pending_buf[s->pending - 1] = ~len >> 8; + + /* Write the stored block header bytes. */ + flush_pending(s->strm); + +#ifdef ZLIB_DEBUG + /* Update debugging counts for the data about to be copied. */ + s->compressed_len += len << 3; + s->bits_sent += len << 3; +#endif + + /* Copy uncompressed bytes from the window to next_out. */ + if (left) { + if (left > len) + left = len; + zmemcpy(s->strm->next_out, s->window + s->block_start, left); + s->strm->next_out += left; + s->strm->avail_out -= left; + s->strm->total_out += left; + s->block_start += left; + len -= left; + } + + /* Copy uncompressed bytes directly from next_in to next_out, updating + * the check value. + */ + if (len) { + read_buf(s->strm, s->strm->next_out, len); + s->strm->next_out += len; + s->strm->avail_out -= len; + s->strm->total_out += len; + } + } while (last == 0); + + /* Update the sliding window with the last s->w_size bytes of the copied + * data, or append all of the copied data to the existing window if less + * than s->w_size bytes were copied. Also update the number of bytes to + * insert in the hash tables, in the event that deflateParams() switches to + * a non-zero compression level. + */ + used -= s->strm->avail_in; /* number of input bytes directly copied */ + if (used) { + /* If any input was used, then no unused input remains in the window, + * therefore s->block_start == s->strstart. + */ + if (used >= s->w_size) { /* supplant the previous history */ + s->matches = 2; /* clear hash */ + zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size); + s->strstart = s->w_size; + } + else { + if (s->window_size - s->strstart <= used) { + /* Slide the window down. */ + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + } + zmemcpy(s->window + s->strstart, s->strm->next_in - used, used); + s->strstart += used; + } + s->block_start = s->strstart; + s->insert += MIN(used, s->w_size - s->insert); + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* If the last block was written to next_out, then done. */ + if (last) + return finish_done; + + /* If flushing and all input has been consumed, then done. */ + if (flush != Z_NO_FLUSH && flush != Z_FINISH && + s->strm->avail_in == 0 && (long)s->strstart == s->block_start) + return block_done; + + /* Fill the window with any remaining input. */ + have = s->window_size - s->strstart - 1; + if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) { + /* Slide the window down. */ + s->block_start -= s->w_size; + s->strstart -= s->w_size; + zmemcpy(s->window, s->window + s->w_size, s->strstart); + if (s->matches < 2) + s->matches++; /* add a pending slide_hash() */ + have += s->w_size; /* more space now */ + } + if (have > s->strm->avail_in) + have = s->strm->avail_in; + if (have) { + read_buf(s->strm, s->window + s->strstart, have); + s->strstart += have; + } + if (s->high_water < s->strstart) + s->high_water = s->strstart; + + /* There was not enough avail_out to write a complete worthy or flushed + * stored block to next_out. Write a stored block to pending instead, if we + * have enough input for a worthy block, or if flushing and there is enough + * room for the remaining input as a stored block in the pending buffer. + */ + have = (s->bi_valid + 42) >> 3; /* number of header bytes */ + /* maximum stored block length that will fit in pending: */ + have = MIN(s->pending_buf_size - have, MAX_STORED); + min_block = MIN(have, s->w_size); + left = s->strstart - s->block_start; + if (left >= min_block || + ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH && + s->strm->avail_in == 0 && left <= have)) { + len = MIN(left, have); + last = flush == Z_FINISH && s->strm->avail_in == 0 && + len == left ? 1 : 0; + _tr_stored_block(s, (charf *)s->window + s->block_start, len, last); + s->block_start += len; + flush_pending(s->strm); + } + + /* We've done all we can with the available input and output. */ + return last ? finish_started : need_more; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s->lookahead <= MAX_MATCH) { + fill_window(s); + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (uInt)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} diff --git a/src/zlib/gzclose.c b/src/zlib/gzclose.c new file mode 100644 index 0000000..20eee6c --- /dev/null +++ b/src/zlib/gzclose.c @@ -0,0 +1,25 @@ +/* gzclose.c -- zlib gzclose() function + * Copyright (C) 2004, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "include/zlib/gzguts.h" + +/* gzclose() is in a separate file so that it is linked in only if it is used. + That way the other gzclose functions can be used instead to avoid linking in + unneeded compression or decompression routines. */ +int ZEXPORT gzclose(file) + gzFile file; +{ +#ifndef NO_GZCOMPRESS + gz_statep state; + + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file); +#else + return gzclose_r(file); +#endif +} diff --git a/src/zlib/gzlib.c b/src/zlib/gzlib.c new file mode 100644 index 0000000..a24cfa6 --- /dev/null +++ b/src/zlib/gzlib.c @@ -0,0 +1,637 @@ +/* gzlib.c -- zlib functions common to reading and writing gzip files + * Copyright (C) 2004-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "include/zlib/gzguts.h" + +#if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__) +# define LSEEK _lseeki64 +#else +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +# define LSEEK lseek64 +#else +# define LSEEK lseek +#endif +#endif + +/* Local functions */ +local void gz_reset OF((gz_statep)); +local gzFile gz_open OF((const void *, int, const char *)); + +#if defined UNDER_CE + +/* Map the Windows error number in ERROR to a locale-dependent error message + string and return a pointer to it. Typically, the values for ERROR come + from GetLastError. + + The string pointed to shall not be modified by the application, but may be + overwritten by a subsequent call to gz_strwinerror + + The gz_strwinerror function does not change the current setting of + GetLastError. */ +char ZLIB_INTERNAL *gz_strwinerror (error) + DWORD error; +{ + static char buf[1024]; + + wchar_t *msgbuf; + DWORD lasterr = GetLastError(); + DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPVOID)&msgbuf, + 0, + NULL); + if (chars != 0) { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > sizeof (buf) - 1) { + chars = sizeof (buf) - 1; + msgbuf[chars] = 0; + } + + wcstombs(buf, msgbuf, chars + 1); + LocalFree(msgbuf); + } + else { + sprintf(buf, "unknown win32 error (%ld)", error); + } + + SetLastError(lasterr); + return buf; +} + +#endif /* UNDER_CE */ + +/* Reset gzip file state */ +local void gz_reset(state) + gz_statep state; +{ + state->x.have = 0; /* no output data available */ + if (state->mode == GZ_READ) { /* for reading ... */ + state->eof = 0; /* not at end of file */ + state->past = 0; /* have not read past end yet */ + state->how = LOOK; /* look for gzip header */ + } + state->seek = 0; /* no seek request pending */ + gz_error(state, Z_OK, NULL); /* clear error */ + state->x.pos = 0; /* no uncompressed data yet */ + state->strm.avail_in = 0; /* no input data yet */ +} + +/* Open a gzip file either by name or file descriptor. */ +local gzFile gz_open(path, fd, mode) + const void *path; + int fd; + const char *mode; +{ + gz_statep state; + z_size_t len; + int oflag; +#ifdef O_CLOEXEC + int cloexec = 0; +#endif +#ifdef O_EXCL + int exclusive = 0; +#endif + + /* check input */ + if (path == NULL) + return NULL; + + /* allocate gzFile structure to return */ + state = (gz_statep)malloc(sizeof(gz_state)); + if (state == NULL) + return NULL; + state->size = 0; /* no buffers allocated yet */ + state->want = GZBUFSIZE; /* requested buffer size */ + state->msg = NULL; /* no error message yet */ + + /* interpret mode */ + state->mode = GZ_NONE; + state->level = Z_DEFAULT_COMPRESSION; + state->strategy = Z_DEFAULT_STRATEGY; + state->direct = 0; + while (*mode) { + if (*mode >= '0' && *mode <= '9') + state->level = *mode - '0'; + else + switch (*mode) { + case 'r': + state->mode = GZ_READ; + break; +#ifndef NO_GZCOMPRESS + case 'w': + state->mode = GZ_WRITE; + break; + case 'a': + state->mode = GZ_APPEND; + break; +#endif + case '+': /* can't read and write at the same time */ + free(state); + return NULL; + case 'b': /* ignore -- will request binary anyway */ + break; +#ifdef O_CLOEXEC + case 'e': + cloexec = 1; + break; +#endif +#ifdef O_EXCL + case 'x': + exclusive = 1; + break; +#endif + case 'f': + state->strategy = Z_FILTERED; + break; + case 'h': + state->strategy = Z_HUFFMAN_ONLY; + break; + case 'R': + state->strategy = Z_RLE; + break; + case 'F': + state->strategy = Z_FIXED; + break; + case 'T': + state->direct = 1; + break; + default: /* could consider as an error, but just ignore */ + ; + } + mode++; + } + + /* must provide an "r", "w", or "a" */ + if (state->mode == GZ_NONE) { + free(state); + return NULL; + } + + /* can't force transparent read */ + if (state->mode == GZ_READ) { + if (state->direct) { + free(state); + return NULL; + } + state->direct = 1; /* for empty file */ + } + + /* save the path name for error messages */ +#ifdef WIDECHAR + if (fd == -2) { + len = wcstombs(NULL, path, 0); + if (len == (z_size_t)-1) + len = 0; + } + else +#endif + len = strlen((const char *)path); + state->path = (char *)malloc(len + 1); + if (state->path == NULL) { + free(state); + return NULL; + } +#ifdef WIDECHAR + if (fd == -2) + if (len) + wcstombs(state->path, path, len + 1); + else + *(state->path) = 0; + else +#endif +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + (void)snprintf(state->path, len + 1, "%s", (const char *)path); +#else + strcpy(state->path, path); +#endif + + /* compute the flags for open() */ + oflag = +#ifdef O_LARGEFILE + O_LARGEFILE | +#endif +#ifdef O_BINARY + O_BINARY | +#endif +#ifdef O_CLOEXEC + (cloexec ? O_CLOEXEC : 0) | +#endif + (state->mode == GZ_READ ? + O_RDONLY : + (O_WRONLY | O_CREAT | +#ifdef O_EXCL + (exclusive ? O_EXCL : 0) | +#endif + (state->mode == GZ_WRITE ? + O_TRUNC : + O_APPEND))); + + /* open the file with the appropriate flags (or just use fd) */ + state->fd = fd > -1 ? fd : ( +#ifdef WIDECHAR + fd == -2 ? _wopen(path, oflag, 0666) : +#endif + open((const char *)path, oflag, 0666)); + if (state->fd == -1) { + free(state->path); + free(state); + return NULL; + } + if (state->mode == GZ_APPEND) { + LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */ + state->mode = GZ_WRITE; /* simplify later checks */ + } + + /* save the current position for rewinding (only if reading) */ + if (state->mode == GZ_READ) { + state->start = LSEEK(state->fd, 0, SEEK_CUR); + if (state->start == -1) state->start = 0; + } + + /* initialize stream */ + gz_reset(state); + + /* return stream */ + return (gzFile)state; +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen64(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzdopen(fd, mode) + int fd; + const char *mode; +{ + char *path; /* identifier for error messages */ + gzFile gz; + + if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) + return NULL; +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + (void)snprintf(path, 7 + 3 * sizeof(int), "", fd); +#else + sprintf(path, "", fd); /* for debugging */ +#endif + gz = gz_open(path, fd, mode); + free(path); + return gz; +} + +/* -- see zlib.h -- */ +#ifdef WIDECHAR +gzFile ZEXPORT gzopen_w(path, mode) + const wchar_t *path; + const char *mode; +{ + return gz_open(path, -2, mode); +} +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzbuffer(file, size) + gzFile file; + unsigned size; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* make sure we haven't already allocated memory */ + if (state->size != 0) + return -1; + + /* check and set requested size */ + if ((size << 1) < size) + return -1; /* need to be able to double it */ + if (size < 2) + size = 2; /* need two bytes to check magic header */ + state->want = size; + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzrewind(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* back up and start over */ + if (LSEEK(state->fd, state->start, SEEK_SET) == -1) + return -1; + gz_reset(state); + return 0; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzseek64(file, offset, whence) + gzFile file; + z_off64_t offset; + int whence; +{ + unsigned n; + z_off64_t ret; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* check that there's no error */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + + /* can only seek from start or relative to current position */ + if (whence != SEEK_SET && whence != SEEK_CUR) + return -1; + + /* normalize offset to a SEEK_CUR specification */ + if (whence == SEEK_SET) + offset -= state->x.pos; + else if (state->seek) + offset += state->skip; + state->seek = 0; + + /* if within raw area while reading, just go there */ + if (state->mode == GZ_READ && state->how == COPY && + state->x.pos + offset >= 0) { + ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); + if (ret == -1) + return -1; + state->x.have = 0; + state->eof = 0; + state->past = 0; + state->seek = 0; + gz_error(state, Z_OK, NULL); + state->strm.avail_in = 0; + state->x.pos += offset; + return state->x.pos; + } + + /* calculate skip amount, rewinding if needed for back seek when reading */ + if (offset < 0) { + if (state->mode != GZ_READ) /* writing -- can't go backwards */ + return -1; + offset += state->x.pos; + if (offset < 0) /* before start of file! */ + return -1; + if (gzrewind(file) == -1) /* rewind, then skip to offset */ + return -1; + } + + /* if reading, skip what's in output buffer (one less gzgetc() check) */ + if (state->mode == GZ_READ) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? + (unsigned)offset : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + offset -= n; + } + + /* request skip (if not zero) */ + if (offset) { + state->seek = 1; + state->skip = offset; + } + return state->x.pos + offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzseek(file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + z_off64_t ret; + + ret = gzseek64(file, (z_off64_t)offset, whence); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gztell64(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* return position */ + return state->x.pos + (state->seek ? state->skip : 0); +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gztell(file) + gzFile file; +{ + z_off64_t ret; + + ret = gztell64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzoffset64(file) + gzFile file; +{ + z_off64_t offset; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* compute and return effective offset in file */ + offset = LSEEK(state->fd, 0, SEEK_CUR); + if (offset == -1) + return -1; + if (state->mode == GZ_READ) /* reading */ + offset -= state->strm.avail_in; /* don't count buffered input */ + return offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzoffset(file) + gzFile file; +{ + z_off64_t ret; + + ret = gzoffset64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzeof(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return 0; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return 0; + + /* return end-of-file state */ + return state->mode == GZ_READ ? state->past : 0; +} + +/* -- see zlib.h -- */ +const char * ZEXPORT gzerror(file, errnum) + gzFile file; + int *errnum; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return NULL; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return NULL; + + /* return error information */ + if (errnum != NULL) + *errnum = state->err; + return state->err == Z_MEM_ERROR ? "out of memory" : + (state->msg == NULL ? "" : state->msg); +} + +/* -- see zlib.h -- */ +void ZEXPORT gzclearerr(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return; + + /* clear error and end-of-file */ + if (state->mode == GZ_READ) { + state->eof = 0; + state->past = 0; + } + gz_error(state, Z_OK, NULL); +} + +/* Create an error message in allocated memory and set state->err and + state->msg accordingly. Free any previous error message already there. Do + not try to free or allocate space if the error is Z_MEM_ERROR (out of + memory). Simply save the error message as a static string. If there is an + allocation failure constructing the error message, then convert the error to + out of memory. */ +void ZLIB_INTERNAL gz_error(state, err, msg) + gz_statep state; + int err; + const char *msg; +{ + /* free previously allocated message and clear */ + if (state->msg != NULL) { + if (state->err != Z_MEM_ERROR) + free(state->msg); + state->msg = NULL; + } + + /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ + if (err != Z_OK && err != Z_BUF_ERROR) + state->x.have = 0; + + /* set error code, and if no message, then done */ + state->err = err; + if (msg == NULL) + return; + + /* for an out of memory error, return literal string when requested */ + if (err == Z_MEM_ERROR) + return; + + /* construct error message with path */ + if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) == + NULL) { + state->err = Z_MEM_ERROR; + return; + } +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3, + "%s%s%s", state->path, ": ", msg); +#else + strcpy(state->msg, state->path); + strcat(state->msg, ": "); + strcat(state->msg, msg); +#endif +} + +#ifndef INT_MAX +/* portably return maximum value for an int (when limits.h presumed not + available) -- we need to do this to cover cases where 2's complement not + used, since C standard permits 1's complement and sign-bit representations, + otherwise we could just use ((unsigned)-1) >> 1 */ +unsigned ZLIB_INTERNAL gz_intmax() +{ + unsigned p, q; + + p = 1; + do { + q = p; + p <<= 1; + p++; + } while (p > q); + return q >> 1; +} +#endif diff --git a/src/zlib/gzread.c b/src/zlib/gzread.c new file mode 100644 index 0000000..9f79950 --- /dev/null +++ b/src/zlib/gzread.c @@ -0,0 +1,654 @@ +/* gzread.c -- zlib functions for reading gzip files + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "include/zlib/gzguts.h" + +/* Local functions */ +local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); +local int gz_avail OF((gz_statep)); +local int gz_look OF((gz_statep)); +local int gz_decomp OF((gz_statep)); +local int gz_fetch OF((gz_statep)); +local int gz_skip OF((gz_statep, z_off64_t)); +local z_size_t gz_read OF((gz_statep, voidp, z_size_t)); + +/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from + state->fd, and update state->eof, state->err, and state->msg as appropriate. + This function needs to loop on read(), since read() is not guaranteed to + read the number of bytes requested, depending on the type of descriptor. */ +local int gz_load(state, buf, len, have) + gz_statep state; + unsigned char *buf; + unsigned len; + unsigned *have; +{ + int ret; + unsigned get, max = ((unsigned)-1 >> 2) + 1; + + *have = 0; + do { + get = len - *have; + if (get > max) + get = max; + ret = read(state->fd, buf + *have, get); + if (ret <= 0) + break; + *have += (unsigned)ret; + } while (*have < len); + if (ret < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (ret == 0) + state->eof = 1; + return 0; +} + +/* Load up input buffer and set eof flag if last data loaded -- return -1 on + error, 0 otherwise. Note that the eof flag is set when the end of the input + file is reached, even though there may be unused data in the buffer. Once + that data has been used, no more attempts will be made to read the file. + If strm->avail_in != 0, then the current data is moved to the beginning of + the input buffer, and then the remainder of the buffer is loaded with the + available data from the input file. */ +local int gz_avail(state) + gz_statep state; +{ + unsigned got; + z_streamp strm = &(state->strm); + + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + if (state->eof == 0) { + if (strm->avail_in) { /* copy what's there to the start */ + unsigned char *p = state->in; + unsigned const char *q = strm->next_in; + unsigned n = strm->avail_in; + do { + *p++ = *q++; + } while (--n); + } + if (gz_load(state, state->in + strm->avail_in, + state->size - strm->avail_in, &got) == -1) + return -1; + strm->avail_in += got; + strm->next_in = state->in; + } + return 0; +} + +/* Look for gzip header, set up for inflate or copy. state->x.have must be 0. + If this is the first time in, allocate required memory. state->how will be + left unchanged if there is no more input data available, will be set to COPY + if there is no gzip header and direct copying will be performed, or it will + be set to GZIP for decompression. If direct copying, then leftover input + data from the input buffer will be copied to the output buffer. In that + case, all further file reads will be directly to either the output buffer or + a user buffer. If decompressing, the inflate state will be initialized. + gz_look() will return 0 on success or -1 on failure. */ +local int gz_look(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + /* allocate read buffers and inflate memory */ + if (state->size == 0) { + /* allocate buffers */ + state->in = (unsigned char *)malloc(state->want); + state->out = (unsigned char *)malloc(state->want << 1); + if (state->in == NULL || state->out == NULL) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + state->size = state->want; + + /* allocate inflate memory */ + state->strm.zalloc = Z_NULL; + state->strm.zfree = Z_NULL; + state->strm.opaque = Z_NULL; + state->strm.avail_in = 0; + state->strm.next_in = Z_NULL; + if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */ + free(state->out); + free(state->in); + state->size = 0; + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + } + + /* get at least the magic bytes in the input buffer */ + if (strm->avail_in < 2) { + if (gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) + return 0; + } + + /* look for gzip magic bytes -- if there, do gzip decoding (note: there is + a logical dilemma here when considering the case of a partially written + gzip file, to wit, if a single 31 byte is written, then we cannot tell + whether this is a single-byte file, or just a partially written gzip + file -- for here we assume that if a gzip file is being written, then + the header will be written in a single operation, so that reading a + single byte is sufficient indication that it is not a gzip file) */ + if (strm->avail_in > 1 && + strm->next_in[0] == 31 && strm->next_in[1] == 139) { + inflateReset(strm); + state->how = GZIP; + state->direct = 0; + return 0; + } + + /* no gzip header -- if we were decoding gzip before, then this is trailing + garbage. Ignore the trailing garbage and finish. */ + if (state->direct == 0) { + strm->avail_in = 0; + state->eof = 1; + state->x.have = 0; + return 0; + } + + /* doing raw i/o, copy any leftover input to output -- this assumes that + the output buffer is larger than the input buffer, which also assures + space for gzungetc() */ + state->x.next = state->out; + if (strm->avail_in) { + memcpy(state->x.next, strm->next_in, strm->avail_in); + state->x.have = strm->avail_in; + strm->avail_in = 0; + } + state->how = COPY; + state->direct = 1; + return 0; +} + +/* Decompress from input to the provided next_out and avail_out in the state. + On return, state->x.have and state->x.next point to the just decompressed + data. If the gzip stream completes, state->how is reset to LOOK to look for + the next gzip stream or raw data, once state->x.have is depleted. Returns 0 + on success, -1 on failure. */ +local int gz_decomp(state) + gz_statep state; +{ + int ret = Z_OK; + unsigned had; + z_streamp strm = &(state->strm); + + /* fill output buffer up to end of deflate stream */ + had = strm->avail_out; + do { + /* get more input for inflate() */ + if (strm->avail_in == 0 && gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) { + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); + break; + } + + /* decompress and handle errors */ + ret = inflate(strm, Z_NO_FLUSH); + if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { + gz_error(state, Z_STREAM_ERROR, + "internal error: inflate stream corrupt"); + return -1; + } + if (ret == Z_MEM_ERROR) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ + gz_error(state, Z_DATA_ERROR, + strm->msg == NULL ? "compressed data error" : strm->msg); + return -1; + } + } while (strm->avail_out && ret != Z_STREAM_END); + + /* update available output */ + state->x.have = had - strm->avail_out; + state->x.next = strm->next_out - state->x.have; + + /* if the gzip stream completed successfully, look for another */ + if (ret == Z_STREAM_END) + state->how = LOOK; + + /* good decompression */ + return 0; +} + +/* Fetch data and put it in the output buffer. Assumes state->x.have is 0. + Data is either copied from the input file or decompressed from the input + file depending on state->how. If state->how is LOOK, then a gzip header is + looked for to determine whether to copy or decompress. Returns -1 on error, + otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the + end of the input file has been reached and all data has been processed. */ +local int gz_fetch(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + do { + switch(state->how) { + case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ + if (gz_look(state) == -1) + return -1; + if (state->how == LOOK) + return 0; + break; + case COPY: /* -> COPY */ + if (gz_load(state, state->out, state->size << 1, &(state->x.have)) + == -1) + return -1; + state->x.next = state->out; + return 0; + case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */ + strm->avail_out = state->size << 1; + strm->next_out = state->out; + if (gz_decomp(state) == -1) + return -1; + } + } while (state->x.have == 0 && (!state->eof || strm->avail_in)); + return 0; +} + +/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ +local int gz_skip(state, len) + gz_statep state; + z_off64_t len; +{ + unsigned n; + + /* skip over len bytes or reach end-of-file, whichever comes first */ + while (len) + /* skip over whatever is in output buffer */ + if (state->x.have) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ? + (unsigned)len : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + len -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && state->strm.avail_in == 0) + break; + + /* need more data to skip -- load up output buffer */ + else { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return -1; + } + return 0; +} + +/* Read len bytes into buf from file, or less than len up to the end of the + input. Return the number of bytes read. If zero is returned, either the + end of file was reached, or there was an error. state->err must be + consulted in that case to determine which. */ +local z_size_t gz_read(state, buf, len) + gz_statep state; + voidp buf; + z_size_t len; +{ + z_size_t got; + unsigned n; + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return 0; + } + + /* get len bytes to buf, or less than len if at the end */ + got = 0; + do { + /* set n to the maximum amount of len that fits in an unsigned int */ + n = -1; + if (n > len) + n = len; + + /* first just try copying data from the output buffer */ + if (state->x.have) { + if (state->x.have < n) + n = state->x.have; + memcpy(buf, state->x.next, n); + state->x.next += n; + state->x.have -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && state->strm.avail_in == 0) { + state->past = 1; /* tried to read past end */ + break; + } + + /* need output data -- for small len or new stream load up our output + buffer */ + else if (state->how == LOOK || n < (state->size << 1)) { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return 0; + continue; /* no progress yet -- go back to copy above */ + /* the copy above assures that we will leave with space in the + output buffer, allowing at least one gzungetc() to succeed */ + } + + /* large len -- read directly into user buffer */ + else if (state->how == COPY) { /* read directly */ + if (gz_load(state, (unsigned char *)buf, n, &n) == -1) + return 0; + } + + /* large len -- decompress directly into user buffer */ + else { /* state->how == GZIP */ + state->strm.avail_out = n; + state->strm.next_out = (unsigned char *)buf; + if (gz_decomp(state) == -1) + return 0; + n = state->x.have; + state->x.have = 0; + } + + /* update progress */ + len -= n; + buf = (char *)buf + n; + got += n; + state->x.pos += n; + } while (len); + + /* return number of bytes read into user buffer */ + return got; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzread(file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids a flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_STREAM_ERROR, "request does not fit in an int"); + return -1; + } + + /* read len or fewer bytes to buf */ + len = gz_read(state, buf, len); + + /* check for an error */ + if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + + /* return the number of bytes read (this is assured to fit in an int) */ + return (int)len; +} + +/* -- see zlib.h -- */ +z_size_t ZEXPORT gzfread(buf, size, nitems, file) + voidp buf; + z_size_t size; + z_size_t nitems; + gzFile file; +{ + z_size_t len; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return 0; + + /* compute bytes to read -- error on overflow */ + len = nitems * size; + if (size && len / size != nitems) { + gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); + return 0; + } + + /* read len or fewer bytes to buf, return the number of full items read */ + return len ? gz_read(state, buf, len) / size : 0; +} + +/* -- see zlib.h -- */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +#else +# undef gzgetc +#endif +int ZEXPORT gzgetc(file) + gzFile file; +{ + int ret; + unsigned char buf[1]; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* try output buffer (no need to check for skip request) */ + if (state->x.have) { + state->x.have--; + state->x.pos++; + return *(state->x.next)++; + } + + /* nothing there -- try gz_read() */ + ret = gz_read(state, buf, 1); + return ret < 1 ? -1 : buf[0]; +} + +int ZEXPORT gzgetc_(file) +gzFile file; +{ + return gzgetc(file); +} + +/* -- see zlib.h -- */ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* can't push EOF */ + if (c < 0) + return -1; + + /* if output buffer empty, put byte at end (allows more pushing) */ + if (state->x.have == 0) { + state->x.have = 1; + state->x.next = state->out + (state->size << 1) - 1; + state->x.next[0] = (unsigned char)c; + state->x.pos--; + state->past = 0; + return c; + } + + /* if no room, give up (must have already done a gzungetc()) */ + if (state->x.have == (state->size << 1)) { + gz_error(state, Z_DATA_ERROR, "out of room to push characters"); + return -1; + } + + /* slide output data if needed and insert byte before existing data */ + if (state->x.next == state->out) { + unsigned char *src = state->out + state->x.have; + unsigned char *dest = state->out + (state->size << 1); + while (src > state->out) + *--dest = *--src; + state->x.next = dest; + } + state->x.have++; + state->x.next--; + state->x.next[0] = (unsigned char)c; + state->x.pos--; + state->past = 0; + return c; +} + +/* -- see zlib.h -- */ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + unsigned left, n; + char *str; + unsigned char *eol; + gz_statep state; + + /* check parameters and get internal structure */ + if (file == NULL || buf == NULL || len < 1) + return NULL; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return NULL; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return NULL; + } + + /* copy output bytes up to new line or len - 1, whichever comes first -- + append a terminating zero to the string (we don't check for a zero in + the contents, let the user worry about that) */ + str = buf; + left = (unsigned)len - 1; + if (left) do { + /* assure that something is in the output buffer */ + if (state->x.have == 0 && gz_fetch(state) == -1) + return NULL; /* error */ + if (state->x.have == 0) { /* end of file */ + state->past = 1; /* read past end */ + break; /* return what we have */ + } + + /* look for end-of-line in current output buffer */ + n = state->x.have > left ? left : state->x.have; + eol = (unsigned char *)memchr(state->x.next, '\n', n); + if (eol != NULL) + n = (unsigned)(eol - state->x.next) + 1; + + /* copy through end-of-line, or remainder if not found */ + memcpy(buf, state->x.next, n); + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + left -= n; + buf += n; + } while (left && eol == NULL); + + /* return terminated string, or if nothing, end of file */ + if (buf == str) + return NULL; + buf[0] = 0; + return str; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzdirect(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* if the state is not known, but we can find out, then do so (this is + mainly for right after a gzopen() or gzdopen()) */ + if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) + (void)gz_look(state); + + /* return 1 if transparent, 0 if processing a gzip stream */ + return state->direct; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_r(file) + gzFile file; +{ + int ret, err; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're reading */ + if (state->mode != GZ_READ) + return Z_STREAM_ERROR; + + /* free memory and close file */ + if (state->size) { + inflateEnd(&(state->strm)); + free(state->out); + free(state->in); + } + err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK; + gz_error(state, Z_OK, NULL); + free(state->path); + ret = close(state->fd); + free(state); + return ret ? Z_ERRNO : err; +} diff --git a/src/zlib/gzwrite.c b/src/zlib/gzwrite.c new file mode 100644 index 0000000..d65a4cf --- /dev/null +++ b/src/zlib/gzwrite.c @@ -0,0 +1,665 @@ +/* gzwrite.c -- zlib functions for writing gzip files + * Copyright (C) 2004-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "include/zlib/gzguts.h" + +/* Local functions */ +local int gz_init OF((gz_statep)); +local int gz_comp OF((gz_statep, int)); +local int gz_zero OF((gz_statep, z_off64_t)); +local z_size_t gz_write OF((gz_statep, voidpc, z_size_t)); + +/* Initialize state for writing a gzip file. Mark initialization by setting + state->size to non-zero. Return -1 on a memory allocation failure, or 0 on + success. */ +local int gz_init(state) + gz_statep state; +{ + int ret; + z_streamp strm = &(state->strm); + + /* allocate input buffer (double size for gzprintf) */ + state->in = (unsigned char *)malloc(state->want << 1); + if (state->in == NULL) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* only need output buffer and deflate state if compressing */ + if (!state->direct) { + /* allocate output buffer */ + state->out = (unsigned char *)malloc(state->want); + if (state->out == NULL) { + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* allocate deflate memory, set up for gzip compression */ + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = deflateInit2(strm, state->level, Z_DEFLATED, + MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); + if (ret != Z_OK) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + strm->next_in = NULL; + } + + /* mark state as initialized */ + state->size = state->want; + + /* initialize write buffer if compressing */ + if (!state->direct) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = strm->next_out; + } + return 0; +} + +/* Compress whatever is at avail_in and next_in and write to the output file. + Return -1 if there is an error writing to the output file or if gz_init() + fails to allocate memory, otherwise 0. flush is assumed to be a valid + deflate() flush value. If flush is Z_FINISH, then the deflate() state is + reset to start a new gzip stream. If gz->direct is true, then simply write + to the output file without compressing, and ignore flush. */ +local int gz_comp(state, flush) + gz_statep state; + int flush; +{ + int ret, writ; + unsigned have, put, max = ((unsigned)-1 >> 2) + 1; + z_streamp strm = &(state->strm); + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return -1; + + /* write directly if requested */ + if (state->direct) { + while (strm->avail_in) { + put = strm->avail_in > max ? max : strm->avail_in; + writ = write(state->fd, strm->next_in, put); + if (writ < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + strm->avail_in -= (unsigned)writ; + strm->next_in += writ; + } + return 0; + } + + /* run deflate() on provided input until it produces no more output */ + ret = Z_OK; + do { + /* write out current buffer contents if full, or if flushing, but if + doing Z_FINISH then don't write until we get to Z_STREAM_END */ + if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && + (flush != Z_FINISH || ret == Z_STREAM_END))) { + while (strm->next_out > state->x.next) { + put = strm->next_out - state->x.next > (int)max ? max : + (unsigned)(strm->next_out - state->x.next); + writ = write(state->fd, state->x.next, put); + if (writ < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + state->x.next += writ; + } + if (strm->avail_out == 0) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = state->out; + } + } + + /* compress */ + have = strm->avail_out; + ret = deflate(strm, flush); + if (ret == Z_STREAM_ERROR) { + gz_error(state, Z_STREAM_ERROR, + "internal error: deflate stream corrupt"); + return -1; + } + have -= strm->avail_out; + } while (have); + + /* if that completed a deflate stream, allow another to start */ + if (flush == Z_FINISH) + deflateReset(strm); + + /* all done, no errors */ + return 0; +} + +/* Compress len zeros to output. Return -1 on a write error or memory + allocation failure by gz_comp(), or 0 on success. */ +local int gz_zero(state, len) + gz_statep state; + z_off64_t len; +{ + int first; + unsigned n; + z_streamp strm = &(state->strm); + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + + /* compress len zeros (len guaranteed > 0) */ + first = 1; + while (len) { + n = GT_OFF(state->size) || (z_off64_t)state->size > len ? + (unsigned)len : state->size; + if (first) { + memset(state->in, 0, n); + first = 0; + } + strm->avail_in = n; + strm->next_in = state->in; + state->x.pos += n; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + len -= n; + } + return 0; +} + +/* Write len bytes from buf to file. Return the number of bytes written. If + the returned value is less than len, then there was an error. */ +local z_size_t gz_write(state, buf, len) + gz_statep state; + voidpc buf; + z_size_t len; +{ + z_size_t put = len; + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* for small len, copy to input buffer, otherwise compress directly */ + if (len < state->size) { + /* copy to input buffer, compress when full */ + do { + unsigned have, copy; + + if (state->strm.avail_in == 0) + state->strm.next_in = state->in; + have = (unsigned)((state->strm.next_in + state->strm.avail_in) - + state->in); + copy = state->size - have; + if (copy > len) + copy = len; + memcpy(state->in + have, buf, copy); + state->strm.avail_in += copy; + state->x.pos += copy; + buf = (const char *)buf + copy; + len -= copy; + if (len && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } while (len); + } + else { + /* consume whatever's left in the input buffer */ + if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* directly compress user buffer to file */ + state->strm.next_in = (z_const Bytef *)buf; + do { + unsigned n = (unsigned)-1; + if (n > len) + n = len; + state->strm.avail_in = n; + state->x.pos += n; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + len -= n; + } while (len); + } + + /* input was all buffered or compressed */ + return put; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzwrite(file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids a flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); + return 0; + } + + /* write len bytes from buf (the return value will fit in an int) */ + return (int)gz_write(state, buf, len); +} + +/* -- see zlib.h -- */ +z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) + voidpc buf; + z_size_t size; + z_size_t nitems; + gzFile file; +{ + z_size_t len; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* compute bytes to read -- error on overflow */ + len = nitems * size; + if (size && len / size != nitems) { + gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); + return 0; + } + + /* write len bytes to buf, return the number of full items written */ + return len ? gz_write(state, buf, len) / size : 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned have; + unsigned char buf[1]; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return -1; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* try writing to input buffer for speed (state->size == 0 if buffer not + initialized) */ + if (state->size) { + if (strm->avail_in == 0) + strm->next_in = state->in; + have = (unsigned)((strm->next_in + strm->avail_in) - state->in); + if (have < state->size) { + state->in[have] = (unsigned char)c; + strm->avail_in++; + state->x.pos++; + return c & 0xff; + } + } + + /* no room in buffer or not initialized, use gz_write() */ + buf[0] = (unsigned char)c; + if (gz_write(state, buf, 1) != 1) + return -1; + return c & 0xff; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputs(file, str) + gzFile file; + const char *str; +{ + int ret; + z_size_t len; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return -1; + + /* write string */ + len = strlen(str); + ret = gz_write(state, str, len); + return ret == 0 && len != 0 ? -1 : ret; +} + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +#include + +/* -- see zlib.h -- */ +int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) +{ + int len; + unsigned left; + char *next; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return state->err; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->err; + } + + /* do the printf() into the input buffer, put length in len -- the input + buffer is double-sized just for this function, so there is guaranteed to + be state->size bytes available after the current contents */ + if (strm->avail_in == 0) + strm->next_in = state->in; + next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in); + next[state->size - 1] = 0; +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf(next, format, va); + for (len = 0; len < state->size; len++) + if (next[len] == 0) break; +# else + len = vsprintf(next, format, va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf(next, state->size, format, va); + len = strlen(next); +# else + len = vsnprintf(next, state->size, format, va); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0) + return 0; + + /* update buffer and position, compress first half if past that */ + strm->avail_in += (unsigned)len; + state->x.pos += len; + if (strm->avail_in >= state->size) { + left = strm->avail_in - state->size; + strm->avail_in = state->size; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return state->err; + memcpy(state->in, state->in + state->size, left); + strm->next_in = state->in; + strm->avail_in = left; + } + return len; +} + +int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) +{ + va_list va; + int ret; + + va_start(va, format); + ret = gzvprintf(file, format, va); + va_end(va); + return ret; +} + +#else /* !STDC && !Z_HAVE_STDARG_H */ + +/* -- see zlib.h -- */ +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + unsigned len, left; + char *next; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that can really pass pointer in ints */ + if (sizeof(int) != sizeof(void *)) + return Z_STREAM_ERROR; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return state->error; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->error; + } + + /* do the printf() into the input buffer, put length in len -- the input + buffer is double-sized just for this function, so there is guaranteed to + be state->size bytes available after the current contents */ + if (strm->avail_in == 0) + strm->next_in = state->in; + next = (char *)(strm->next_in + strm->avail_in); + next[state->size - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, + a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < size; len++) + if (next[len] == 0) + break; +# else + len = sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, + a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#else +# ifdef HAS_snprintf_void + snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, + a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen(next); +# else + len = snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len == 0 || len >= state->size || next[state->size - 1] != 0) + return 0; + + /* update buffer and position, compress first half if past that */ + strm->avail_in += len; + state->x.pos += len; + if (strm->avail_in >= state->size) { + left = strm->avail_in - state->size; + strm->avail_in = state->size; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return state->err; + memcpy(state->in, state->in + state->size, left); + strm->next_in = state->in; + strm->avail_in = left; + } + return (int)len; +} + +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzflush(file, flush) + gzFile file; + int flush; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* check flush parameter */ + if (flush < 0 || flush > Z_FINISH) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->err; + } + + /* compress remaining data with requested flush */ + (void)gz_comp(state, flush); + return state->err; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzsetparams(file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* if no change is requested, then do nothing */ + if (level == state->level && strategy == state->strategy) + return Z_OK; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return state->err; + } + + /* change compression parameters for subsequent input */ + if (state->size) { + /* flush previous input with previous parameters before changing */ + if (strm->avail_in && gz_comp(state, Z_BLOCK) == -1) + return state->err; + deflateParams(strm, level, strategy); + } + state->level = level; + state->strategy = strategy; + return Z_OK; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_w(file) + gzFile file; +{ + int ret = Z_OK; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're writing */ + if (state->mode != GZ_WRITE) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + ret = state->err; + } + + /* flush, free memory, and close file */ + if (gz_comp(state, Z_FINISH) == -1) + ret = state->err; + if (state->size) { + if (!state->direct) { + (void)deflateEnd(&(state->strm)); + free(state->out); + } + free(state->in); + } + gz_error(state, Z_OK, NULL); + free(state->path); + if (close(state->fd) == -1) + ret = Z_ERRNO; + free(state); + return ret; +} diff --git a/src/zlib/inffast.c b/src/zlib/inffast.c new file mode 100644 index 0000000..923e983 --- /dev/null +++ b/src/zlib/inffast.c @@ -0,0 +1,323 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "include/zlib/zutil.h" +#include "include/zlib/inftrees.h" +#include "include/zlib/inflate.h" +#include "include/zlib/inffast.h" + +#ifdef ASMINF +# pragma message("Assembler code may have bugs -- use at your own risk") +#else + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in; + last = in + (strm->avail_in - 5); + out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + *out++ = *from++; + } while (--len); + continue; + } +#endif + } + from = window; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = window; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } while (len > 2); + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in; + strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/src/zlib/inflate.c b/src/zlib/inflate.c new file mode 100644 index 0000000..401a7d9 --- /dev/null +++ b/src/zlib/inflate.c @@ -0,0 +1,1561 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2016 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "include/zlib/zutil.h" +#include "include/zlib/inftrees.h" +#include "include/zlib/inflate.h" +#include "include/zlib/inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local int inflateStateCheck OF((z_streamp strm)); +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +local int inflateStateCheck(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) + return 1; + state = (struct inflate_state FAR *)strm->state; + if (state == Z_NULL || state->strm != strm || + state->mode < HEAD || state->mode > SYNC) + return 1; + return 0; +} + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 5; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->strm = strm; + state->window = Z_NULL; + state->mode = HEAD; /* to pass state test in inflateReset2() */ + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += (unsigned)value << state->bits; + state->bits += (uInt)bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "include/zlib/inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (inflateStateCheck(strm) || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + if (state->wbits == 0) + state->wbits = 15; + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + if (len > 15 || len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if ((state->flags & 0x0200) && (state->wrap & 4)) + CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = (Bytef)len; + } while (len && copy < have); + if ((state->flags & 0x0200) && (state->wrap & 4)) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if ((state->wrap & 4) && hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if ((state->wrap & 4) && ( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if ((state->wrap & 4) && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = (int)state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (inflateStateCheck(source) || dest == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + copy->strm = dest; + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + state->sane = !subvert; + return Z_OK; +#else + (void)subvert; + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +int ZEXPORT inflateValidate(strm, check) +z_streamp strm; +int check; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (check) + state->wrap |= 4; + else + state->wrap &= ~4; + return Z_OK; +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (inflateStateCheck(strm)) + return -(1L << 16); + state = (struct inflate_state FAR *)strm->state; + return (long)(((unsigned long)((long)state->back)) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} + +unsigned long ZEXPORT inflateCodesUsed(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (inflateStateCheck(strm)) return (unsigned long)-1; + state = (struct inflate_state FAR *)strm->state; + return (unsigned long)(state->next - state->codes); +} diff --git a/src/zlib/inftrees.c b/src/zlib/inftrees.c new file mode 100644 index 0000000..50530d2 --- /dev/null +++ b/src/zlib/inftrees.c @@ -0,0 +1,304 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2017 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "include/zlib/zutil.h" +#include "include/zlib/inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.11 Copyright 1995-2017 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + unsigned match; /* use base and extra for symbol >= match */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + match = 20; + break; + case LENS: + base = lbase; + extra = lext; + match = 257; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + match = 0; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if (work[sym] + 1U < match) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if (work[sym] >= match) { + here.op = (unsigned char)(extra[work[sym] - match]); + here.val = base[work[sym] - match]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/src/zlib/trees.c b/src/zlib/trees.c new file mode 100644 index 0000000..b0576a8 --- /dev/null +++ b/src/zlib/trees.c @@ -0,0 +1,1203 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2017 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "include/zlib/deflate.h" + +#ifdef ZLIB_DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "include/zlib/trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local const static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local const static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local const static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, const ct_data *ltree, + const ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef ZLIB_DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* !ZLIB_DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef ZLIB_DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !ZLIB_DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = (int)value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* ZLIB_DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef ZLIB_DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (unsigned)(bits + xbits); + if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits); + } + if (overflow == 0) return; + + Tracev((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + unsigned code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + code = (code + bl_count[bits-1]) << 1; + next_code[bits] = (ush)code; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ + bi_windup(s); /* align on byte boundary */ + put_short(s, (ush)stored_len); + put_short(s, (ush)~stored_len); + zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len); + s->pending += stored_len; +#ifdef ZLIB_DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; + s->bits_sent += 2*16; + s->bits_sent += stored_len<<3; +#endif +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef ZLIB_DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and write out the encoded block. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef ZLIB_DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef ZLIB_DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + const ct_data *ltree; /* literal tree */ + const ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= (unsigned)base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef ZLIB_DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} diff --git a/src/zlib/uncompr.c b/src/zlib/uncompr.c new file mode 100644 index 0000000..6b774d6 --- /dev/null +++ b/src/zlib/uncompr.c @@ -0,0 +1,93 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "include/zlib/zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. *sourceLen is + the byte length of the source buffer. Upon entry, *destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, + *destLen is the size of the decompressed data and *sourceLen is the number + of source bytes consumed. Upon return, source + *sourceLen points to the + first unused input byte. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, or + Z_DATA_ERROR if the input data was corrupted, including if the input data is + an incomplete zlib stream. +*/ +int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong *sourceLen; +{ + z_stream stream; + int err; + const uInt max = (uInt)-1; + uLong len, left; + Byte buf[1]; /* for detection of incomplete stream when *destLen == 0 */ + + len = *sourceLen; + if (*destLen) { + left = *destLen; + *destLen = 0; + } + else { + left = 1; + dest = buf; + } + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = 0; + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + stream.next_out = dest; + stream.avail_out = 0; + + do { + if (stream.avail_out == 0) { + stream.avail_out = left > (uLong)max ? max : (uInt)left; + left -= stream.avail_out; + } + if (stream.avail_in == 0) { + stream.avail_in = len > (uLong)max ? max : (uInt)len; + len -= stream.avail_in; + } + err = inflate(&stream, Z_NO_FLUSH); + } while (err == Z_OK); + + *sourceLen -= len + stream.avail_in; + if (dest != buf) + *destLen = stream.total_out; + else if (stream.total_out && err == Z_BUF_ERROR) + left = 1; + + inflateEnd(&stream); + return err == Z_STREAM_END ? Z_OK : + err == Z_NEED_DICT ? Z_DATA_ERROR : + err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR : + err; +} + +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return uncompress2(dest, destLen, source, &sourceLen); +} diff --git a/src/zlib/zutil.c b/src/zlib/zutil.c new file mode 100644 index 0000000..b9713a7 --- /dev/null +++ b/src/zlib/zutil.c @@ -0,0 +1,325 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2017 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "include/zlib/zutil.h" +#ifndef Z_SOLO +# include "include/zlib/gzguts.h" +#endif + +z_const char * const z_errmsg[10] = { + (z_const char *)"need dictionary", /* Z_NEED_DICT 2 */ + (z_const char *)"stream end", /* Z_STREAM_END 1 */ + (z_const char *)"", /* Z_OK 0 */ + (z_const char *)"file error", /* Z_ERRNO (-1) */ + (z_const char *)"stream error", /* Z_STREAM_ERROR (-2) */ + (z_const char *)"data error", /* Z_DATA_ERROR (-3) */ + (z_const char *)"insufficient memory", /* Z_MEM_ERROR (-4) */ + (z_const char *)"buffer error", /* Z_BUF_ERROR (-5) */ + (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */ + (z_const char *)"" +}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef ZLIB_DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef ZLIB_DEBUG +#include +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf; + ulg bsize = (ulg)items*size; + + (void)opaque; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + + (void)opaque; + + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + (void)opaque; + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + (void)opaque; + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + (void)opaque; + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + (void)opaque; + free(ptr); +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/zlib.3.pdf b/zlib.3.pdf new file mode 100644 index 0000000..6fa519c Binary files /dev/null and b/zlib.3.pdf differ