# HG changeset patch # User Sebastien Jodogne # Date 1451913711 -3600 # Node ID f7379096e0145a52f11107b1a6df1075efc48380 # Parent a07ee8b6946e1a6f9dd70afbdf6946dd70a16686 fix diff -r a07ee8b6946e -r f7379096e014 CMakeLists.txt --- a/CMakeLists.txt Mon Jan 04 14:04:43 2016 +0100 +++ b/CMakeLists.txt Mon Jan 04 14:21:51 2016 +0100 @@ -21,6 +21,7 @@ # Some basic inclusions SET(ORTHANC_ROOT ${CMAKE_SOURCE_DIR}/Orthanc) SET(ENABLE_SSL ON) +SET(ENABLE_PLUGINS_VERSION_SCRIPT OFF) include(CheckIncludeFiles) include(CheckIncludeFileCXX) @@ -76,19 +77,20 @@ set(ORTHANC_CPP_CLIENT_AUX ${OPENSSL_SOURCES}) endif() +add_definitions( + -DORTHANC_ENABLE_MD5=0 + -DORTHANC_ENABLE_BASE64=0 + -DORTHANC_ENABLE_LOGGING=0 + ) add_library(OrthancClient SHARED + Orthanc/Core/ChunkedBuffer.cpp + Orthanc/Core/Enumerations.cpp Orthanc/Core/HttpClient.cpp - Orthanc/Core/ImageFormats/PngReader.cpp - Orthanc/Core/ImageFormats/ImageAccessor.cpp + Orthanc/Core/Images/ImageAccessor.cpp + Orthanc/Core/Images/PngReader.cpp Orthanc/Core/MultiThreading/SharedMessageQueue.cpp Orthanc/Core/Toolbox.cpp - Orthanc/Core/ChunkedBuffer.cpp - Orthanc/Core/Enumerations.cpp - Orthanc/Core/OrthancException.cpp - Orthanc/Resources/ThirdParty/base64/base64.cpp - Orthanc/Resources/ThirdParty/base64/base64.cpp - Orthanc/Resources/ThirdParty/md5/md5.c CppClient/Instance.cpp CppClient/OrthancConnection.cpp @@ -109,7 +111,9 @@ add_executable(UnitTests CppClient/ArrayFilledByThreads.cpp CppClient/ThreadedCommandProcessor.cpp + Orthanc/Core/Enumerations.cpp Orthanc/Core/MultiThreading/SharedMessageQueue.cpp + Orthanc/Core/Toolbox.cpp UnitTestsSources/MultiThreadingTests.cpp UnitTestsSources/UnitTestsMain.cpp diff -r a07ee8b6946e -r f7379096e014 CppClient/Instance.h --- a/CppClient/Instance.h Mon Jan 04 14:04:43 2016 +0100 +++ b/CppClient/Instance.h Mon Jan 04 14:21:51 2016 +0100 @@ -38,7 +38,7 @@ #include "PublicEnumerations.h" #include "OrthancClientException.h" #include "../Orthanc/Core/IDynamicObject.h" -#include "../Orthanc/Core/ImageFormats/PngReader.h" +#include "../Orthanc/Core/Images/PngReader.h" namespace OrthancClient { diff -r a07ee8b6946e -r f7379096e014 CppClient/OrthancClientException.h --- a/CppClient/OrthancClientException.h Mon Jan 04 14:04:43 2016 +0100 +++ b/CppClient/OrthancClientException.h Mon Jan 04 14:21:51 2016 +0100 @@ -41,7 +41,7 @@ { public: OrthancClientException(Orthanc::ErrorCode code) : - LaawException(Orthanc::OrthancException::GetDescription(code)) + LaawException(Orthanc::EnumerationToString(code)) { } diff -r a07ee8b6946e -r f7379096e014 CppClient/OrthancConnection.cpp --- a/CppClient/OrthancConnection.cpp Mon Jan 04 14:04:43 2016 +0100 +++ b/CppClient/OrthancConnection.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -87,8 +87,8 @@ client_.SetUrl(orthancUrl_ + "/instances"); // Copy the DICOM file in the POST body. TODO - Avoid memory copy - client_.AccessPostData().resize(static_cast(size)); - memcpy(&client_.AccessPostData()[0], dicom, static_cast(size)); + client_.GetBody().resize(static_cast(size)); + memcpy(&client_.GetBody()[0], dicom, static_cast(size)); Json::Value v; if (!client_.Apply(v)) diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/ChunkedBuffer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/ChunkedBuffer.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,99 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#include "PrecompiledHeaders.h" +#include "ChunkedBuffer.h" + +#include +#include + + +namespace Orthanc +{ + void ChunkedBuffer::Clear() + { + numBytes_ = 0; + + for (Chunks::iterator it = chunks_.begin(); + it != chunks_.end(); ++it) + { + delete *it; + } + } + + + void ChunkedBuffer::AddChunk(const char* chunkData, + size_t chunkSize) + { + if (chunkSize == 0) + { + return; + } + + assert(chunkData != NULL); + chunks_.push_back(new std::string(chunkData, chunkSize)); + numBytes_ += chunkSize; + } + + + void ChunkedBuffer::AddChunk(const std::string& chunk) + { + if (chunk.size() > 0) + { + AddChunk(&chunk[0], chunk.size()); + } + } + + + void ChunkedBuffer::Flatten(std::string& result) + { + result.resize(numBytes_); + + size_t pos = 0; + for (Chunks::iterator it = chunks_.begin(); + it != chunks_.end(); ++it) + { + assert(*it != NULL); + + size_t s = (*it)->size(); + if (s != 0) + { + memcpy(&result[pos], (*it)->c_str(), s); + pos += s; + } + + delete *it; + } + + chunks_.clear(); + } +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/ChunkedBuffer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/ChunkedBuffer.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,71 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include +#include + +namespace Orthanc +{ + class ChunkedBuffer + { + private: + typedef std::list Chunks; + size_t numBytes_; + Chunks chunks_; + + void Clear(); + + public: + ChunkedBuffer() : numBytes_(0) + { + } + + ~ChunkedBuffer() + { + Clear(); + } + + size_t GetNumBytes() const + { + return numBytes_; + } + + void AddChunk(const char* chunkData, + size_t chunkSize); + + void AddChunk(const std::string& chunk); + + void Flatten(std::string& result); + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Enumerations.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Enumerations.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,1154 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#include "PrecompiledHeaders.h" +#include "Enumerations.h" + +#include "OrthancException.h" +#include "Toolbox.h" + +#include + +namespace Orthanc +{ + // This function is autogenerated by the script + // "Resources/GenerateErrorCodes.py" + const char* EnumerationToString(ErrorCode error) + { + switch (error) + { + case ErrorCode_InternalError: + return "Internal error"; + + case ErrorCode_Success: + return "Success"; + + case ErrorCode_Plugin: + return "Error encountered within the plugin engine"; + + case ErrorCode_NotImplemented: + return "Not implemented yet"; + + case ErrorCode_ParameterOutOfRange: + return "Parameter out of range"; + + case ErrorCode_NotEnoughMemory: + return "Not enough memory"; + + case ErrorCode_BadParameterType: + return "Bad type for a parameter"; + + case ErrorCode_BadSequenceOfCalls: + return "Bad sequence of calls"; + + case ErrorCode_InexistentItem: + return "Accessing an inexistent item"; + + case ErrorCode_BadRequest: + return "Bad request"; + + case ErrorCode_NetworkProtocol: + return "Error in the network protocol"; + + case ErrorCode_SystemCommand: + return "Error while calling a system command"; + + case ErrorCode_Database: + return "Error with the database engine"; + + case ErrorCode_UriSyntax: + return "Badly formatted URI"; + + case ErrorCode_InexistentFile: + return "Inexistent file"; + + case ErrorCode_CannotWriteFile: + return "Cannot write to file"; + + case ErrorCode_BadFileFormat: + return "Bad file format"; + + case ErrorCode_Timeout: + return "Timeout"; + + case ErrorCode_UnknownResource: + return "Unknown resource"; + + case ErrorCode_IncompatibleDatabaseVersion: + return "Incompatible version of the database"; + + case ErrorCode_FullStorage: + return "The file storage is full"; + + case ErrorCode_CorruptedFile: + return "Corrupted file (e.g. inconsistent MD5 hash)"; + + case ErrorCode_InexistentTag: + return "Inexistent tag"; + + case ErrorCode_ReadOnly: + return "Cannot modify a read-only data structure"; + + case ErrorCode_IncompatibleImageFormat: + return "Incompatible format of the images"; + + case ErrorCode_IncompatibleImageSize: + return "Incompatible size of the images"; + + case ErrorCode_SharedLibrary: + return "Error while using a shared library (plugin)"; + + case ErrorCode_UnknownPluginService: + return "Plugin invoking an unknown service"; + + case ErrorCode_UnknownDicomTag: + return "Unknown DICOM tag"; + + case ErrorCode_BadJson: + return "Cannot parse a JSON document"; + + case ErrorCode_Unauthorized: + return "Bad credentials were provided to an HTTP request"; + + case ErrorCode_BadFont: + return "Badly formatted font file"; + + case ErrorCode_DatabasePlugin: + return "The plugin implementing a custom database back-end does not fulfill the proper interface"; + + case ErrorCode_StorageAreaPlugin: + return "Error in the plugin implementing a custom storage area"; + + case ErrorCode_EmptyRequest: + return "The request is empty"; + + case ErrorCode_NotAcceptable: + return "Cannot send a response which is acceptable according to the Accept HTTP header"; + + case ErrorCode_SQLiteNotOpened: + return "SQLite: The database is not opened"; + + case ErrorCode_SQLiteAlreadyOpened: + return "SQLite: Connection is already open"; + + case ErrorCode_SQLiteCannotOpen: + return "SQLite: Unable to open the database"; + + case ErrorCode_SQLiteStatementAlreadyUsed: + return "SQLite: This cached statement is already being referred to"; + + case ErrorCode_SQLiteExecute: + return "SQLite: Cannot execute a command"; + + case ErrorCode_SQLiteRollbackWithoutTransaction: + return "SQLite: Rolling back a nonexistent transaction (have you called Begin()?)"; + + case ErrorCode_SQLiteCommitWithoutTransaction: + return "SQLite: Committing a nonexistent transaction"; + + case ErrorCode_SQLiteRegisterFunction: + return "SQLite: Unable to register a function"; + + case ErrorCode_SQLiteFlush: + return "SQLite: Unable to flush the database"; + + case ErrorCode_SQLiteCannotRun: + return "SQLite: Cannot run a cached statement"; + + case ErrorCode_SQLiteCannotStep: + return "SQLite: Cannot step over a cached statement"; + + case ErrorCode_SQLiteBindOutOfRange: + return "SQLite: Bing a value while out of range (serious error)"; + + case ErrorCode_SQLitePrepareStatement: + return "SQLite: Cannot prepare a cached statement"; + + case ErrorCode_SQLiteTransactionAlreadyStarted: + return "SQLite: Beginning the same transaction twice"; + + case ErrorCode_SQLiteTransactionCommit: + return "SQLite: Failure when committing the transaction"; + + case ErrorCode_SQLiteTransactionBegin: + return "SQLite: Cannot start a transaction"; + + case ErrorCode_DirectoryOverFile: + return "The directory to be created is already occupied by a regular file"; + + case ErrorCode_FileStorageCannotWrite: + return "Unable to create a subdirectory or a file in the file storage"; + + case ErrorCode_DirectoryExpected: + return "The specified path does not point to a directory"; + + case ErrorCode_HttpPortInUse: + return "The TCP port of the HTTP server is already in use"; + + case ErrorCode_DicomPortInUse: + return "The TCP port of the DICOM server is already in use"; + + case ErrorCode_BadHttpStatusInRest: + return "This HTTP status is not allowed in a REST API"; + + case ErrorCode_RegularFileExpected: + return "The specified path does not point to a regular file"; + + case ErrorCode_PathToExecutable: + return "Unable to get the path to the executable"; + + case ErrorCode_MakeDirectory: + return "Cannot create a directory"; + + case ErrorCode_BadApplicationEntityTitle: + return "An application entity title (AET) cannot be empty or be longer than 16 characters"; + + case ErrorCode_NoCFindHandler: + return "No request handler factory for DICOM C-FIND SCP"; + + case ErrorCode_NoCMoveHandler: + return "No request handler factory for DICOM C-MOVE SCP"; + + case ErrorCode_NoCStoreHandler: + return "No request handler factory for DICOM C-STORE SCP"; + + case ErrorCode_NoApplicationEntityFilter: + return "No application entity filter"; + + case ErrorCode_NoSopClassOrInstance: + return "DicomUserConnection: Unable to find the SOP class and instance"; + + case ErrorCode_NoPresentationContext: + return "DicomUserConnection: No acceptable presentation context for modality"; + + case ErrorCode_DicomFindUnavailable: + return "DicomUserConnection: The C-FIND command is not supported by the remote SCP"; + + case ErrorCode_DicomMoveUnavailable: + return "DicomUserConnection: The C-MOVE command is not supported by the remote SCP"; + + case ErrorCode_CannotStoreInstance: + return "Cannot store an instance"; + + case ErrorCode_CreateDicomNotString: + return "Only string values are supported when creating DICOM instances"; + + case ErrorCode_CreateDicomOverrideTag: + return "Trying to override a value inherited from a parent module"; + + case ErrorCode_CreateDicomUseContent: + return "Use \"Content\" to inject an image into a new DICOM instance"; + + case ErrorCode_CreateDicomNoPayload: + return "No payload is present for one instance in the series"; + + case ErrorCode_CreateDicomUseDataUriScheme: + return "The payload of the DICOM instance must be specified according to Data URI scheme"; + + case ErrorCode_CreateDicomBadParent: + return "Trying to attach a new DICOM instance to an inexistent resource"; + + case ErrorCode_CreateDicomParentIsInstance: + return "Trying to attach a new DICOM instance to an instance (must be a series, study or patient)"; + + case ErrorCode_CreateDicomParentEncoding: + return "Unable to get the encoding of the parent resource"; + + case ErrorCode_UnknownModality: + return "Unknown modality"; + + case ErrorCode_BadJobOrdering: + return "Bad ordering of filters in a job"; + + case ErrorCode_JsonToLuaTable: + return "Cannot convert the given JSON object to a Lua table"; + + case ErrorCode_CannotCreateLua: + return "Cannot create the Lua context"; + + case ErrorCode_CannotExecuteLua: + return "Cannot execute a Lua command"; + + case ErrorCode_LuaAlreadyExecuted: + return "Arguments cannot be pushed after the Lua function is executed"; + + case ErrorCode_LuaBadOutput: + return "The Lua function does not give the expected number of outputs"; + + case ErrorCode_NotLuaPredicate: + return "The Lua function is not a predicate (only true/false outputs allowed)"; + + case ErrorCode_LuaReturnsNoString: + return "The Lua function does not return a string"; + + case ErrorCode_StorageAreaAlreadyRegistered: + return "Another plugin has already registered a custom storage area"; + + case ErrorCode_DatabaseBackendAlreadyRegistered: + return "Another plugin has already registered a custom database back-end"; + + case ErrorCode_DatabaseNotInitialized: + return "Plugin trying to call the database during its initialization"; + + case ErrorCode_SslDisabled: + return "Orthanc has been built without SSL support"; + + case ErrorCode_CannotOrderSlices: + return "Unable to order the slices of the series"; + + case ErrorCode_NoWorklistHandler: + return "No request handler factory for DICOM C-Find Modality SCP"; + + default: + if (error >= ErrorCode_START_PLUGINS) + { + return "Error encountered within some plugin"; + } + else + { + return "Unknown error code"; + } + } + } + + + const char* EnumerationToString(HttpMethod method) + { + switch (method) + { + case HttpMethod_Get: + return "GET"; + + case HttpMethod_Post: + return "POST"; + + case HttpMethod_Delete: + return "DELETE"; + + case HttpMethod_Put: + return "PUT"; + + default: + return "?"; + } + } + + + const char* EnumerationToString(HttpStatus status) + { + switch (status) + { + case HttpStatus_100_Continue: + return "Continue"; + + case HttpStatus_101_SwitchingProtocols: + return "Switching Protocols"; + + case HttpStatus_102_Processing: + return "Processing"; + + case HttpStatus_200_Ok: + return "OK"; + + case HttpStatus_201_Created: + return "Created"; + + case HttpStatus_202_Accepted: + return "Accepted"; + + case HttpStatus_203_NonAuthoritativeInformation: + return "Non-Authoritative Information"; + + case HttpStatus_204_NoContent: + return "No Content"; + + case HttpStatus_205_ResetContent: + return "Reset Content"; + + case HttpStatus_206_PartialContent: + return "Partial Content"; + + case HttpStatus_207_MultiStatus: + return "Multi-Status"; + + case HttpStatus_208_AlreadyReported: + return "Already Reported"; + + case HttpStatus_226_IMUsed: + return "IM Used"; + + case HttpStatus_300_MultipleChoices: + return "Multiple Choices"; + + case HttpStatus_301_MovedPermanently: + return "Moved Permanently"; + + case HttpStatus_302_Found: + return "Found"; + + case HttpStatus_303_SeeOther: + return "See Other"; + + case HttpStatus_304_NotModified: + return "Not Modified"; + + case HttpStatus_305_UseProxy: + return "Use Proxy"; + + case HttpStatus_307_TemporaryRedirect: + return "Temporary Redirect"; + + case HttpStatus_400_BadRequest: + return "Bad Request"; + + case HttpStatus_401_Unauthorized: + return "Unauthorized"; + + case HttpStatus_402_PaymentRequired: + return "Payment Required"; + + case HttpStatus_403_Forbidden: + return "Forbidden"; + + case HttpStatus_404_NotFound: + return "Not Found"; + + case HttpStatus_405_MethodNotAllowed: + return "Method Not Allowed"; + + case HttpStatus_406_NotAcceptable: + return "Not Acceptable"; + + case HttpStatus_407_ProxyAuthenticationRequired: + return "Proxy Authentication Required"; + + case HttpStatus_408_RequestTimeout: + return "Request Timeout"; + + case HttpStatus_409_Conflict: + return "Conflict"; + + case HttpStatus_410_Gone: + return "Gone"; + + case HttpStatus_411_LengthRequired: + return "Length Required"; + + case HttpStatus_412_PreconditionFailed: + return "Precondition Failed"; + + case HttpStatus_413_RequestEntityTooLarge: + return "Request Entity Too Large"; + + case HttpStatus_414_RequestUriTooLong: + return "Request-URI Too Long"; + + case HttpStatus_415_UnsupportedMediaType: + return "Unsupported Media Type"; + + case HttpStatus_416_RequestedRangeNotSatisfiable: + return "Requested Range Not Satisfiable"; + + case HttpStatus_417_ExpectationFailed: + return "Expectation Failed"; + + case HttpStatus_422_UnprocessableEntity: + return "Unprocessable Entity"; + + case HttpStatus_423_Locked: + return "Locked"; + + case HttpStatus_424_FailedDependency: + return "Failed Dependency"; + + case HttpStatus_426_UpgradeRequired: + return "Upgrade Required"; + + case HttpStatus_500_InternalServerError: + return "Internal Server Error"; + + case HttpStatus_501_NotImplemented: + return "Not Implemented"; + + case HttpStatus_502_BadGateway: + return "Bad Gateway"; + + case HttpStatus_503_ServiceUnavailable: + return "Service Unavailable"; + + case HttpStatus_504_GatewayTimeout: + return "Gateway Timeout"; + + case HttpStatus_505_HttpVersionNotSupported: + return "HTTP Version Not Supported"; + + case HttpStatus_506_VariantAlsoNegotiates: + return "Variant Also Negotiates"; + + case HttpStatus_507_InsufficientStorage: + return "Insufficient Storage"; + + case HttpStatus_509_BandwidthLimitExceeded: + return "Bandwidth Limit Exceeded"; + + case HttpStatus_510_NotExtended: + return "Not Extended"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + const char* EnumerationToString(ResourceType type) + { + switch (type) + { + case ResourceType_Patient: + return "Patient"; + + case ResourceType_Study: + return "Study"; + + case ResourceType_Series: + return "Series"; + + case ResourceType_Instance: + return "Instance"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + const char* EnumerationToString(ImageFormat format) + { + switch (format) + { + case ImageFormat_Png: + return "Png"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + const char* EnumerationToString(Encoding encoding) + { + switch (encoding) + { + case Encoding_Ascii: + return "Ascii"; + + case Encoding_Utf8: + return "Utf8"; + + case Encoding_Latin1: + return "Latin1"; + + case Encoding_Latin2: + return "Latin2"; + + case Encoding_Latin3: + return "Latin3"; + + case Encoding_Latin4: + return "Latin4"; + + case Encoding_Latin5: + return "Latin5"; + + case Encoding_Cyrillic: + return "Cyrillic"; + + case Encoding_Windows1251: + return "Windows1251"; + + case Encoding_Arabic: + return "Arabic"; + + case Encoding_Greek: + return "Greek"; + + case Encoding_Hebrew: + return "Hebrew"; + + case Encoding_Thai: + return "Thai"; + + case Encoding_Japanese: + return "Japanese"; + + case Encoding_Chinese: + return "Chinese"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + const char* EnumerationToString(PhotometricInterpretation photometric) + { + switch (photometric) + { + case PhotometricInterpretation_RGB: + return "RGB"; + + case PhotometricInterpretation_Monochrome1: + return "Monochrome1"; + + case PhotometricInterpretation_Monochrome2: + return "Monochrome2"; + + case PhotometricInterpretation_ARGB: + return "ARGB"; + + case PhotometricInterpretation_CMYK: + return "CMYK"; + + case PhotometricInterpretation_HSV: + return "HSV"; + + case PhotometricInterpretation_Palette: + return "Palette color"; + + case PhotometricInterpretation_YBRFull: + return "YBR full"; + + case PhotometricInterpretation_YBRFull422: + return "YBR full 422"; + + case PhotometricInterpretation_YBRPartial420: + return "YBR partial 420"; + + case PhotometricInterpretation_YBRPartial422: + return "YBR partial 422"; + + case PhotometricInterpretation_YBR_ICT: + return "YBR ICT"; + + case PhotometricInterpretation_YBR_RCT: + return "YBR RCT"; + + case PhotometricInterpretation_Unknown: + return "Unknown"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + const char* EnumerationToString(RequestOrigin origin) + { + switch (origin) + { + case RequestOrigin_Unknown: + return "Unknown"; + + case RequestOrigin_DicomProtocol: + return "DicomProtocol"; + + case RequestOrigin_RestApi: + return "RestApi"; + + case RequestOrigin_Plugins: + return "Plugins"; + + case RequestOrigin_Lua: + return "Lua"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + const char* EnumerationToString(LogLevel level) + { + switch (level) + { + case LogLevel_Error: + return "ERROR"; + + case LogLevel_Warning: + return "WARNING"; + + case LogLevel_Info: + return "INFO"; + + case LogLevel_Trace: + return "TRACE"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + Encoding StringToEncoding(const char* encoding) + { + std::string s(encoding); + Toolbox::ToUpperCase(s); + + if (s == "UTF8") + { + return Encoding_Utf8; + } + + if (s == "ASCII") + { + return Encoding_Ascii; + } + + if (s == "LATIN1") + { + return Encoding_Latin1; + } + + if (s == "LATIN2") + { + return Encoding_Latin2; + } + + if (s == "LATIN3") + { + return Encoding_Latin3; + } + + if (s == "LATIN4") + { + return Encoding_Latin4; + } + + if (s == "LATIN5") + { + return Encoding_Latin5; + } + + if (s == "CYRILLIC") + { + return Encoding_Cyrillic; + } + + if (s == "WINDOWS1251") + { + return Encoding_Windows1251; + } + + if (s == "ARABIC") + { + return Encoding_Arabic; + } + + if (s == "GREEK") + { + return Encoding_Greek; + } + + if (s == "HEBREW") + { + return Encoding_Hebrew; + } + + if (s == "THAI") + { + return Encoding_Thai; + } + + if (s == "JAPANESE") + { + return Encoding_Japanese; + } + + if (s == "CHINESE") + { + return Encoding_Chinese; + } + + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + + + ResourceType StringToResourceType(const char* type) + { + std::string s(type); + Toolbox::ToUpperCase(s); + + if (s == "PATIENT" || s == "PATIENTS") + { + return ResourceType_Patient; + } + else if (s == "STUDY" || s == "STUDIES") + { + return ResourceType_Study; + } + else if (s == "SERIES") + { + return ResourceType_Series; + } + else if (s == "INSTANCE" || s == "IMAGE" || + s == "INSTANCES" || s == "IMAGES") + { + return ResourceType_Instance; + } + + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + + + ImageFormat StringToImageFormat(const char* format) + { + std::string s(format); + Toolbox::ToUpperCase(s); + + if (s == "PNG") + { + return ImageFormat_Png; + } + + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + + + LogLevel StringToLogLevel(const char *level) + { + if (strcmp(level, "ERROR") == 0) + { + return LogLevel_Error; + } + else if (strcmp(level, "WARNING") == 0) + { + return LogLevel_Warning; + } + else if (strcmp(level, "INFO") == 0) + { + return LogLevel_Info; + } + else if (strcmp(level, "TRACE") == 0) + { + return LogLevel_Trace; + } + else + { + throw OrthancException(ErrorCode_InternalError); + } + } + + + unsigned int GetBytesPerPixel(PixelFormat format) + { + switch (format) + { + case PixelFormat_Grayscale8: + return 1; + + case PixelFormat_Grayscale16: + case PixelFormat_SignedGrayscale16: + return 2; + + case PixelFormat_RGB24: + return 3; + + case PixelFormat_RGBA32: + return 4; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + bool GetDicomEncoding(Encoding& encoding, + const char* specificCharacterSet) + { + std::string s = specificCharacterSet; + Toolbox::ToUpperCase(s); + + // http://www.dabsoft.ch/dicom/3/C.12.1.1.2/ + // https://github.com/dcm4che/dcm4che/blob/master/dcm4che-core/src/main/java/org/dcm4che3/data/SpecificCharacterSet.java + if (s == "ISO_IR 6" || + s == "ISO_IR 192" || + s == "ISO 2022 IR 6") + { + encoding = Encoding_Utf8; + } + else if (s == "ISO_IR 100" || + s == "ISO 2022 IR 100") + { + encoding = Encoding_Latin1; + } + else if (s == "ISO_IR 101" || + s == "ISO 2022 IR 101") + { + encoding = Encoding_Latin2; + } + else if (s == "ISO_IR 109" || + s == "ISO 2022 IR 109") + { + encoding = Encoding_Latin3; + } + else if (s == "ISO_IR 110" || + s == "ISO 2022 IR 110") + { + encoding = Encoding_Latin4; + } + else if (s == "ISO_IR 148" || + s == "ISO 2022 IR 148") + { + encoding = Encoding_Latin5; + } + else if (s == "ISO_IR 144" || + s == "ISO 2022 IR 144") + { + encoding = Encoding_Cyrillic; + } + else if (s == "ISO_IR 127" || + s == "ISO 2022 IR 127") + { + encoding = Encoding_Arabic; + } + else if (s == "ISO_IR 126" || + s == "ISO 2022 IR 126") + { + encoding = Encoding_Greek; + } + else if (s == "ISO_IR 138" || + s == "ISO 2022 IR 138") + { + encoding = Encoding_Hebrew; + } + else if (s == "ISO_IR 166" || s == "ISO 2022 IR 166") + { + encoding = Encoding_Thai; + } + else if (s == "ISO_IR 13" || s == "ISO 2022 IR 13") + { + encoding = Encoding_Japanese; + } + else if (s == "GB18030") + { + encoding = Encoding_Chinese; + } + /* + else if (s == "ISO 2022 IR 149") + { + TODO + } + else if (s == "ISO 2022 IR 159") + { + TODO + } + else if (s == "ISO 2022 IR 87") + { + TODO + } + */ + else + { + return false; + } + + // The encoding was properly detected + return true; + } + + + ResourceType GetChildResourceType(ResourceType type) + { + switch (type) + { + case ResourceType_Patient: + return ResourceType_Study; + + case ResourceType_Study: + return ResourceType_Series; + + case ResourceType_Series: + return ResourceType_Instance; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + ResourceType GetParentResourceType(ResourceType type) + { + switch (type) + { + case ResourceType_Study: + return ResourceType_Patient; + + case ResourceType_Series: + return ResourceType_Study; + + case ResourceType_Instance: + return ResourceType_Series; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + DicomModule GetModule(ResourceType type) + { + switch (type) + { + case ResourceType_Patient: + return DicomModule_Patient; + + case ResourceType_Study: + return DicomModule_Study; + + case ResourceType_Series: + return DicomModule_Series; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + + const char* GetDicomSpecificCharacterSet(Encoding encoding) + { + // http://www.dabsoft.ch/dicom/3/C.12.1.1.2/ + switch (encoding) + { + case Encoding_Utf8: + case Encoding_Ascii: + return "ISO_IR 192"; + + case Encoding_Latin1: + return "ISO_IR 100"; + + case Encoding_Latin2: + return "ISO_IR 101"; + + case Encoding_Latin3: + return "ISO_IR 109"; + + case Encoding_Latin4: + return "ISO_IR 110"; + + case Encoding_Latin5: + return "ISO_IR 148"; + + case Encoding_Cyrillic: + return "ISO_IR 144"; + + case Encoding_Arabic: + return "ISO_IR 127"; + + case Encoding_Greek: + return "ISO_IR 126"; + + case Encoding_Hebrew: + return "ISO_IR 138"; + + case Encoding_Japanese: + return "ISO_IR 13"; + + case Encoding_Chinese: + return "GB18030"; + + case Encoding_Thai: + return "ISO_IR 166"; + + default: + throw OrthancException(ErrorCode_ParameterOutOfRange); + } + } + + + // This function is autogenerated by the script + // "Resources/GenerateErrorCodes.py" + HttpStatus ConvertErrorCodeToHttpStatus(ErrorCode error) + { + switch (error) + { + case ErrorCode_Success: + return HttpStatus_200_Ok; + + case ErrorCode_ParameterOutOfRange: + return HttpStatus_400_BadRequest; + + case ErrorCode_BadParameterType: + return HttpStatus_400_BadRequest; + + case ErrorCode_InexistentItem: + return HttpStatus_404_NotFound; + + case ErrorCode_BadRequest: + return HttpStatus_400_BadRequest; + + case ErrorCode_UriSyntax: + return HttpStatus_400_BadRequest; + + case ErrorCode_InexistentFile: + return HttpStatus_404_NotFound; + + case ErrorCode_BadFileFormat: + return HttpStatus_400_BadRequest; + + case ErrorCode_UnknownResource: + return HttpStatus_404_NotFound; + + case ErrorCode_InexistentTag: + return HttpStatus_404_NotFound; + + case ErrorCode_BadJson: + return HttpStatus_400_BadRequest; + + case ErrorCode_Unauthorized: + return HttpStatus_401_Unauthorized; + + case ErrorCode_NotAcceptable: + return HttpStatus_406_NotAcceptable; + + default: + return HttpStatus_500_InternalServerError; + } + } + + + bool IsUserContentType(FileContentType type) + { + return (type >= FileContentType_StartUser && + type <= FileContentType_EndUser); + } +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Enumerations.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Enumerations.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,470 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +namespace Orthanc +{ + enum Endianness + { + Endianness_Unknown, + Endianness_Big, + Endianness_Little + }; + + // This enumeration is autogenerated by the script + // "Resources/GenerateErrorCodes.py" + enum ErrorCode + { + ErrorCode_InternalError = -1 /*!< Internal error */, + ErrorCode_Success = 0 /*!< Success */, + ErrorCode_Plugin = 1 /*!< Error encountered within the plugin engine */, + ErrorCode_NotImplemented = 2 /*!< Not implemented yet */, + ErrorCode_ParameterOutOfRange = 3 /*!< Parameter out of range */, + ErrorCode_NotEnoughMemory = 4 /*!< Not enough memory */, + ErrorCode_BadParameterType = 5 /*!< Bad type for a parameter */, + ErrorCode_BadSequenceOfCalls = 6 /*!< Bad sequence of calls */, + ErrorCode_InexistentItem = 7 /*!< Accessing an inexistent item */, + ErrorCode_BadRequest = 8 /*!< Bad request */, + ErrorCode_NetworkProtocol = 9 /*!< Error in the network protocol */, + ErrorCode_SystemCommand = 10 /*!< Error while calling a system command */, + ErrorCode_Database = 11 /*!< Error with the database engine */, + ErrorCode_UriSyntax = 12 /*!< Badly formatted URI */, + ErrorCode_InexistentFile = 13 /*!< Inexistent file */, + ErrorCode_CannotWriteFile = 14 /*!< Cannot write to file */, + ErrorCode_BadFileFormat = 15 /*!< Bad file format */, + ErrorCode_Timeout = 16 /*!< Timeout */, + ErrorCode_UnknownResource = 17 /*!< Unknown resource */, + ErrorCode_IncompatibleDatabaseVersion = 18 /*!< Incompatible version of the database */, + ErrorCode_FullStorage = 19 /*!< The file storage is full */, + ErrorCode_CorruptedFile = 20 /*!< Corrupted file (e.g. inconsistent MD5 hash) */, + ErrorCode_InexistentTag = 21 /*!< Inexistent tag */, + ErrorCode_ReadOnly = 22 /*!< Cannot modify a read-only data structure */, + ErrorCode_IncompatibleImageFormat = 23 /*!< Incompatible format of the images */, + ErrorCode_IncompatibleImageSize = 24 /*!< Incompatible size of the images */, + ErrorCode_SharedLibrary = 25 /*!< Error while using a shared library (plugin) */, + ErrorCode_UnknownPluginService = 26 /*!< Plugin invoking an unknown service */, + ErrorCode_UnknownDicomTag = 27 /*!< Unknown DICOM tag */, + ErrorCode_BadJson = 28 /*!< Cannot parse a JSON document */, + ErrorCode_Unauthorized = 29 /*!< Bad credentials were provided to an HTTP request */, + ErrorCode_BadFont = 30 /*!< Badly formatted font file */, + ErrorCode_DatabasePlugin = 31 /*!< The plugin implementing a custom database back-end does not fulfill the proper interface */, + ErrorCode_StorageAreaPlugin = 32 /*!< Error in the plugin implementing a custom storage area */, + ErrorCode_EmptyRequest = 33 /*!< The request is empty */, + ErrorCode_NotAcceptable = 34 /*!< Cannot send a response which is acceptable according to the Accept HTTP header */, + ErrorCode_SQLiteNotOpened = 1000 /*!< SQLite: The database is not opened */, + ErrorCode_SQLiteAlreadyOpened = 1001 /*!< SQLite: Connection is already open */, + ErrorCode_SQLiteCannotOpen = 1002 /*!< SQLite: Unable to open the database */, + ErrorCode_SQLiteStatementAlreadyUsed = 1003 /*!< SQLite: This cached statement is already being referred to */, + ErrorCode_SQLiteExecute = 1004 /*!< SQLite: Cannot execute a command */, + ErrorCode_SQLiteRollbackWithoutTransaction = 1005 /*!< SQLite: Rolling back a nonexistent transaction (have you called Begin()?) */, + ErrorCode_SQLiteCommitWithoutTransaction = 1006 /*!< SQLite: Committing a nonexistent transaction */, + ErrorCode_SQLiteRegisterFunction = 1007 /*!< SQLite: Unable to register a function */, + ErrorCode_SQLiteFlush = 1008 /*!< SQLite: Unable to flush the database */, + ErrorCode_SQLiteCannotRun = 1009 /*!< SQLite: Cannot run a cached statement */, + ErrorCode_SQLiteCannotStep = 1010 /*!< SQLite: Cannot step over a cached statement */, + ErrorCode_SQLiteBindOutOfRange = 1011 /*!< SQLite: Bing a value while out of range (serious error) */, + ErrorCode_SQLitePrepareStatement = 1012 /*!< SQLite: Cannot prepare a cached statement */, + ErrorCode_SQLiteTransactionAlreadyStarted = 1013 /*!< SQLite: Beginning the same transaction twice */, + ErrorCode_SQLiteTransactionCommit = 1014 /*!< SQLite: Failure when committing the transaction */, + ErrorCode_SQLiteTransactionBegin = 1015 /*!< SQLite: Cannot start a transaction */, + ErrorCode_DirectoryOverFile = 2000 /*!< The directory to be created is already occupied by a regular file */, + ErrorCode_FileStorageCannotWrite = 2001 /*!< Unable to create a subdirectory or a file in the file storage */, + ErrorCode_DirectoryExpected = 2002 /*!< The specified path does not point to a directory */, + ErrorCode_HttpPortInUse = 2003 /*!< The TCP port of the HTTP server is already in use */, + ErrorCode_DicomPortInUse = 2004 /*!< The TCP port of the DICOM server is already in use */, + ErrorCode_BadHttpStatusInRest = 2005 /*!< This HTTP status is not allowed in a REST API */, + ErrorCode_RegularFileExpected = 2006 /*!< The specified path does not point to a regular file */, + ErrorCode_PathToExecutable = 2007 /*!< Unable to get the path to the executable */, + ErrorCode_MakeDirectory = 2008 /*!< Cannot create a directory */, + ErrorCode_BadApplicationEntityTitle = 2009 /*!< An application entity title (AET) cannot be empty or be longer than 16 characters */, + ErrorCode_NoCFindHandler = 2010 /*!< No request handler factory for DICOM C-FIND SCP */, + ErrorCode_NoCMoveHandler = 2011 /*!< No request handler factory for DICOM C-MOVE SCP */, + ErrorCode_NoCStoreHandler = 2012 /*!< No request handler factory for DICOM C-STORE SCP */, + ErrorCode_NoApplicationEntityFilter = 2013 /*!< No application entity filter */, + ErrorCode_NoSopClassOrInstance = 2014 /*!< DicomUserConnection: Unable to find the SOP class and instance */, + ErrorCode_NoPresentationContext = 2015 /*!< DicomUserConnection: No acceptable presentation context for modality */, + ErrorCode_DicomFindUnavailable = 2016 /*!< DicomUserConnection: The C-FIND command is not supported by the remote SCP */, + ErrorCode_DicomMoveUnavailable = 2017 /*!< DicomUserConnection: The C-MOVE command is not supported by the remote SCP */, + ErrorCode_CannotStoreInstance = 2018 /*!< Cannot store an instance */, + ErrorCode_CreateDicomNotString = 2019 /*!< Only string values are supported when creating DICOM instances */, + ErrorCode_CreateDicomOverrideTag = 2020 /*!< Trying to override a value inherited from a parent module */, + ErrorCode_CreateDicomUseContent = 2021 /*!< Use \"Content\" to inject an image into a new DICOM instance */, + ErrorCode_CreateDicomNoPayload = 2022 /*!< No payload is present for one instance in the series */, + ErrorCode_CreateDicomUseDataUriScheme = 2023 /*!< The payload of the DICOM instance must be specified according to Data URI scheme */, + ErrorCode_CreateDicomBadParent = 2024 /*!< Trying to attach a new DICOM instance to an inexistent resource */, + ErrorCode_CreateDicomParentIsInstance = 2025 /*!< Trying to attach a new DICOM instance to an instance (must be a series, study or patient) */, + ErrorCode_CreateDicomParentEncoding = 2026 /*!< Unable to get the encoding of the parent resource */, + ErrorCode_UnknownModality = 2027 /*!< Unknown modality */, + ErrorCode_BadJobOrdering = 2028 /*!< Bad ordering of filters in a job */, + ErrorCode_JsonToLuaTable = 2029 /*!< Cannot convert the given JSON object to a Lua table */, + ErrorCode_CannotCreateLua = 2030 /*!< Cannot create the Lua context */, + ErrorCode_CannotExecuteLua = 2031 /*!< Cannot execute a Lua command */, + ErrorCode_LuaAlreadyExecuted = 2032 /*!< Arguments cannot be pushed after the Lua function is executed */, + ErrorCode_LuaBadOutput = 2033 /*!< The Lua function does not give the expected number of outputs */, + ErrorCode_NotLuaPredicate = 2034 /*!< The Lua function is not a predicate (only true/false outputs allowed) */, + ErrorCode_LuaReturnsNoString = 2035 /*!< The Lua function does not return a string */, + ErrorCode_StorageAreaAlreadyRegistered = 2036 /*!< Another plugin has already registered a custom storage area */, + ErrorCode_DatabaseBackendAlreadyRegistered = 2037 /*!< Another plugin has already registered a custom database back-end */, + ErrorCode_DatabaseNotInitialized = 2038 /*!< Plugin trying to call the database during its initialization */, + ErrorCode_SslDisabled = 2039 /*!< Orthanc has been built without SSL support */, + ErrorCode_CannotOrderSlices = 2040 /*!< Unable to order the slices of the series */, + ErrorCode_NoWorklistHandler = 2041 /*!< No request handler factory for DICOM C-Find Modality SCP */, + ErrorCode_START_PLUGINS = 1000000 + }; + + enum LogLevel + { + LogLevel_Error, + LogLevel_Warning, + LogLevel_Info, + LogLevel_Trace + }; + + + /** + * {summary}{The memory layout of the pixels (resp. voxels) of a 2D (resp. 3D) image.} + **/ + enum PixelFormat + { + /** + * {summary}{Color image in RGB24 format.} + * {description}{This format describes a color image. The pixels are stored in 3 + * consecutive bytes. The memory layout is RGB.} + **/ + PixelFormat_RGB24 = 1, + + /** + * {summary}{Color image in RGBA32 format.} + * {description}{This format describes a color image. The pixels are stored in 4 + * consecutive bytes. The memory layout is RGBA.} + **/ + PixelFormat_RGBA32 = 2, + + /** + * {summary}{Graylevel 8bpp image.} + * {description}{The image is graylevel. Each pixel is unsigned and stored in one byte.} + **/ + PixelFormat_Grayscale8 = 3, + + /** + * {summary}{Graylevel, unsigned 16bpp image.} + * {description}{The image is graylevel. Each pixel is unsigned and stored in two bytes.} + **/ + PixelFormat_Grayscale16 = 4, + + /** + * {summary}{Graylevel, signed 16bpp image.} + * {description}{The image is graylevel. Each pixel is signed and stored in two bytes.} + **/ + PixelFormat_SignedGrayscale16 = 5 + }; + + + /** + * {summary}{The extraction mode specifies the way the values of the pixels are scaled when downloading a 2D image.} + **/ + enum ImageExtractionMode + { + /** + * {summary}{Rescaled to 8bpp.} + * {description}{The minimum value of the image is set to 0, and its maximum value is set to 255.} + **/ + ImageExtractionMode_Preview = 1, + + /** + * {summary}{Truncation to the [0, 255] range.} + **/ + ImageExtractionMode_UInt8 = 2, + + /** + * {summary}{Truncation to the [0, 65535] range.} + **/ + ImageExtractionMode_UInt16 = 3, + + /** + * {summary}{Truncation to the [-32768, 32767] range.} + **/ + ImageExtractionMode_Int16 = 4 + }; + + + /** + * Most common, non-joke and non-experimental HTTP status codes + * http://en.wikipedia.org/wiki/List_of_HTTP_status_codes + **/ + enum HttpStatus + { + HttpStatus_None = -1, + + // 1xx Informational + HttpStatus_100_Continue = 100, + HttpStatus_101_SwitchingProtocols = 101, + HttpStatus_102_Processing = 102, + + // 2xx Success + HttpStatus_200_Ok = 200, + HttpStatus_201_Created = 201, + HttpStatus_202_Accepted = 202, + HttpStatus_203_NonAuthoritativeInformation = 203, + HttpStatus_204_NoContent = 204, + HttpStatus_205_ResetContent = 205, + HttpStatus_206_PartialContent = 206, + HttpStatus_207_MultiStatus = 207, + HttpStatus_208_AlreadyReported = 208, + HttpStatus_226_IMUsed = 226, + + // 3xx Redirection + HttpStatus_300_MultipleChoices = 300, + HttpStatus_301_MovedPermanently = 301, + HttpStatus_302_Found = 302, + HttpStatus_303_SeeOther = 303, + HttpStatus_304_NotModified = 304, + HttpStatus_305_UseProxy = 305, + HttpStatus_307_TemporaryRedirect = 307, + + // 4xx Client Error + HttpStatus_400_BadRequest = 400, + HttpStatus_401_Unauthorized = 401, + HttpStatus_402_PaymentRequired = 402, + HttpStatus_403_Forbidden = 403, + HttpStatus_404_NotFound = 404, + HttpStatus_405_MethodNotAllowed = 405, + HttpStatus_406_NotAcceptable = 406, + HttpStatus_407_ProxyAuthenticationRequired = 407, + HttpStatus_408_RequestTimeout = 408, + HttpStatus_409_Conflict = 409, + HttpStatus_410_Gone = 410, + HttpStatus_411_LengthRequired = 411, + HttpStatus_412_PreconditionFailed = 412, + HttpStatus_413_RequestEntityTooLarge = 413, + HttpStatus_414_RequestUriTooLong = 414, + HttpStatus_415_UnsupportedMediaType = 415, + HttpStatus_416_RequestedRangeNotSatisfiable = 416, + HttpStatus_417_ExpectationFailed = 417, + HttpStatus_422_UnprocessableEntity = 422, + HttpStatus_423_Locked = 423, + HttpStatus_424_FailedDependency = 424, + HttpStatus_426_UpgradeRequired = 426, + + // 5xx Server Error + HttpStatus_500_InternalServerError = 500, + HttpStatus_501_NotImplemented = 501, + HttpStatus_502_BadGateway = 502, + HttpStatus_503_ServiceUnavailable = 503, + HttpStatus_504_GatewayTimeout = 504, + HttpStatus_505_HttpVersionNotSupported = 505, + HttpStatus_506_VariantAlsoNegotiates = 506, + HttpStatus_507_InsufficientStorage = 507, + HttpStatus_509_BandwidthLimitExceeded = 509, + HttpStatus_510_NotExtended = 510 + }; + + + enum HttpMethod + { + HttpMethod_Get = 0, + HttpMethod_Post = 1, + HttpMethod_Delete = 2, + HttpMethod_Put = 3 + }; + + + enum ImageFormat + { + ImageFormat_Png = 1 + }; + + + // https://en.wikipedia.org/wiki/HTTP_compression + enum HttpCompression + { + HttpCompression_None, + HttpCompression_Deflate, + HttpCompression_Gzip + }; + + + // http://www.dabsoft.ch/dicom/3/C.12.1.1.2/ + enum Encoding + { + Encoding_Ascii, + Encoding_Utf8, + Encoding_Latin1, + Encoding_Latin2, + Encoding_Latin3, + Encoding_Latin4, + Encoding_Latin5, // Turkish + Encoding_Cyrillic, + Encoding_Windows1251, // Windows-1251 (commonly used for Cyrillic) + Encoding_Arabic, + Encoding_Greek, + Encoding_Hebrew, + Encoding_Thai, // TIS 620-2533 + Encoding_Japanese, // JIS X 0201 (Shift JIS): Katakana + Encoding_Chinese // GB18030 - Chinese simplified + //Encoding_JapaneseKanji, // Multibyte - JIS X 0208: Kanji + //Encoding_JapaneseSupplementaryKanji, // Multibyte - JIS X 0212: Supplementary Kanji set + //Encoding_Korean, // Multibyte - KS X 1001: Hangul and Hanja + }; + + + // https://www.dabsoft.ch/dicom/3/C.7.6.3.1.2/ + enum PhotometricInterpretation + { + PhotometricInterpretation_ARGB, // Retired + PhotometricInterpretation_CMYK, // Retired + PhotometricInterpretation_HSV, // Retired + PhotometricInterpretation_Monochrome1, + PhotometricInterpretation_Monochrome2, + PhotometricInterpretation_Palette, + PhotometricInterpretation_RGB, + PhotometricInterpretation_YBRFull, + PhotometricInterpretation_YBRFull422, + PhotometricInterpretation_YBRPartial420, + PhotometricInterpretation_YBRPartial422, + PhotometricInterpretation_YBR_ICT, + PhotometricInterpretation_YBR_RCT, + PhotometricInterpretation_Unknown + }; + + enum DicomModule + { + DicomModule_Patient, + DicomModule_Study, + DicomModule_Series, + DicomModule_Instance, + DicomModule_Image + }; + + enum RequestOrigin + { + RequestOrigin_Unknown, + RequestOrigin_DicomProtocol, + RequestOrigin_RestApi, + RequestOrigin_Plugins, + RequestOrigin_Lua + }; + + + /** + * WARNING: Do not change the explicit values in the enumerations + * below this point. This would result in incompatible databases + * between versions of Orthanc! + **/ + + enum CompressionType + { + /** + * Buffer/file that is stored as-is, in a raw fashion, without + * compression. + **/ + CompressionType_None = 1, + + /** + * Buffer that is compressed using the "deflate" algorithm (RFC + * 1951), wrapped inside the zlib data format (RFC 1950), prefixed + * with a "uint64_t" (8 bytes) that encodes the size of the + * uncompressed buffer. If the compressed buffer is empty, its + * represents an empty uncompressed buffer. This format is + * internal to Orthanc. If the 8 first bytes are skipped AND the + * buffer is non-empty, the buffer is compatible with the + * "deflate" HTTP compression. + **/ + CompressionType_ZlibWithSize = 2 + }; + + enum FileContentType + { + // If you add a value below, insert it in "PluginStorageArea" in + // the file "Plugins/Engine/OrthancPlugins.cpp" + FileContentType_Unknown = 0, + FileContentType_Dicom = 1, + FileContentType_DicomAsJson = 2, + + // Make sure that the value "65535" can be stored into this enumeration + FileContentType_StartUser = 1024, + FileContentType_EndUser = 65535 + }; + + enum ResourceType + { + ResourceType_Patient = 1, + ResourceType_Study = 2, + ResourceType_Series = 3, + ResourceType_Instance = 4 + }; + + + const char* EnumerationToString(ErrorCode code); + + const char* EnumerationToString(HttpMethod method); + + const char* EnumerationToString(HttpStatus status); + + const char* EnumerationToString(ResourceType type); + + const char* EnumerationToString(ImageFormat format); + + const char* EnumerationToString(Encoding encoding); + + const char* EnumerationToString(PhotometricInterpretation photometric); + + const char* EnumerationToString(LogLevel level); + + const char* EnumerationToString(RequestOrigin origin); + + Encoding StringToEncoding(const char* encoding); + + ResourceType StringToResourceType(const char* type); + + ImageFormat StringToImageFormat(const char* format); + + LogLevel StringToLogLevel(const char* format); + + unsigned int GetBytesPerPixel(PixelFormat format); + + bool GetDicomEncoding(Encoding& encoding, + const char* specificCharacterSet); + + ResourceType GetChildResourceType(ResourceType type); + + ResourceType GetParentResourceType(ResourceType type); + + DicomModule GetModule(ResourceType type); + + const char* GetDicomSpecificCharacterSet(Encoding encoding); + + HttpStatus ConvertErrorCodeToHttpStatus(ErrorCode error); + + bool IsUserContentType(FileContentType type); +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/HttpClient.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/HttpClient.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,432 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#include "PrecompiledHeaders.h" +#include "HttpClient.h" + +#include "Toolbox.h" +#include "OrthancException.h" +#include "Logging.h" + +#include +#include +#include + + +static std::string globalCACertificates_; +static bool globalVerifyPeers_ = true; +static long globalTimeout_ = 0; + +extern "C" +{ + static CURLcode GetHttpStatus(CURLcode code, CURL* curl, long* status) + { + if (code == CURLE_OK) + { + code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, status); + return code; + } + else + { + *status = 0; + return code; + } + } + + // This is a dummy wrapper function to suppress any OpenSSL-related + // problem in valgrind. Inlining is prevented. +#if defined(__GNUC__) || defined(__clang__) + __attribute__((noinline)) +#endif + static CURLcode OrthancHttpClientPerformSSL(CURL* curl, long* status) + { + return GetHttpStatus(curl_easy_perform(curl), curl, status); + } +} + + + +namespace Orthanc +{ + struct HttpClient::PImpl + { + CURL* curl_; + struct curl_slist *postHeaders_; + }; + + + static void ThrowException(HttpStatus status) + { + switch (status) + { + case HttpStatus_400_BadRequest: + throw OrthancException(ErrorCode_BadRequest); + + case HttpStatus_401_Unauthorized: + throw OrthancException(ErrorCode_Unauthorized); + + case HttpStatus_404_NotFound: + throw OrthancException(ErrorCode_InexistentItem); + + default: + throw OrthancException(ErrorCode_NetworkProtocol); + } + } + + + + static CURLcode CheckCode(CURLcode code) + { + if (code != CURLE_OK) + { + LOG(ERROR) << "libCURL error: " + std::string(curl_easy_strerror(code)); + throw OrthancException(ErrorCode_NetworkProtocol); + } + + return code; + } + + + static size_t CurlCallback(void *buffer, size_t size, size_t nmemb, void *payload) + { + std::string& target = *(static_cast(payload)); + + size_t length = size * nmemb; + if (length == 0) + return 0; + + size_t pos = target.size(); + + target.resize(pos + length); + memcpy(&target.at(pos), buffer, length); + + return length; + } + + + void HttpClient::Setup() + { + pimpl_->postHeaders_ = NULL; + if ((pimpl_->postHeaders_ = curl_slist_append(pimpl_->postHeaders_, "Expect:")) == NULL) + { + throw OrthancException(ErrorCode_NotEnoughMemory); + } + + pimpl_->curl_ = curl_easy_init(); + if (!pimpl_->curl_) + { + curl_slist_free_all(pimpl_->postHeaders_); + throw OrthancException(ErrorCode_NotEnoughMemory); + } + + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_WRITEFUNCTION, &CurlCallback)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_HEADER, 0)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_FOLLOWLOCATION, 1)); + + // This fixes the "longjmp causes uninitialized stack frame" crash + // that happens on modern Linux versions. + // http://stackoverflow.com/questions/9191668/error-longjmp-causes-uninitialized-stack-frame + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_NOSIGNAL, 1)); + + url_ = ""; + method_ = HttpMethod_Get; + lastStatus_ = HttpStatus_200_Ok; + isVerbose_ = false; + timeout_ = globalTimeout_; + verifyPeers_ = globalVerifyPeers_; + } + + + HttpClient::HttpClient() : pimpl_(new PImpl) + { + Setup(); + } + + + HttpClient::HttpClient(const HttpClient& other) : pimpl_(new PImpl) + { + Setup(); + + if (other.IsVerbose()) + { + SetVerbose(true); + } + + if (other.credentials_.size() != 0) + { + credentials_ = other.credentials_; + } + } + + + HttpClient::~HttpClient() + { + curl_easy_cleanup(pimpl_->curl_); + curl_slist_free_all(pimpl_->postHeaders_); + } + + + void HttpClient::SetVerbose(bool isVerbose) + { + isVerbose_ = isVerbose; + + if (isVerbose_) + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_VERBOSE, 1)); + } + else + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_VERBOSE, 0)); + } + } + + + bool HttpClient::Apply(std::string& answer) + { + answer.clear(); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_URL, url_.c_str())); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_WRITEDATA, &answer)); + + // Setup HTTPS-related options +#if ORTHANC_SSL_ENABLED == 1 + if (IsHttpsVerifyPeers()) + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_CAINFO, GetHttpsCACertificates().c_str())); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_SSL_VERIFYPEER, 1)); + } + else + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_SSL_VERIFYPEER, 0)); + } +#endif + + // Reset the parameters from previous calls to Apply() + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_HTTPHEADER, NULL)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_HTTPGET, 0L)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POST, 0L)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_NOBODY, 0L)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_CUSTOMREQUEST, NULL)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POSTFIELDS, NULL)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POSTFIELDSIZE, 0)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_PROXY, NULL)); + + // Set timeouts + if (timeout_ <= 0) + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_TIMEOUT, 10)); /* default: 10 seconds */ + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_CONNECTTIMEOUT, 10)); /* default: 10 seconds */ + } + else + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_TIMEOUT, timeout_)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_CONNECTTIMEOUT, timeout_)); + } + + if (credentials_.size() != 0) + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_USERPWD, credentials_.c_str())); + } + + if (proxy_.size() != 0) + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_PROXY, proxy_.c_str())); + } + + switch (method_) + { + case HttpMethod_Get: + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_HTTPGET, 1L)); + break; + + case HttpMethod_Post: + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POST, 1L)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_HTTPHEADER, pimpl_->postHeaders_)); + break; + + case HttpMethod_Delete: + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_NOBODY, 1L)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_CUSTOMREQUEST, "DELETE")); + break; + + case HttpMethod_Put: + // http://stackoverflow.com/a/7570281/881731: Don't use + // CURLOPT_PUT if there is a body + + // CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_PUT, 1L)); + + curl_easy_setopt(pimpl_->curl_, CURLOPT_CUSTOMREQUEST, "PUT"); /* !!! */ + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_HTTPHEADER, pimpl_->postHeaders_)); + break; + + default: + throw OrthancException(ErrorCode_InternalError); + } + + + if (method_ == HttpMethod_Post || + method_ == HttpMethod_Put) + { + if (body_.size() > 0) + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POSTFIELDS, body_.c_str())); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POSTFIELDSIZE, body_.size())); + } + else + { + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POSTFIELDS, NULL)); + CheckCode(curl_easy_setopt(pimpl_->curl_, CURLOPT_POSTFIELDSIZE, 0)); + } + } + + + // Do the actual request + CURLcode code; + long status = 0; + + if (boost::starts_with(url_, "https://")) + { + code = OrthancHttpClientPerformSSL(pimpl_->curl_, &status); + } + else + { + code = GetHttpStatus(curl_easy_perform(pimpl_->curl_), pimpl_->curl_, &status); + } + + CheckCode(code); + + if (status == 0) + { + // This corresponds to a call to an inexistent host + lastStatus_ = HttpStatus_500_InternalServerError; + } + else + { + lastStatus_ = static_cast(status); + } + + return (status >= 200 && status < 300); + } + + + bool HttpClient::Apply(Json::Value& answer) + { + std::string s; + if (Apply(s)) + { + Json::Reader reader; + return reader.parse(s, answer); + } + else + { + return false; + } + } + + + void HttpClient::SetCredentials(const char* username, + const char* password) + { + credentials_ = std::string(username) + ":" + std::string(password); + } + + + const std::string& HttpClient::GetHttpsCACertificates() const + { + if (caCertificates_.empty()) + { + return globalCACertificates_; + } + else + { + return caCertificates_; + } + } + + + void HttpClient::GlobalInitialize(bool httpsVerifyPeers, + const std::string& httpsVerifyCertificates) + { + globalVerifyPeers_ = httpsVerifyPeers; + globalCACertificates_ = httpsVerifyCertificates; + +#if ORTHANC_SSL_ENABLED == 1 + if (httpsVerifyPeers) + { + if (globalCACertificates_.empty()) + { + LOG(WARNING) << "No certificates are provided to validate peers, " + << "set \"HttpsCACertificates\" if you need to do HTTPS requests"; + } + else + { + LOG(WARNING) << "HTTPS will use the CA certificates from this file: " << globalCACertificates_; + } + } + else + { + LOG(WARNING) << "The verification of the peers in HTTPS requests is disabled!"; + } +#endif + + CheckCode(curl_global_init(CURL_GLOBAL_DEFAULT)); + } + + + void HttpClient::GlobalFinalize() + { + curl_global_cleanup(); + } + + + void HttpClient::SetDefaultTimeout(long timeout) + { + LOG(INFO) << "Setting the default timeout for HTTP client connections: " << timeout << " seconds"; + globalTimeout_ = timeout; + } + + + void HttpClient::ApplyAndThrowException(std::string& answer) + { + if (!Apply(answer)) + { + ThrowException(GetLastStatus()); + } + } + + void HttpClient::ApplyAndThrowException(Json::Value& answer) + { + if (!Apply(answer)) + { + ThrowException(GetLastStatus()); + } + } +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/HttpClient.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/HttpClient.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,173 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include "Enumerations.h" + +#include +#include +#include + +namespace Orthanc +{ + class HttpClient + { + private: + struct PImpl; + boost::shared_ptr pimpl_; + + std::string url_; + std::string credentials_; + HttpMethod method_; + HttpStatus lastStatus_; + std::string body_; // This only makes sense for POST and PUT requests + bool isVerbose_; + long timeout_; + std::string proxy_; + bool verifyPeers_; + std::string caCertificates_; + + void Setup(); + + void operator= (const HttpClient&); // Forbidden + + public: + HttpClient(const HttpClient& base); + + HttpClient(); + + ~HttpClient(); + + void SetUrl(const char* url) + { + url_ = std::string(url); + } + + void SetUrl(const std::string& url) + { + url_ = url; + } + + const std::string& GetUrl() const + { + return url_; + } + + void SetMethod(HttpMethod method) + { + method_ = method; + } + + HttpMethod GetMethod() const + { + return method_; + } + + void SetTimeout(long seconds) + { + timeout_ = seconds; + } + + long GetTimeout() const + { + return timeout_; + } + + void SetBody(const std::string& data) + { + body_ = data; + } + + std::string& GetBody() + { + return body_; + } + + const std::string& GetBody() const + { + return body_; + } + + void SetVerbose(bool isVerbose); + + bool IsVerbose() const + { + return isVerbose_; + } + + bool Apply(std::string& answer); + + bool Apply(Json::Value& answer); + + HttpStatus GetLastStatus() const + { + return lastStatus_; + } + + void SetCredentials(const char* username, + const char* password); + + void SetProxy(const std::string& proxy) + { + proxy_ = proxy; + } + + void SetHttpsVerifyPeers(bool verify) + { + verifyPeers_ = verify; + } + + bool IsHttpsVerifyPeers() const + { + return verifyPeers_; + } + + void SetHttpsCACertificates(const std::string& certificates) + { + caCertificates_ = certificates; + } + + const std::string& GetHttpsCACertificates() const; + + static void GlobalInitialize(bool httpsVerifyPeers, + const std::string& httpsCACertificates); + + static void GlobalFinalize(); + + static void SetDefaultTimeout(long timeout); + + void ApplyAndThrowException(std::string& answer); + + void ApplyAndThrowException(Json::Value& answer); + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/ICommand.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/ICommand.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,48 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include "IDynamicObject.h" + +namespace Orthanc +{ + /** + * This class is the base class for the "Command" design pattern. + * http://en.wikipedia.org/wiki/Command_pattern + **/ + class ICommand : public IDynamicObject + { + public: + virtual bool Execute() = 0; + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/IDynamicObject.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/IDynamicObject.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,52 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include + +namespace Orthanc +{ + /** + * This class should be the ancestor to any class whose type is + * determined at the runtime, and that can be dynamically allocated. + * Being a child of IDynamicObject only implies the existence of a + * virtual destructor. + **/ + class IDynamicObject : public boost::noncopyable + { + public: + virtual ~IDynamicObject() + { + } + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Images/ImageAccessor.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Images/ImageAccessor.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,229 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#include "../PrecompiledHeaders.h" +#include "ImageAccessor.h" + +#include "../Logging.h" +#include "../OrthancException.h" +#include "../ChunkedBuffer.h" + +#include +#include +#include + + + +namespace Orthanc +{ + template + static void ToMatlabStringInternal(ChunkedBuffer& target, + const ImageAccessor& source) + { + target.AddChunk("double([ "); + + for (unsigned int y = 0; y < source.GetHeight(); y++) + { + const PixelType* p = reinterpret_cast(source.GetConstRow(y)); + + std::string s; + if (y > 0) + { + s = "; "; + } + + s.reserve(source.GetWidth() * 8); + + for (unsigned int x = 0; x < source.GetWidth(); x++, p++) + { + s += boost::lexical_cast(static_cast(*p)) + " "; + } + + target.AddChunk(s); + } + + target.AddChunk("])"); + } + + + static void RGB24ToMatlabString(ChunkedBuffer& target, + const ImageAccessor& source) + { + assert(source.GetFormat() == PixelFormat_RGB24); + + target.AddChunk("double(permute(reshape([ "); + + for (unsigned int y = 0; y < source.GetHeight(); y++) + { + const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); + + std::string s; + s.reserve(source.GetWidth() * 3 * 8); + + for (unsigned int x = 0; x < 3 * source.GetWidth(); x++, p++) + { + s += boost::lexical_cast(static_cast(*p)) + " "; + } + + target.AddChunk(s); + } + + target.AddChunk("], [ 3 " + boost::lexical_cast(source.GetHeight()) + + " " + boost::lexical_cast(source.GetWidth()) + " ]), [ 3 2 1 ]))"); + } + + + void* ImageAccessor::GetBuffer() const + { + if (readOnly_) + { +#if ORTHANC_ENABLE_LOGGING == 1 + LOG(ERROR) << "Trying to write on a read-only image"; +#endif + + throw OrthancException(ErrorCode_ReadOnly); + } + + return buffer_; + } + + + const void* ImageAccessor::GetConstRow(unsigned int y) const + { + if (buffer_ != NULL) + { + return reinterpret_cast(buffer_) + y * pitch_; + } + else + { + return NULL; + } + } + + + void* ImageAccessor::GetRow(unsigned int y) const + { + if (readOnly_) + { +#if ORTHANC_ENABLE_LOGGING == 1 + LOG(ERROR) << "Trying to write on a read-only image"; +#endif + + throw OrthancException(ErrorCode_ReadOnly); + } + + if (buffer_ != NULL) + { + return reinterpret_cast(buffer_) + y * pitch_; + } + else + { + return NULL; + } + } + + + void ImageAccessor::AssignEmpty(PixelFormat format) + { + readOnly_ = false; + format_ = format; + width_ = 0; + height_ = 0; + pitch_ = 0; + buffer_ = NULL; + } + + + void ImageAccessor::AssignReadOnly(PixelFormat format, + unsigned int width, + unsigned int height, + unsigned int pitch, + const void *buffer) + { + readOnly_ = true; + format_ = format; + width_ = width; + height_ = height; + pitch_ = pitch; + buffer_ = const_cast(buffer); + + assert(GetBytesPerPixel() * width_ <= pitch_); + } + + + void ImageAccessor::AssignWritable(PixelFormat format, + unsigned int width, + unsigned int height, + unsigned int pitch, + void *buffer) + { + readOnly_ = false; + format_ = format; + width_ = width; + height_ = height; + pitch_ = pitch; + buffer_ = buffer; + + assert(GetBytesPerPixel() * width_ <= pitch_); + } + + + void ImageAccessor::ToMatlabString(std::string& target) const + { + ChunkedBuffer buffer; + + switch (GetFormat()) + { + case PixelFormat_Grayscale8: + ToMatlabStringInternal(buffer, *this); + break; + + case PixelFormat_Grayscale16: + ToMatlabStringInternal(buffer, *this); + break; + + case PixelFormat_SignedGrayscale16: + ToMatlabStringInternal(buffer, *this); + break; + + case PixelFormat_RGB24: + RGB24ToMatlabString(buffer, *this); + break; + + default: + throw OrthancException(ErrorCode_NotImplemented); + } + + buffer.Flatten(target); + } + +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Images/ImageAccessor.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Images/ImageAccessor.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,123 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include "../Enumerations.h" + +#include + +namespace Orthanc +{ + class ImageAccessor + { + private: + bool readOnly_; + PixelFormat format_; + unsigned int width_; + unsigned int height_; + unsigned int pitch_; + void *buffer_; + + public: + ImageAccessor() + { + AssignEmpty(PixelFormat_Grayscale8); + } + + virtual ~ImageAccessor() + { + } + + bool IsReadOnly() const + { + return readOnly_; + } + + PixelFormat GetFormat() const + { + return format_; + } + + unsigned int GetBytesPerPixel() const + { + return ::Orthanc::GetBytesPerPixel(format_); + } + + unsigned int GetWidth() const + { + return width_; + } + + unsigned int GetHeight() const + { + return height_; + } + + unsigned int GetPitch() const + { + return pitch_; + } + + unsigned int GetSize() const + { + return GetHeight() * GetPitch(); + } + + const void* GetConstBuffer() const + { + return buffer_; + } + + void* GetBuffer() const; + + const void* GetConstRow(unsigned int y) const; + + void* GetRow(unsigned int y) const; + + void AssignEmpty(PixelFormat format); + + void AssignReadOnly(PixelFormat format, + unsigned int width, + unsigned int height, + unsigned int pitch, + const void *buffer); + + void AssignWritable(PixelFormat format, + unsigned int width, + unsigned int height, + unsigned int pitch, + void *buffer); + + void ToMatlabString(std::string& target) const; + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Images/PngReader.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Images/PngReader.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,313 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#include "../PrecompiledHeaders.h" +#include "PngReader.h" + +#include "../OrthancException.h" +#include "../Toolbox.h" + +#include +#include // For memcpy() + +namespace Orthanc +{ + namespace + { + struct FileRabi + { + FILE* fp_; + + FileRabi(const char* filename) + { + fp_ = fopen(filename, "rb"); + if (!fp_) + { + throw OrthancException(ErrorCode_InexistentFile); + } + } + + ~FileRabi() + { + if (fp_) + fclose(fp_); + } + }; + } + + + struct PngReader::PngRabi + { + png_structp png_; + png_infop info_; + png_infop endInfo_; + + void Destruct() + { + if (png_) + { + png_destroy_read_struct(&png_, &info_, &endInfo_); + + png_ = NULL; + info_ = NULL; + endInfo_ = NULL; + } + } + + PngRabi() + { + png_ = NULL; + info_ = NULL; + endInfo_ = NULL; + + png_ = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (!png_) + { + throw OrthancException(ErrorCode_NotEnoughMemory); + } + + info_ = png_create_info_struct(png_); + if (!info_) + { + png_destroy_read_struct(&png_, NULL, NULL); + throw OrthancException(ErrorCode_NotEnoughMemory); + } + + endInfo_ = png_create_info_struct(png_); + if (!info_) + { + png_destroy_read_struct(&png_, &info_, NULL); + throw OrthancException(ErrorCode_NotEnoughMemory); + } + } + + ~PngRabi() + { + Destruct(); + } + + static void MemoryCallback(png_structp png_ptr, + png_bytep data, + png_size_t size); + }; + + + void PngReader::CheckHeader(const void* header) + { + int is_png = !png_sig_cmp((png_bytep) header, 0, 8); + if (!is_png) + { + throw OrthancException(ErrorCode_BadFileFormat); + } + } + + PngReader::PngReader() + { + } + + void PngReader::Read(PngRabi& rabi) + { + png_set_sig_bytes(rabi.png_, 8); + + png_read_info(rabi.png_, rabi.info_); + + png_uint_32 width, height; + int bit_depth, color_type, interlace_type; + int compression_type, filter_method; + // get size and bit-depth of the PNG-image + png_get_IHDR(rabi.png_, rabi.info_, + &width, &height, + &bit_depth, &color_type, &interlace_type, + &compression_type, &filter_method); + + PixelFormat format; + unsigned int pitch; + + if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth == 8) + { + format = PixelFormat_Grayscale8; + pitch = width; + } + else if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth == 16) + { + format = PixelFormat_Grayscale16; + pitch = 2 * width; + + if (Toolbox::DetectEndianness() == Endianness_Little) + { + png_set_swap(rabi.png_); + } + } + else if (color_type == PNG_COLOR_TYPE_RGB && bit_depth == 8) + { + format = PixelFormat_RGB24; + pitch = 3 * width; + } + else if (color_type == PNG_COLOR_TYPE_RGBA && bit_depth == 8) + { + format = PixelFormat_RGBA32; + pitch = 4 * width; + } + else + { + throw OrthancException(ErrorCode_NotImplemented); + } + + data_.resize(height * pitch); + + if (height == 0 || width == 0) + { + // Empty image, we are done + AssignEmpty(format); + return; + } + + png_read_update_info(rabi.png_, rabi.info_); + + std::vector rows(height); + for (size_t i = 0; i < height; i++) + { + rows[i] = &data_[0] + i * pitch; + } + + png_read_image(rabi.png_, &rows[0]); + + AssignWritable(format, width, height, pitch, &data_[0]); + } + + void PngReader::ReadFromFile(const char* filename) + { + FileRabi f(filename); + + char header[8]; + if (fread(header, 1, 8, f.fp_) != 8) + { + throw OrthancException(ErrorCode_BadFileFormat); + } + + CheckHeader(header); + + PngRabi rabi; + + if (setjmp(png_jmpbuf(rabi.png_))) + { + rabi.Destruct(); + throw OrthancException(ErrorCode_BadFileFormat); + } + + png_init_io(rabi.png_, f.fp_); + + Read(rabi); + } + + + namespace + { + struct MemoryBuffer + { + const uint8_t* buffer_; + size_t size_; + size_t pos_; + bool ok_; + }; + } + + + void PngReader::PngRabi::MemoryCallback(png_structp png_ptr, + png_bytep outBytes, + png_size_t byteCountToRead) + { + MemoryBuffer* from = reinterpret_cast(png_get_io_ptr(png_ptr)); + + if (!from->ok_) + { + return; + } + + if (from->pos_ + byteCountToRead > from->size_) + { + from->ok_ = false; + return; + } + + memcpy(outBytes, from->buffer_ + from->pos_, byteCountToRead); + + from->pos_ += byteCountToRead; + } + + + void PngReader::ReadFromMemory(const void* buffer, + size_t size) + { + if (size < 8) + { + throw OrthancException(ErrorCode_BadFileFormat); + } + + CheckHeader(buffer); + + PngRabi rabi; + + if (setjmp(png_jmpbuf(rabi.png_))) + { + rabi.Destruct(); + throw OrthancException(ErrorCode_BadFileFormat); + } + + MemoryBuffer tmp; + tmp.buffer_ = reinterpret_cast(buffer) + 8; // We skip the header + tmp.size_ = size - 8; + tmp.pos_ = 0; + tmp.ok_ = true; + + png_set_read_fn(rabi.png_, &tmp, PngRabi::MemoryCallback); + + Read(rabi); + + if (!tmp.ok_) + { + throw OrthancException(ErrorCode_BadFileFormat); + } + } + + void PngReader::ReadFromMemory(const std::string& buffer) + { + if (buffer.size() != 0) + { + ReadFromMemory(&buffer[0], buffer.size()); + } + else + { + ReadFromMemory(NULL, 0); + } + } +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Images/PngReader.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Images/PngReader.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,71 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include "ImageAccessor.h" + +#include "../Enumerations.h" + +#include +#include +#include + +namespace Orthanc +{ + class PngReader : public ImageAccessor + { + private: + struct PngRabi; + + std::vector data_; + + void CheckHeader(const void* header); + + void Read(PngRabi& rabi); + + public: + PngReader(); + + void ReadFromFile(const char* filename); + + void ReadFromFile(const std::string& filename) + { + ReadFromFile(filename.c_str()); + } + + void ReadFromMemory(const void* buffer, + size_t size); + + void ReadFromMemory(const std::string& buffer); + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Logging.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Logging.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,112 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include + +namespace Orthanc +{ + namespace Logging + { + void Initialize(); + + void Finalize(); + + void EnableInfoLevel(bool enabled); + + void EnableTraceLevel(bool enabled); + + void SetTargetFolder(const std::string& path); + + struct NullStream : public std::ostream + { + NullStream() : + std::ios(0), + std::ostream(0) + { + } + + std::ostream& operator<< (const std::string& message) + { + return *this; + } + }; + } +} + + +#if ORTHANC_ENABLE_LOGGING != 1 + +# define LOG(level) ::Orthanc::Logging::NullStream() +# define VLOG(level) ::Orthanc::Logging::NullStream() + +#else /* ORTHANC_ENABLE_LOGGING == 1 */ + +#if ORTHANC_ENABLE_GOOGLE_LOG == 1 +# include // Including this fixes a problem in glog for recent releases of MinGW +# include +#else +# include +# define LOG(level) ::Orthanc::Logging::InternalLogger(#level, __FILE__, __LINE__) +# define VLOG(level) ::Orthanc::Logging::InternalLogger("TRACE", __FILE__, __LINE__) +#endif + +#if ORTHANC_ENABLE_GOOGLE_LOG != 1 +namespace Orthanc +{ + namespace Logging + { + class InternalLogger + { + private: + boost::mutex::scoped_lock lock_; + NullStream null_; + std::ostream* stream_; + + public: + InternalLogger(const char* level, + const char* file, + int line); + + ~InternalLogger(); + + std::ostream& operator<< (const std::string& message) + { + return (*stream_) << message; + } + }; + } +} +#endif + +#endif // ORTHANC_ENABLE_LOGGING diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/MultiThreading/SharedMessageQueue.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/MultiThreading/SharedMessageQueue.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,188 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#include "../PrecompiledHeaders.h" +#include "SharedMessageQueue.h" + + + +/** + * FIFO (queue): + * + * back front + * +--+--+--+--+--+--+--+--+--+--+--+ + * Enqueue -> | | | | | | | | | | | | + * | | | | | | | | | | | | -> Dequeue + * +--+--+--+--+--+--+--+--+--+--+--+ + * ^ + * | + * Make room here + * + * + * LIFO (stack): + * + * back front + * +--+--+--+--+--+--+--+--+--+--+--+ + * | | | | | | | | | | | | <- Enqueue + * | | | | | | | | | | | | -> Dequeue + * +--+--+--+--+--+--+--+--+--+--+--+ + * ^ + * | + * Make room here + **/ + + +namespace Orthanc +{ + SharedMessageQueue::SharedMessageQueue(unsigned int maxSize) : + isFifo_(true), + maxSize_(maxSize) + { + } + + + SharedMessageQueue::~SharedMessageQueue() + { + for (Queue::iterator it = queue_.begin(); it != queue_.end(); ++it) + { + delete *it; + } + } + + + void SharedMessageQueue::Enqueue(IDynamicObject* message) + { + boost::mutex::scoped_lock lock(mutex_); + + if (maxSize_ != 0 && queue_.size() > maxSize_) + { + if (isFifo_) + { + // Too many elements in the queue: Make room + delete queue_.front(); + queue_.pop_front(); + } + else + { + // Too many elements in the stack: Make room + delete queue_.back(); + queue_.pop_back(); + } + } + + if (isFifo_) + { + // Queue policy (FIFO) + queue_.push_back(message); + } + else + { + // Stack policy (LIFO) + queue_.push_front(message); + } + + elementAvailable_.notify_one(); + } + + + IDynamicObject* SharedMessageQueue::Dequeue(int32_t millisecondsTimeout) + { + boost::mutex::scoped_lock lock(mutex_); + + // Wait for a message to arrive in the FIFO queue + while (queue_.empty()) + { + if (millisecondsTimeout == 0) + { + elementAvailable_.wait(lock); + } + else + { + bool success = elementAvailable_.timed_wait + (lock, boost::posix_time::milliseconds(millisecondsTimeout)); + if (!success) + { + return NULL; + } + } + } + + std::auto_ptr message(queue_.front()); + queue_.pop_front(); + + if (queue_.empty()) + { + emptied_.notify_all(); + } + + return message.release(); + } + + + + bool SharedMessageQueue::WaitEmpty(int32_t millisecondsTimeout) + { + boost::mutex::scoped_lock lock(mutex_); + + // Wait for the queue to become empty + while (!queue_.empty()) + { + if (millisecondsTimeout == 0) + { + emptied_.wait(lock); + } + else + { + if (!emptied_.timed_wait + (lock, boost::posix_time::milliseconds(millisecondsTimeout))) + { + return false; + } + } + } + + return true; + } + + + void SharedMessageQueue::SetFifoPolicy() + { + boost::mutex::scoped_lock lock(mutex_); + isFifo_ = true; + } + + void SharedMessageQueue::SetLifoPolicy() + { + boost::mutex::scoped_lock lock(mutex_); + isFifo_ = false; + } +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/MultiThreading/SharedMessageQueue.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/MultiThreading/SharedMessageQueue.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,82 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include "../IDynamicObject.h" + +#include +#include +#include + +namespace Orthanc +{ + class SharedMessageQueue : public boost::noncopyable + { + private: + typedef std::list Queue; + + bool isFifo_; + unsigned int maxSize_; + Queue queue_; + boost::mutex mutex_; + boost::condition_variable elementAvailable_; + boost::condition_variable emptied_; + + public: + explicit SharedMessageQueue(unsigned int maxSize = 0); + + ~SharedMessageQueue(); + + // This transfers the ownership of the message + void Enqueue(IDynamicObject* message); + + // The caller is responsible to delete the dequeud message! + IDynamicObject* Dequeue(int32_t millisecondsTimeout); + + bool WaitEmpty(int32_t millisecondsTimeout); + + bool IsFifoPolicy() const + { + return isFifo_; + } + + bool IsLifoPolicy() const + { + return !isFifo_; + } + + void SetFifoPolicy(); + + void SetLifoPolicy(); + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/OrthancException.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/OrthancException.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,76 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include +#include +#include "Enumerations.h" + +namespace Orthanc +{ + class OrthancException + { + protected: + ErrorCode errorCode_; + HttpStatus httpStatus_; + + public: + OrthancException(ErrorCode errorCode) : + errorCode_(errorCode), + httpStatus_(ConvertErrorCodeToHttpStatus(errorCode)) + { + } + + OrthancException(ErrorCode errorCode, + HttpStatus httpStatus) : + errorCode_(errorCode), + httpStatus_(httpStatus) + { + } + + ErrorCode GetErrorCode() const + { + return errorCode_; + } + + HttpStatus GetHttpStatus() const + { + return httpStatus_; + } + + const char* What() const + { + return EnumerationToString(errorCode_); + } + }; +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/PrecompiledHeaders.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/PrecompiledHeaders.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,61 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#if defined(_WIN32) && !defined(NOMINMAX) +#define NOMINMAX +#endif + +#if ORTHANC_USE_PRECOMPILED_HEADERS == 1 + +#include +#include +#include +#include +#include +#include +#include + +#include + +#if ORTHANC_PUGIXML_ENABLED == 1 +#include +#endif + +#include "Enumerations.h" +#include "Logging.h" +#include "OrthancException.h" +#include "Toolbox.h" +#include "Uuid.h" + +#endif diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Toolbox.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Toolbox.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,1386 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#include "PrecompiledHeaders.h" +#include "Toolbox.h" + +#include "OrthancException.h" +#include "Logging.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if BOOST_HAS_DATE_TIME == 1 +#include +#endif + +#if BOOST_HAS_REGEX == 1 +#include +#endif + +#if defined(_WIN32) +#include +#include // For "_spawnvp()" and "_getpid()" +#else +#include // For "execvp()" +#include // For "waitpid()" +#endif + +#if defined(__APPLE__) && defined(__MACH__) +#include /* _NSGetExecutablePath */ +#include /* PATH_MAX */ +#endif + +#if defined(__linux) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__) +#include /* PATH_MAX */ +#include +#include +#endif + +#if BOOST_HAS_LOCALE != 1 +#error Since version 0.7.6, Orthanc entirely relies on boost::locale +#endif + +#include + + +#if !defined(ORTHANC_ENABLE_MD5) || ORTHANC_ENABLE_MD5 == 1 +#include "../Resources/ThirdParty/md5/md5.h" +#endif + + +#if !defined(ORTHANC_ENABLE_BASE64) || ORTHANC_ENABLE_BASE64 == 1 +#include "../Resources/ThirdParty/base64/base64.h" +#endif + + +#if defined(_MSC_VER) && (_MSC_VER < 1800) +// Patch for the missing "_strtoll" symbol when compiling with Visual Studio < 2013 +extern "C" +{ + int64_t _strtoi64(const char *nptr, char **endptr, int base); + int64_t strtoll(const char *nptr, char **endptr, int base) + { + return _strtoi64(nptr, endptr, base); + } +} +#endif + + +#if ORTHANC_PUGIXML_ENABLED == 1 +#include "ChunkedBuffer.h" +#include +#endif + + +namespace Orthanc +{ + static bool finish; + +#if defined(_WIN32) + static BOOL WINAPI ConsoleControlHandler(DWORD dwCtrlType) + { + // http://msdn.microsoft.com/en-us/library/ms683242(v=vs.85).aspx + finish = true; + return true; + } +#else + static void SignalHandler(int) + { + finish = true; + } +#endif + + void Toolbox::USleep(uint64_t microSeconds) + { +#if defined(_WIN32) + ::Sleep(static_cast(microSeconds / static_cast(1000))); +#elif defined(__linux) || defined(__APPLE__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__) + usleep(microSeconds); +#else +#error Support your platform here +#endif + } + + + static void ServerBarrierInternal(const bool* stopFlag) + { +#if defined(_WIN32) + SetConsoleCtrlHandler(ConsoleControlHandler, true); +#else + signal(SIGINT, SignalHandler); + signal(SIGQUIT, SignalHandler); + signal(SIGTERM, SignalHandler); +#endif + + // Active loop that awakens every 100ms + finish = false; + while (!(*stopFlag || finish)) + { + Toolbox::USleep(100 * 1000); + } + +#if defined(_WIN32) + SetConsoleCtrlHandler(ConsoleControlHandler, false); +#else + signal(SIGINT, NULL); + signal(SIGQUIT, NULL); + signal(SIGTERM, NULL); +#endif + } + + + void Toolbox::ServerBarrier(const bool& stopFlag) + { + ServerBarrierInternal(&stopFlag); + } + + void Toolbox::ServerBarrier() + { + const bool stopFlag = false; + ServerBarrierInternal(&stopFlag); + } + + + void Toolbox::ToUpperCase(std::string& s) + { + std::transform(s.begin(), s.end(), s.begin(), toupper); + } + + + void Toolbox::ToLowerCase(std::string& s) + { + std::transform(s.begin(), s.end(), s.begin(), tolower); + } + + + void Toolbox::ToUpperCase(std::string& result, + const std::string& source) + { + result = source; + ToUpperCase(result); + } + + void Toolbox::ToLowerCase(std::string& result, + const std::string& source) + { + result = source; + ToLowerCase(result); + } + + + void Toolbox::ReadFile(std::string& content, + const std::string& path) + { + if (!boost::filesystem::is_regular_file(path)) + { + LOG(ERROR) << std::string("The path does not point to a regular file: ") << path; + throw OrthancException(ErrorCode_RegularFileExpected); + } + + boost::filesystem::ifstream f; + f.open(path, std::ifstream::in | std::ifstream::binary); + if (!f.good()) + { + throw OrthancException(ErrorCode_InexistentFile); + } + + // http://www.cplusplus.com/reference/iostream/istream/tellg/ + f.seekg(0, std::ios::end); + std::streamsize size = f.tellg(); + f.seekg(0, std::ios::beg); + + content.resize(size); + if (size != 0) + { + f.read(reinterpret_cast(&content[0]), size); + } + + f.close(); + } + + + void Toolbox::WriteFile(const void* content, + size_t size, + const std::string& path) + { + boost::filesystem::ofstream f; + f.open(path, std::ofstream::binary); + if (!f.good()) + { + throw OrthancException(ErrorCode_CannotWriteFile); + } + + if (size != 0) + { + f.write(reinterpret_cast(content), size); + } + + f.close(); + } + + + void Toolbox::WriteFile(const std::string& content, + const std::string& path) + { + WriteFile(content.size() > 0 ? content.c_str() : NULL, + content.size(), path); + } + + + void Toolbox::RemoveFile(const std::string& path) + { + if (boost::filesystem::exists(path)) + { + if (boost::filesystem::is_regular_file(path)) + { + boost::filesystem::remove(path); + } + else + { + throw OrthancException(ErrorCode_RegularFileExpected); + } + } + } + + + + void Toolbox::SplitUriComponents(UriComponents& components, + const std::string& uri) + { + static const char URI_SEPARATOR = '/'; + + components.clear(); + + if (uri.size() == 0 || + uri[0] != URI_SEPARATOR) + { + throw OrthancException(ErrorCode_UriSyntax); + } + + // Count the number of slashes in the URI to make an assumption + // about the number of components in the URI + unsigned int estimatedSize = 0; + for (unsigned int i = 0; i < uri.size(); i++) + { + if (uri[i] == URI_SEPARATOR) + estimatedSize++; + } + + components.reserve(estimatedSize - 1); + + unsigned int start = 1; + unsigned int end = 1; + while (end < uri.size()) + { + // This is the loop invariant + assert(uri[start - 1] == '/' && (end >= start)); + + if (uri[end] == '/') + { + components.push_back(std::string(&uri[start], end - start)); + end++; + start = end; + } + else + { + end++; + } + } + + if (start < uri.size()) + { + components.push_back(std::string(&uri[start], end - start)); + } + + for (size_t i = 0; i < components.size(); i++) + { + if (components[i].size() == 0) + { + // Empty component, as in: "/coucou//e" + throw OrthancException(ErrorCode_UriSyntax); + } + } + } + + + void Toolbox::TruncateUri(UriComponents& target, + const UriComponents& source, + size_t fromLevel) + { + target.clear(); + + if (source.size() > fromLevel) + { + target.resize(source.size() - fromLevel); + + size_t j = 0; + for (size_t i = fromLevel; i < source.size(); i++, j++) + { + target[j] = source[i]; + } + + assert(j == target.size()); + } + } + + + + bool Toolbox::IsChildUri(const UriComponents& baseUri, + const UriComponents& testedUri) + { + if (testedUri.size() < baseUri.size()) + { + return false; + } + + for (size_t i = 0; i < baseUri.size(); i++) + { + if (baseUri[i] != testedUri[i]) + return false; + } + + return true; + } + + + std::string Toolbox::AutodetectMimeType(const std::string& path) + { + std::string contentType; + size_t lastDot = path.rfind('.'); + size_t lastSlash = path.rfind('/'); + + if (lastDot == std::string::npos || + (lastSlash != std::string::npos && lastDot < lastSlash)) + { + // No trailing dot, unable to detect the content type + } + else + { + const char* extension = &path[lastDot + 1]; + + // http://en.wikipedia.org/wiki/Mime_types + // Text types + if (!strcmp(extension, "txt")) + contentType = "text/plain"; + else if (!strcmp(extension, "html")) + contentType = "text/html"; + else if (!strcmp(extension, "xml")) + contentType = "text/xml"; + else if (!strcmp(extension, "css")) + contentType = "text/css"; + + // Application types + else if (!strcmp(extension, "js")) + contentType = "application/javascript"; + else if (!strcmp(extension, "json")) + contentType = "application/json"; + else if (!strcmp(extension, "pdf")) + contentType = "application/pdf"; + + // Images types + else if (!strcmp(extension, "jpg") || !strcmp(extension, "jpeg")) + contentType = "image/jpeg"; + else if (!strcmp(extension, "gif")) + contentType = "image/gif"; + else if (!strcmp(extension, "png")) + contentType = "image/png"; + } + + return contentType; + } + + + std::string Toolbox::FlattenUri(const UriComponents& components, + size_t fromLevel) + { + if (components.size() <= fromLevel) + { + return "/"; + } + else + { + std::string r; + + for (size_t i = fromLevel; i < components.size(); i++) + { + r += "/" + components[i]; + } + + return r; + } + } + + + + uint64_t Toolbox::GetFileSize(const std::string& path) + { + try + { + return static_cast(boost::filesystem::file_size(path)); + } + catch (boost::filesystem::filesystem_error&) + { + throw OrthancException(ErrorCode_InexistentFile); + } + } + + +#if !defined(ORTHANC_ENABLE_MD5) || ORTHANC_ENABLE_MD5 == 1 + static char GetHexadecimalCharacter(uint8_t value) + { + assert(value < 16); + + if (value < 10) + { + return value + '0'; + } + else + { + return (value - 10) + 'a'; + } + } + + + void Toolbox::ComputeMD5(std::string& result, + const std::string& data) + { + if (data.size() > 0) + { + ComputeMD5(result, &data[0], data.size()); + } + else + { + ComputeMD5(result, NULL, 0); + } + } + + + void Toolbox::ComputeMD5(std::string& result, + const void* data, + size_t size) + { + md5_state_s state; + md5_init(&state); + + if (size > 0) + { + md5_append(&state, + reinterpret_cast(data), + static_cast(size)); + } + + md5_byte_t actualHash[16]; + md5_finish(&state, actualHash); + + result.resize(32); + for (unsigned int i = 0; i < 16; i++) + { + result[2 * i] = GetHexadecimalCharacter(static_cast(actualHash[i] / 16)); + result[2 * i + 1] = GetHexadecimalCharacter(static_cast(actualHash[i] % 16)); + } + } +#endif + + +#if !defined(ORTHANC_ENABLE_BASE64) || ORTHANC_ENABLE_BASE64 == 1 + void Toolbox::EncodeBase64(std::string& result, + const std::string& data) + { + result = base64_encode(data); + } + + void Toolbox::DecodeBase64(std::string& result, + const std::string& data) + { + result = base64_decode(data); + } + + +# if BOOST_HAS_REGEX == 1 + void Toolbox::DecodeDataUriScheme(std::string& mime, + std::string& content, + const std::string& source) + { + boost::regex pattern("data:([^;]+);base64,([a-zA-Z0-9=+/]*)", + boost::regex::icase /* case insensitive search */); + + boost::cmatch what; + if (regex_match(source.c_str(), what, pattern)) + { + mime = what[1]; + DecodeBase64(content, what[2]); + } + else + { + throw OrthancException(ErrorCode_BadFileFormat); + } + } +# endif + + + void Toolbox::EncodeDataUriScheme(std::string& result, + const std::string& mime, + const std::string& content) + { + result = "data:" + mime + ";base64," + base64_encode(content); + } + +#endif + + + +#if defined(_WIN32) + static std::string GetPathToExecutableInternal() + { + // Yes, this is ugly, but there is no simple way to get the + // required buffer size, so we use a big constant + std::vector buffer(32768); + /*int bytes =*/ GetModuleFileNameA(NULL, &buffer[0], static_cast(buffer.size() - 1)); + return std::string(&buffer[0]); + } + +#elif defined(__linux) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__) + static std::string GetPathToExecutableInternal() + { + std::vector buffer(PATH_MAX + 1); + ssize_t bytes = readlink("/proc/self/exe", &buffer[0], buffer.size() - 1); + if (bytes == 0) + { + throw OrthancException(ErrorCode_PathToExecutable); + } + + return std::string(&buffer[0]); + } + +#elif defined(__APPLE__) && defined(__MACH__) + static std::string GetPathToExecutableInternal() + { + char pathbuf[PATH_MAX + 1]; + unsigned int bufsize = static_cast(sizeof(pathbuf)); + + _NSGetExecutablePath( pathbuf, &bufsize); + + return std::string(pathbuf); + } + +#else +#error Support your platform here +#endif + + + std::string Toolbox::GetPathToExecutable() + { + boost::filesystem::path p(GetPathToExecutableInternal()); + return boost::filesystem::absolute(p).string(); + } + + + std::string Toolbox::GetDirectoryOfExecutable() + { + boost::filesystem::path p(GetPathToExecutableInternal()); + return boost::filesystem::absolute(p.parent_path()).string(); + } + + + static const char* GetBoostLocaleEncoding(const Encoding sourceEncoding) + { + switch (sourceEncoding) + { + case Encoding_Utf8: + return "UTF-8"; + + case Encoding_Ascii: + return "ASCII"; + + case Encoding_Latin1: + return "ISO-8859-1"; + break; + + case Encoding_Latin2: + return "ISO-8859-2"; + break; + + case Encoding_Latin3: + return "ISO-8859-3"; + break; + + case Encoding_Latin4: + return "ISO-8859-4"; + break; + + case Encoding_Latin5: + return "ISO-8859-9"; + break; + + case Encoding_Cyrillic: + return "ISO-8859-5"; + break; + + case Encoding_Windows1251: + return "WINDOWS-1251"; + break; + + case Encoding_Arabic: + return "ISO-8859-6"; + break; + + case Encoding_Greek: + return "ISO-8859-7"; + break; + + case Encoding_Hebrew: + return "ISO-8859-8"; + break; + + case Encoding_Japanese: + return "SHIFT-JIS"; + break; + + case Encoding_Chinese: + return "GB18030"; + break; + + case Encoding_Thai: + return "TIS620.2533-0"; + break; + + default: + throw OrthancException(ErrorCode_NotImplemented); + } + } + + + std::string Toolbox::ConvertToUtf8(const std::string& source, + Encoding sourceEncoding) + { + if (sourceEncoding == Encoding_Utf8) + { + // Already in UTF-8: No conversion is required + return source; + } + + if (sourceEncoding == Encoding_Ascii) + { + return ConvertToAscii(source); + } + + const char* encoding = GetBoostLocaleEncoding(sourceEncoding); + + try + { + return boost::locale::conv::to_utf(source, encoding); + } + catch (std::runtime_error&) + { + // Bad input string or bad encoding + return ConvertToAscii(source); + } + } + + + std::string Toolbox::ConvertFromUtf8(const std::string& source, + Encoding targetEncoding) + { + if (targetEncoding == Encoding_Utf8) + { + // Already in UTF-8: No conversion is required + return source; + } + + if (targetEncoding == Encoding_Ascii) + { + return ConvertToAscii(source); + } + + const char* encoding = GetBoostLocaleEncoding(targetEncoding); + + try + { + return boost::locale::conv::from_utf(source, encoding); + } + catch (std::runtime_error&) + { + // Bad input string or bad encoding + return ConvertToAscii(source); + } + } + + + std::string Toolbox::ConvertToAscii(const std::string& source) + { + std::string result; + + result.reserve(source.size() + 1); + for (size_t i = 0; i < source.size(); i++) + { + if (source[i] <= 127 && source[i] >= 0 && !iscntrl(source[i])) + { + result.push_back(source[i]); + } + } + + return result; + } + + + void Toolbox::ComputeSHA1(std::string& result, + const void* data, + size_t size) + { + boost::uuids::detail::sha1 sha1; + + if (size > 0) + { + sha1.process_bytes(data, size); + } + + unsigned int digest[5]; + + // Sanity check for the memory layout: A SHA-1 digest is 160 bits wide + assert(sizeof(unsigned int) == 4 && sizeof(digest) == (160 / 8)); + + sha1.get_digest(digest); + + result.resize(8 * 5 + 4); + sprintf(&result[0], "%08x-%08x-%08x-%08x-%08x", + digest[0], + digest[1], + digest[2], + digest[3], + digest[4]); + } + + void Toolbox::ComputeSHA1(std::string& result, + const std::string& data) + { + if (data.size() > 0) + { + ComputeSHA1(result, data.c_str(), data.size()); + } + else + { + ComputeSHA1(result, NULL, 0); + } + } + + + bool Toolbox::IsSHA1(const char* str, + size_t size) + { + if (size == 0) + { + return false; + } + + const char* start = str; + const char* end = str + size; + + // Trim the beginning of the string + while (start < end) + { + if (*start == '\0' || + isspace(*start)) + { + start++; + } + else + { + break; + } + } + + // Trim the trailing of the string + while (start < end) + { + if (*(end - 1) == '\0' || + isspace(*(end - 1))) + { + end--; + } + else + { + break; + } + } + + if (end - start != 44) + { + return false; + } + + for (unsigned int i = 0; i < 44; i++) + { + if (i == 8 || + i == 17 || + i == 26 || + i == 35) + { + if (start[i] != '-') + return false; + } + else + { + if (!isalnum(start[i])) + return false; + } + } + + return true; + } + + + bool Toolbox::IsSHA1(const std::string& s) + { + if (s.size() == 0) + { + return false; + } + else + { + return IsSHA1(s.c_str(), s.size()); + } + } + + +#if BOOST_HAS_DATE_TIME == 1 + std::string Toolbox::GetNowIsoString() + { + boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); + return boost::posix_time::to_iso_string(now); + } + + void Toolbox::GetNowDicom(std::string& date, + std::string& time) + { + boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); + tm tm = boost::posix_time::to_tm(now); + + char s[32]; + sprintf(s, "%04d%02d%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); + date.assign(s); + + // TODO milliseconds + sprintf(s, "%02d%02d%02d.%06d", tm.tm_hour, tm.tm_min, tm.tm_sec, 0); + time.assign(s); + } +#endif + + + std::string Toolbox::StripSpaces(const std::string& source) + { + size_t first = 0; + + while (first < source.length() && + isspace(source[first])) + { + first++; + } + + if (first == source.length()) + { + // String containing only spaces + return ""; + } + + size_t last = source.length(); + while (last > first && + isspace(source[last - 1])) + { + last--; + } + + assert(first <= last); + return source.substr(first, last - first); + } + + + static char Hex2Dec(char c) + { + return ((c >= '0' && c <= '9') ? c - '0' : + ((c >= 'a' && c <= 'f') ? c - 'a' + 10 : c - 'A' + 10)); + } + + void Toolbox::UrlDecode(std::string& s) + { + // http://en.wikipedia.org/wiki/Percent-encoding + // http://www.w3schools.com/tags/ref_urlencode.asp + // http://stackoverflow.com/questions/154536/encode-decode-urls-in-c + + if (s.size() == 0) + { + return; + } + + size_t source = 0; + size_t target = 0; + + while (source < s.size()) + { + if (s[source] == '%' && + source + 2 < s.size() && + isalnum(s[source + 1]) && + isalnum(s[source + 2])) + { + s[target] = (Hex2Dec(s[source + 1]) << 4) | Hex2Dec(s[source + 2]); + source += 3; + target += 1; + } + else + { + if (s[source] == '+') + s[target] = ' '; + else + s[target] = s[source]; + + source++; + target++; + } + } + + s.resize(target); + } + + + Endianness Toolbox::DetectEndianness() + { + // http://sourceforge.net/p/predef/wiki/Endianness/ + + uint8_t buffer[4]; + + buffer[0] = 0x00; + buffer[1] = 0x01; + buffer[2] = 0x02; + buffer[3] = 0x03; + + switch (*((uint32_t *)buffer)) + { + case 0x00010203: + return Endianness_Big; + + case 0x03020100: + return Endianness_Little; + + default: + throw OrthancException(ErrorCode_NotImplemented); + } + } + + +#if BOOST_HAS_REGEX == 1 + std::string Toolbox::WildcardToRegularExpression(const std::string& source) + { + // TODO - Speed up this with a regular expression + + std::string result = source; + + // Escape all special characters + boost::replace_all(result, "\\", "\\\\"); + boost::replace_all(result, "^", "\\^"); + boost::replace_all(result, ".", "\\."); + boost::replace_all(result, "$", "\\$"); + boost::replace_all(result, "|", "\\|"); + boost::replace_all(result, "(", "\\("); + boost::replace_all(result, ")", "\\)"); + boost::replace_all(result, "[", "\\["); + boost::replace_all(result, "]", "\\]"); + boost::replace_all(result, "+", "\\+"); + boost::replace_all(result, "/", "\\/"); + boost::replace_all(result, "{", "\\{"); + boost::replace_all(result, "}", "\\}"); + + // Convert wildcards '*' and '?' to their regex equivalents + boost::replace_all(result, "?", "."); + boost::replace_all(result, "*", ".*"); + + return result; + } +#endif + + + + void Toolbox::TokenizeString(std::vector& result, + const std::string& value, + char separator) + { + result.clear(); + + std::string currentItem; + + for (size_t i = 0; i < value.size(); i++) + { + if (value[i] == separator) + { + result.push_back(currentItem); + currentItem.clear(); + } + else + { + currentItem.push_back(value[i]); + } + } + + result.push_back(currentItem); + } + + + void Toolbox::MakeDirectory(const std::string& path) + { + if (boost::filesystem::exists(path)) + { + if (!boost::filesystem::is_directory(path)) + { + throw OrthancException(ErrorCode_DirectoryOverFile); + } + } + else + { + if (!boost::filesystem::create_directories(path)) + { + throw OrthancException(ErrorCode_MakeDirectory); + } + } + } + + + bool Toolbox::IsExistingFile(const std::string& path) + { + return boost::filesystem::exists(path); + } + + +#if ORTHANC_PUGIXML_ENABLED == 1 + class ChunkedBufferWriter : public pugi::xml_writer + { + private: + ChunkedBuffer buffer_; + + public: + virtual void write(const void *data, size_t size) + { + if (size > 0) + { + buffer_.AddChunk(reinterpret_cast(data), size); + } + } + + void Flatten(std::string& s) + { + buffer_.Flatten(s); + } + }; + + + static void JsonToXmlInternal(pugi::xml_node& target, + const Json::Value& source, + const std::string& arrayElement) + { + // http://jsoncpp.sourceforge.net/value_8h_source.html#l00030 + + switch (source.type()) + { + case Json::nullValue: + { + target.append_child(pugi::node_pcdata).set_value("null"); + break; + } + + case Json::intValue: + { + std::string s = boost::lexical_cast(source.asInt()); + target.append_child(pugi::node_pcdata).set_value(s.c_str()); + break; + } + + case Json::uintValue: + { + std::string s = boost::lexical_cast(source.asUInt()); + target.append_child(pugi::node_pcdata).set_value(s.c_str()); + break; + } + + case Json::realValue: + { + std::string s = boost::lexical_cast(source.asFloat()); + target.append_child(pugi::node_pcdata).set_value(s.c_str()); + break; + } + + case Json::stringValue: + { + target.append_child(pugi::node_pcdata).set_value(source.asString().c_str()); + break; + } + + case Json::booleanValue: + { + target.append_child(pugi::node_pcdata).set_value(source.asBool() ? "true" : "false"); + break; + } + + case Json::arrayValue: + { + for (Json::Value::ArrayIndex i = 0; i < source.size(); i++) + { + pugi::xml_node node = target.append_child(); + node.set_name(arrayElement.c_str()); + JsonToXmlInternal(node, source[i], arrayElement); + } + break; + } + + case Json::objectValue: + { + Json::Value::Members members = source.getMemberNames(); + + for (size_t i = 0; i < members.size(); i++) + { + pugi::xml_node node = target.append_child(); + node.set_name(members[i].c_str()); + JsonToXmlInternal(node, source[members[i]], arrayElement); + } + + break; + } + + default: + throw OrthancException(ErrorCode_NotImplemented); + } + } + + + void Toolbox::JsonToXml(std::string& target, + const Json::Value& source, + const std::string& rootElement, + const std::string& arrayElement) + { + pugi::xml_document doc; + + pugi::xml_node n = doc.append_child(rootElement.c_str()); + JsonToXmlInternal(n, source, arrayElement); + + pugi::xml_node decl = doc.prepend_child(pugi::node_declaration); + decl.append_attribute("version").set_value("1.0"); + decl.append_attribute("encoding").set_value("utf-8"); + + ChunkedBufferWriter writer; + doc.save(writer, " ", pugi::format_default, pugi::encoding_utf8); + writer.Flatten(target); + } + +#endif + + + void Toolbox::ExecuteSystemCommand(const std::string& command, + const std::vector& arguments) + { + // Convert the arguments as a C array + std::vector args(arguments.size() + 2); + + args.front() = const_cast(command.c_str()); + + for (size_t i = 0; i < arguments.size(); i++) + { + args[i + 1] = const_cast(arguments[i].c_str()); + } + + args.back() = NULL; + + int status; + +#if defined(_WIN32) + // http://msdn.microsoft.com/en-us/library/275khfab.aspx + status = static_cast(_spawnvp(_P_OVERLAY, command.c_str(), &args[0])); + +#else + int pid = fork(); + + if (pid == -1) + { + // Error in fork() +#if ORTHANC_ENABLE_LOGGING == 1 + LOG(ERROR) << "Cannot fork a child process"; +#endif + + throw OrthancException(ErrorCode_SystemCommand); + } + else if (pid == 0) + { + // Execute the system command in the child process + execvp(command.c_str(), &args[0]); + + // We should never get here + _exit(1); + } + else + { + // Wait for the system command to exit + waitpid(pid, &status, 0); + } +#endif + + if (status != 0) + { +#if ORTHANC_ENABLE_LOGGING == 1 + LOG(ERROR) << "System command failed with status code " << status; +#endif + + throw OrthancException(ErrorCode_SystemCommand); + } + } + + + bool Toolbox::IsInteger(const std::string& str) + { + std::string s = StripSpaces(str); + + if (s.size() == 0) + { + return false; + } + + size_t pos = 0; + if (s[0] == '-') + { + if (s.size() == 1) + { + return false; + } + + pos = 1; + } + + while (pos < s.size()) + { + if (!isdigit(s[pos])) + { + return false; + } + + pos++; + } + + return true; + } + + + void Toolbox::CopyJsonWithoutComments(Json::Value& target, + const Json::Value& source) + { + switch (source.type()) + { + case Json::nullValue: + target = Json::nullValue; + break; + + case Json::intValue: + target = source.asInt64(); + break; + + case Json::uintValue: + target = source.asUInt64(); + break; + + case Json::realValue: + target = source.asDouble(); + break; + + case Json::stringValue: + target = source.asString(); + break; + + case Json::booleanValue: + target = source.asBool(); + break; + + case Json::arrayValue: + { + target = Json::arrayValue; + for (Json::Value::ArrayIndex i = 0; i < source.size(); i++) + { + Json::Value& item = target.append(Json::nullValue); + CopyJsonWithoutComments(item, source[i]); + } + + break; + } + + case Json::objectValue: + { + target = Json::objectValue; + Json::Value::Members members = source.getMemberNames(); + for (Json::Value::ArrayIndex i = 0; i < members.size(); i++) + { + const std::string item = members[i]; + CopyJsonWithoutComments(target[item], source[item]); + } + + break; + } + + default: + break; + } + } + + + bool Toolbox::StartsWith(const std::string& str, + const std::string& prefix) + { + if (str.size() < prefix.size()) + { + return false; + } + else + { + return str.compare(0, prefix.size(), prefix) == 0; + } + } + + + int Toolbox::GetProcessId() + { +#if defined(_WIN32) + return static_cast(_getpid()); +#else + return static_cast(getpid()); +#endif + } +} + diff -r a07ee8b6946e -r f7379096e014 Orthanc/Core/Toolbox.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Core/Toolbox.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,194 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * In addition, as a special exception, the copyright holders of this + * program give permission to link the code of its release with the + * OpenSSL project's "OpenSSL" library (or with modified versions of it + * that use the same license as the "OpenSSL" library), and distribute + * the linked executables. You must obey the GNU General Public License + * in all respects for all of the code used other than "OpenSSL". If you + * modify file(s) with this exception, you may extend this exception to + * your version of the file(s), but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files + * in the program, then also delete it here. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + **/ + + +#pragma once + +#include "Enumerations.h" + +#include +#include +#include +#include + +namespace Orthanc +{ + typedef std::vector UriComponents; + + class NullType + { + }; + + namespace Toolbox + { + void ServerBarrier(const bool& stopFlag); + + void ServerBarrier(); + + void ToUpperCase(std::string& s); // Inplace version + + void ToLowerCase(std::string& s); // Inplace version + + void ToUpperCase(std::string& result, + const std::string& source); + + void ToLowerCase(std::string& result, + const std::string& source); + + void ReadFile(std::string& content, + const std::string& path); + + void WriteFile(const std::string& content, + const std::string& path); + + void WriteFile(const void* content, + size_t size, + const std::string& path); + + void USleep(uint64_t microSeconds); + + void RemoveFile(const std::string& path); + + void SplitUriComponents(UriComponents& components, + const std::string& uri); + + void TruncateUri(UriComponents& target, + const UriComponents& source, + size_t fromLevel); + + bool IsChildUri(const UriComponents& baseUri, + const UriComponents& testedUri); + + std::string AutodetectMimeType(const std::string& path); + + std::string FlattenUri(const UriComponents& components, + size_t fromLevel = 0); + + uint64_t GetFileSize(const std::string& path); + +#if !defined(ORTHANC_ENABLE_MD5) || ORTHANC_ENABLE_MD5 == 1 + void ComputeMD5(std::string& result, + const std::string& data); + + void ComputeMD5(std::string& result, + const void* data, + size_t size); +#endif + + void ComputeSHA1(std::string& result, + const std::string& data); + + void ComputeSHA1(std::string& result, + const void* data, + size_t size); + + bool IsSHA1(const char* str, + size_t size); + + bool IsSHA1(const std::string& s); + +#if !defined(ORTHANC_ENABLE_BASE64) || ORTHANC_ENABLE_BASE64 == 1 + void DecodeBase64(std::string& result, + const std::string& data); + + void EncodeBase64(std::string& result, + const std::string& data); + +# if BOOST_HAS_REGEX == 1 + void DecodeDataUriScheme(std::string& mime, + std::string& content, + const std::string& source); +# endif + + void EncodeDataUriScheme(std::string& result, + const std::string& mime, + const std::string& content); +#endif + + std::string GetPathToExecutable(); + + std::string GetDirectoryOfExecutable(); + + std::string ConvertToUtf8(const std::string& source, + Encoding sourceEncoding); + + std::string ConvertFromUtf8(const std::string& source, + Encoding targetEncoding); + + std::string ConvertToAscii(const std::string& source); + + std::string StripSpaces(const std::string& source); + +#if BOOST_HAS_DATE_TIME == 1 + std::string GetNowIsoString(); + + void GetNowDicom(std::string& date, + std::string& time); +#endif + + // In-place percent-decoding for URL + void UrlDecode(std::string& s); + + Endianness DetectEndianness(); + +#if BOOST_HAS_REGEX == 1 + std::string WildcardToRegularExpression(const std::string& s); +#endif + + void TokenizeString(std::vector& result, + const std::string& source, + char separator); + + void MakeDirectory(const std::string& path); + + bool IsExistingFile(const std::string& path); + +#if ORTHANC_PUGIXML_ENABLED == 1 + void JsonToXml(std::string& target, + const Json::Value& source, + const std::string& rootElement = "root", + const std::string& arrayElement = "item"); +#endif + + void ExecuteSystemCommand(const std::string& command, + const std::vector& arguments); + + bool IsInteger(const std::string& str); + + void CopyJsonWithoutComments(Json::Value& target, + const Json::Value& source); + + bool StartsWith(const std::string& str, + const std::string& prefix); + + int GetProcessId(); + } +} diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/BoostConfiguration.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/BoostConfiguration.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,145 @@ +if (STATIC_BUILD OR NOT USE_SYSTEM_BOOST) + set(BOOST_STATIC 1) +else() + include(FindBoost) + + set(BOOST_STATIC 0) + #set(Boost_DEBUG 1) + #set(Boost_USE_STATIC_LIBS ON) + + find_package(Boost + COMPONENTS filesystem thread system date_time regex locale) + + if (NOT Boost_FOUND) + message(FATAL_ERROR "Unable to locate Boost on this system") + endif() + + # Boost releases 1.44 through 1.47 supply both V2 and V3 filesystem + # http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/index.htm + if (${Boost_VERSION} LESS 104400) + add_definitions( + -DBOOST_HAS_FILESYSTEM_V3=0 + ) + else() + add_definitions( + -DBOOST_HAS_FILESYSTEM_V3=1 + -DBOOST_FILESYSTEM_VERSION=3 + ) + endif() + + #if (${Boost_VERSION} LESS 104800) + # boost::locale is only available from 1.48.00 + #message("Too old version of Boost (${Boost_LIB_VERSION}): Building the static version") + # set(BOOST_STATIC 1) + #endif() + + include_directories(${Boost_INCLUDE_DIRS}) + link_libraries(${Boost_LIBRARIES}) +endif() + + +if (BOOST_STATIC) + # Parameters for Boost 1.59.0 + set(BOOST_NAME boost_1_59_0) + set(BOOST_BCP_SUFFIX bcpdigest-0.9.5) + set(BOOST_MD5 "08abb7cdbea0b380f9ab0d5cce476f12") + set(BOOST_URL "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/${BOOST_NAME}_${BOOST_BCP_SUFFIX}.tar.gz") + set(BOOST_FILESYSTEM_SOURCES_DIR "${BOOST_NAME}/libs/filesystem/src") + set(BOOST_SOURCES_DIR ${CMAKE_BINARY_DIR}/${BOOST_NAME}) + + DownloadPackage(${BOOST_MD5} ${BOOST_URL} "${BOOST_SOURCES_DIR}") + + set(BOOST_SOURCES) + + if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "Darwin" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD") + list(APPEND BOOST_SOURCES + ${BOOST_SOURCES_DIR}/libs/thread/src/pthread/once.cpp + ${BOOST_SOURCES_DIR}/libs/thread/src/pthread/thread.cpp + ) + add_definitions( + -DBOOST_LOCALE_WITH_ICONV=1 + ) + + if ("${CMAKE_SYSTEM_VERSION}" STREQUAL "LinuxStandardBase") + add_definitions(-DBOOST_HAS_SCHED_YIELD=1) + endif() + + elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") + list(APPEND BOOST_SOURCES + ${BOOST_SOURCES_DIR}/libs/thread/src/win32/tss_dll.cpp + ${BOOST_SOURCES_DIR}/libs/thread/src/win32/thread.cpp + ${BOOST_SOURCES_DIR}/libs/thread/src/win32/tss_pe.cpp + ${BOOST_FILESYSTEM_SOURCES_DIR}/windows_file_codecvt.cpp + ) + + # Starting with release 0.8.2, Orthanc statically links against + # libiconv, even on Windows. Indeed, the "WCONV" library of + # Windows XP seems not to support properly several codepages + # (notably "Latin3", "Hebrew", and "Arabic"). + + if (USE_BOOST_ICONV) + include(${ORTHANC_ROOT}/Resources/CMake/LibIconvConfiguration.cmake) + else() + add_definitions(-DBOOST_LOCALE_WITH_WCONV=1) + endif() + + else() + message(FATAL_ERROR "Support your platform here") + endif() + + if (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin") + list(APPEND BOOST_SOURCES + ${BOOST_SOURCES_DIR}/libs/filesystem/src/utf8_codecvt_facet.cpp + ) + endif() + + aux_source_directory(${BOOST_SOURCES_DIR}/libs/regex/src BOOST_REGEX_SOURCES) + + list(APPEND BOOST_SOURCES + ${BOOST_REGEX_SOURCES} + ${BOOST_SOURCES_DIR}/libs/date_time/src/gregorian/greg_month.cpp + ${BOOST_FILESYSTEM_SOURCES_DIR}/codecvt_error_category.cpp + ${BOOST_FILESYSTEM_SOURCES_DIR}/operations.cpp + ${BOOST_FILESYSTEM_SOURCES_DIR}/path.cpp + ${BOOST_FILESYSTEM_SOURCES_DIR}/path_traits.cpp + ${BOOST_SOURCES_DIR}/libs/locale/src/encoding/codepage.cpp + ${BOOST_SOURCES_DIR}/libs/system/src/error_code.cpp + ) + + add_definitions( + # Static build of Boost + -DBOOST_ALL_NO_LIB + -DBOOST_ALL_NOLIB + -DBOOST_DATE_TIME_NO_LIB + -DBOOST_THREAD_BUILD_LIB + -DBOOST_PROGRAM_OPTIONS_NO_LIB + -DBOOST_REGEX_NO_LIB + -DBOOST_SYSTEM_NO_LIB + -DBOOST_LOCALE_NO_LIB + -DBOOST_HAS_LOCALE=1 + -DBOOST_HAS_FILESYSTEM_V3=1 + ) + + if (CMAKE_COMPILER_IS_GNUCXX) + add_definitions(-isystem ${BOOST_SOURCES_DIR}) + endif() + + include_directories( + ${BOOST_SOURCES_DIR} + ) + + source_group(ThirdParty\\Boost REGULAR_EXPRESSION ${BOOST_SOURCES_DIR}/.*) +else() + add_definitions( + -DBOOST_HAS_LOCALE=1 + ) +endif() + + +add_definitions( + -DBOOST_HAS_DATE_TIME=1 + -DBOOST_HAS_REGEX=1 + ) diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/Compiler.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/Compiler.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,157 @@ +# This file sets all the compiler-related flags + +if (CMAKE_CROSSCOMPILING) + # Cross-compilation necessarily implies standalone and static build + SET(STATIC_BUILD ON) + SET(STANDALONE_BUILD ON) +endif() + +if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-long-long -Wno-implicit-function-declaration") + # --std=c99 makes libcurl not to compile + # -pedantic gives a lot of warnings on OpenSSL + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -pedantic -Wno-long-long -Wno-variadic-macros") + + if (CMAKE_CROSSCOMPILING) + # http://stackoverflow.com/a/3543845/881731 + set(CMAKE_RC_COMPILE_OBJECT " -O coff -I ") + endif() + +elseif (MSVC) + # Use static runtime under Visual Studio + # http://www.cmake.org/Wiki/CMake_FAQ#Dynamic_Replace + # http://stackoverflow.com/a/6510446 + foreach(flag_var + CMAKE_C_FLAGS_DEBUG + CMAKE_CXX_FLAGS_DEBUG + CMAKE_C_FLAGS_RELEASE + CMAKE_CXX_FLAGS_RELEASE + CMAKE_C_FLAGS_MINSIZEREL + CMAKE_CXX_FLAGS_MINSIZEREL + CMAKE_C_FLAGS_RELWITHDEBINFO + CMAKE_CXX_FLAGS_RELWITHDEBINFO) + string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") + string(REGEX REPLACE "/MDd" "/MTd" ${flag_var} "${${flag_var}}") + endforeach(flag_var) + + # Add /Zm256 compiler option to Visual Studio to fix PCH errors + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zm256") + + add_definitions( + -D_CRT_SECURE_NO_WARNINGS=1 + -D_CRT_SECURE_NO_DEPRECATE=1 + ) + include_directories(${ORTHANC_ROOT}/Resources/ThirdParty/VisualStudio) + link_libraries(netapi32) +endif() + + +if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,--no-undefined") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--no-undefined") + + if (NOT DEFINED ENABLE_PLUGINS_VERSION_SCRIPT OR + ENABLE_PLUGINS_VERSION_SCRIPT) + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--version-script=${ORTHANC_ROOT}/Plugins/Samples/Common/VersionScript.map") + endif() + + # Remove the "-rdynamic" option + # http://www.mail-archive.com/cmake@cmake.org/msg08837.html + set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") + link_libraries(uuid pthread rt) + + if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--as-needed") + set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,--as-needed") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--as-needed") + add_definitions( + -D_LARGEFILE64_SOURCE=1 + -D_FILE_OFFSET_BITS=64 + ) + link_libraries(dl) + endif() + +elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") + if (MSVC) + message("MSVC compiler version = " ${MSVC_VERSION} "\n") + # Starting Visual Studio 2013 (version 1800), it is not possible + # to target Windows XP anymore + if (MSVC_VERSION LESS 1800) + add_definitions( + -DWINVER=0x0501 + -D_WIN32_WINNT=0x0501 + ) + endif() + else() + add_definitions( + -DWINVER=0x0501 + -D_WIN32_WINNT=0x0501 + ) + endif() + + add_definitions( + -D_CRT_SECURE_NO_WARNINGS=1 + ) + link_libraries(rpcrt4 ws2_32) + + if (CMAKE_COMPILER_IS_GNUCXX) + # This is a patch for MinGW64 + SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--allow-multiple-definition -static-libgcc -static-libstdc++") + SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--allow-multiple-definition -static-libgcc -static-libstdc++") + + CHECK_LIBRARY_EXISTS(winpthread pthread_create "" HAVE_WIN_PTHREAD) + if (HAVE_WIN_PTHREAD) + # This line is necessary to compile with recent versions of MinGW, + # otherwise "libwinpthread-1.dll" is not statically linked. + SET(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -Wl,-Bstatic -lstdc++ -lpthread -Wl,-Bdynamic") + add_definitions(-DHAVE_WIN_PTHREAD=1) + else() + add_definitions(-DHAVE_WIN_PTHREAD=0) + endif() + endif() + +elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin") + SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -exported_symbols_list ${ORTHANC_ROOT}/Plugins/Samples/Common/ExportedSymbols.list") + + add_definitions( + -D_XOPEN_SOURCE=1 + ) + link_libraries(iconv) + +endif() + + +if ("${CMAKE_SYSTEM_VERSION}" STREQUAL "LinuxStandardBase") + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --lsb-target-version=${LSB_TARGET_VERSION} -I${LSB_PATH}/include") + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --lsb-target-version=${LSB_TARGET_VERSION} -nostdinc++ -I${LSB_PATH}/include -I${LSB_PATH}/include/c++ -I${LSB_PATH}/include/c++/backward -fpermissive") + SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --lsb-target-version=${LSB_TARGET_VERSION} -L${LSB_LIBPATH}") +endif() + + +if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") + # In FreeBSD, the "/usr/local/" folder contains the ports and need to be imported + SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include") + SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include") + SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib") + SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -L/usr/local/lib") +endif() + + +if (${CMAKE_SYSTEM_NAME} STREQUAL "Windows") + CHECK_INCLUDE_FILES(rpc.h HAVE_UUID_H) +else() + CHECK_INCLUDE_FILES(uuid/uuid.h HAVE_UUID_H) +endif() + +if (NOT HAVE_UUID_H) + message(FATAL_ERROR "Please install the uuid-dev package") +endif() + + +if (STATIC_BUILD) + add_definitions(-DORTHANC_STATIC=1) +else() + add_definitions(-DORTHANC_STATIC=0) +endif() diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/DownloadPackage.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/DownloadPackage.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,154 @@ +macro(GetUrlFilename TargetVariable Url) + string(REGEX REPLACE "^.*/" "" ${TargetVariable} "${Url}") +endmacro() + + +macro(GetUrlExtension TargetVariable Url) + #string(REGEX REPLACE "^.*/[^.]*\\." "" TMP "${Url}") + string(REGEX REPLACE "^.*\\." "" TMP "${Url}") + string(TOLOWER "${TMP}" "${TargetVariable}") +endmacro() + + + +## +## Setup the patch command-line tool +## + +if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") + set(PATCH_EXECUTABLE ${CMAKE_SOURCE_DIR}/Resources/ThirdParty/patch/patch.exe) +else () + find_program(PATCH_EXECUTABLE patch) + if (${PATCH_EXECUTABLE} MATCHES "PATCH_EXECUTABLE-NOTFOUND") + message(FATAL_ERROR "Please install the 'patch' standard command-line tool") + endif() +endif() + + + +## +## Check the existence of the required decompression tools +## + +if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") + find_program(ZIP_EXECUTABLE 7z + PATHS + "$ENV{ProgramFiles}/7-Zip" + "$ENV{ProgramW6432}/7-Zip" + ) + + if (${ZIP_EXECUTABLE} MATCHES "ZIP_EXECUTABLE-NOTFOUND") + message(FATAL_ERROR "Please install the '7-zip' software (http://www.7-zip.org/)") + endif() + +else() + find_program(UNZIP_EXECUTABLE unzip) + if (${UNZIP_EXECUTABLE} MATCHES "UNZIP_EXECUTABLE-NOTFOUND") + message(FATAL_ERROR "Please install the 'unzip' package") + endif() + + find_program(TAR_EXECUTABLE tar) + if (${TAR_EXECUTABLE} MATCHES "TAR_EXECUTABLE-NOTFOUND") + message(FATAL_ERROR "Please install the 'tar' package") + endif() +endif() + + +macro(DownloadPackage MD5 Url TargetDirectory) + if (NOT IS_DIRECTORY "${TargetDirectory}") + GetUrlFilename(TMP_FILENAME "${Url}") + + set(TMP_PATH "${CMAKE_SOURCE_DIR}/ThirdPartyDownloads/${TMP_FILENAME}") + if (NOT EXISTS "${TMP_PATH}") + message("Downloading ${Url}") + + # This fixes issue 6: "I think cmake shouldn't download the + # packages which are not in the system, it should stop and let + # user know." + # https://code.google.com/p/orthanc/issues/detail?id=6 + if (NOT STATIC_BUILD AND NOT ALLOW_DOWNLOADS) + message(FATAL_ERROR "CMake is not allowed to download from Internet. Please set the ALLOW_DOWNLOADS option to ON") + endif() + + file(DOWNLOAD "${Url}" "${TMP_PATH}" SHOW_PROGRESS EXPECTED_MD5 "${MD5}") + else() + message("Using local copy of ${Url}") + endif() + + GetUrlExtension(TMP_EXTENSION "${Url}") + #message(${TMP_EXTENSION}) + message("Uncompressing ${TMP_FILENAME}") + + if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") + # How to silently extract files using 7-zip + # http://superuser.com/questions/331148/7zip-command-line-extract-silently-quietly + + if (("${TMP_EXTENSION}" STREQUAL "gz") OR ("${TMP_EXTENSION}" STREQUAL "tgz")) + execute_process( + COMMAND ${ZIP_EXECUTABLE} e -y ${TMP_PATH} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + RESULT_VARIABLE Failure + OUTPUT_QUIET + ) + + if (Failure) + message(FATAL_ERROR "Error while running the uncompression tool") + endif() + + if ("${TMP_EXTENSION}" STREQUAL "tgz") + string(REGEX REPLACE ".tgz$" ".tar" TMP_FILENAME2 "${TMP_FILENAME}") + else() + string(REGEX REPLACE ".gz$" "" TMP_FILENAME2 "${TMP_FILENAME}") + endif() + + execute_process( + COMMAND ${ZIP_EXECUTABLE} x -y ${TMP_FILENAME2} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + RESULT_VARIABLE Failure + OUTPUT_QUIET + ) + elseif ("${TMP_EXTENSION}" STREQUAL "zip") + execute_process( + COMMAND ${ZIP_EXECUTABLE} x -y ${TMP_PATH} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + RESULT_VARIABLE Failure + OUTPUT_QUIET + ) + else() + message(FATAL_ERROR "Support your platform here") + endif() + + else() + if ("${TMP_EXTENSION}" STREQUAL "zip") + execute_process( + COMMAND sh -c "${UNZIP_EXECUTABLE} -q ${TMP_PATH}" + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + RESULT_VARIABLE Failure + ) + elseif (("${TMP_EXTENSION}" STREQUAL "gz") OR ("${TMP_EXTENSION}" STREQUAL "tgz")) + #message("tar xvfz ${TMP_PATH}") + execute_process( + COMMAND sh -c "${TAR_EXECUTABLE} xfz ${TMP_PATH}" + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + RESULT_VARIABLE Failure + ) + elseif ("${TMP_EXTENSION}" STREQUAL "bz2") + execute_process( + COMMAND sh -c "${TAR_EXECUTABLE} xfj ${TMP_PATH}" + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + RESULT_VARIABLE Failure + ) + else() + message(FATAL_ERROR "Unknown package format.") + endif() + endif() + + if (Failure) + message(FATAL_ERROR "Error while running the uncompression tool") + endif() + + if (NOT IS_DIRECTORY "${TargetDirectory}") + message(FATAL_ERROR "The package was not uncompressed at the proper location. Check the CMake instructions.") + endif() + endif() +endmacro() diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/GoogleTestConfiguration.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/GoogleTestConfiguration.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,39 @@ +if (USE_GTEST_DEBIAN_SOURCE_PACKAGE) + set(GTEST_SOURCES /usr/src/gtest/src/gtest-all.cc) + include_directories(/usr/src/gtest) + + if (NOT EXISTS /usr/include/gtest/gtest.h OR + NOT EXISTS ${GTEST_SOURCES}) + message(FATAL_ERROR "Please install the libgtest-dev package") + endif() + +elseif (STATIC_BUILD OR NOT USE_SYSTEM_GOOGLE_TEST) + set(GTEST_SOURCES_DIR ${CMAKE_BINARY_DIR}/gtest-1.7.0) + set(GTEST_URL "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/gtest-1.7.0.zip") + set(GTEST_MD5 "2d6ec8ccdf5c46b05ba54a9fd1d130d7") + + DownloadPackage(${GTEST_MD5} ${GTEST_URL} "${GTEST_SOURCES_DIR}") + + include_directories( + ${GTEST_SOURCES_DIR}/include + ${GTEST_SOURCES_DIR} + ) + + set(GTEST_SOURCES + ${GTEST_SOURCES_DIR}/src/gtest-all.cc + ) + + # https://code.google.com/p/googletest/issues/detail?id=412 + if (MSVC) # VS2012 does not support tuples correctly yet + add_definitions(/D _VARIADIC_MAX=10) + endif() + +else() + include(FindGTest) + if (NOT GTEST_FOUND) + message(FATAL_ERROR "Unable to find GoogleTest") + endif() + + include_directories(${GTEST_INCLUDE_DIRS}) + link_libraries(${GTEST_LIBRARIES}) +endif() diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/JsonCppConfiguration.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/JsonCppConfiguration.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,35 @@ +if (STATIC_BUILD OR NOT USE_SYSTEM_JSONCPP) + set(JSONCPP_SOURCES_DIR ${CMAKE_BINARY_DIR}/jsoncpp-0.10.5) + set(JSONCPP_URL "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/jsoncpp-0.10.5.tar.gz") + set(JSONCPP_MD5 "db146bac5a126ded9bd728ab7b61ed6b") + + DownloadPackage(${JSONCPP_MD5} ${JSONCPP_URL} "${JSONCPP_SOURCES_DIR}") + + set(JSONCPP_SOURCES + ${JSONCPP_SOURCES_DIR}/src/lib_json/json_reader.cpp + ${JSONCPP_SOURCES_DIR}/src/lib_json/json_value.cpp + ${JSONCPP_SOURCES_DIR}/src/lib_json/json_writer.cpp + ) + + include_directories( + ${JSONCPP_SOURCES_DIR}/include + ) + + source_group(ThirdParty\\JsonCpp REGULAR_EXPRESSION ${JSONCPP_SOURCES_DIR}/.*) + +else() + find_path(JSONCPP_INCLUDE_DIR json/reader.h + /usr/include/jsoncpp + /usr/local/include/jsoncpp + ) + + message("JsonCpp include dir: ${JSONCPP_INCLUDE_DIR}") + include_directories(${JSONCPP_INCLUDE_DIR}) + link_libraries(jsoncpp) + + CHECK_INCLUDE_FILE_CXX(${JSONCPP_INCLUDE_DIR}/json/reader.h HAVE_JSONCPP_H) + if (NOT HAVE_JSONCPP_H) + message(FATAL_ERROR "Please install the libjsoncpp-dev package") + endif() + +endif() diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/LibCurlConfiguration.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/LibCurlConfiguration.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,112 @@ +if (STATIC_BUILD OR NOT USE_SYSTEM_CURL) + SET(CURL_SOURCES_DIR ${CMAKE_BINARY_DIR}/curl-7.44.0) + SET(CURL_URL "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/curl-7.44.0.tar.gz") + SET(CURL_MD5 "cf46112b5151e2f1a3fd38439bdade23") + + DownloadPackage(${CURL_MD5} ${CURL_URL} "${CURL_SOURCES_DIR}") + + include_directories( + ${CURL_SOURCES_DIR}/include + ) + + AUX_SOURCE_DIRECTORY(${CURL_SOURCES_DIR}/lib CURL_SOURCES) + AUX_SOURCE_DIRECTORY(${CURL_SOURCES_DIR}/lib/vtls CURL_SOURCES) + source_group(ThirdParty\\LibCurl REGULAR_EXPRESSION ${CURL_SOURCES_DIR}/.*) + + add_definitions( + -DBUILDING_LIBCURL=1 + -DCURL_STATICLIB=1 + -DCURL_DISABLE_LDAPS=1 + -DCURL_DISABLE_LDAP=1 + -DCURL_DISABLE_DICT=1 + -DCURL_DISABLE_FILE=1 + -DCURL_DISABLE_FTP=1 + -DCURL_DISABLE_GOPHER=1 + -DCURL_DISABLE_LDAP=1 + -DCURL_DISABLE_LDAPS=1 + -DCURL_DISABLE_POP3=1 + #-DCURL_DISABLE_PROXY=1 + -DCURL_DISABLE_RTSP=1 + -DCURL_DISABLE_TELNET=1 + -DCURL_DISABLE_TFTP=1 + ) + + if (ENABLE_SSL) + add_definitions( + #-DHAVE_LIBSSL=1 + -DUSE_OPENSSL=1 + -DUSE_SSLEAY=1 + ) + endif() + + file(WRITE ${CURL_SOURCES_DIR}/lib/curl_config.h "") + + file(GLOB CURL_LIBS_HEADERS ${CURL_SOURCES_DIR}/lib/*.h) + foreach (header IN LISTS CURL_LIBS_HEADERS) + get_filename_component(filename ${header} NAME) + file(WRITE ${CURL_SOURCES_DIR}/lib/vtls/${filename} "#include \"../${filename}\"\n") + endforeach() + + if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "Darwin" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD" OR + ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD") + if ("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + SET(TMP_OS "x86_64") + else() + SET(TMP_OS "x86") + endif() + + set_property( + SOURCE ${CURL_SOURCES} + PROPERTY COMPILE_DEFINITIONS "HAVE_TIME_H;HAVE_STRUCT_TIMEVAL;HAVE_SYS_STAT_H;HAVE_SOCKET;HAVE_STRUCT_SOCKADDR_STORAGE;HAVE_SYS_SOCKET_H;HAVE_SOCKET;HAVE_SYS_SOCKET_H;HAVE_NETINET_IN_H;HAVE_NETDB_H;HAVE_FCNTL_O_NONBLOCK;HAVE_FCNTL_H;HAVE_SELECT;HAVE_ERRNO_H;HAVE_SEND;HAVE_RECV;HAVE_LONGLONG;OS=\"${TMP_OS}\"" + ) + + if ("${CMAKE_SIZEOF_VOID_P}" EQUAL "8") + add_definitions( + -DRECV_TYPE_ARG1=int + -DRECV_TYPE_ARG2=void* + -DRECV_TYPE_ARG3=size_t + -DRECV_TYPE_ARG4=int + -DRECV_TYPE_RETV=ssize_t + -DSEND_TYPE_ARG1=int + -DSEND_TYPE_ARG2=void* + -DSEND_QUAL_ARG2=const + -DSEND_TYPE_ARG3=size_t + -DSEND_TYPE_ARG4=int + -DSEND_TYPE_RETV=ssize_t + -DSIZEOF_SHORT=2 + -DSIZEOF_INT=4 + -DSIZEOF_SIZE_T=8 + ) + elseif ("${CMAKE_SIZEOF_VOID_P}" EQUAL "4") + add_definitions( + -DRECV_TYPE_ARG1=int + -DRECV_TYPE_ARG2=void* + -DRECV_TYPE_ARG3=size_t + -DRECV_TYPE_ARG4=int + -DRECV_TYPE_RETV=int + -DSEND_TYPE_ARG1=int + -DSEND_TYPE_ARG2=void* + -DSEND_QUAL_ARG2=const + -DSEND_TYPE_ARG3=size_t + -DSEND_TYPE_ARG4=int + -DSEND_TYPE_RETV=int + -DSIZEOF_SHORT=2 + -DSIZEOF_INT=4 + -DSIZEOF_SIZE_T=4 + ) + else() + message(FATAL_ERROR "Support your platform here") + endif() + endif() + +else() + include(FindCURL) + include_directories(${CURL_INCLUDE_DIRS}) + link_libraries(${CURL_LIBRARIES}) + + if (NOT ${CURL_FOUND}) + message(FATAL_ERROR "Unable to find LibCurl") + endif() +endif() diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/LibPngConfiguration.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/LibPngConfiguration.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,61 @@ +if (STATIC_BUILD OR NOT USE_SYSTEM_LIBPNG) + SET(LIBPNG_SOURCES_DIR ${CMAKE_BINARY_DIR}/libpng-1.5.12) + SET(LIBPNG_URL "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/libpng-1.5.12.tar.gz") + SET(LIBPNG_MD5 "8ea7f60347a306c5faf70b977fa80e28") + + DownloadPackage(${LIBPNG_MD5} ${LIBPNG_URL} "${LIBPNG_SOURCES_DIR}") + + include_directories( + ${LIBPNG_SOURCES_DIR} + ) + + configure_file( + ${LIBPNG_SOURCES_DIR}/scripts/pnglibconf.h.prebuilt + ${LIBPNG_SOURCES_DIR}/pnglibconf.h + ) + + set(LIBPNG_SOURCES + #${LIBPNG_SOURCES_DIR}/example.c + ${LIBPNG_SOURCES_DIR}/png.c + ${LIBPNG_SOURCES_DIR}/pngerror.c + ${LIBPNG_SOURCES_DIR}/pngget.c + ${LIBPNG_SOURCES_DIR}/pngmem.c + ${LIBPNG_SOURCES_DIR}/pngpread.c + ${LIBPNG_SOURCES_DIR}/pngread.c + ${LIBPNG_SOURCES_DIR}/pngrio.c + ${LIBPNG_SOURCES_DIR}/pngrtran.c + ${LIBPNG_SOURCES_DIR}/pngrutil.c + ${LIBPNG_SOURCES_DIR}/pngset.c + #${LIBPNG_SOURCES_DIR}/pngtest.c + ${LIBPNG_SOURCES_DIR}/pngtrans.c + ${LIBPNG_SOURCES_DIR}/pngwio.c + ${LIBPNG_SOURCES_DIR}/pngwrite.c + ${LIBPNG_SOURCES_DIR}/pngwtran.c + ${LIBPNG_SOURCES_DIR}/pngwutil.c + ) + + #set_property( + # SOURCE ${LIBPNG_SOURCES} + # PROPERTY COMPILE_FLAGS -UHAVE_CONFIG_H) + + add_definitions( + -DPNG_NO_CONSOLE_IO=1 + -DPNG_NO_STDIO=1 + # The following declaration avoids "__declspec(dllexport)" in + # libpng to prevent publicly exposing its symbols by the DLLs + -DPNG_IMPEXP= + ) + + source_group(ThirdParty\\Libpng REGULAR_EXPRESSION ${LIBPNG_SOURCES_DIR}/.*) + +else() + include(FindPNG) + + if (NOT ${PNG_FOUND}) + message(FATAL_ERROR "Unable to find libpng") + endif() + + include_directories(${PNG_INCLUDE_DIRS}) + link_libraries(${PNG_LIBRARIES}) + add_definitions(${PNG_DEFINITIONS}) +endif() diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/OpenSslConfiguration.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/OpenSslConfiguration.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,205 @@ +if (STATIC_BUILD OR NOT USE_SYSTEM_OPENSSL) + # WARNING - We had to repack the upstream ".tar.gz" file to a ZIP + # file, as the upstream distribution ships symbolic links that are + # not always properly handled when uncompressing on Windows. + + SET(OPENSSL_SOURCES_DIR ${CMAKE_BINARY_DIR}/openssl-1.0.2d) + SET(OPENSSL_URL "www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/openssl-1.0.2d.zip") + SET(OPENSSL_MD5 "4b2ac15fc6db17f3dadc54482d3eee85") + + if (IS_DIRECTORY "${OPENSSL_SOURCES_DIR}") + set(FirstRun OFF) + else() + set(FirstRun ON) + endif() + + DownloadPackage(${OPENSSL_MD5} ${OPENSSL_URL} "${OPENSSL_SOURCES_DIR}") + + add_definitions( + -DOPENSSL_THREADS + -DOPENSSL_IA32_SSE2 + -DOPENSSL_NO_ASM + -DOPENSSL_NO_DYNAMIC_ENGINE + -DNO_WINDOWS_BRAINDEATH + + -DOPENSSL_NO_BF + -DOPENSSL_NO_CAMELLIA + -DOPENSSL_NO_CAST + -DOPENSSL_NO_EC + -DOPENSSL_NO_ECDH + -DOPENSSL_NO_ECDSA + -DOPENSSL_NO_EC_NISTP_64_GCC_128 + -DOPENSSL_NO_GMP + -DOPENSSL_NO_GOST + -DOPENSSL_NO_HW + -DOPENSSL_NO_JPAKE + -DOPENSSL_NO_IDEA + -DOPENSSL_NO_KRB5 + -DOPENSSL_NO_MD2 + -DOPENSSL_NO_MDC2 + -DOPENSSL_NO_MD4 + -DOPENSSL_NO_RC2 + -DOPENSSL_NO_RC4 + -DOPENSSL_NO_RC5 + -DOPENSSL_NO_RFC3779 + -DOPENSSL_NO_SCTP + -DOPENSSL_NO_STORE + -DOPENSSL_NO_SEED + -DOPENSSL_NO_WHIRLPOOL + -DOPENSSL_NO_RIPEMD + ) + + include_directories( + ${OPENSSL_SOURCES_DIR} + ${OPENSSL_SOURCES_DIR}/crypto + ${OPENSSL_SOURCES_DIR}/crypto/asn1 + ${OPENSSL_SOURCES_DIR}/crypto/modes + ${OPENSSL_SOURCES_DIR}/crypto/evp + ${OPENSSL_SOURCES_DIR}/include + ) + + set(OPENSSL_SOURCES_SUBDIRS + ${OPENSSL_SOURCES_DIR}/crypto + ${OPENSSL_SOURCES_DIR}/crypto/aes + ${OPENSSL_SOURCES_DIR}/crypto/asn1 + ${OPENSSL_SOURCES_DIR}/crypto/bio + ${OPENSSL_SOURCES_DIR}/crypto/bn + ${OPENSSL_SOURCES_DIR}/crypto/buffer + ${OPENSSL_SOURCES_DIR}/crypto/cmac + ${OPENSSL_SOURCES_DIR}/crypto/cms + ${OPENSSL_SOURCES_DIR}/crypto/comp + ${OPENSSL_SOURCES_DIR}/crypto/conf + ${OPENSSL_SOURCES_DIR}/crypto/des + ${OPENSSL_SOURCES_DIR}/crypto/dh + ${OPENSSL_SOURCES_DIR}/crypto/dsa + ${OPENSSL_SOURCES_DIR}/crypto/dso + ${OPENSSL_SOURCES_DIR}/crypto/engine + ${OPENSSL_SOURCES_DIR}/crypto/err + ${OPENSSL_SOURCES_DIR}/crypto/evp + ${OPENSSL_SOURCES_DIR}/crypto/hmac + ${OPENSSL_SOURCES_DIR}/crypto/lhash + ${OPENSSL_SOURCES_DIR}/crypto/md5 + ${OPENSSL_SOURCES_DIR}/crypto/modes + ${OPENSSL_SOURCES_DIR}/crypto/objects + ${OPENSSL_SOURCES_DIR}/crypto/ocsp + ${OPENSSL_SOURCES_DIR}/crypto/pem + ${OPENSSL_SOURCES_DIR}/crypto/pkcs12 + ${OPENSSL_SOURCES_DIR}/crypto/pkcs7 + ${OPENSSL_SOURCES_DIR}/crypto/pqueue + ${OPENSSL_SOURCES_DIR}/crypto/rand + ${OPENSSL_SOURCES_DIR}/crypto/rsa + ${OPENSSL_SOURCES_DIR}/crypto/sha + ${OPENSSL_SOURCES_DIR}/crypto/srp + ${OPENSSL_SOURCES_DIR}/crypto/stack + ${OPENSSL_SOURCES_DIR}/crypto/ts + ${OPENSSL_SOURCES_DIR}/crypto/txt_db + ${OPENSSL_SOURCES_DIR}/crypto/ui + ${OPENSSL_SOURCES_DIR}/crypto/x509 + ${OPENSSL_SOURCES_DIR}/crypto/x509v3 + ${OPENSSL_SOURCES_DIR}/ssl + ) + + foreach(d ${OPENSSL_SOURCES_SUBDIRS}) + AUX_SOURCE_DIRECTORY(${d} OPENSSL_SOURCES) + endforeach() + + list(REMOVE_ITEM OPENSSL_SOURCES + ${OPENSSL_SOURCES_DIR}/crypto/LPdir_unix.c + ${OPENSSL_SOURCES_DIR}/crypto/LPdir_vms.c + ${OPENSSL_SOURCES_DIR}/crypto/LPdir_win.c + ${OPENSSL_SOURCES_DIR}/crypto/LPdir_win32.c + ${OPENSSL_SOURCES_DIR}/crypto/LPdir_wince.c + ${OPENSSL_SOURCES_DIR}/crypto/armcap.c + ${OPENSSL_SOURCES_DIR}/crypto/bf/bfs.cpp + ${OPENSSL_SOURCES_DIR}/crypto/bio/bss_rtcp.c + ${OPENSSL_SOURCES_DIR}/crypto/bn/exp.c + ${OPENSSL_SOURCES_DIR}/crypto/conf/cnf_save.c + ${OPENSSL_SOURCES_DIR}/crypto/conf/test.c + ${OPENSSL_SOURCES_DIR}/crypto/des/des.c + ${OPENSSL_SOURCES_DIR}/crypto/des/des3s.cpp + ${OPENSSL_SOURCES_DIR}/crypto/des/des_opts.c + ${OPENSSL_SOURCES_DIR}/crypto/des/dess.cpp + ${OPENSSL_SOURCES_DIR}/crypto/des/read_pwd.c + ${OPENSSL_SOURCES_DIR}/crypto/des/speed.c + ${OPENSSL_SOURCES_DIR}/crypto/evp/e_dsa.c + ${OPENSSL_SOURCES_DIR}/crypto/evp/m_ripemd.c + ${OPENSSL_SOURCES_DIR}/crypto/lhash/lh_test.c + ${OPENSSL_SOURCES_DIR}/crypto/md5/md5s.cpp + ${OPENSSL_SOURCES_DIR}/crypto/pkcs7/bio_ber.c + ${OPENSSL_SOURCES_DIR}/crypto/pkcs7/pk7_enc.c + ${OPENSSL_SOURCES_DIR}/crypto/ppccap.c + ${OPENSSL_SOURCES_DIR}/crypto/rand/randtest.c + ${OPENSSL_SOURCES_DIR}/crypto/s390xcap.c + ${OPENSSL_SOURCES_DIR}/crypto/sparcv9cap.c + ${OPENSSL_SOURCES_DIR}/crypto/x509v3/tabtest.c + ${OPENSSL_SOURCES_DIR}/crypto/x509v3/v3conf.c + ${OPENSSL_SOURCES_DIR}/ssl/ssl_task.c + ${OPENSSL_SOURCES_DIR}/crypto/LPdir_nyi.c + ${OPENSSL_SOURCES_DIR}/crypto/aes/aes_x86core.c + ${OPENSSL_SOURCES_DIR}/crypto/bio/bss_dgram.c + ${OPENSSL_SOURCES_DIR}/crypto/bn/bntest.c + ${OPENSSL_SOURCES_DIR}/crypto/bn/expspeed.c + ${OPENSSL_SOURCES_DIR}/crypto/bn/exptest.c + ${OPENSSL_SOURCES_DIR}/crypto/engine/enginetest.c + ${OPENSSL_SOURCES_DIR}/crypto/evp/evp_test.c + ${OPENSSL_SOURCES_DIR}/crypto/hmac/hmactest.c + ${OPENSSL_SOURCES_DIR}/crypto/md5/md5.c + ${OPENSSL_SOURCES_DIR}/crypto/md5/md5test.c + ${OPENSSL_SOURCES_DIR}/crypto/o_dir_test.c + ${OPENSSL_SOURCES_DIR}/crypto/pkcs7/dec.c + ${OPENSSL_SOURCES_DIR}/crypto/pkcs7/enc.c + ${OPENSSL_SOURCES_DIR}/crypto/pkcs7/sign.c + ${OPENSSL_SOURCES_DIR}/crypto/pkcs7/verify.c + ${OPENSSL_SOURCES_DIR}/crypto/rsa/rsa_test.c + ${OPENSSL_SOURCES_DIR}/crypto/sha/sha.c + ${OPENSSL_SOURCES_DIR}/crypto/sha/sha1.c + ${OPENSSL_SOURCES_DIR}/crypto/sha/sha1t.c + ${OPENSSL_SOURCES_DIR}/crypto/sha/sha1test.c + ${OPENSSL_SOURCES_DIR}/crypto/sha/sha256t.c + ${OPENSSL_SOURCES_DIR}/crypto/sha/sha512t.c + ${OPENSSL_SOURCES_DIR}/crypto/sha/shatest.c + ${OPENSSL_SOURCES_DIR}/crypto/srp/srptest.c + + ${OPENSSL_SOURCES_DIR}/crypto/bn/divtest.c + ${OPENSSL_SOURCES_DIR}/crypto/bn/bnspeed.c + ${OPENSSL_SOURCES_DIR}/crypto/des/destest.c + ${OPENSSL_SOURCES_DIR}/crypto/dh/p192.c + ${OPENSSL_SOURCES_DIR}/crypto/dh/p512.c + ${OPENSSL_SOURCES_DIR}/crypto/dh/p1024.c + ${OPENSSL_SOURCES_DIR}/crypto/des/rpw.c + ${OPENSSL_SOURCES_DIR}/ssl/ssltest.c + ${OPENSSL_SOURCES_DIR}/crypto/dsa/dsagen.c + ${OPENSSL_SOURCES_DIR}/crypto/dsa/dsatest.c + ${OPENSSL_SOURCES_DIR}/crypto/dh/dhtest.c + ${OPENSSL_SOURCES_DIR}/crypto/pqueue/pq_test.c + ${OPENSSL_SOURCES_DIR}/crypto/des/ncbc_enc.c + ) + + if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") + set_source_files_properties( + ${OPENSSL_SOURCES} + PROPERTIES COMPILE_DEFINITIONS + "OPENSSL_SYSNAME_WIN32;SO_WIN32;WIN32_LEAN_AND_MEAN;L_ENDIAN") + + elseif ("${CMAKE_SYSTEM_VERSION}" STREQUAL "LinuxStandardBase") + execute_process( + COMMAND ${PATCH_EXECUTABLE} -N ui_openssl.c -i ${ORTHANC_ROOT}/Resources/Patches/openssl-lsb.diff + WORKING_DIRECTORY ${OPENSSL_SOURCES_DIR}/crypto/ui + RESULT_VARIABLE Failure + ) + + if (Failure AND FirstRun) + message(FATAL_ERROR "Error while patching a file") + endif() + endif() + +else() + include(FindOpenSSL) + + if (NOT ${OPENSSL_FOUND}) + message(FATAL_ERROR "Unable to find OpenSSL") + endif() + + include_directories(${OPENSSL_INCLUDE_DIR}) + link_libraries(${OPENSSL_LIBRARIES}) +endif() diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/Uninstall.cmake.in --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/Uninstall.cmake.in Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,25 @@ +# Code taken from the CMake FAQ +# http://www.cmake.org/Wiki/CMake_FAQ#Can_I_do_.22make_uninstall.22_with_CMake.3F + +if (NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + message(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") +endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + +file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) +string(REGEX REPLACE "\n" ";" files "${files}") +list(REVERSE files) +foreach (file ${files}) + message(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"") + if (EXISTS "$ENV{DESTDIR}${file}") + execute_process( + COMMAND @CMAKE_COMMAND@ -E remove "$ENV{DESTDIR}${file}" + OUTPUT_VARIABLE rm_out + RESULT_VARIABLE rm_retval + ) + if(NOT ${rm_retval} EQUAL 0) + message(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"") + endif (NOT ${rm_retval} EQUAL 0) + else (EXISTS "$ENV{DESTDIR}${file}") + message(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.") + endif (EXISTS "$ENV{DESTDIR}${file}") +endforeach(file) diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/CMake/ZlibConfiguration.cmake --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/CMake/ZlibConfiguration.cmake Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,36 @@ +if (STATIC_BUILD OR NOT USE_SYSTEM_ZLIB) + SET(ZLIB_SOURCES_DIR ${CMAKE_BINARY_DIR}/zlib-1.2.7) + SET(ZLIB_URL "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/zlib-1.2.7.tar.gz") + SET(ZLIB_MD5 "60df6a37c56e7c1366cca812414f7b85") + + DownloadPackage(${ZLIB_MD5} ${ZLIB_URL} "${ZLIB_SOURCES_DIR}") + + include_directories( + ${ZLIB_SOURCES_DIR} + ) + + list(APPEND ZLIB_SOURCES + ${ZLIB_SOURCES_DIR}/adler32.c + ${ZLIB_SOURCES_DIR}/compress.c + ${ZLIB_SOURCES_DIR}/crc32.c + ${ZLIB_SOURCES_DIR}/deflate.c + ${ZLIB_SOURCES_DIR}/gzclose.c + ${ZLIB_SOURCES_DIR}/gzlib.c + ${ZLIB_SOURCES_DIR}/gzread.c + ${ZLIB_SOURCES_DIR}/gzwrite.c + ${ZLIB_SOURCES_DIR}/infback.c + ${ZLIB_SOURCES_DIR}/inffast.c + ${ZLIB_SOURCES_DIR}/inflate.c + ${ZLIB_SOURCES_DIR}/inftrees.c + ${ZLIB_SOURCES_DIR}/trees.c + ${ZLIB_SOURCES_DIR}/uncompr.c + ${ZLIB_SOURCES_DIR}/zutil.c + ) + +else() + include(FindZLIB) + include_directories(${ZLIB_INCLUDE_DIRS}) + link_libraries(${ZLIB_LIBRARIES}) +endif() + +source_group(ThirdParty\\ZLib REGULAR_EXPRESSION ${ZLIB_SOURCES_DIR}/.*) diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/OrthancLogoDocumentation.png Binary file Orthanc/Resources/OrthancLogoDocumentation.png has changed diff -r a07ee8b6946e -r f7379096e014 Orthanc/Resources/ThirdParty/VisualStudio/stdint.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Orthanc/Resources/ThirdParty/VisualStudio/stdint.h Mon Jan 04 14:21:51 2016 +0100 @@ -0,0 +1,247 @@ +// ISO C9x compliant stdint.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006-2008 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. The name of the author may 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. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_STDINT_H_ // [ +#define _MSC_STDINT_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +// For Visual Studio 6 in C++ mode and for many Visual Studio versions when +// compiling for ARM we should wrap include with 'extern "C++" {}' +// or compiler give many errors like this: +// error C2733: second C linkage of overloaded function 'wmemchr' not allowed +#ifdef __cplusplus +extern "C" { +#endif +# include +#ifdef __cplusplus +} +#endif + +// Define _W64 macros to mark types changing their size, like intptr_t. +#ifndef _W64 +# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +# define _W64 __w64 +# else +# define _W64 +# endif +#endif + + +// 7.18.1 Integer types + +// 7.18.1.1 Exact-width integer types + +// Visual Studio 6 and Embedded Visual C++ 4 doesn't +// realize that, e.g. char has the same size as __int8 +// so we give up on __intX for them. +#if (_MSC_VER < 1300) + typedef signed char int8_t; + typedef signed short int16_t; + typedef signed int int32_t; + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; +#else + typedef signed __int8 int8_t; + typedef signed __int16 int16_t; + typedef signed __int32 int32_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; +#endif +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; + + +// 7.18.1.2 Minimum-width integer types +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; + +// 7.18.1.3 Fastest minimum-width integer types +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; + +// 7.18.1.4 Integer types capable of holding object pointers +#ifdef _WIN64 // [ + typedef signed __int64 intptr_t; + typedef unsigned __int64 uintptr_t; +#else // _WIN64 ][ + typedef _W64 signed int intptr_t; + typedef _W64 unsigned int uintptr_t; +#endif // _WIN64 ] + +// 7.18.1.5 Greatest-width integer types +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + + +// 7.18.2 Limits of specified-width integer types + +#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 + +// 7.18.2.1 Limits of exact-width integer types +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX + +// 7.18.2.2 Limits of minimum-width integer types +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +// 7.18.2.3 Limits of fastest minimum-width integer types +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +// 7.18.2.4 Limits of integer types capable of holding object pointers +#ifdef _WIN64 // [ +# define INTPTR_MIN INT64_MIN +# define INTPTR_MAX INT64_MAX +# define UINTPTR_MAX UINT64_MAX +#else // _WIN64 ][ +# define INTPTR_MIN INT32_MIN +# define INTPTR_MAX INT32_MAX +# define UINTPTR_MAX UINT32_MAX +#endif // _WIN64 ] + +// 7.18.2.5 Limits of greatest-width integer types +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +// 7.18.3 Limits of other integer types + +#ifdef _WIN64 // [ +# define PTRDIFF_MIN _I64_MIN +# define PTRDIFF_MAX _I64_MAX +#else // _WIN64 ][ +# define PTRDIFF_MIN _I32_MIN +# define PTRDIFF_MAX _I32_MAX +#endif // _WIN64 ] + +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX + +#ifndef SIZE_MAX // [ +# ifdef _WIN64 // [ +# define SIZE_MAX _UI64_MAX +# else // _WIN64 ][ +# define SIZE_MAX _UI32_MAX +# endif // _WIN64 ] +#endif // SIZE_MAX ] + +// WCHAR_MIN and WCHAR_MAX are also defined in +#ifndef WCHAR_MIN // [ +# define WCHAR_MIN 0 +#endif // WCHAR_MIN ] +#ifndef WCHAR_MAX // [ +# define WCHAR_MAX _UI16_MAX +#endif // WCHAR_MAX ] + +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX + +#endif // __STDC_LIMIT_MACROS ] + + +// 7.18.4 Limits of other integer types + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 + +// 7.18.4.1 Macros for minimum-width integer constants + +#define INT8_C(val) val##i8 +#define INT16_C(val) val##i16 +#define INT32_C(val) val##i32 +#define INT64_C(val) val##i64 + +#define UINT8_C(val) val##ui8 +#define UINT16_C(val) val##ui16 +#define UINT32_C(val) val##ui32 +#define UINT64_C(val) val##ui64 + +// 7.18.4.2 Macros for greatest-width integer constants +#define INTMAX_C INT64_C +#define UINTMAX_C UINT64_C + +#endif // __STDC_CONSTANT_MACROS ] + + +#endif // _MSC_STDINT_H_ ] diff -r a07ee8b6946e -r f7379096e014 Resources/SyncOrthancFolder.py --- a/Resources/SyncOrthancFolder.py Mon Jan 04 14:04:43 2016 +0100 +++ b/Resources/SyncOrthancFolder.py Mon Jan 04 14:21:51 2016 +0100 @@ -16,6 +16,7 @@ FILES = [ 'Core/ChunkedBuffer.cpp', 'Core/ChunkedBuffer.h', + 'Core/Enumerations.h', 'Core/Enumerations.cpp', 'Core/HttpClient.cpp', 'Core/HttpClient.h', @@ -25,6 +26,7 @@ 'Core/Images/ImageAccessor.h', 'Core/Images/PngReader.cpp', 'Core/Images/PngReader.h', + 'Core/Logging.h', 'Core/MultiThreading/SharedMessageQueue.cpp', 'Core/MultiThreading/SharedMessageQueue.h', 'Core/OrthancException.h', @@ -42,16 +44,6 @@ 'Resources/CMake/Uninstall.cmake.in', 'Resources/CMake/ZlibConfiguration.cmake', 'Resources/OrthancLogoDocumentation.png', - 'Resources/ThirdParty/base64/base64.cpp', - 'Resources/ThirdParty/base64/base64.h', - 'Resources/ThirdParty/md5/md5.c', - 'Resources/ThirdParty/md5/md5.h', - 'Resources/ThirdParty/minizip/NOTES', - 'Resources/ThirdParty/minizip/crypt.h', - 'Resources/ThirdParty/minizip/ioapi.c', - 'Resources/ThirdParty/minizip/ioapi.h', - 'Resources/ThirdParty/minizip/zip.c', - 'Resources/ThirdParty/minizip/zip.h', 'Resources/ThirdParty/VisualStudio/stdint.h', 'Core/Enumerations.h', ] diff -r a07ee8b6946e -r f7379096e014 SharedLibrary/SharedLibrary.cpp --- a/SharedLibrary/SharedLibrary.cpp Mon Jan 04 14:04:43 2016 +0100 +++ b/SharedLibrary/SharedLibrary.cpp Mon Jan 04 14:21:51 2016 +0100 @@ -40,7 +40,7 @@ public: SharedLibrarySingleton() { - Orthanc::HttpClient::GlobalInitialize(); + Orthanc::HttpClient::GlobalInitialize(false, ""); } ~SharedLibrarySingleton()