Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
home:adrianSuSE:link
libArcus
libArcus-2.5.0.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File libArcus-2.5.0.obscpio of Package libArcus
0707010082A6F9000081A4000003E80000006400000001592BFB850000052F000000080000000200000000000000000000002B00000000libArcus-2.5.0/cmake/COPYING-CMAKE-SCRIPTSRedistribution 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 copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. 0707010082A6FA000081A4000003E8000000640000000157679D16000014E1000000080000000200000000000000000000002500000000libArcus-2.5.0/cmake/SIPMacros.cmake# Macros for SIP # ~~~~~~~~~~~~~~ # Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # This file defines the following macros: # # ADD_SIP_PYTHON_MODULE (MODULE_NAME MODULE_SIP [library1, libaray2, ...]) # Specifies a SIP file to be built into a Python module and installed. # MODULE_NAME is the name of Python module including any path name. (e.g. # os.sys, Foo.bar etc). MODULE_SIP the path and filename of the .sip file # to process and compile. libraryN are libraries that the Python module, # which is typically a shared library, should be linked to. The built # module will also be install into Python's site-packages directory. # # The behaviour of the ADD_SIP_PYTHON_MODULE macro can be controlled by a # number of variables: # # SIP_INCLUDES - List of directories which SIP will scan through when looking # for included .sip files. (Corresponds to the -I option for SIP.) # # SIP_TAGS - List of tags to define when running SIP. (Corresponds to the -t # option for SIP.) # # SIP_CONCAT_PARTS - An integer which defines the number of parts the C++ code # of each module should be split into. Defaults to 8. (Corresponds to the # -j option for SIP.) # # SIP_DISABLE_FEATURES - List of feature names which should be disabled # running SIP. (Corresponds to the -x option for SIP.) # # SIP_EXTRA_OPTIONS - Extra command line options which should be passed on to # SIP. SET(SIP_INCLUDES) SET(SIP_TAGS) SET(SIP_CONCAT_PARTS 8) SET(SIP_DISABLE_FEATURES) SET(SIP_EXTRA_OPTIONS) MACRO(ADD_SIP_PYTHON_MODULE MODULE_NAME MODULE_SIP) SET(EXTRA_LINK_LIBRARIES ${ARGN}) STRING(REPLACE "." "/" _x ${MODULE_NAME}) GET_FILENAME_COMPONENT(_parent_module_path ${_x} PATH) GET_FILENAME_COMPONENT(_child_module_name ${_x} NAME) GET_FILENAME_COMPONENT(_module_path ${MODULE_SIP} PATH) GET_FILENAME_COMPONENT(_abs_module_sip ${MODULE_SIP} ABSOLUTE) # We give this target a long logical target name. # (This is to avoid having the library name clash with any already # install library names. If that happens then cmake dependency # tracking get confused.) STRING(REPLACE "." "_" _logical_name ${MODULE_NAME}) SET(_logical_name "python_module_${_logical_name}") FILE(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${_module_path}) # Output goes in this dir. SET(_sip_includes) FOREACH (_inc ${SIP_INCLUDES}) GET_FILENAME_COMPONENT(_abs_inc ${_inc} ABSOLUTE) LIST(APPEND _sip_includes -I ${_abs_inc}) ENDFOREACH (_inc ) SET(_sip_tags) FOREACH (_tag ${SIP_TAGS}) LIST(APPEND _sip_tags -t ${_tag}) ENDFOREACH (_tag) SET(_sip_x) FOREACH (_x ${SIP_DISABLE_FEATURES}) LIST(APPEND _sip_x -x ${_x}) ENDFOREACH (_x ${SIP_DISABLE_FEATURES}) SET(_message "-DMESSAGE=Generating CPP code for module ${MODULE_NAME}") SET(_sip_output_files) FOREACH(CONCAT_NUM RANGE 0 ${SIP_CONCAT_PARTS} ) IF( ${CONCAT_NUM} LESS ${SIP_CONCAT_PARTS} ) SET(_sip_output_files ${_sip_output_files} ${CMAKE_CURRENT_BINARY_DIR}/${_module_path}/sip${_child_module_name}part${CONCAT_NUM}.cpp ) ENDIF( ${CONCAT_NUM} LESS ${SIP_CONCAT_PARTS} ) ENDFOREACH(CONCAT_NUM RANGE 0 ${SIP_CONCAT_PARTS} ) # Suppress warnings IF(PEDANTIC) IF(MSVC) # 4996 deprecation warnings (bindings re-export deprecated methods) # 4701 potentially uninitialized variable used (sip generated code) # 4702 unreachable code (sip generated code) ADD_DEFINITIONS( /wd4996 /wd4701 /wd4702 ) ELSE(MSVC) # disable all warnings ADD_DEFINITIONS( -w ) ENDIF(MSVC) ENDIF(PEDANTIC) ADD_CUSTOM_COMMAND( OUTPUT ${_sip_output_files} COMMAND ${CMAKE_COMMAND} -E echo ${message} COMMAND ${CMAKE_COMMAND} -E touch ${_sip_output_files} COMMAND ${SIP_BINARY_PATH} ${_sip_tags} ${_sip_x} ${SIP_EXTRA_OPTIONS} -j ${SIP_CONCAT_PARTS} -c ${CMAKE_CURRENT_BINARY_DIR}/${_module_path} ${_sip_includes} ${_abs_module_sip} DEPENDS ${_abs_module_sip} ${SIP_EXTRA_FILES_DEPEND} ) # not sure if type MODULE could be uses anywhere, limit to cygwin for now IF (CYGWIN OR APPLE) ADD_LIBRARY(${_logical_name} MODULE ${_sip_output_files} ${SIP_EXTRA_SOURCE_FILES}) ELSE (CYGWIN OR APPLE) ADD_LIBRARY(${_logical_name} SHARED ${_sip_output_files} ${SIP_EXTRA_SOURCE_FILES}) ENDIF (CYGWIN OR APPLE) IF (NOT APPLE) TARGET_LINK_LIBRARIES(${_logical_name} ${PYTHON_LIBRARIES}) ENDIF (NOT APPLE) TARGET_LINK_LIBRARIES(${_logical_name} ${EXTRA_LINK_LIBRARIES}) IF (APPLE) SET_TARGET_PROPERTIES(${_logical_name} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup") ENDIF (APPLE) SET_TARGET_PROPERTIES(${_logical_name} PROPERTIES PREFIX "" OUTPUT_NAME ${_child_module_name}) IF (WIN32) SET_TARGET_PROPERTIES(${_logical_name} PROPERTIES SUFFIX ".pyd" IMPORT_PREFIX "_") ENDIF (WIN32) INSTALL(TARGETS ${_logical_name} DESTINATION "${PYTHON_SITE_PACKAGES_DIR}/${_parent_module_path}") ENDMACRO(ADD_SIP_PYTHON_MODULE) 0707010082A6FB000081A4000003E80000006400000001576A4ACE00000847000000080000000200000000000000000000002000000000libArcus-2.5.0/cmake/FindSIP.py# FindSIP.py # # Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. import sys import os.path def fail(msg="Unable to determine your sip configuration."): print(msg) sys.exit(1) try: # Try the old sipconfig. Many Linux distros still ship this in their packages. import sipconfig sipcfg = sipconfig.Configuration() sip_version = sipcfg.sip_version sip_version = sipcfg.sip_version sip_version_str = sipcfg.sip_version_str sip_bin = sipcfg.sip_bin default_sip_dir = sipcfg.default_sip_dir sip_inc_dir = sipcfg.sip_inc_dir except ImportError: try: if sys.platform == "win32": # Collect the info from the sip module and guess the rest. import sip from distutils import sysconfig sip_version = sip.SIP_VERSION sip_version_str = sip.SIP_VERSION_STR exe = sys.executable if exe is None: fail() base_path = os.path.dirname(exe) sip_bin = os.path.join(base_path, "Lib\\site-packages\\PyQt5\\sip.exe") if not os.path.exists(sip_bin): fail() sip_inc_dir = os.path.join(base_path, "Lib\\site-packages\\PyQt5\\include\\") if not os.path.exists(sip_inc_dir): fail() default_sip_dir = os.path.join(base_path, "Lib\\site-packages\\PyQt5\\sip\\") if not os.path.exists(default_sip_dir): fail() else: fail("Unable to import sipconfig and determine your sip configuration.") except ImportError: fail("Unable to import sipconfig and determine your sip configuration.") print("sip_version:%06.0x" % sip_version) print("sip_version_num:%d" % sip_version) print("sip_version_str:%s" % sip_version_str) print("sip_bin:%s" % sip_bin) print("default_sip_dir:%s" % default_sip_dir) print("sip_inc_dir:%s" % sip_inc_dir) 0707010082A6FC000081A4000003E80000006400000001592BFB85000009B9000000080000000200000000000000000000002300000000libArcus-2.5.0/cmake/FindSIP.cmake# Find SIP # ~~~~~~~~ # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # Find the installed version of SIP. FindSIP should be called after Python # has been found. # # This file defines the following variables: # # SIP_VERSION - The version of SIP found expressed as a 6 digit hex number # suitable for comparision as a string. # # SIP_VERSION_STR - The version of SIP found as a human readable string. # # SIP_BINARY_PATH - Path and filename of the SIP command line executable. # # SIP_INCLUDE_DIR - Directory holding the SIP C++ header file. # # SIP_DEFAULT_SIP_DIR - Default directory where .sip files should be installed # into. # Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. if(APPLE) # Workaround for broken FindPythonLibs. It will always find Python 2.7 libs on OSX set(CMAKE_FIND_FRAMEWORK LAST) endif() find_package(PythonInterp 3.4.0 REQUIRED) find_package(PythonLibs 3.4.0 REQUIRED) IF(SIP_VERSION) # Already in cache, be silent SET(SIP_FOUND TRUE) ELSE(SIP_VERSION) FIND_FILE(_find_sip_py FindSIP.py PATHS ${CMAKE_MODULE_PATH}) SET(ENV{PYTHONPATH} ${CMAKE_INSTALL_PREFIX}/${PYTHON_SITE_PACKAGES_DIR}) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${_find_sip_py} OUTPUT_VARIABLE sip_config RESULT_VARIABLE sip_config_returncode) IF(sip_config_returncode EQUAL 0) STRING(REGEX REPLACE "^sip_version:([^\n]+).*$" "\\1" SIP_VERSION ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_num:([^\n]+).*$" "\\1" SIP_VERSION_NUM ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_str:([^\n]+).*$" "\\1" SIP_VERSION_STR ${sip_config}) STRING(REGEX REPLACE ".*\nsip_bin:([^\n]+).*$" "\\1" SIP_BINARY_PATH ${sip_config}) STRING(REGEX REPLACE ".*\ndefault_sip_dir:([^\n]+).*$" "\\1" SIP_DEFAULT_SIP_DIR ${sip_config}) STRING(REGEX REPLACE ".*\nsip_inc_dir:([^\n]+).*$" "\\1" SIP_INCLUDE_DIR ${sip_config}) SET(SIP_FOUND TRUE) ENDIF(sip_config_returncode EQUAL 0) IF(SIP_FOUND) IF(NOT SIP_FIND_QUIETLY) MESSAGE(STATUS "Found SIP version: ${SIP_VERSION_STR}") ENDIF(NOT SIP_FIND_QUIETLY) include(${CMAKE_MODULE_PATH}/SIPMacros.cmake) ELSE(SIP_FOUND) IF(SIP_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find SIP") ENDIF(SIP_FIND_REQUIRED) ENDIF(SIP_FOUND) ENDIF(SIP_VERSION) 0707010082A6FD000081A4000003E8000000640000000157679D1600000274000000080000000200000000000000000000002600000000libArcus-2.5.0/examples/example.protosyntax = "proto3"; package Example; message ObjectList { repeated Object objects = 1; } message Object { int32 id = 1; bytes vertices = 2; //An array of 3 floats. bytes normals = 3; //An array of 3 floats. bytes indices = 4; //An array of ints. } message ProgressUpdate { int32 objectId = 1; int32 amount = 2; } message SlicedObjectList { repeated SlicedObject objects = 1; } message SlicedObject { int32 id = 1; repeated Polygon polygons = 2; } message Polygon { enum Type { InnerType = 0; OuterType = 1; } Type type = 1; bytes points = 2; } 0707010082A6FE000081ED000003E8000000640000000157679D160000007C000000080000000200000000000000000000002600000000libArcus-2.5.0/examples/example_py.sh#!/bin/sh PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}:${CMAKE_SOURCE_DIR}/python python3 ${CMAKE_CURRENT_SOURCE_DIR}/example.py 0707010082A6FF000081A4000003E8000000640000000157679D160000035A000000080000000200000000000000000000002700000000libArcus-2.5.0/examples/CMakeLists.txt include_directories(example ${CMAKE_CURRENT_BINARY_DIR}) set(example_SRCS example.cpp example_pb2.py ) protobuf_generate_cpp(example_PB_SRCS example_PB_HDRS "example.proto") add_executable(example ${example_SRCS} ${example_PB_SRCS}) target_link_libraries(example Arcus) if(NOT WIN32 OR CMAKE_COMPILER_IS_GNUCXX) target_link_libraries(example pthread) set_target_properties(example PROPERTIES COMPILE_FLAGS "-std=c++11") endif() add_custom_command( OUTPUT example_pb2.py COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} ARGS --python_out ${CMAKE_CURRENT_BINARY_DIR} --proto_path=${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/example.proto COMMENT "Running Python protocol buffer compiler on example.proto" VERBATIM ) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/example_py.sh ${CMAKE_CURRENT_BINARY_DIR}/example_py.sh) 0707010082A700000081A4000003E8000000640000000157679D1600000927000000080000000200000000000000000000002300000000libArcus-2.5.0/examples/example.pyimport Arcus import time import os.path class Listener(Arcus.SocketListener): def stateChanged(self, state): print("Socket state changed:", state) def messageReceived(self): message = self.getSocket().takeNextMessage() if message.getTypeName() == "Example.ProgressUpdate": print("Progress:", message.amount) if message.getTypeName() == "Example.SlicedObjectList": print("Sliced Objects:", message.repeatedMessageCount("objects")) for i in range(message.repeatedMessageCount("objects")): obj = message.getRepeatedMessage("objects", i) print(" Object ID:", obj.id) print(" Polygon Count:", obj.repeatedMessageCount("polygons")) def error(self, error): print(error) print("Creating socket") socket = Arcus.Socket() print("Registering message types") path = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") if not socket.registerAllMessageTypes(path + "/example.proto"): print("Failed to register messages:", socket.getLastError()) print("Creating listener") listener = Listener() socket.addListener(listener) print("Listening for connections on 127.0.0.1:56789") socket.listen('127.0.0.1', 56789) while(socket.getState() != Arcus.SocketState.Connected): time.sleep(0.1) #time.sleep(5) #Sleep for a bit so the other side can connect if(socket.getState() == Arcus.SocketState.Connected): print("Connection established") else: print(socket.getState()) print("Could not establish a connection:", socket.getLastError()) exit(1) for i in range(10): msg = socket.createMessage("Example.ObjectList") for i in range(100): obj = msg.addRepeatedMessage("objects") obj.id = i obj.vertices = b'abcdefghijklmnopqrstuvwxyz' * 10 obj.normals = b'abcdefghijklmnopqrstuvwxyz' * 10 obj.indices = b'abcdefghijklmnopqrstuvwxyz' * 10 print("Sending message containing", msg.repeatedMessageCount("objects"), "objects") socket.sendMessage(msg) time.sleep(1) if socket.getState() != Arcus.SocketState.Connected: print("Socket lost connection, aborting!") break time.sleep(5) #Sleep for a bit more so we can receive replies to what we just sent. print("Closing connection") socket.close() 0707010082A701000081A4000003E8000000640000000157679D1600000DCE000000080000000200000000000000000000002400000000libArcus-2.5.0/examples/example.cpp#include <vector> #include <iostream> #include <thread> #include "../src/Socket.h" #include "../src/SocketListener.h" #include "../src/Error.h" #include "example.pb.h" struct Object { public: int id; std::string vertices; std::string normals; std::string indices; }; class Listener : public Arcus::SocketListener { public: void stateChanged(Arcus::SocketState::SocketState new_state) { std::cout << "State Changed: " << new_state << std::endl; } void messageReceived() { } void error(const Arcus::Error& new_error) { std::cout << new_error << std::endl; } }; std::vector<Object> objects; void handleMessage(Arcus::Socket& socket, Arcus::MessagePtr message); int main(int argc, char** argv) { Arcus::Socket socket; socket.registerMessageType(&Example::ObjectList::default_instance()); socket.registerMessageType(&Example::ProgressUpdate::default_instance()); socket.registerMessageType(&Example::SlicedObjectList::default_instance()); socket.addListener(new Listener()); std::cout << "Connecting to server\n"; socket.connect("127.0.0.1", 56789); while(socket.getState() != Arcus::SocketState::Connected) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } std::cout << "Connected to server\n"; while(true) { if(socket.getState() == Arcus::SocketState::Connected) { auto message = socket.takeNextMessage(); if(message) { handleMessage(socket, message); } std::this_thread::sleep_for(std::chrono::milliseconds(250)); } else if(socket.getState() == Arcus::SocketState::Closed || socket.getState() == Arcus::SocketState::Error) { break; } } socket.close(); return 0; } void handleMessage(Arcus::Socket& socket, Arcus::MessagePtr message) { // (Dynamicly) cast the message to one of our types. If this works (does not return a nullptr), we've found the right type. auto objectList = dynamic_cast<Example::ObjectList*>(message.get()); if(objectList) { objects.clear(); std::cout << "Received object list containing " << objectList->objects_size() << " objects" << std::endl; for(auto objectDesc : objectList->objects()) { Object obj; obj.id = objectDesc.id(); obj.vertices = objectDesc.vertices(); obj.normals = objectDesc.normals(); obj.indices = objectDesc.indices(); objects.push_back(obj); } auto msg = std::make_shared<Example::SlicedObjectList>(); int progress = 0; for(auto object : objects) { auto slicedObject = msg->add_objects(); slicedObject->set_id(object.id); for(int i = 0; i < 1000; ++i) { auto polygon = slicedObject->add_polygons(); polygon->set_type(i % 2 == 0 ? Example::Polygon_Type_InnerType : Example::Polygon_Type_OuterType); polygon->set_points(object.vertices); } auto update = std::make_shared<Example::ProgressUpdate>(); update->set_objectid(object.id); update->set_amount((float(++progress) / float(objects.size())) * 100.f); socket.sendMessage(update); } std::cout << "Sending SlicedObjectList" << std::endl; socket.sendMessage(msg); return; } } 0707010082A704000081A4000003E80000006400000001592BFB850000174D000000080000000200000000000000000000002800000000libArcus-2.5.0/src/MessageTypeStore.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "MessageTypeStore.h" #include <unordered_map> #include <sstream> #include <iostream> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/compiler/importer.h> using namespace Arcus; /** * Taken from libstdc++, this implements hashing a string to an int. * * Since we rely on the hashing method for type ID generation and the implementation * of std::hash differs between compilers, we need to make sure we use the same * implementation everywhere. */ uint32_t hash(const std::string& input) { const char* data = input.c_str(); uint32_t length = input.size(); uint32_t result = static_cast<uint32_t>(2166136261UL); for(; length; --length) { result ^= static_cast<uint32_t>(*data++); result *= static_cast<uint32_t>(16777619UL); } return result; } class ErrorCollector : public google::protobuf::compiler::MultiFileErrorCollector { public: ErrorCollector() : _error_count(0) { } void AddError(const std::string& filename, int line, int column, const std::string& message) override { _stream << "[" << filename << " (" << line << "," << column << ")] " << message << std::endl; _error_count++; } std::string getAllErrors() { return _stream.str(); } int getErrorCount() { return _error_count; } private: std::stringstream _stream; int _error_count; }; class MessageTypeStore::Private { public: std::unordered_map<uint, const google::protobuf::Message*> message_types; std::unordered_map<const google::protobuf::Descriptor*, uint> message_type_mapping; std::shared_ptr<ErrorCollector> error_collector; std::shared_ptr<google::protobuf::compiler::DiskSourceTree> source_tree; std::shared_ptr<google::protobuf::compiler::Importer> importer; std::shared_ptr<google::protobuf::DynamicMessageFactory> message_factory; }; Arcus::MessageTypeStore::MessageTypeStore() : d(new Private) { } Arcus::MessageTypeStore::~MessageTypeStore() { } bool Arcus::MessageTypeStore::hasType(uint32_t type_id) const { if(d->message_types.find(type_id) != d->message_types.end()) { return true; } return false; } bool Arcus::MessageTypeStore::hasType(const std::string& type_name) const { uint32_t type_id = hash(type_name); return hasType(type_id); } MessagePtr Arcus::MessageTypeStore::createMessage(uint32_t type_id) const { if(!hasType(type_id)) { return MessagePtr(); } return MessagePtr(d->message_types[type_id]->New()); } MessagePtr Arcus::MessageTypeStore::createMessage(const std::string& type_name) const { uint32_t type_id = hash(type_name); return createMessage(type_id); } uint32_t Arcus::MessageTypeStore::getMessageTypeId(const MessagePtr& message) { return hash(message->GetTypeName()); } std::string Arcus::MessageTypeStore::getErrorMessages() const { return d->error_collector->getAllErrors(); } bool Arcus::MessageTypeStore::registerMessageType(const google::protobuf::Message* message_type) { uint32_t type_id = hash(message_type->GetTypeName()); if(hasType(type_id)) { return false; } d->message_types[type_id] = message_type; d->message_type_mapping[message_type->GetDescriptor()] = type_id; return true; } bool Arcus::MessageTypeStore::registerAllMessageTypes(const std::string& file_name) { if(!d->importer) { d->error_collector = std::make_shared<ErrorCollector>(); d->source_tree = std::make_shared<google::protobuf::compiler::DiskSourceTree>(); #ifndef _WIN32 d->source_tree->MapPath("/", "/"); #else // Because of silly DiskSourceTree, we need to make sure absolute paths to // the protocol file are properly mapped. for(auto letter : std::string("abcdefghijklmnopqrstuvwxyz")) { std::string lc(1, letter); std::string uc(1, toupper(letter)); d->source_tree->MapPath(lc + ":/", lc + ":\\"); d->source_tree->MapPath(uc + ":/", uc + ":\\"); } #endif d->importer = std::make_shared<google::protobuf::compiler::Importer>(d->source_tree.get(), d->error_collector.get()); } auto descriptor = d->importer->Import(file_name); if(d->error_collector->getErrorCount() > 0) { return false; } if(!d->message_factory) { d->message_factory = std::make_shared<google::protobuf::DynamicMessageFactory>(); } for(int i = 0; i < descriptor->message_type_count(); ++i) { auto message_type_descriptor = descriptor->message_type(i); auto message_type = d->message_factory->GetPrototype(message_type_descriptor); uint32_t type_id = hash(message_type->GetTypeName()); d->message_types[type_id] = message_type; d->message_type_mapping[message_type_descriptor] = type_id; } return true; } void Arcus::MessageTypeStore::dumpMessageTypes() { for(auto type : d->message_types) { std::cout << "Type ID: " << type.first << " Type Name: " << type.second->GetTypeName() << std::endl; } } 0707010082A705000081A4000003E80000006400000001592BFB8500000748000000080000000200000000000000000000001B00000000libArcus-2.5.0/src/Types.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_TYPES_H #define ARCUS_TYPES_H #include <string> #include <memory> namespace google { namespace protobuf { class Message; } } namespace Arcus { // Convenience typedef so uint can be used. typedef uint32_t uint; // Convenience typedef for standard message argument. typedef std::shared_ptr<google::protobuf::Message> MessagePtr; /** * Socket state. */ namespace SocketState { // Note: Not using enum class due to incompatibility with SIP. enum SocketState { Initial, ///< Created, not running. Connecting, ///< Connecting to an address and port. Connected, ///< Connected and capable of sending and receiving messages. Opening, ///< Opening for incoming connections. Listening, ///< Listening for incoming connections. Closing, ///< Closing down. Closed, ///< Closed, not running. Error ///< A fatal error happened that blocks the socket from operating. }; } } #endif //ARCUS_TYPES_H 0707010082A706000081A4000003E8000000640000000157679D1600000E24000000080000000200000000000000000000001B00000000libArcus-2.5.0/src/Error.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_ERROR_H #define ARCUS_ERROR_H #include "ArcusExport.h" #include "Types.h" namespace Arcus { /** * Possible error codes. */ namespace ErrorCode { // Note: Not using enum class due to incompatibility with SIP. enum ErrorCode { UnknownError, ///< An unknown error occurred. CreationError, ///< Socket creation failed. ConnectFailedError, ///< Connection failed. BindFailedError, ///< Bind to IP and port failed. AcceptFailedError, ///< Accepting an incoming connection failed. SendFailedError, ///< Sending a message failed. ReceiveFailedError, ///< Receiving a message failed. UnknownMessageTypeError, ///< Received a message with an unknown message type. ParseFailedError, ///< Parsing the received message failed. ConnectionResetError, ///< The connection was reset by peer. MessageRegistrationFailedError, ///< Message registration failed. InvalidStateError, ///< Socket is in an invalid state. InvalidMessageError, ///< Message being handled is a nullptr or otherwise invalid. Debug, //Debug messages }; } /** * A class representing an error with an error code and an error message. */ class ARCUS_EXPORT Error { public: /** * Default constructor. */ Error(); /** * Create an error with an error code and error message. */ Error(ErrorCode::ErrorCode error_code, const std::string& error_message); /** * Get the error code of this error. */ ErrorCode::ErrorCode getErrorCode() const; /** * Get the error message. */ std::string getErrorMessage() const; /** * Is this error considered a fatal error? */ bool isFatalError() const; /** * Is this error valid? */ bool isValid() const; /** * The error code as reported by the platform. */ int getNativeErrorCode() const; /** * Set whether this should be considered a fatal error. */ void setFatalError(bool fatal); /** * Set the native error code, if any. */ void setNativeErrorCode(int code); /** * Convert the error to a string that can be printed. */ std::string toString() const; private: ErrorCode::ErrorCode _error_code; std::string _error_message; bool _fatal_error; int _native_error_code; }; } // Output the error to a stream. ARCUS_EXPORT std::ostream& operator<<(std::ostream& stream, const Arcus::Error& error); #endif //ARCUS_ERROR_H 0707010082A707000081A4000003E80000006400000001592BFB8500000B88000000080000000200000000000000000000002300000000libArcus-2.5.0/src/WireMessage_p.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_WIRE_MESSAGE_P_H #define ARCUS_WIRE_MESSAGE_P_H #include "Types.h" namespace Arcus { namespace Private { /** * Private class that encapsulates a message being sent over the wire. */ class WireMessage { public: /** * Current state of the message. */ enum class MessageState { Header, ///< Check for the header. Size, ///< Check for the message size. Type, ///< Check for the message type. Data, ///< Get the message data. Dispatch ///< Process the message and parse it into a protobuf message. }; WireMessage() : state(MessageState::Header) , size(0) , received_size(0) , valid(true) , type(0) , data(nullptr) { } inline ~WireMessage() { if(size > 0 && data) { delete[] data; } } // Current message state. MessageState state; // Size of the message. uint32_t size; // Amount of bytes received so far. uint32_t received_size; // Is this a potentially valid message? bool valid; // The type of message. uint32_t type; // The data of the message. char* data; // Return how many bytes are remaining for this message to be complete. inline uint32_t getRemainingSize() const { return size - received_size; } // Allocate data for this message based on size. inline void allocateData() { data = new char[size]; } // Check if the message can be considered complete. inline bool isComplete() const { return received_size >= size; } }; } } #endif //ARCUS_WIRE_MESSAGE_P_H 0707010082A708000081A4000003E8000000640000000157679D16000003DB000000080000000200000000000000000000002600000000libArcus-2.5.0/src/SocketListener.cpp/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SocketListener.h" #include "Socket.h" using namespace Arcus; Socket* SocketListener::getSocket() const { return _socket; } void SocketListener::setSocket(Socket* socket) { _socket = socket; } 0707010082A709000081A4000003E8000000640000000157679D1600000969000000080000000200000000000000000000001D00000000libArcus-2.5.0/src/Error.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Error.h" #include <iostream> using namespace Arcus; Arcus::Error::Error() : _error_code(ErrorCode::UnknownError), _fatal_error(false), _native_error_code(0) { } Arcus::Error::Error(ErrorCode::ErrorCode error_code, const std::string& error_message) : _error_code(ErrorCode::UnknownError), _fatal_error(false), _native_error_code(0) { _error_code = error_code; _error_message = error_message; } ErrorCode::ErrorCode Arcus::Error::getErrorCode() const { return _error_code; } std::string Arcus::Error::getErrorMessage() const { return _error_message; } bool Arcus::Error::isFatalError() const { return _fatal_error; } bool Arcus::Error::isValid() const { return _error_code != ErrorCode::UnknownError || !_error_message.empty(); } int Arcus::Error::getNativeErrorCode() const { return _native_error_code; } void Arcus::Error::setFatalError(bool fatal) { _fatal_error = fatal; } void Arcus::Error::setNativeErrorCode(int code) { _native_error_code = code; } std::string Arcus::Error::toString() const { static std::string error_start("Arcus Error ("); static std::string fatal_error_start("Arcus Fatal Error ("); static std::string native_prefix(", native "); static std::string message_separator("): "); return (_fatal_error ? fatal_error_start : error_start) + std::to_string(static_cast<int>(_error_code)) + (_native_error_code != 0 ? native_prefix + std::to_string(_native_error_code) : "") + message_separator + _error_message; } std::ostream & operator<<(std::ostream& stream, const Arcus::Error& error) { return stream << error.toString(); } 0707010082A70A000081A4000003E80000006400000001592BFB850000196C000000080000000200000000000000000000002600000000libArcus-2.5.0/src/PlatformSocket.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PlatformSocket_p.h" #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #include <errno.h> #endif #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0x0 //Don't request NOSIGNAL on systems where this is not implemented. #endif #ifndef MSG_DONTWAIT #define MSG_DONTWAIT 0x0 #endif using namespace Arcus::Private; #ifdef _WIN32 void initializeWSA() { static bool wsaInitialized = false; if(!wsaInitialized) { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); wsaInitialized = true; } } #endif // Create a sockaddr_in structure from an address and port. sockaddr_in createAddress(const std::string& address, int port) { sockaddr_in a; a.sin_family = AF_INET; #ifdef _WIN32 InetPton(AF_INET, address.c_str(), &(a.sin_addr)); //Note: Vista and higher only. #else ::inet_pton(AF_INET, address.c_str(), &(a.sin_addr)); #endif a.sin_port = htons(port); return a; } Arcus::Private::PlatformSocket::PlatformSocket() { #ifdef _WIN32 initializeWSA(); #endif } Arcus::Private::PlatformSocket::~PlatformSocket() { } bool Arcus::Private::PlatformSocket::create() { _socket_id = ::socket(AF_INET, SOCK_STREAM, 0); return _socket_id != -1; } bool Arcus::Private::PlatformSocket::connect(const std::string& address, int port) { auto address_data = createAddress(address, port); int result = ::connect(_socket_id, reinterpret_cast<sockaddr*>(&address_data), sizeof(address_data)); return result == 0; } bool Arcus::Private::PlatformSocket::bind(const std::string& address, int port) { auto address_data = createAddress(address, port); int result = ::bind(_socket_id, reinterpret_cast<sockaddr*>(&address_data), sizeof(address_data)); return result == 0; } bool Arcus::Private::PlatformSocket::listen(int backlog) { int result = ::listen(_socket_id, backlog); return result == 0; } bool Arcus::Private::PlatformSocket::accept() { int new_socket = ::accept(_socket_id, 0, 0); #ifdef _WIN32 ::closesocket(_socket_id); #else ::close(_socket_id); #endif if(new_socket == -1) { return false; } else { _socket_id = new_socket; return true; } } bool Arcus::Private::PlatformSocket::close() { int result = 0; #ifdef _WIN32 result = ::closesocket(_socket_id); #else result = ::close(_socket_id); #endif return result == 0; } bool Arcus::Private::PlatformSocket::shutdown(PlatformSocket::ShutdownDirection direction) { int flag = 0; switch(direction) { case ShutdownDirection::ShutdownRead: #ifdef _WIN32 flag = SD_RECEIVE; #else flag = SHUT_RD; #endif break; case ShutdownDirection::ShutdownWrite: #ifdef _WIN32 flag = SD_SEND; #else flag = SHUT_WR; #endif break; case ShutdownDirection::ShutdownBoth: #ifdef _WIN32 flag = SD_BOTH; #else flag = SHUT_RDWR; #endif } return (::shutdown(_socket_id, flag) == 0); } void Arcus::Private::PlatformSocket::flush() { char* buffer = new char[256]; socket_size num = 0; while(num > 0) { num = ::recv(_socket_id, buffer, 256, MSG_DONTWAIT); } } socket_size Arcus::Private::PlatformSocket::writeUInt32(uint32_t data) { uint32_t temp = htonl(data); socket_size sent_size = ::send(_socket_id, reinterpret_cast<const char*>(&temp), 4, MSG_NOSIGNAL); return sent_size; } socket_size Arcus::Private::PlatformSocket::writeBytes(std::size_t size, const char* data) { return ::send(_socket_id, data, size, MSG_NOSIGNAL); } socket_size Arcus::Private::PlatformSocket::readUInt32(uint32_t* output) { #ifndef _WIN32 errno = 0; #endif uint32_t buffer; socket_size num = ::recv(_socket_id, reinterpret_cast<char*>(&buffer), 4, 0); if(num != 4) { #ifdef _WIN32 if(num == WSAETIMEDOUT) { return 0; } else if(WSAGetLastError() == WSAETIMEDOUT) { return 0; } #else if(errno == EAGAIN) { return 0; } #endif return -1; } *output = ntohl(buffer); return num; } socket_size Arcus::Private::PlatformSocket::readBytes(std::size_t size, char* output) { #ifndef _WIN32 errno = 0; #endif socket_size num = ::recv(_socket_id, output, size, 0); #ifdef _WIN32 if(num == SOCKET_ERROR && WSAGetLastError() == WSAETIMEDOUT) { return 0; } #else if(num <= 0 && errno == EAGAIN) { return 0; } #endif return num; } bool Arcus::Private::PlatformSocket::setReceiveTimeout(int timeout) { int result = 0; #ifdef _WIN32 result = ::setsockopt(_socket_id, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout), sizeof(timeout)); return result != SOCKET_ERROR; #else timeval t; t.tv_sec = 0; t.tv_usec = timeout * 1000; result = ::setsockopt(_socket_id, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&t), sizeof(t)); return result == 0; #endif } int Arcus::Private::PlatformSocket::getNativeErrorCode() { #ifdef _WIN32 return WSAGetLastError(); #else return errno; #endif } 0707010082A70B000081A4000003E8000000640000000157679D16000011D6000000080000000200000000000000000000001C00000000libArcus-2.5.0/src/Socket.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_SOCKET_H #define ARCUS_SOCKET_H #include <memory> #include "Types.h" #include "Error.h" #include "ArcusExport.h" namespace Arcus { class SocketListener; /** * \brief Threaded socket class. * * This class represents a socket and the logic for parsing and handling * protobuf messages that can be sent and received over this socket. * * Please see the README in libArcus for more details. */ class ARCUS_EXPORT Socket { public: Socket(); virtual ~Socket(); /** * Get the socket state. * * \return The current socket state. */ SocketState::SocketState getState() const; /** * Get the last error. * * \return The last error that occurred. */ Error getLastError() const; /** * Clear any error that was set previously. */ void clearError(); /** * Register a new type of Message to handle. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param message_type An instance of the Message that will be used as factory object. * */ bool registerMessageType(const google::protobuf::Message* message_type); /** * Register all message types contained in a Protobuf protocol description file. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param file_name The absolute path to a Protobuf protocol file to load message types from. */ bool registerAllMessageTypes(const std::string& file_name); /** * Add a listener object that will be notified of socket events. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param listener The listener to add. */ void addListener(SocketListener* listener); /** * Remove a listener from the list of listeners. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param listener The listener to remove. */ void removeListener(SocketListener* listener); /** * Connect to an address and port. * * \param address The IP address to connect to. * \param port The port to connect to. */ void connect(const std::string& address, int port); /** * Listen for connections on an address and port. * * \param address The IP address to listen on. * \param port The port to listen on. */ void listen(const std::string& address, int port); /** * Close the connection and stop handling any messages. */ void close(); /** * Reset a socket for re-use. State must be Closed or Error */ void reset(); /** * Send a message across the socket. */ void sendMessage(MessagePtr message); /** * Remove and return the next pending message from the queue. */ MessagePtr takeNextMessage(); /** * Create an instance of a Message class. * * \param type_name The type name of the Message type to create an instance of. */ MessagePtr createMessage(const std::string& type_name); private: // Copy and assignment is not supported. Socket(const Socket&); Socket& operator=(const Socket& other); class Private; const std::unique_ptr<Private> d; }; } #endif // ARCUS_SOCKET_H 0707010082A70C000081A4000003E80000006400000001592BFB8500000E1E000000080000000200000000000000000000002600000000libArcus-2.5.0/src/MessageTypeStore.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_MESSAGE_TYPE_STORE_H #define ARCUS_MESSAGE_TYPE_STORE_H #include <memory> #include "Types.h" namespace Arcus { /** * A class to manage the different types of messages that are available. */ class MessageTypeStore { public: MessageTypeStore(); ~MessageTypeStore(); /** * Check if a certain message type was registered. * * \param type_id The ID of the type to check for. * * \return true if the message type was registered, false if not. */ bool hasType(uint32_t type_id) const; /** * Check if a certain message type was registered. * * \param type_name The name of the type to check for. * * \return true if the message type was registered, false if not. */ bool hasType(const std::string& type_name) const; /** * Create a Message instance of a certain type. * * \param type_id The type ID of the message type to create an instance of. * * \return A new instance of a Message or an invalid pointer if type_id was an invalid type. */ MessagePtr createMessage(uint32_t type_id) const; /** * Create a Message instance of a certain type. * * \param type_name The name of the message type to create an instance of. * * \return A new instance of a Message or an invalid pointer if type_id was an invalid type. */ MessagePtr createMessage(const std::string& type_name) const; /** * Get the type ID of a message. * * \param message The message to get the type ID of. * * \return The type id of the message. */ uint32_t getMessageTypeId(const MessagePtr& message); std::string getErrorMessages() const; /** * Register a message type. * * \param message_type An instance of a message that will be used as factory to create new messages. * * \return true if registration was successful, false if not. */ bool registerMessageType(const google::protobuf::Message* message_type); /** * Register all message types from a Protobuf protocol description file. * * \param file_name The absolute path to a Protobuf proto file. * * \return true if registration was successful, false if not. */ bool registerAllMessageTypes(const std::string& file_name); /** * Dump all message type IDs and type names to stdout. */ void dumpMessageTypes(); private: class Private; const std::unique_ptr<Private> d; }; } #endif //ARCUS_MESSAGE_TYPE_STORE_H 0707010082A70D000081A4000003E80000006400000001592BFB8500001999000000080000000200000000000000000000002600000000libArcus-2.5.0/src/PlatformSocket_p.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_PLATFORM_SOCKET_P_H #define ARCUS_PLATFORM_SOCKET_P_H #include <memory> #include <string> namespace Arcus { namespace Private { #ifdef _WIN32 typedef int socket_size; #else typedef ssize_t socket_size; #endif /** * Private class that wraps the platform C API for dealing with Sockets. */ class PlatformSocket { public: /** * Which connection direction should be shutdown? */ enum class ShutdownDirection { ShutdownRead, ///< Shutdown reads from the connection. ShutdownWrite, ///< Shutdown writes to the connection. ShutdownBoth, ///< Shutdown the connection both ways. }; PlatformSocket(); ~PlatformSocket(); /** * Create the socket. * * \return true if socket creation was successful, false if not. */ bool create(); /** * Connect to an IP address and port. * * \param address The IP address to connect to. * \param port The port to bind to. * * \return true if the connection was successful, false if not. */ bool connect(const std::string& address, int port); /** * Bind the socket to an address and port. * * \param address The IP address to bind to. * \param port The port to bind to. * * \return true if successful, false if not. */ bool bind(const std::string& address, int port); /** * Mark the socket as listening for new connections. * * \param backlog The amount of queued connections to accept. * * \return true if successful, false if not. */ bool listen(int backlog); /** * Accept the waiting incoming connection and use it as connected socket. * * \return true if successful, false if not. * * \note This call will block until there is a connection waiting to be accepted. */ bool accept(); /** * Close the socket. * * \return true if successful, false if not. */ bool close(); /** * Shutdown the socket. * * \param direction The direction to shutdown. * * \return true if successful, false if not. */ bool shutdown(ShutdownDirection direction); /** * Flush all waiting data and discard it. * * This is mostly intended as an error recovery mechanism, if we detect a failure * in the messages sent over the wire, we can no longer be sure about the rest of * the data on the wire. So rather than trying to figure out if there is an actual * message hidden somewhere, just flush all data so we start with a clean slate. */ void flush(); /** * Write an unsigned 32-bit integer to the socket. * * \param data The integer to write. Will be converted from local endianness to network endianness. * * \return The amount of bytes written (4) or -1 if an error occurred. */ socket_size writeUInt32(uint32_t data); /** * Write data to the the socket. * * \param size The amount of data to write. * \param data A pointer to the data to send. * * \return The amount of bytes written, or -1 if an error occurred. */ socket_size writeBytes(std::size_t size, const char* data); /** * Read an unsigned 32-bit integer from the socket. * * \param output A pointer to an integer that will be written to. * * \return The amount of bytes read (4) or -1 if an error occurred. * * \note This call will block if the amount of data waiting to be read is less than 4. */ socket_size readUInt32(uint32_t* output); /** * Read an amount of bytes from the socket. * * \param size The amount of bytes to read. * \param output A pointer to a block of data that can be written to. * * \return The amount of bytes read or -1 if an error occurred. * * \note This call will block if the amount of data waiting to be read is less than size. */ socket_size readBytes(std::size_t size, char* output); /** * Set the timeout for the read-related methods. * * The readInt32 and readBytes methods will block for a certain amount of time when * there is not enough data available. This call will set the maximum amount of time these * calls will block. * * \param timeout The amount of time in milliseconds to wait for data. */ bool setReceiveTimeout(int timeout); /** * Return the last error code as reported by the underlying platform. */ int getNativeErrorCode(); private: int _socket_id; }; } } #endif //ARCUS_PLATFORM_SOCKET_P_H 0707010082A70E000081A4000003E80000006400000001592BFB8500004E82000000080000000200000000000000000000001E00000000libArcus-2.5.0/src/Socket_p.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <thread> #include <mutex> #include <string> #include <list> #include <unordered_map> #include <deque> #include <iostream> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #endif #include <google/protobuf/message.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <google/protobuf/io/coded_stream.h> #include "Socket.h" #include "Types.h" #include "SocketListener.h" #include "MessageTypeStore.h" #include "Error.h" #include "WireMessage_p.h" #include "PlatformSocket_p.h" #define VERSION_MAJOR 1 #define VERSION_MINOR 0 #define ARCUS_SIGNATURE 0x2BAD #define SIG(n) (((n) & 0xffff0000) >> 16) #define SOCKET_CLOSE 0xf0f0f0f0 #ifdef ARCUS_DEBUG #define DEBUG(message) debug(message) #else #define DEBUG(message) #endif /** * Private implementation details for Socket. */ namespace Arcus { using namespace Private; class Socket::Private { public: Private() : state(SocketState::Initial) , next_state(SocketState::Initial) , received_close(false) , port(0) , thread(nullptr) { } void run(); void sendMessage(const MessagePtr& message); void receiveNextMessage(); void handleMessage(const std::shared_ptr<WireMessage>& wire_message); void checkConnectionState(); #ifdef ARCUS_DEBUG void debug(const std::string& message); #endif void error(ErrorCode::ErrorCode error_code, const std::string& message); void fatalError(ErrorCode::ErrorCode error_code, const std::string& msg); SocketState::SocketState state; SocketState::SocketState next_state; bool received_close; std::string address; uint port; std::thread* thread; std::list<SocketListener*> listeners; MessageTypeStore message_types; std::shared_ptr<Arcus::Private::WireMessage> current_message; std::deque<MessagePtr> sendQueue; std::mutex sendQueueMutex; std::deque<MessagePtr> receiveQueue; std::mutex receiveQueueMutex; Arcus::Private::PlatformSocket platform_socket; Error last_error; std::chrono::system_clock::time_point last_keep_alive_sent; static const int keep_alive_rate = 500; //Number of milliseconds between sending keepalive packets // This value determines when protobuf should warn about very large messages. static const int message_size_warning = 400 * 1048576; // This value determines when protobuf should error out because the message is too large. // Due to the way Protobuf is implemented, messages large than 512MiB will cause issues. static const int message_size_maximum = 500 * 1048576; }; #ifdef ARCUS_DEBUG void Socket::Private::debug(const std::string& message) { Error error(ErrorCode::Debug, std::string("[DEBUG] ") + message); for(auto listener : listeners) { listener->error(error); } } #endif // Report an error that should not cause the connection to abort. void Socket::Private::error(ErrorCode::ErrorCode error_code, const std::string& message) { Error error(error_code, message); error.setNativeErrorCode(platform_socket.getNativeErrorCode()); last_error = error; for(auto listener : listeners) { listener->error(error); } } // Report an error that should cause the socket to go into an error state and abort the connection. void Socket::Private::fatalError(ErrorCode::ErrorCode error_code, const std::string& message) { Error error(error_code, message); error.setFatalError(true); error.setNativeErrorCode(platform_socket.getNativeErrorCode()); last_error = error; platform_socket.close(); next_state = SocketState::Error; for(auto listener : listeners) { listener->error(error); } } // Thread run method. void Socket::Private::run() { while(state != SocketState::Closed && state != SocketState::Error) { switch(state) { case SocketState::Connecting: { if(!platform_socket.create()) { fatalError(ErrorCode::CreationError, "Could not create a socket"); } else if(!platform_socket.connect(address, port)) { fatalError(ErrorCode::ConnectFailedError, "Could not connect to the given address"); } else { if(!platform_socket.setReceiveTimeout(250)) { fatalError(ErrorCode::ConnectFailedError, "Failed to set socket receive timeout"); } else { DEBUG("Socket connected"); next_state = SocketState::Connected; } } break; } case SocketState::Opening: { if(!platform_socket.create()) { fatalError(ErrorCode::CreationError, "Could not create a socket"); } else if(!platform_socket.bind(address, port)) { fatalError(ErrorCode::BindFailedError, "Could not bind to the given address and port"); } else { next_state = SocketState::Listening; } break; } case SocketState::Listening: { platform_socket.listen(1); if(!platform_socket.accept()) { fatalError(ErrorCode::AcceptFailedError, "Could not accept the incoming connection"); } else { if(!platform_socket.setReceiveTimeout(250)) { fatalError(ErrorCode::AcceptFailedError, "Could not set receive timeout of socket"); } else { DEBUG("Socket connected"); next_state = SocketState::Connected; } } break; } case SocketState::Connected: { //Get all the messages from the queue and store them in a temporary array so we can //unlock the queue before performing the send. std::list<MessagePtr> messagesToSend; sendQueueMutex.lock(); while(sendQueue.size() > 0) { messagesToSend.push_back(sendQueue.front()); sendQueue.pop_front(); } sendQueueMutex.unlock(); for(auto message : messagesToSend) { sendMessage(message); } receiveNextMessage(); if(next_state != SocketState::Error) { checkConnectionState(); } break; } case SocketState::Closing: { if(!received_close) { // We want to close the socket. // First, flush the send queue so it is empty. std::list<MessagePtr> messagesToSend; sendQueueMutex.lock(); while(sendQueue.size() > 0) { messagesToSend.push_back(sendQueue.front()); sendQueue.pop_front(); } sendQueueMutex.unlock(); for(auto message : messagesToSend) { sendMessage(message); } // Communicate to the other side that we want to close. platform_socket.writeUInt32(SOCKET_CLOSE); // Disable further writing to the socket. error(ErrorCode::Debug, "We got a request to close the socket."); platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownWrite); // Wait until we receive confirmation from the other side to actually close. uint32_t data = 0; while(data != SOCKET_CLOSE && next_state == SocketState::Closing) { if(platform_socket.readUInt32(&data) == -1) { break; } } } else { // The other side requested a close. Drop all pending messages // since the other socket will not process them anyway. sendQueueMutex.lock(); sendQueue.clear(); sendQueueMutex.unlock(); // Send confirmation to the other side that we received their close // request and are also closing down. platform_socket.writeUInt32(SOCKET_CLOSE); // Prevent further writing to the socket. platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownWrite); // At this point the socket can safely be closed, assuming that SOCKET_CLOSE // is the last data received from the other socket and everything was received // in order (which should be guaranteed by TCP). } error(ErrorCode::Debug, "Closing socket because other side requested close."); platform_socket.close(); next_state = SocketState::Closed; break; } default: break; } if(next_state != state) { state = next_state; for(auto listener : listeners) { listener->stateChanged(state); } } } } // Send a message to the connected socket. void Socket::Private::sendMessage(const MessagePtr& message) { uint32_t header = (ARCUS_SIGNATURE << 16) | (VERSION_MAJOR << 8) | (VERSION_MINOR); if(platform_socket.writeUInt32(header) == -1) { error(ErrorCode::SendFailedError, "Could not send message header"); return; } uint32_t message_size = message->ByteSize(); if(platform_socket.writeUInt32(message_size) == -1) { error(ErrorCode::SendFailedError, "Could not send message size"); return; } uint32_t type_id = message_types.getMessageTypeId(message); if(platform_socket.writeUInt32(type_id) == -1) { error(ErrorCode::SendFailedError, "Could not send message type"); return; } std::string data = message->SerializeAsString(); if(platform_socket.writeBytes(data.size(), data.data()) == -1) { error(ErrorCode::SendFailedError, "Could not send message data"); } DEBUG(std::string("Sending message of type ") + std::to_string(type_id) + " and size " + std::to_string(message_size)); } // Handle receiving data until we have a proper message. void Socket::Private::receiveNextMessage() { int result = 0; if(!current_message) { current_message = std::make_shared<WireMessage>(); } if(current_message->state == WireMessage::MessageState::Header) { uint32_t header = 0; platform_socket.readUInt32(&header); if(header == 0) // Keep-alive, just return { return; } else if(header == SOCKET_CLOSE) { // We received a close request from the other socket, so close this socket as well. next_state = SocketState::Closing; received_close = true; return; } int signature = (header & 0xffff0000) >> 16; int major_version = (header & 0x0000ff00) >> 8; int minor_version = header & 0x000000ff; if(signature != ARCUS_SIGNATURE) { // Someone might be speaking to us in a different protocol? error(ErrorCode::ReceiveFailedError, "Header mismatch"); current_message.reset(); platform_socket.flush(); return; } if(major_version != VERSION_MAJOR) { error(ErrorCode::ReceiveFailedError, "Protocol version mismatch"); current_message.reset(); platform_socket.flush(); return; } if(minor_version != VERSION_MINOR) { error(ErrorCode::ReceiveFailedError, "Protocol version mismatch"); current_message.reset(); platform_socket.flush(); return; } DEBUG("Incoming message, header ok"); current_message->state = WireMessage::MessageState::Size; } if(current_message->state == WireMessage::MessageState::Size) { uint32_t size = 0; result = platform_socket.readUInt32(&size); if(result == 0) { return; } else if(result == -1) { error(ErrorCode::ReceiveFailedError, "Size invalid"); current_message.reset(); platform_socket.flush(); return; } DEBUG(std::string("Incoming message size: ") + std::to_string(size)); current_message->size = size; current_message->state = WireMessage::MessageState::Type; } if (current_message->state == WireMessage::MessageState::Type) { uint32_t type = 0; result = platform_socket.readUInt32(&type); if(result == 0) { return; } else if(result == -1) { error(ErrorCode::ReceiveFailedError, "Receiving type failed"); current_message->valid = false; } uint32_t real_type = static_cast<uint32_t>(type); try { current_message->allocateData(); } catch (std::bad_alloc&) { // Either way we're in trouble. current_message.reset(); fatalError(ErrorCode::ReceiveFailedError, "Out of memory"); return; } DEBUG(std::string("Incoming message type: ") + std::to_string(real_type)); current_message->type = real_type; current_message->state = WireMessage::MessageState::Data; } if (current_message->state == WireMessage::MessageState::Data) { result = platform_socket.readBytes(current_message->getRemainingSize(), ¤t_message->data[current_message->received_size]); if(result < 0) { error(ErrorCode::ReceiveFailedError, "Could not receive data for message"); current_message.reset(); return; } else { current_message->received_size = current_message->received_size + result; DEBUG("Received " + std::to_string(result) + " bytes data"); if(current_message->isComplete()) { if(!current_message->valid) { current_message.reset(); return; } current_message->state = WireMessage::MessageState::Dispatch; } } } if (current_message->state == WireMessage::MessageState::Dispatch) { handleMessage(current_message); current_message.reset(); } } // Parse and process a message received on the socket. void Socket::Private::handleMessage(const std::shared_ptr<WireMessage>& wire_message) { if(!message_types.hasType(wire_message->type)) { DEBUG(std::string("Received message type: ") + std::to_string(wire_message->type)); error(ErrorCode::UnknownMessageTypeError, "Unknown message type"); return; } MessagePtr message = message_types.createMessage(wire_message->type); google::protobuf::io::ArrayInputStream array(wire_message->data, wire_message->size); google::protobuf::io::CodedInputStream stream(&array); stream.SetTotalBytesLimit(message_size_maximum, message_size_warning); if(!message->ParseFromCodedStream(&stream)) { error(ErrorCode::ParseFailedError, "Failed to parse message:" + std::string(wire_message->data)); return; } DEBUG(std::string("Received a message of type ") + std::to_string(wire_message->type) + " and size " + std::to_string(wire_message->size)); receiveQueueMutex.lock(); receiveQueue.push_back(message); receiveQueueMutex.unlock(); for(auto listener : listeners) { listener->messageReceived(); } } // Send a keepalive packet to check whether we are still connected. void Socket::Private::checkConnectionState() { auto now = std::chrono::system_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_keep_alive_sent); if(diff.count() > keep_alive_rate) { int32_t keepalive = 0; if(platform_socket.writeUInt32(keepalive) == -1) { error(ErrorCode::ConnectionResetError, "Connection reset by peer"); next_state = SocketState::Closing; } last_keep_alive_sent = now; } } } 0707010082A70F000081A4000003E8000000640000000157679D16000000E7000000080000000200000000000000000000002100000000libArcus-2.5.0/src/ArcusExport.h#ifndef ARCUS_EXPORT_H #define ARCUS_EXPORT_H #if _WIN32 #ifdef MAKE_ARCUS_LIB #define ARCUS_EXPORT __declspec(dllexport) #else #define ARCUS_EXPORT #endif #else #define ARCUS_EXPORT #endif #endif 0707010082A710000081A4000003E8000000640000000157679D1600000B88000000080000000200000000000000000000002400000000libArcus-2.5.0/src/SocketListener.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_SOCKETLISTENER_H #define ARCUS_SOCKETLISTENER_H #include "Types.h" #include "ArcusExport.h" namespace Arcus { class Socket; class Error; /** * Interface for socket event listeners. * * This interface should be implemented to receive notifications when * certain events occur on the socket. The methods of this interface * are called from the Socket's worker thread and thus with that thread * as current thread. This interface is thus primarily intended as an * abstraction to implement your own thread synchronisation. * * For example, when using the Qt event loop, you could emit a queued * signal from a subclass of this class, to make sure the actual event * is handled on the main thread. */ class ARCUS_EXPORT SocketListener { public: SocketListener() : _socket(nullptr) { } virtual ~SocketListener() { } /** * \return The socket this listener is listening to. */ Socket* getSocket() const; /** * Called whenever the socket's state changes. * * \param newState The new state of the socket. */ virtual void stateChanged(SocketState::SocketState newState) = 0; /** * Called whenever a new message has been received and * correctly parsed. * * \note This is explicitly not passed the received message. Instead, it is put * on a receive queue so other threads can take care of it. */ virtual void messageReceived() = 0; /** * Called whenever an error occurs on the socket. * * \param errorMessage The error message. */ virtual void error(const Error& error) = 0; private: // So we can call setSocket from Socket without making it public interface. friend class Socket; // Set the socket this listener is listening to. // This is automatically called by the socket when Socket::addListener() is called. void setSocket(Socket* socket); Socket* _socket; }; } #endif // ARCUS_SOCKETLISTENER_H 0707010082A711000081A4000003E80000006400000001592BFB8500001768000000080000000200000000000000000000001E00000000libArcus-2.5.0/src/Socket.cpp/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Socket.h" #include "Socket_p.h" #include <algorithm> using namespace Arcus; Socket::Socket() : d(new Private) { } Socket::~Socket() { if(d->thread) { if(d->state != SocketState::Closed || d->state != SocketState::Error) { close(); } delete d->thread; } for(auto listener : d->listeners) { delete listener; } } SocketState::SocketState Socket::getState() const { return d->state; } Error Socket::getLastError() const { return d->last_error; } void Socket::clearError() { d->last_error = Error(); } bool Socket::registerMessageType(const google::protobuf::Message* message_type) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return false; } return d->message_types.registerMessageType(message_type); } bool Socket::registerAllMessageTypes(const std::string& file_name) { if(file_name.empty()) { d->error(ErrorCode::MessageRegistrationFailedError, "Empty file name"); return false; } if(d->state != SocketState::Initial) { d->error(ErrorCode::MessageRegistrationFailedError, "Socket is not in initial state"); return false; } if(!d->message_types.registerAllMessageTypes(file_name)) { d->error(ErrorCode::MessageRegistrationFailedError, d->message_types.getErrorMessages()); return false; } return true; } void Socket::addListener(SocketListener* listener) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } listener->setSocket(this); d->listeners.push_back(listener); } void Socket::removeListener(SocketListener* listener) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } auto itr = std::find(d->listeners.begin(), d->listeners.end(), listener); d->listeners.erase(itr); } void Socket::connect(const std::string& address, int port) { if(d->state != SocketState::Initial || d->thread != nullptr) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } d->address = address; d->port = port; d->thread = new std::thread([&]() { d->run(); }); d->next_state = SocketState::Connecting; } void Socket::reset() { if (d->state != SocketState::Closed && d->state != SocketState::Error) { d->error(ErrorCode::InvalidStateError, "Socket is not in closed or error state"); return; } if(d->thread) { d->thread->join(); d->thread = nullptr; } d->state = SocketState::Initial; d->next_state = SocketState::Initial; clearError(); } void Socket::listen(const std::string& address, int port) { if(d->state != SocketState::Initial || d->thread != nullptr) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } d->address = address; d->port = port; d->thread = new std::thread([&]() { d->run(); }); d->next_state = SocketState::Opening; } void Socket::close() { if(d->state == SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Cannot close a socket in initial state"); return; } if(d->state == SocketState::Closed || d->state == SocketState::Error) { // Silently ignore this, as calling close on an already closed socket should be fine. return; } if(d->state == SocketState::Connected) { // Make the socket request close. d->next_state = SocketState::Closing; // Wait with closing until we properly clear the send queue. while(d->state == SocketState::Closing) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } else { // We are still in an unconnected state but want to abort any connection // attempt. So disable any communication on the socket to make sure calls // like accept() exit, then close the socket. d->platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownBoth); d->platform_socket.close(); d->next_state = SocketState::Closed; } if(d->thread) { d->thread->join(); delete d->thread; d->thread = nullptr; } } void Socket::sendMessage(MessagePtr message) { if(!message) { d->error(ErrorCode::InvalidMessageError, "Message cannot be nullptr"); return; } std::lock_guard<std::mutex> lock(d->sendQueueMutex); d->sendQueue.push_back(message); } MessagePtr Socket::takeNextMessage() { std::lock_guard<std::mutex> lock(d->receiveQueueMutex); if(d->receiveQueue.size() > 0) { MessagePtr next = d->receiveQueue.front(); d->receiveQueue.pop_front(); return next; } else { return nullptr; } } MessagePtr Arcus::Socket::createMessage(const std::string& type) { return d->message_types.createMessage(type); } 0707010082A713000081A4000003E8000000640000000157679D16000006F7000000080000000200000000000000000000002800000000libArcus-2.5.0/python/PythonMessage.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ class PythonMessage { %TypeHeaderCode #include "PythonMessage.h" %End public: virtual ~PythonMessage(); std::string getTypeName() const; bool __hasattr__(const std::string&) const /AllowNone/; PyObject* __getattr__(const std::string&) const /AllowNone, HoldGIL/; void __setattr__(const std::string&, PyObject*) /AllowNone/; %MethodCode sipCpp->__setattr__(*a0, a1); %End void __delattr__(const std::string&); %MethodCode PyErr_SetString(PyExc_NotImplementedError, "__delattr__ not supported on messages."); return 0; %End PythonMessage* addRepeatedMessage(const std::string& field_name) /TransferBack/; int repeatedMessageCount(const std::string& field_name) const; PythonMessage* getRepeatedMessage(const std::string& field_name, int index) /TransferBack/; PythonMessage* getMessage(const std::string& field_name) /TransferBack/; int getEnumValue(const std::string& enum_value) const; private: PythonMessage(); }; 0707010082A714000081A4000003E8000000640000000157679D16000020AE000000080000000200000000000000000000002800000000libArcus-2.5.0/python/PythonMessage.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PythonMessage.h" #include <Python.h> #include <google/protobuf/message.h> #include <google/protobuf/reflection.h> using namespace Arcus; using namespace google::protobuf; PythonMessage::PythonMessage(google::protobuf::Message* message) { _message = message; _reflection = message->GetReflection(); _descriptor = message->GetDescriptor(); } Arcus::PythonMessage::PythonMessage(const MessagePtr& message) { _shared_message = message; _message = message.get(); _reflection = message->GetReflection(); _descriptor = message->GetDescriptor(); } PythonMessage::~PythonMessage() { } std::string Arcus::PythonMessage::getTypeName() const { return _message->GetTypeName(); } MessagePtr Arcus::PythonMessage::getSharedMessage() const { return _shared_message; } bool Arcus::PythonMessage::__hasattr__(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); return bool(field); } PyObject* Arcus::PythonMessage::__getattr__(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } switch(field->type()) { case FieldDescriptor::TYPE_FLOAT: return PyFloat_FromDouble(_reflection->GetFloat(*_message, field)); case FieldDescriptor::TYPE_DOUBLE: return PyFloat_FromDouble(_reflection->GetDouble(*_message, field)); case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SFIXED32: return PyLong_FromLong(_reflection->GetInt32(*_message, field)); case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: return PyLong_FromLongLong(_reflection->GetInt64(*_message, field)); case FieldDescriptor::TYPE_UINT32: return PyLong_FromUnsignedLong(_reflection->GetUInt32(*_message, field)); case FieldDescriptor::TYPE_UINT64: return PyLong_FromUnsignedLongLong(_reflection->GetUInt64(*_message, field)); case FieldDescriptor::TYPE_BOOL: if(_reflection->GetBool(*_message, field)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } case FieldDescriptor::TYPE_BYTES: { std::string data = _reflection->GetString(*_message, field); return PyBytes_FromStringAndSize(data.c_str(), data.size()); } case FieldDescriptor::TYPE_STRING: return PyUnicode_FromString(_reflection->GetString(*_message, field).c_str()); case FieldDescriptor::TYPE_ENUM: return PyLong_FromLong(_reflection->GetEnumValue(*_message, field)); default: PyErr_SetString(PyExc_ValueError, "Could not handle value of field"); return nullptr; } } void Arcus::PythonMessage::__setattr__(const std::string& field_name, PyObject* value) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return; } switch(field->type()) { case FieldDescriptor::TYPE_FLOAT: _reflection->SetFloat(_message, field, PyFloat_AsDouble(value)); break; case FieldDescriptor::TYPE_DOUBLE: _reflection->SetDouble(_message, field, PyFloat_AsDouble(value)); break; case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_SFIXED32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SINT32: _reflection->SetInt32(_message, field, PyLong_AsLong(value)); break; case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: _reflection->SetInt64(_message, field, PyLong_AsLongLong(value)); break; case FieldDescriptor::TYPE_UINT32: _reflection->SetUInt32(_message, field, PyLong_AsUnsignedLong(value)); break; case FieldDescriptor::TYPE_UINT64: _reflection->SetUInt64(_message, field, PyLong_AsUnsignedLongLong(value)); break; case FieldDescriptor::TYPE_BOOL: if(value == Py_True) { _reflection->SetBool(_message, field, true); } else { _reflection->SetBool(_message, field, false); } break; case FieldDescriptor::TYPE_BYTES: { Py_buffer buffer; PyObject_GetBuffer(value, &buffer, PyBUF_SIMPLE); std::string str(reinterpret_cast<char*>(buffer.buf), buffer.len); _reflection->SetString(_message, field, str); break; } case FieldDescriptor::TYPE_STRING: _reflection->SetString(_message, field, PyUnicode_AsUTF8(value)); break; case FieldDescriptor::TYPE_ENUM: { if(PyUnicode_Check(value)) { auto enum_value = _descriptor->FindEnumValueByName(PyUnicode_AsUTF8(value)); _reflection->SetEnum(_message, field, enum_value); } else { _reflection->SetEnumValue(_message, field, PyLong_AsLong(value)); } break; } default: PyErr_SetString(PyExc_ValueError, "Could not handle value of field"); break; } } PythonMessage* Arcus::PythonMessage::addRepeatedMessage(const std::string& field_name) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } Message* message = _reflection->AddMessage(_message, field); return new PythonMessage(message); } int PythonMessage::repeatedMessageCount(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return -1; } return _reflection->FieldSize(*_message, field); } PythonMessage* Arcus::PythonMessage::getMessage(const std::string& field_name) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } return new PythonMessage(_reflection->MutableMessage(_message, field)); } PythonMessage* Arcus::PythonMessage::getRepeatedMessage(const std::string& field_name, int index) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } if(index < 0 || index > _reflection->FieldSize(*_message, field)) { PyErr_SetString(PyExc_IndexError, field_name.c_str()); return nullptr; } return new PythonMessage(_reflection->MutableRepeatedMessage(_message, field, index)); } int Arcus::PythonMessage::getEnumValue(const std::string& enum_value) const { auto field = _descriptor->FindEnumValueByName(enum_value); if(!field) { return -1; } return field->number(); } 0707010082A715000081A4000003E8000000640000000157679D1600000471000000080000000200000000000000000000002900000000libArcus-2.5.0/python/SocketListener.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ class SocketListener { %TypeHeaderCode #include "SocketListener.h" %End public: SocketListener(); virtual ~SocketListener(); Socket* getSocket(); virtual void stateChanged(SocketState::SocketState newState) = 0 /HoldGIL/; virtual void messageReceived() = 0 /HoldGIL/; virtual void error(const Error& error) = 0 /HoldGIL/; }; 0707010082A716000081A4000003E8000000640000000157679D1600001049000000080000000200000000000000000000002600000000libArcus-2.5.0/python/PythonMessage.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_PYTHON_MESSAGE_H #define ARCUS_PYTHON_MESSAGE_H #include <Python.h> #include "Types.h" namespace google { namespace protobuf { class Descriptor; class Reflection; } } namespace Arcus { /** * A simple wrapper around a Protobuf message so it can be used from Python. * * This class wraps a Protobuf message and makes it possible to get and set * values from the message. Message properties are exposed as Python properties * so can be set using things like `message.data = b"something"` from Python. * * Repeated messages are supported, using addRepeatedMessage, repeatedMessageCount * and getRepeatedMessage. A repeated message is returned as a PythonMessage object * so exposes the same API as the top level message. */ class PythonMessage { public: PythonMessage(google::protobuf::Message* message); PythonMessage(const MessagePtr& message); virtual ~PythonMessage(); /** * Get the message type name of this message. */ std::string getTypeName() const; /** * Python property interface. */ bool __hasattr__(const std::string& field_name) const; PyObject* __getattr__(const std::string& field_name) const; void __setattr__(const std::string& name, PyObject* value); /** * Add an instance of a Repeated Message to a specific field. * * \param field_name The name of the field to add a message to. * * \return A pointer to an instance of PythonMessage wrapping the new Message in the field. */ PythonMessage* addRepeatedMessage(const std::string& field_name); /** * Get the number of messages in a repeated message field. */ int repeatedMessageCount(const std::string& field_name) const; /** * Get a specific instance of a message in a repeated message field. * * \param field_name The name of a repeated message field to get an instance from. * \param index The index of the item to get in the repeated field. * * \return A pointer to an instance of PythonMessage wrapping the specified repeated message. */ PythonMessage* getRepeatedMessage(const std::string& field_name, int index); /** * Get a specific instance of a message in a message field. * * \param field_name The name of a repeated message field to get an instance from. * * \return A pointer to an instance of PythonMessage wrapping the specified repeated message. */ PythonMessage* getMessage(const std::string& field_name); /** * Get the value of a certain enumeration. * * \param enum_value The fully-qualified name of an Enum value. * * \return The integer value of the specified enum. */ int getEnumValue(const std::string& enum_value) const; /** * Internal. */ MessagePtr getSharedMessage() const; private: MessagePtr _shared_message; google::protobuf::Message* _message; const google::protobuf::Reflection* _reflection; const google::protobuf::Descriptor* _descriptor; }; } #endif //ARCUS_MESSAGE_PTR_H 0707010082A717000081A4000003E8000000640000000157679D16000006D5000000080000000200000000000000000000002100000000libArcus-2.5.0/python/Socket.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ %Module(name = Arcus, call_super_init = True) %Include Types.sip %Include SocketListener.sip %Include PythonMessage.sip %Include Error.sip %ModuleHeaderCode using namespace Arcus; %End class Socket { %TypeHeaderCode #include "Socket.h" %End public: Socket(); virtual ~Socket(); SocketState::SocketState getState() const; Error getLastError() const; void clearError(); void addListener(SocketListener* listener /TransferThis/); void removeListener(SocketListener* listener); void connect(const std::string& address, int port); void listen(const std::string& address, int port); void close() /ReleaseGIL/; void reset() /ReleaseGIL/; void sendMessage(MessagePtr message); MessagePtr takeNextMessage(); MessagePtr createMessage(const std::string& type_name); bool registerAllMessageTypes(const std::string& file_name); private: Socket(const Socket&); Socket& operator=(const Socket&); }; 0707010082A718000081A4000003E8000000640000000157679D1600000EC8000000080000000200000000000000000000002000000000libArcus-2.5.0/python/Types.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Convert a python str object to a std::string. %MappedType std::string { %TypeHeaderCode #include <string> %End %ConvertFromTypeCode // convert an std::string to a Python (unicode) string PyObject* newstring; newstring = PyUnicode_DecodeUTF8(sipCpp->c_str(), sipCpp->length(), NULL); if(newstring == NULL) { PyErr_Clear(); newstring = PyBytes_FromString(sipCpp->c_str()); } return newstring; %End %ConvertToTypeCode // Allow a Python string (or a unicode string) whenever a string is // expected. // If argument is a Unicode string, just decode it to UTF-8 // If argument is a Python string, assume it's UTF-8 if (sipIsErr == NULL) return (PyBytes_Check(sipPy) || PyUnicode_Check(sipPy)); if (sipPy == Py_None) { *sipCppPtr = new std::string; return 1; } if (PyUnicode_Check(sipPy)) { PyObject* s = PyUnicode_AsEncodedString(sipPy, "UTF-8", ""); *sipCppPtr = new std::string(PyBytes_AS_STRING(s)); Py_DECREF(s); return 1; } if (PyBytes_Check(sipPy)) { *sipCppPtr = new std::string(PyBytes_AS_STRING(sipPy)); return 1; } return 0; %End }; // Convert a MessagePtr (aka std::shared_ptr<google::protobuf::Message>) to a PythonMessage* %MappedType MessagePtr { %TypeHeaderCode #include <memory> #include "PythonMessage.h" %End %ConvertFromTypeCode // Convert a Protobuf message to a Python object if(!(*sipCpp)) { PyErr_SetString(PyExc_ValueError, "Unknown message type"); return NULL; } const sipTypeDef* message_type = sipFindType("PythonMessage"); PythonMessage* message = new PythonMessage(*sipCpp); sipTransferObj = Py_None; PyObject* msg = sipConvertFromType(message, message_type, sipTransferObj); if(!msg) { delete message; return NULL; } return msg; %End %ConvertToTypeCode // Convert a Python object to a Protobuf message const sipTypeDef* message_type = sipFindType("PythonMessage"); if(sipIsErr == NULL) { return sipCanConvertToType(sipPy, message_type, SIP_NOT_NONE); } if(sipCanConvertToType(sipPy, message_type, SIP_NOT_NONE)) { int iserr = 0; int state = 0; PythonMessage* message = reinterpret_cast<PythonMessage*>(sipConvertToType(sipPy, message_type, NULL, 0, &state, &iserr)); if(iserr != 0) { PyErr_SetString(PyExc_ValueError, "Could not convert to Message"); return 0; } MessagePtr msg = message->getSharedMessage(); *sipCppPtr = new MessagePtr(msg); sipReleaseType(message, message_type, state); } return sipGetState(sipTransferObj); %End }; %UnitCode #include "Types.h" %End namespace SocketState { enum SocketState { Initial, Connecting, Connected, Opening, Listening, Closing, Closed, Error }; }; 0707010082A719000081A4000003E8000000640000000157679D16000006A8000000080000000200000000000000000000002000000000libArcus-2.5.0/python/Error.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace ErrorCode { enum ErrorCode { UnknownError, CreationError, ConnectFailedError, BindFailedError, AcceptFailedError, SendFailedError, ReceiveFailedError, UnknownMessageTypeError, ParseFailedError, ConnectionResetError, MessageRegistrationFailedError, InvalidStateError, InvalidMessageError, Debug, }; }; class Error { %TypeHeaderCode #include "Error.h" %End public: Error(); Error(ErrorCode::ErrorCode error_code, const std::string& error_message); Error(const Error& error); ErrorCode::ErrorCode getErrorCode() const; std::string getErrorMessage() const; bool isFatalError() const; bool isValid() const; void setFatalError(bool fatal); PyObject* __repr__(); %MethodCode return PyUnicode_FromString(sipCpp->toString().c_str()); %End }; 0707010082E20C000041ED000003E80000006400000002592BFB8500000000000000080000000200000000000000000000001500000000libArcus-2.5.0/cmake0707010082E20D000041ED000003E8000000640000000257679D1600000000000000080000000200000000000000000000001800000000libArcus-2.5.0/examples0707010082E20E000041ED000003E80000006400000002592BFB8500000000000000080000000200000000000000000000001300000000libArcus-2.5.0/src0707010082E20F000041ED000003E80000006400000002592BFB8500000000000000080000000200000000000000000000001600000000libArcus-2.5.0/python0707010082A6F7000081A4000003E8000000640000000157679D16000086C3000000080000000200000000000000000000001700000000libArcus-2.5.0/LICENSEGNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.0707010082A6F8000081A4000003E80000006400000001592BFB8500000793000000080000000200000000000000000000001B00000000libArcus-2.5.0/Jenkinsfilenode("linux && cura") { stage('Prepare') { step([$class: 'WsCleanup']) checkout scm } catchError { dir('build') { stage('Build') { sh 'cmake .. -DCMAKE_PREFIX_PATH=/opt/ultimaker/cura-build-environment -DCMAKE_BUILD_TYPE=Release' sh 'make' } } } stage('Finalize') { if(currentBuild.result && currentBuild.result != "SUCCESS") { if(currentBuild.previousBuild.result != currentBuild.result) { emailext( subject: "[Jenkins] Build ${currentBuild.fullDisplayName} has become ${currentBuild.result}", body: "Jenkins build ${currentBuild.fullDisplayName} changed from ${currentBuild.previousBuild.result} to ${currentBuild.result}.\n\nPlease check the build output at ${env.BUILD_URL} for details.", to: env.CURA_EMAIL_RECIPIENTS ) } else { emailext ( subject: "[Jenkins] Build ${currentBuild.fullDisplayName} is ${currentBuild.result}", body: "Jenkins build ${currentBuild.fullDisplayName} is ${currentBuild.result}\n\nPlease check the build output at ${env.BUILD_URL} for details.", to: env.CURA_EMAIL_RECIPIENTS ) } } else { if(currentBuild.previousBuild.result != currentBuild.result) { emailext( subject: "[Jenkins] Build ${currentBuild.fullDisplayName} was fixed!", body: "Jenkins build ${currentBuild.fullDisplayName} was ${currentBuild.previousBuild.result} but is now stable again.\n\nPlease check the build output at ${env.BUILD_URL} for details.", to: env.CURA_EMAIL_RECIPIENTS ) } } } } 0707010082A702000081A4000003E80000006400000001592BFB85000011F9000000080000000200000000000000000000001E00000000libArcus-2.5.0/CMakeLists.txtproject(arcus) cmake_minimum_required(VERSION 2.8.12) include(GNUInstallDirs) include(CMakePackageConfigHelpers) option(BUILD_PYTHON "Build " ON) option(BUILD_EXAMPLES "Build the example programs" ON) option(BUILD_STATIC "Build as a static library" OFF) option(MSVC_STATIC_RUNTIME "Link the MSVC runtime statically" OFF) # We want to have access to protobuf_generate_cpp and other FindProtobuf features. # However, if ProtobufConfig is used instead, there is a CMake option that controls # this, which defaults to OFF. We need to force this option to ON instead. set(protobuf_MODULE_COMPATIBLE ON CACHE "" INTERNAL FORCE) find_package(Protobuf 3.0.0 REQUIRED) if(BUILD_PYTHON) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake) find_package(SIP REQUIRED) if(EXISTS /etc/debian_version) # Running on a debian-based system, which requires special handling for python modules. set(PYTHON_SITE_PACKAGES_DIR lib/python3/dist-packages CACHE STRING "Directory to install Python bindings to") else() set(PYTHON_SITE_PACKAGES_DIR lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages CACHE STRING "Directory to install Python bindings to") endif() include_directories(python/ src/ ${SIP_INCLUDE_DIR} ${PYTHON_INCLUDE_DIR}) endif() if(NOT ${CMAKE_VERSION} VERSION_LESS 3.1) set(CMAKE_CXX_STANDARD 11) else() set(CMAKE_CXX_FLAGS "-std=c++11") endif() if(APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") endif() set(arcus_SRCS src/Socket.cpp src/SocketListener.cpp src/MessageTypeStore.cpp src/PlatformSocket.cpp src/Error.cpp ) set(arcus_HDRS src/Socket.h src/SocketListener.h src/Types.h src/ArcusExport.h src/MessageTypeStore.h src/Error.h ) set(ARCUS_VERSION 1.1.0) set(ARCUS_SOVERSION 3) set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") if(BUILD_STATIC) add_library(Arcus STATIC ${arcus_SRCS}) if(NOT WIN32 OR CMAKE_COMPILER_IS_GNUCXX) target_link_libraries(Arcus PRIVATE pthread) set_target_properties(Arcus PROPERTIES COMPILE_FLAGS -fPIC) endif() else() add_library(Arcus SHARED ${arcus_SRCS}) endif() if(MSVC_STATIC_RUNTIME) foreach(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) if(${flag_var} MATCHES "/MD") string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") endif(${flag_var} MATCHES "/MD") endforeach(flag_var) endif() if(BUILD_PYTHON) set(SIP_EXTRA_FILES_DEPEND python/SocketListener.sip python/Types.sip python/PythonMessage.sip python/Error.sip) set(SIP_EXTRA_SOURCE_FILES python/PythonMessage.cpp) set(SIP_EXTRA_OPTIONS -g) # -g means always release the GIL before calling C++ methods. add_sip_python_module(Arcus python/Socket.sip Arcus) endif() target_include_directories(Arcus PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> ${PROTOBUF_INCLUDE_DIR} ) target_link_libraries(Arcus PUBLIC ${PROTOBUF_LIBRARIES}) if(WIN32) add_definitions(-D_WIN32_WINNT=0x0600) # Declare we require Vista or higher, this allows us to use IPv6 functions. target_link_libraries(Arcus PUBLIC Ws2_32) endif() if(${CMAKE_BUILD_TYPE}) if(${CMAKE_BUILD_TYPE} STREQUAL "Debug" OR ${CMAKE_BUILD_TYPE} STREQUAL "RelWithDebInfo") add_definitions(-DARCUS_DEBUG) endif() endif() set_target_properties(Arcus PROPERTIES FRAMEWORK FALSE VERSION ${ARCUS_VERSION} SOVERSION ${ARCUS_SOVERSION} PUBLIC_HEADER "${arcus_HDRS}" DEFINE_SYMBOL MAKE_ARCUS_LIB ) if(BUILD_EXAMPLES) add_subdirectory(examples) endif() install(TARGETS Arcus EXPORT Arcus-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/Arcus ) install(EXPORT Arcus-targets DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus ) configure_package_config_file(ArcusConfig.cmake.in ${CMAKE_BINARY_DIR}/ArcusConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus) write_basic_package_version_file(${CMAKE_BINARY_DIR}/ArcusConfigVersion.cmake VERSION ${ARCUS_VERSION} COMPATIBILITY SameMajorVersion) install(FILES ${CMAKE_BINARY_DIR}/ArcusConfig.cmake ${CMAKE_BINARY_DIR}/ArcusConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus ) include(CPackConfig.cmake) 0707010082A703000081A4000003E80000006400000001592BFB8500001280000000080000000200000000000000000000001900000000libArcus-2.5.0/README.mdArcus ===== This library contains C++ code and Python3 bindings for creating a socket in a thread and using this socket to send and receive messages based on the Protocol Buffers library. It is designed to facilitate the communication between Cura and its backend and similar code. Installing Protobuf ------------------- 1. Be sure to have libtool installed. 2. Download ```protobuf``` >= 3.0.0 from https://github.com/google/protobuf/releases (download ZIP and unZIP at desired location, or clone the repo). The protocol buffer is used for communication between the CuraEngine and the GUI. 3. Compile protobuf from the protobuf directory: $ ```$ mkdir build && cd build``` 4. Open CMAKE GUI and disable building of tests: $ ```$ cmake-gui``` 5. $ ```$ make``` 6. $ ```# make install``` (Please note the ```#```. It indicates the need of superuser, as known as root, priviliges.) 7. (In case the shared library cannot be loaded, you can try ```sudo ldconfig``` on Linux systems) Installing Protobuf on Windows ------------------------------ C++ (Make sure to use the latest MinGW stable version, e.g. MinGW 4.8.1) 1. Download and install MinGW-get from http://sourceforge.net/projects/mingw/files/Installer/mingw-get/ 2. With MinGW-get, install the MSYS package for MinGW 3. With MinGW-get, install msys-autogen, msys-automake, msys-libtool 4. Download ProtoBuf from https://github.com/google/protobuf (tested with version 3.0.0) 5. Extract ProtoBuf to ```.../MinGW/msys/1.0/local``` 6. Launch ```.../MinGW/msys/1.0/msys.bat``` (run as administrator!) 7. Open a terminal and navigate to ```.../MinGW/msys/1.0/local/protobuf-3.0.0-alpha-1``` 8. ```$ ./autogen.sh``` 1. If at this point you are getting errors of missing AM_PROG_AR, you must make sure the ```ar.exe``` binary is installed and the newest stable version. 9. ```$ ./configure``` 10. ```$ mingw32-make``` 11. ```$ mingw32-make install``` Building ======== To build the library, you need CMake and Protobuf installed (see below). In addition, if the Python module should be installed, you need a python interpreter available withh the sip tool installed. Only Python 3 is supported. Building the library can be done with: - ```$ mkdir build && cd build``` - ```$ cmake ..``` - ```$ make``` - ```# make install``` This will install to CMake's default install prefix, ```/usr/local```. To change the prefix, set ```CMAKE_INSTALL_PREFIX```. By default, the examples directory is also built. To disable this, set BUILD_EXAMPLES to off. To disable building the Python bindings, set BUILD_PYTHON to OFF. They will be installed into ```$prefix/lib/python3.4/site-packages``` on Mac OSX and Windows and to ```$prefix/lib/python3/dist-packages``` on Linux. To override this directory, set ```PYTHON_SITE_PACKAGES_DIR``` . Building the Python bindings on 64-bit Windows requires you to build with Microsoft Visual C++ since the module will fail to import if built with MinGW. Using the Socket ================ The socket assumes a very simple and strict wire protocol: one 32-bit integer with a header, one 32-bit integer with the message size, one 32-bit integer with a type id then a byte array containing the message as serialized by Protobuf. The receiving side checks for these fields and will deserialize the message, after which it can be processed by the application. To send or receive messages, the message first needs to be registered on both sides with a call to `registerMessageType()`. You can also register all messages from a Protobuf .proto file with a call to `registerAllMessageTypes()`. For the Python bindings, this is the only supported way of registering since there are no Python classses for individual message types. The Python bindings expose the same API as the Public C++ API, except for the missing `registerMessageType()` and the individual messages. The Python bindings wrap the messages in a class that exposes the message's properties as Python properties, and can thus be set the same way you would set any other Python property. The exception is repeated fields. Currently, only repeated messages are supported, which can be created through the `addRepeatedMessage()` method. `repeatedMessageCount()` will return the number of repeated messages on an object and `getRepeatedMessage()` will get a certain instance of a repeated message. See python/PythonMessage.h for more details. Origin of the Name ================== The name Arcus is from the Roman god Arcus. This god is the roman equivalent of the goddess Iris, who is the personification of the rainbow and the messenger of the gods. Java ==== There is a Java port of libArcus, which can be found [here](https://github.com/Ocarthon/libArcus-Java). 0707010082A712000081A4000003E8000000640000000157679D160000037B000000080000000200000000000000000000002100000000libArcus-2.5.0/CPackConfig.cmakeset(CPACK_PACKAGE_VENDOR "Ultimaker") set(CPACK_PACKAGE_CONTACT "Arjen Hiemstra <a.hiemstra@ultimaker.com>") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "libArcus Communication library") if(NOT DEFINED CPACK_PACKAGE_VERSION) set(CPACK_PACKAGE_VERSION "15.05.91") endif() set(CPACK_GENERATOR "DEB") if(NOT DEFINED CPACK_DEBIAN_PACKAGE_ARCHITECTURE) execute_process(COMMAND dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE OUTPUT_STRIP_TRAILING_WHITESPACE) endif() set(CPACK_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${CPACK_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(DEB_DEPENDS "python3 (>= 3.4.0)" "libgcc1 (>= 4.9.0)" "libstdc++6 (>= 4.9.0)" "libc6 (>= 2.19)" "zlib1g (>= 1.2.0)" "protobuf (>= 3.0.0)" ) string(REPLACE ";" ", " DEB_DEPENDS "${DEB_DEPENDS}") set(CPACK_DEBIAN_PACKAGE_DEPENDS ${DEB_DEPENDS}) include(CPack) 0707010082A71A000081A4000003E8000000640000000157679D1600000134000000080000000200000000000000000000001700000000libArcus-2.5.0/TODO.mdThings to add later =================== - Support for Unix file sockets in addition to streamed local TCP sockets. - Support for DNS resolving. - Find some way to unit test this. - Use a hash function on the message type name to automatically determine message type id. - Improve error handling / checking. 0707010082A71B000081A4000003E80000006400000001592BFB85000001D0000000080000000200000000000000000000002400000000libArcus-2.5.0/ArcusConfig.cmake.in@PACKAGE_INIT@ # We want to have access to protobuf_generate_cpp and other FindProtobuf features. # However, if ProtobufConfig is used instead, there is a CMake option that controls # this, which defaults to OFF. We need to force this option to ON instead. set(protobuf_MODULE_COMPATIBLE ON CACHE "" INTERNAL FORCE) find_package(Protobuf 3.0.0 REQUIRED) get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) include(${SELF_DIR}/Arcus-targets.cmake) 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!319 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor