Initial commit of server program and common lib 36/66336/1
authorKyungwook Tak <k.tak@samsung.com>
Wed, 16 Mar 2016 04:54:33 +0000 (13:54 +0900)
committerKyungwook Tak <k.tak@samsung.com>
Mon, 18 Apr 2016 11:11:56 +0000 (20:11 +0900)
Base code of IPC is from device-policy-manager package
which is written by Jaemin Ryu (jm77.ryu@samsung.com)

Change-Id: Id00a88ee5711281ba6fc6a87dbeaba051c630246
Signed-off-by: Kyungwook Tak <k.tak@samsung.com>
82 files changed:
CMakeLists.txt
LICENSE
LICENSE.BSL-1.0 [new file with mode: 0644]
README [deleted file]
csr-framework.changes [deleted file]
doc/Tizen Content Screening API Specification.pdf [deleted file]
doc/Tizen Content Screening Plugin API Specification.pdf [deleted file]
doc/Tizen Content Screening Test Specification.pdf [deleted file]
doc/Tizen Content Security Framework Proposal.pdf [deleted file]
doc/Tizen Web Protection API Specification.pdf [deleted file]
doc/Tizen Web Protection Plugin API Specification.pdf [deleted file]
doc/Tizen Web Protection Test Specification.pdf [deleted file]
doc/csrfw_TCSImpl_doc.h [deleted file]
doc/csrfw_TWPImpl_doc.h [deleted file]
doc/csrfw_doc.h [deleted file]
doc/images/csr_framework_overview.png [deleted file]
framework/CMakeLists.txt [deleted file]
framework/CsrLog.h [deleted file]
packaging/csr-client.manifest.in [new file with mode: 0644]
packaging/csr-common.manifest.in [new file with mode: 0644]
packaging/csr-framework.manifest [deleted file]
packaging/csr-framework.spec
packaging/csr.manifest.in [new file with mode: 0644]
pkgconfig/CMakeLists.txt
pkgconfig/csr.pc.in [moved from pkgconfig/csr-framework.pc.in with 79% similarity]
src/CMakeLists.txt
src/framework/CMakeLists.txt
src/framework/client/TCSImpl.c [deleted file]
src/framework/client/TWPImpl.c [deleted file]
src/framework/client/api.cpp [new file with mode: 0644]
src/framework/common/audit/console-sink.cpp [new file with mode: 0644]
src/framework/common/audit/console-sink.h [new file with mode: 0644]
src/framework/common/audit/dlog-sink.cpp [new file with mode: 0644]
src/framework/common/audit/dlog-sink.h [new file with mode: 0644]
src/framework/common/audit/log-sink.h [new file with mode: 0644]
src/framework/common/audit/logger.cpp [new file with mode: 0644]
src/framework/common/audit/logger.h [new file with mode: 0644]
src/framework/common/binary-queue.cpp [new file with mode: 0644]
src/framework/common/binary-queue.h [new file with mode: 0644]
src/framework/common/command-id.h [new file with mode: 0644]
src/framework/common/connection.cpp [new file with mode: 0644]
src/framework/common/connection.h [new file with mode: 0644]
src/framework/common/message-buffer.cpp [new file with mode: 0644]
src/framework/common/message-buffer.h [new file with mode: 0644]
src/framework/common/raw-buffer.h [new file with mode: 0644]
src/framework/common/serialization.h [new file with mode: 0644]
src/framework/common/socket.cpp [new file with mode: 0644]
src/framework/common/socket.h [new file with mode: 0644]
src/framework/main/csr-main.cpp [new file with mode: 0644]
src/framework/main/mainloop.cpp [new file with mode: 0644]
src/framework/main/mainloop.h [new file with mode: 0644]
src/framework/service/logic.cpp [new file with mode: 0644]
src/framework/service/logic.h [new file with mode: 0644]
src/framework/service/service.cpp [new file with mode: 0644]
src/framework/service/service.h [new file with mode: 0644]
src/include/CMakeLists.txt
src/include/csr/TCSErrorCodes.h [deleted file]
src/include/csr/TCSImpl.h [deleted file]
src/include/csr/TWPImpl.h [deleted file]
src/include/csr/api.h [new file with mode: 0644]
src/include/csr/error.h [new file with mode: 0644]
systemd/CMakeLists.txt [new file with mode: 0644]
systemd/csr.service.in [new file with mode: 0644]
systemd/csr.socket.in [new file with mode: 0644]
test/CMakeLists.txt
test/SampleInfo.c [deleted file]
test/SampleInfo.h [deleted file]
test/TCSTest.c [deleted file]
test/TCSTest.h [deleted file]
test/TCSTestUtils.c [deleted file]
test/TWPTest.c [deleted file]
test/TWPTest.h [deleted file]
test/TWPTestUtils.c [deleted file]
test/UrlInfo.h [deleted file]
test/XMHttp.c [deleted file]
test/XMHttp.h [deleted file]
test/XMPHttp.c [deleted file]
test/XMPHttp.h [deleted file]
test/colour_log_formatter.cpp [new file with mode: 0644]
test/colour_log_formatter.h [new file with mode: 0644]
test/test-api.cpp [new file with mode: 0644]
test/test-main.cpp [new file with mode: 0644]

index c341561..6b8e194 100644 (file)
@@ -25,8 +25,8 @@ SET(CMAKE_C_FLAGS_PROFILING    "-g -O0 -pg -Wp,-U_FORTIFY_SOURCE")
 SET(CMAKE_CXX_FLAGS_PROFILING  "-g -std=c++0x -O0 -pg -Wp,-U_FORTIFY_SOURCE")
 SET(CMAKE_C_FLAGS_DEBUG        "-g -O0 -ggdb -Wp,-U_FORTIFY_SOURCE")
 SET(CMAKE_CXX_FLAGS_DEBUG      "-g -std=c++0x -O0 -ggdb -Wp,-U_FORTIFY_SOURCE")
-SET(CMAKE_C_FLAGS_RELEASE      "-g -O2")
-SET(CMAKE_CXX_FLAGS_RELEASE    "-g -std=c++0x -O2")
+SET(CMAKE_C_FLAGS_RELEASE      "-g -O2 -DNDEBUG")
+SET(CMAKE_CXX_FLAGS_RELEASE    "-g -std=c++0x -O2 -DNDEBUG")
 SET(CMAKE_C_FLAGS_CCOV         "-g -O2 --coverage")
 SET(CMAKE_CXX_FLAGS_CCOV       "-g -std=c++0x -O2 --coverage")
 
@@ -37,23 +37,24 @@ ADD_DEFINITIONS("-Wextra")
 
 STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}")
 ADD_DEFINITIONS("-DSERVICE_NAME=\"${SERVICE_NAME}\"")
-ADD_DEFINITIONS("-DCLIENT_NAME=\"${CLIENT_NAME}\"")
 ADD_DEFINITIONS("-DINCLUDE_INSTALL_DIR=\"${INCLUDE_INSTALL_DIR}\"")
+ADD_DEFINITIONS("-DBIN_DIR=\"${BIN_DIR}\"")
 
 IF (CMAKE_BUILD_TYPE MATCHES "DEBUG")
-    ADD_DEFINITIONS("-DTIZEN_DEBUG_ENABLE")
-    ADD_DEFINITIONS("-DBUILD_TYPE_DEBUG")
+       ADD_DEFINITIONS("-DTIZEN_DEBUG_ENABLE")
+       ADD_DEFINITIONS("-DBUILD_TYPE_DEBUG")
 ENDIF (CMAKE_BUILD_TYPE MATCHES "DEBUG")
 
-SET(TARGET_CSR_SERVER "csr")
-#SET(TARGET_CSR_CLIENT "csr-client")
-SET(TARGET_CSR_CLIENT ${CLIENT_NAME}) # for backward-compatibility.
-SET(TARGET_CSR_COMMON "csr-common")
+SET(TARGET_CSR_SERVER ${SERVICE_NAME}-server)
+SET(TARGET_CSR_CLIENT ${SERVICE_NAME}-client)
+SET(TARGET_CSR_COMMON ${SERVICE_NAME}-common)
+SET(TARGET_CSR_TEST ${SERVICE_NAME}-test)
+
+CONFIGURE_FILE(packaging/${SERVICE_NAME}.manifest.in ${SERVICE_NAME}.manifest @ONLY)
+CONFIGURE_FILE(packaging/${SERVICE_NAME}-client.manifest.in ${SERVICE_NAME}-client.manifest @ONLY)
+CONFIGURE_FILE(packaging/${SERVICE_NAME}-common.manifest.in ${SERVICE_NAME}-common.manifest @ONLY)
 
 ADD_SUBDIRECTORY(src)
 ADD_SUBDIRECTORY(pkgconfig)
-
-IF (DEFINED CSR_FW_TEST_BUILD)
-    SET(TARGET_CSR_TEST   "csr-test")
-    ADD_SUBDIRECTORY(test)
-ENDIF (DEFINED CSR_FW_TEST_BUILD)
+ADD_SUBDIRECTORY(systemd)
+ADD_SUBDIRECTORY(test)
diff --git a/LICENSE b/LICENSE
index 81a1a6a..7f41972 100644 (file)
--- a/LICENSE
+++ b/LICENSE
+Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd. All rights reserved.
 
-  Copyright (c) 2013, McAfee, Inc.
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
 
-  All rights reserved.
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
 
-  Redistribution and use in source and binary forms, with or without modification,
-  are permitted provided that the following conditions are met:
+   1. Definitions.
 
-  Redistributions of source code must retain the above copyright notice, this list
-  of conditions and the following disclaimer.
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
 
-  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.
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
 
-  Neither the name of McAfee, Inc. nor the names of its contributors may be used
-  to endorse or promote products derived from this software without specific prior
-  written permission.
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
 
-  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-  OF THE POSSIBILITY OF SUCH DAMAGE.
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/LICENSE.BSL-1.0 b/LICENSE.BSL-1.0
new file mode 100644 (file)
index 0000000..36b7cd9
--- /dev/null
@@ -0,0 +1,23 @@
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/README b/README
deleted file mode 100644 (file)
index 0e61af0..0000000
--- a/README
+++ /dev/null
@@ -1,69 +0,0 @@
-#
-#  Copyright (c) 2013, McAfee, Inc.
-#  
-#  All rights reserved.
-#  
-#  Redistribution and use in source and binary forms, with or without modification,
-#  are permitted provided that the following conditions are met:
-#  
-#  Redistributions of source code must retain the above copyright notice, this list
-#  of conditions and the following disclaimer.
-#  
-#  Redistributions in binary form must reproduce the above copyright notice, this
-#  list of conditions and the following disclaimer in the documentation and/or other
-#  materials provided with the distribution.
-#  
-#  Neither the name of McAfee, Inc. nor the names of its contributors may be used
-#  to endorse or promote products derived from this software without specific prior
-#  written permission.
-#  
-#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-#  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-#  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-#  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-#  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-#  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-#  OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-Tizen Content Screening Framework
-=====================================
-Following steps to create Tizen content screening framework library:
-- cd framework (change your current folder to 'framework')
-- make distclean; make
-- The library can be found inside 'lib'
-
-Tizen Content Screening Test Suite
-=====================================
-Following steps to create test suite
-- cd test (change your current folder to 'test')
-- make distclean; make
-
-Tizen Web Protection Test Suite
-=====================================
-Following steps to create test suite
-- cd test (change your current folder to 'test')
-- make distclean; make -f WPMakefile
-
-Porting
-=====================================
-TCS_CC: use this environment variable to specify your cross compiler
-TCS_LD: use this environment variable to specify your cross linker
-TCS_AR: use this environment variable to specify your cross ar
-PORT: x86, arm
-CFLAGS: use this environment variable to specify your compiler specific compiling flags
-LD_FLAGS: use this environment variable to specify your linker specific linker flags or libraries
-
-Example for Tizen 2.0.18 Emulator:
-export PORT=x86
-export SDK_HOME=${HOME}/tizen-sdk
-export CFLAGS="-I$SDK_HOME/platforms/tizen2.0/rootstraps/tizen-emulator-2.0.cpp.partner/usr/include"
-export LD_FLAGS="-B $SDK_HOME/platforms/tizen2.0/rootstraps/tizen-emulator-2.0.cpp.partner/usr/lib -L$SDK_HOME/platforms/tizen2.0/rootstraps/tizen-emulator-2.0.cpp.partner/lib -L$SDK_HOME/platforms/tizen2.0/rootstraps/tizen-emulator-2.0.cpp.partner/usr/lib -lc-2.13 -lpthread-2.13 -lc_nonshared"
-export TCS_CC="$SDK_HOME/tools/i386-linux-gnueabi-gcc-4.5/bin/i386-linux-gnueabi-gcc"
-export TCS_LD="$SDK_HOME/tools/i386-linux-gnueabi-gcc-4.5/bin/i386-linux-gnueabi-gcc"
-export TCS_AR="$SDK_HOME/tools/i386-linux-gnueabi-gcc-4.5/bin/i386-linux-gnueabi-ar"
-
-
diff --git a/csr-framework.changes b/csr-framework.changes
deleted file mode 100644 (file)
index 7d4005d..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-* Monday Feb 11 2013 Ryan Ware <ryan.r.ware@intel.com> - 1.0.0
-- This is the initial checkin and spec file for csf-framework
-- Adding a default manifest
-
diff --git a/doc/Tizen Content Screening API Specification.pdf b/doc/Tizen Content Screening API Specification.pdf
deleted file mode 100644 (file)
index 1110687..0000000
Binary files a/doc/Tizen Content Screening API Specification.pdf and /dev/null differ
diff --git a/doc/Tizen Content Screening Plugin API Specification.pdf b/doc/Tizen Content Screening Plugin API Specification.pdf
deleted file mode 100644 (file)
index 5802d99..0000000
Binary files a/doc/Tizen Content Screening Plugin API Specification.pdf and /dev/null differ
diff --git a/doc/Tizen Content Screening Test Specification.pdf b/doc/Tizen Content Screening Test Specification.pdf
deleted file mode 100644 (file)
index 7ae0e6b..0000000
Binary files a/doc/Tizen Content Screening Test Specification.pdf and /dev/null differ
diff --git a/doc/Tizen Content Security Framework Proposal.pdf b/doc/Tizen Content Security Framework Proposal.pdf
deleted file mode 100644 (file)
index b46288f..0000000
Binary files a/doc/Tizen Content Security Framework Proposal.pdf and /dev/null differ
diff --git a/doc/Tizen Web Protection API Specification.pdf b/doc/Tizen Web Protection API Specification.pdf
deleted file mode 100644 (file)
index 7730ca2..0000000
Binary files a/doc/Tizen Web Protection API Specification.pdf and /dev/null differ
diff --git a/doc/Tizen Web Protection Plugin API Specification.pdf b/doc/Tizen Web Protection Plugin API Specification.pdf
deleted file mode 100644 (file)
index 3e7191a..0000000
Binary files a/doc/Tizen Web Protection Plugin API Specification.pdf and /dev/null differ
diff --git a/doc/Tizen Web Protection Test Specification.pdf b/doc/Tizen Web Protection Test Specification.pdf
deleted file mode 100644 (file)
index 5461684..0000000
Binary files a/doc/Tizen Web Protection Test Specification.pdf and /dev/null differ
diff --git a/doc/csrfw_TCSImpl_doc.h b/doc/csrfw_TCSImpl_doc.h
deleted file mode 100644 (file)
index b3c92b5..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-#ifndef __TIZEN_CSR_FRAME_WORK_TCS_DOC_H__
-#define __TIZEN_CSR_FRAME_WORK_TCS_DOC_H__
-/**
- * @ingroup CAPI_CSRFW
- * @defgroup CAPI_CSRFW_TCS_MODULE TCS
- * @brief Content Screening API definitions, structures and macros
- * @section CAPI_CSRFW_TCS_MODULE_HEADER Required Header
- *   \#include <TCSImpl.h> \n
- *   \#include <TCSErrorCodes.h>
- * @section CAPI_CSRFW_MODULE_OVERVIEW Overview
- * It provides APIs that the caller enables content screening.
- *
- */
-#endif
diff --git a/doc/csrfw_TWPImpl_doc.h b/doc/csrfw_TWPImpl_doc.h
deleted file mode 100644 (file)
index 2cf52f2..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-#ifndef __TIZEN_CSR_FRAME_WORK_TWP_DOC_H__
-#define __TIZEN_CSR_FRAME_WORK_TWP_DOC_H__
-/**
- * @ingroup CAPI_CSRFW
- * @defgroup CAPI_CSRFW_TWP_MODULE TWP
- * @brief Content Screening API definitions, structures and macros
- * @section CAPI_CSRFW_TCS_MODULE_HEADER Required Header
- *   \#include <TWPImpl.h>
- * @section CAPI_CSRFW_MODULE_OVERVIEW Overview
- * It provides APIs that the caller enables to block an access of malicous web site.
- */
-
-#endif
diff --git a/doc/csrfw_doc.h b/doc/csrfw_doc.h
deleted file mode 100644 (file)
index bae6776..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an AS IS BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __TIZEN_CORE_CSRFW_DOC_H__
-#define __TIZEN_CORE_CSRFW_DOC_H__
-
-/**
- *@defgroup CAPI_CSRFW CSR Framework
- *@brief These APIs provide checking content screening and blocking access of malicious web site.
- *@ingroup CAPI_SECURITY_FRAMEWORK
- *@section CAPI_CSR_FRAMEWORK_OVERVIEW Overview
- *<table>
- *<tr><th>API Prefixes</th><th>Description</th></tr>
- *<tr><td>@ref CAPI_CSRFW_TCS_MODULE</td><td>Providing APIs for content screening</td></tr>
- *<tr><td>@ref CAPI_CSRFW_TWP_MODULE</td><td>Providing APIs for block an access of malicious web site API</td></tr>
- *</table>
- *
- * It proposes the security framework on Tizen platform. Tizen content security
- * framework will be responsible for passing the security API calls to security plug-in, which
- * could be provided by security vendor plug-in. The framework is also responsible for
- * error handling when there is no security vendor plug-in installed.
- *
- * @image html csr_framework_overview.png
- *
- * @section CAPI_CSR_FRAMEWORK_SOLUTION_DESCRIPTION Solution description
- *
- * Both content security framework and security plug-in are shared libraries in Tizen case. All
- * the code is loaded in the application memory space. The authentication of those libraries will
- * be covered by Tizen certificate process.
- * Content security framework (libsecfw.so) will be linked directly to system component which is
- * invoking the security API, while the security plug-in will be loaded in the runtime and
- * installed along with security application package. The security application package should be
- * signed with a trusted certificate which indicates that the package is authorized to carry
- * security plug-in and is ready for use. And as a security consideration, Tizen installer will
- * check this package whenever the application gets installed.
- *
- * @section CAPI_CSR_FRAMEWORK_CONTENT_SECURITY Content security framework
- *
- * API standaridizing:
- *  - Content Security Framework will provide a set of APIs to other system modules with security
- * features. Currently we have site engine and anti-virus engine API defined in this framework.
- * Please refer to Tizen content screening and site engine API specification for detail.
- * Each security vendor who wants to add their plug-in to Tizen platform, need to provide a
- * plug-in library which conforms to the Framework API which we defined in the framework
- * above their own engines.
- *
- * Plug-in managerment:
- *  - Content security framework is responsible for plug-in loading/reloading. It will always try to
- * load the new plug-in from "/opt/usr/share/sec_plugin/libengine.so" when content security
- * framework is reinitialized by library open API call, in this case it is tcs_library_open(). This
- * is saying that the newly installed security plug-in will be loaded only when
- * tcs_library_open() gets called. During the tcs_library_close() and tcs_library_open(), the
- * caller will keep using the old security plug-in until it close the library and reopen it.
- *
- * Error handling:
- *  - Content security framework will return not implemented error code to caller if there is no
- * plug-in found at "/opt/usr/share/sec_plugin".
- *
- * Concurrent Scan Support:
- *  - The TCS security vendor plug-in must support concurrent scan in multi-tasking, so that
- * Tizen component can have multiple threads to scan content concurrently.
- */
-
-#endif /* __TIZEN_CORE_CSRFW_DOC_H__ */
diff --git a/doc/images/csr_framework_overview.png b/doc/images/csr_framework_overview.png
deleted file mode 100644 (file)
index db0d1b5..0000000
Binary files a/doc/images/csr_framework_overview.png and /dev/null differ
diff --git a/framework/CMakeLists.txt b/framework/CMakeLists.txt
deleted file mode 100644 (file)
index 134063d..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-PKG_CHECK_MODULES(${TARGET_LIB}_DEP
-    REQUIRED
-    dlog
-    libtzplatform-config
-    )
-
-SET(${TARGET_LIB}_SRCS
-    TCSImpl.c
-    TWPImpl.c
-    )
-
-INCLUDE_DIRECTORIES(
-    SYSTEM
-    ${CMAKE_CURRENT_SOURCE_DIR}
-    ${${TARGET_LIB}_DEP_INCLUDE_DIRS}
-    )
-
-ADD_LIBRARY(${TARGET_LIB} SHARED ${${TARGET_LIB}_SRCS})
-
-SET_TARGET_PROPERTIES(${TARGET_LIB}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=default"
-        SOVERSION ${SO_VERSION}
-        VERSION ${VERSION}
-    )
-
-TARGET_LINK_LIBRARIES(${TARGET_LIB}
-    ${${TARGET_LIB}_DEP_LIBRARIES}
-    -ldl
-    -lpthread
-    )
-
-INSTALL(TARGETS ${TARGET_LIB} DESTINATION ${LIB_INSTALL_DIR})
-
-INSTALL(
-    FILES
-        TCSErrorCodes.h
-        TCSImpl.h
-        TWPImpl.h
-    DESTINATION ${INCLUDEDIR}
-    )
diff --git a/framework/CsrLog.h b/framework/CsrLog.h
deleted file mode 100644 (file)
index 6e9e4c3..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-    Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
-
-    All rights reserved.
-
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-#ifndef _CSR_LOG_H_
-#define _CSR_LOG_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef LOG_TAG
-#undef LOG_TAG
-#endif
-#define LOG_TAG "CSR_FRAMEWORK"
-
-#include <dlog.h>
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif  /* _CSR_LOG_H */
diff --git a/packaging/csr-client.manifest.in b/packaging/csr-client.manifest.in
new file mode 100644 (file)
index 0000000..a76fdba
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+       <request>
+               <domain name="_" />
+       </request>
+</manifest>
diff --git a/packaging/csr-common.manifest.in b/packaging/csr-common.manifest.in
new file mode 100644 (file)
index 0000000..a76fdba
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+       <request>
+               <domain name="_" />
+       </request>
+</manifest>
diff --git a/packaging/csr-framework.manifest b/packaging/csr-framework.manifest
deleted file mode 100644 (file)
index 017d22d..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<manifest>
- <request>
-    <domain name="_"/>
- </request>
-</manifest>
index 4c99a54..b608e66 100644 (file)
-%global csr_fw_server_build 0
-%global csr_fw_common_Build 0
-%global csr_fw_test_build 0
-
 Summary: A general purpose content screening and reputation solution
 Name: csr-framework
 Version: 2.0.0
 Release: 0
 Source: %{name}-%{version}.tar.gz
-License: BSD-2.0
+License: Apache-2.0 and BSL-1.0
 Group: Security/Service
 URL: http://tizen.org
 BuildRequires: cmake
 BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(libsystemd-daemon)
+Requires:      lib%{name}-common = %{version}-%{release}
+%{?systemd_requires}
 
 %description
 General purpose content screening and reputation solution. Can scan
 file contents and checking url to prevent malicious items.
 
+%global service_name csr
+%global bin_dir      %{_bindir}
+%global sbin_dir     /sbin
+%global ro_data_dir  %{_datadir}
+
+%package -n lib%{name}-common
+Summary: Common library package for %{name}
+License: Apache-2.0
+Group:   Security/Libraries
+Requires: %{sbin_dir}/ldconfig
+Requires: %{sbin_dir}/ldconfig
+
+%description -n lib%{name}-common
+csr-framework common library package.
+
 %package -n lib%{name}-client
 Summary: Client library package for %{name}
-License: BSD-2.0
+License: Apache-2.0
 Group:   Security/Libraries
+BuildRequires: pkgconfig(capi-base-common)
 Requires: %{name} = %{version}-%{release}
+Requires: %{sbin_dir}/ldconfig
+Requires: %{sbin_dir}/ldconfig
 
 %description -n lib%{name}-client
 csr-framework client library package.
 
 %package devel
-Summary:    Development files for %{name}
-Group:      Security/Development
-Requires:   %{name} = %{version}
+Summary: Development files for %{name}
+LICENSE: Apache-2.0
+Group:   Security/Development
+BuildRequires: pkgconfig(capi-base-common)
+Requires:      %{name} = %{version}-%{release}
 
 %description devel
 csr-framework developemnt files including headers and pkgconfig file.
 
-%if 0%{?csr_fw_test_build}
 %package test
-Summary:    test program for %{name}
-Group:      Security/Testing
-Requires:   %{name} = %{version}
+Summary: test program for %{name}
+License: Apache-2.0 and BSL-1.0
+Group:   Security/Testing
+BuildRequires: boost-devel
+Requires:      %{name} = %{version}
 
 %description test
-Comaptilibty test program
-%endif
+test program of csr-framework
 
 %prep
 %setup -q
 
-# assign client name as secfw to support backward compatibility
-%global client_name secfw
-%global bin_dir %{_bindir}
-
 %build
 %cmake . \
     -DCMAKE_BUILD_TYPE=%{?build_type:%build_type}%{!?build_type:RELEASE} \
     -DCMAKE_VERBOSE_MAKEFILE=ON \
     -DCMAKE_INSTALL_PREFIX=%{_prefix} \
-%if 0%{?csr_fw_server_build}
-    -DCSR_FW_COMMON_BUILD=1 \
-%endif
-%if 0%{?csr_fw_server_build}
-    -DCSR_FW_SERVER_BUILD=1 \
-%endif
-%if 0%{?csr_fw_test_build}
-    -DCSR_FW_TEST_BUILD=1 \
-%endif
-    -DSERVICE_NAME=%{name} \
+    -DSERVICE_NAME=%{service_name} \
     -DVERSION=%{version} \
     -DINCLUDE_INSTALL_DIR:PATH=%{_includedir} \
     -DBIN_DIR:PATH=%{bin_dir} \
-    -DCLIENT_NAME=%{client_name}
+    -DSYSTEMD_UNIT_DIR=%{_unitdir}
 
 make %{?jobs:-j%jobs}
 
 %install
 %make_install
-
-%post -p /sbin/ldconfig
-%postun -p /sbin/ldconfig
+mkdir -p %{buildroot}%{_unitdir}/multi-user.target.wants
+mkdir -p %{buildroot}%{_unitdir}/sockets.target.wants
+ln -s ../%{service_name}.service %{buildroot}%{_unitdir}/multi-user.target.wants/%{service_name}.service
+ln -s ../%{service_name}.socket %{buildroot}%{_unitdir}/sockets.target.wants/%{service_name}.socket
+
+mkdir -p %{buildroot}%{ro_data_dir}/license
+cp LICENSE %{buildroot}%{ro_data_dir}/license/%{name}
+cp LICENSE.BSL-1.0 %{buildroot}%{ro_data_dir}/license/%{name}.BSL-1.0
+cp LICENSE %{buildroot}%{ro_data_dir}/license/lib%{name}-client
+cp LICENSE %{buildroot}%{ro_data_dir}/license/lib%{name}-common
+cp LICENSE %{buildroot}%{ro_data_dir}/license/%{name}-test
+cp LICENSE.BSL-1.0 %{buildroot}%{ro_data_dir}/license/%{name}-test.BSL-1.0
+
+%post
+systemctl daemon-reload
+if [ $1 = 1 ]; then
+    systemctl start %{service_name}.socket
+    systemctl start %{service_name}.service
+fi
+
+if [ $1 = 2 ]; then
+    systemctl restart %{service_name}.socket
+    systemctl restart %{service_name}.service
+fi
+
+%preun
+if [ $1 = 0 ]; then
+    systemctl stop %{service_name}.service
+    systemctl stop %{service_name}.socket
+fi
+
+%postun
+if [ $1 = 0 ]; then
+    systemctl daemon-reload
+fi
+
+%post -n lib%{name}-common -p %{sbin_dir}/ldconfig
+%post -n lib%{name}-client -p %{sbin_dir}/ldconfig
+%postun -n lib%{name}-common -p %{sbin_dir}/ldconfig
+%postun -n lib%{name}-client -p %{sbin_dir}/ldconfig
 
 %files
 %defattr(-,root,root,-)
-%license LICENSE
-%if 0%{?csr_fw_server_build}
-# TODO: list up server files here
-%endif
-%if 0%{?csr_fw_common_build}
-# TODO: list up common library files here
-%endif
+%manifest %{service_name}.manifest
+%{ro_data_dir}/license/%{name}
+%{ro_data_dir}/license/%{name}.BSL-1.0
+%{bin_dir}/%{service_name}-server
+%{_unitdir}/multi-user.target.wants/%{service_name}.service
+%{_unitdir}/%{service_name}.service
+%{_unitdir}/sockets.target.wants/%{service_name}.socket
+%{_unitdir}/%{service_name}.socket
+
+%files -n lib%{name}-common
+%defattr(-,root,root,-)
+%manifest %{service_name}-common.manifest
+%{ro_data_dir}/license/lib%{name}-common
+%{_libdir}/lib%{service_name}-common.so.*
 
 %files -n lib%{name}-client
 %defattr(-,root,root,-)
-%license LICENSE
-%{_libdir}/lib%{client_name}.so.*
+%manifest %{service_name}-client.manifest
+%{ro_data_dir}/license/lib%{name}-client
+%{_libdir}/lib%{service_name}-client.so.*
 
 %files devel
-%doc README
-%doc doc/
-%{_includedir}/TCSErrorCodes.h
-%{_includedir}/TCSImpl.h
-%{_includedir}/TWPImpl.h
-%{_libdir}/pkgconfig/%{name}.pc
-%{_libdir}/lib%{client_name}.so
-
-%if 0%{?csr_fw_test_build}
+%defattr(-,root,root,-)
+%{_includedir}/csr/csr/api.h
+%{_includedir}/csr/csr/error.h
+%{_libdir}/pkgconfig/%{service_name}.pc
+%{_libdir}/lib%{service_name}-client.so
+%{_libdir}/lib%{service_name}-common.so
+
 %files test
 %defattr(-,root,root,-)
-%{bin_dir}/csr-test
-%endif
+%{ro_data_dir}/license/%{name}-test
+%{ro_data_dir}/license/%{name}-test.BSL-1.0
+%{bin_dir}/%{service_name}-test
diff --git a/packaging/csr.manifest.in b/packaging/csr.manifest.in
new file mode 100644 (file)
index 0000000..7b06d77
--- /dev/null
@@ -0,0 +1,16 @@
+<manifest>
+       <define>
+               <domain name="@SERVICE_NAME@" />
+               <request>
+                       <smack request="device::sys_logging" type="rw" />
+                       <smack request="device::app_logging" type="rw" />
+                       <smack request="sys-assert::core" type="rwxat" />
+                       <smack request="systemd" type="rx" />
+               </request>
+               <permit>
+               </permit>
+       </define>
+       <request>
+               <domain name="@SERVICE_NAME@" />
+       </request>
+</manifest>
index d7f889f..456eb4a 100644 (file)
@@ -17,9 +17,9 @@
 # @brief       Configure and install pkgconfig files
 #
 CONFIGURE_FILE(
-    ${SERVICE_NAME}.pc.in
-    ${SERVICE_NAME}.pc
-    @ONLY
+       ${SERVICE_NAME}.pc.in
+       ${SERVICE_NAME}.pc
+       @ONLY
 )
 
 INSTALL(FILES ${SERVICE_NAME}.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
similarity index 79%
rename from pkgconfig/csr-framework.pc.in
rename to pkgconfig/csr.pc.in
index 6ba86ef..2579dc6 100644 (file)
@@ -9,5 +9,5 @@ Name: @SERVICE_NAME@
 Description: @PACKAGE_DESCRIPTION@
 Version: @VERSION@
 Requires:
-Libs: -L${libdir} -l@CLIENT_NAME@
+Libs: -L${libdir} -l@SERVICE_NAME@-client -l@SERVICE_NAME@-common
 Cflags: -I${includedir}
index 26a6c31..f87caad 100644 (file)
 # @brief       Make server daemon and client library
 #
 
-IF (DEFINED CSR_FW_SERVER_BUILD)
-
 ###############     SERVER     ###################
 PKG_CHECK_MODULES(${TARGET_CSR_SERVER}_DEP
-    REQUIRED
+       REQUIRED
 )
 
 SET(${TARGET_CSR_SERVER}_SRCS
+       framework/main/csr-main.cpp
+       framework/main/mainloop.cpp
+       framework/service/logic.cpp
+       framework/service/service.cpp
 )
 
 INCLUDE_DIRECTORIES(
-    framework/service/include
-    framework/common/include
-    ${${TARGET_CSR_SERVER}_DEP_INCLUDED_DIRS}
+       framework/common
+       framework/main
+       framework/service
+       ${${TARGET_CSR_SERVER}_DEP_INCLUDED_DIRS}
 )
 
 SET_SOURCE_FILES_PROPERTIES(${${TARGET_CSR_SERVER}_SRCS}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fPIE"
+       PROPERTIES
+               COMPILE_FLAGS "-D_GNU_SOURCE -fPIE"
 )
 
 ADD_EXECUTABLE(${TARGET_CSR_SERVER} ${${TARGET_CSR_SERVER}_SRCS})
 
 SET(${TARGET_CSR_SERVER}_LIST_LINK_LIBRARIES
-    ${${TARGET_CSR_SERVER}_DEP_LIBRARIES}
-    -ldl     # for dynamic loading engine library
-    -pthread
-    -pie
+       ${${TARGET_CSR_SERVER}_DEP_LIBRARIES}
+       -ldl     # for dynamic loading engine library
+       -pthread
+       -pie
 )
 
-IF (DEFINED CSR_FW_COMMON_BUILD)
 SET(${TARGET_CSR_SERVER}_LIST_LINK_LIBRARIES
-    ${${TARGET_CSR_SERVER}_LIST_LINK_LIBRARIES}
-    ${TARGET_CSR_COMMON}
+       ${${TARGET_CSR_SERVER}_LIST_LINK_LIBRARIES}
+       ${TARGET_CSR_COMMON}
 )
-ENDIF (DEFINED CSR_FW_COMMON_BUILD)
 
 TARGET_LINK_LIBRARIES(${TARGET_CSR_SERVER} ${${TARGET_CSR_SERVER}_LIST_LINK_LIBRARIES})
 
 INSTALL(TARGETS ${TARGET_CSR_SERVER} DESTINATION ${BIN_DIR})
 
-ENDIF (DEFINED CSR_FW_SERVER_BUILD)
-
 ###############      CLIENT     ###################
 PKG_CHECK_MODULES(${TARGET_CSR_CLIENT}_DEP
-    REQUIRED
+       REQUIRED
+       capi-base-common
 )
 
 SET(${TARGET_CSR_CLIENT}_SRCS
-    framework/client/TCSImpl.c
-    framework/client/TWPImpl.c
+       framework/client/api.cpp
 )
 
 INCLUDE_DIRECTORIES(
-    framework/common/include
-    framework/client/include
-    ${PROJECT_SOURCE_DIR}/src/include/csr
-    ${${TARGET_CSR_CLIENT}_DEP_INCLUDE_DIRS}
+       framework/common
+       framework/client
+       ${PROJECT_SOURCE_DIR}/src/include
+       ${${TARGET_CSR_CLIENT}_DEP_INCLUDE_DIRS}
 )
 
 ADD_LIBRARY(${TARGET_CSR_CLIENT} SHARED ${${TARGET_CSR_CLIENT}_SRCS})
 
 SET_TARGET_PROPERTIES(${TARGET_CSR_CLIENT}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fvisibility=hidden"
-        SOVERSION ${API_VERSION}
-        VERSION ${VERSION}
+       PROPERTIES
+               COMPILE_FLAGS "-D_GNU_SOURCE -fvisibility=hidden"
+               SOVERSION ${API_VERSION}
+               VERSION ${VERSION}
 )
 
 SET(${TARGET_CSR_CLIENT}_LIST_LINK_LIBRARIES
-    ${${TARGET_CSR_CLIENT}_DEP_LIBRARIES}
+       ${${TARGET_CSR_CLIENT}_DEP_LIBRARIES}
 )
 
-IF (DEFINED CSR_FW_COMMON_BUILD)
 SET(${TARGET_CSR_CLIENT}_LIST_LINK_LIBRARIES
-    ${${TARGET_CSR_CLIENT}_LIST_LINK_LIBRARIES}
-    ${TARGET_CSR_COMMON}
+       ${${TARGET_CSR_CLIENT}_LIST_LINK_LIBRARIES}
+       ${TARGET_CSR_COMMON}
 )
-ENDIF (DEFINED CSR_FW_COMMON_BUILD)
 
 TARGET_LINK_LIBRARIES(${TARGET_CSR_CLIENT} ${${TARGET_CSR_CLIENT}_LIST_LINK_LIBRARIES})
 
index c1eb454..c6ac189 100644 (file)
 # @author      Kyungwook Tak (k.tak@samsung.com)
 # @brief       Make common library for both of server and client
 #
-
-IF (DEFINED CSR_FW_COMMON_BUILD)
-
 PKG_CHECK_MODULES(${TARGET_CSR_COMMON}_DEP
-    REQUIRED
+       REQUIRED
+       dlog
+       libsystemd-daemon
 )
 
 SET(${TARGET_CSR_COMMON}_SRCS
+       common/binary-queue.cpp
+       common/connection.cpp
+       common/message-buffer.cpp
+       common/socket.cpp
+       common/audit/console-sink.cpp
+       common/audit/dlog-sink.cpp
+       common/audit/logger.cpp
 )
 
 INCLUDE_DIRECTORIES(
-    common/include
-    ${${TARGET_CSR_COMMON}_DEP_INCLUDE_DIRS}
+       common
+       ${${TARGET_CSR_COMMON}_DEP_INCLUDE_DIRS}
 )
 
 ADD_LIBRARY(${TARGET_CSR_COMMON} SHARED ${${TARGET_CSR_COMMON}_SRCS})
 
 SET_TARGET_PROPERTIES(${TARGET_CSR_COMMON}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fvisibility=hidden"
-        SOVERSION ${API_VERSION}
-        VERSION ${VERSION}
+       PROPERTIES
+               COMPILE_FLAGS "-D_GNU_SOURCE -fvisibility=default" # TODO: visibility hidden
+               SOVERSION ${API_VERSION}
+               VERSION ${VERSION}
 )
 
 TARGET_LINK_LIBRARIES(${TARGET_CSR_COMMON}
-    ${${TARGET_CSR_COMMON}_DEP_LIBRARIES}
+       ${${TARGET_CSR_COMMON}_DEP_LIBRARIES}
 )
 
-INSTALL(TARGETS ${TARGET_CSR_COMMON} DESTINATION ${LIB_ISNTALL_DIR})
-
-ENDIF (DEFINED CSR_FW_COMMON_BUILD)
+INSTALL(TARGETS ${TARGET_CSR_COMMON} DESTINATION ${LIB_INSTALL_DIR})
diff --git a/src/framework/client/TCSImpl.c b/src/framework/client/TCSImpl.c
deleted file mode 100644 (file)
index d01fd69..0000000
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <stdio.h>
-#include <unistd.h>
-#include <dlfcn.h>
-#include <malloc.h>
-
-#include <tzplatform_config.h>
-
-#include "CsrLog.h"
-#include "TCSImpl.h"
-#include "TCSErrorCodes.h"
-
-
-#define TCS_CONSTRUCT_ERRCODE(m, e) (((m) << 24) | (e))
-#define PLUGIN_PATH tzplatform_mkpath(TZ_USER_SHARE, "sec_plugin/libengine.so")
-
-
-typedef TCSLIB_HANDLE (*FuncLibraryOpen)(void);
-typedef int (*FuncLibraryClose)(TCSLIB_HANDLE hLib);
-typedef TCSErrorCode (*FuncGetLastError)(TCSLIB_HANDLE hLib);
-typedef int (*FuncScanData)(TCSLIB_HANDLE hLib, TCSScanParam *pParam, TCSScanResult *pResult);
-typedef int (*FuncScanFile)(TCSLIB_HANDLE hLib, char const *pszFileName, int iDataType,
-                            int iAction, int iCompressFlag, TCSScanResult *pResult);
-
-
-typedef struct PluginContext_struct
-{
-    TCSLIB_HANDLE hLib;
-    void *pPlugin;
-    FuncLibraryOpen pfLibraryOpen;
-    FuncLibraryClose pfLibraryClose;
-    FuncGetLastError pfGetLastError;
-    FuncScanData pfScanData;
-    FuncScanFile pfScanFile;
-} PluginContext;
-
-
-static PluginContext *LoadPlugin(void);
-
-
-TCSLIB_HANDLE TCSLibraryOpen(void)
-{
-    PluginContext *pCtx = NULL;
-
-    SLOGD("%s", "tcs lib open\n");
-    pCtx = LoadPlugin();
-    if (pCtx != NULL)
-    {
-        if (pCtx->pfLibraryOpen == NULL)
-        {
-            free(pCtx);
-            return INVALID_TCSLIB_HANDLE;
-        }
-        SLOGD("%s", "call to TCSPLibraryOpen\n");
-        pCtx->hLib = (*pCtx->pfLibraryOpen)();
-        if (pCtx->hLib == INVALID_TCSLIB_HANDLE)
-        {
-            SLOGD("%s", "failed to open engine\n");
-            if (pCtx->pPlugin != NULL)
-                dlclose(pCtx->pPlugin);
-            free(pCtx);
-        }
-        else
-        {
-            return (TCSLIB_HANDLE) pCtx;
-        }
-    }
-
-    return INVALID_TCSLIB_HANDLE;
-}
-
-int TCSLibraryClose(TCSLIB_HANDLE hLib)
-{
-    int iRet = -1;
-    PluginContext *pCtx = NULL;
-
-    if (hLib == INVALID_TCSLIB_HANDLE)
-        return iRet;
-
-    pCtx = (PluginContext *) hLib;
-    if (pCtx->pfLibraryClose == NULL)
-        return iRet;
-
-    iRet = (*pCtx->pfLibraryClose)(pCtx->hLib);
-    if (pCtx->pPlugin != NULL)
-        dlclose(pCtx->pPlugin);
-   
-    free(pCtx);
-
-    return iRet;
-}
-
-
-TCSErrorCode TCSGetLastError(TCSLIB_HANDLE hLib)
-{
-    PluginContext *pCtx = (PluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfGetLastError == NULL)
-    {
-        return TCS_CONSTRUCT_ERRCODE(TCS_ERROR_MODULE_GENERIC,
-                                     TCS_ERROR_NOT_IMPLEMENTED);
-    }
-    return (*pCtx->pfGetLastError)(pCtx->hLib);
-}
-
-
-int TCSScanData(TCSLIB_HANDLE hLib, TCSScanParam *pParam, TCSScanResult *pResult)
-{
-    PluginContext *pCtx = (PluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfScanData == NULL)
-    {
-        return -1;
-    }
-    return (*pCtx->pfScanData)(pCtx->hLib, pParam, pResult);
-}
-
-
-int TCSScanFile(TCSLIB_HANDLE hLib, char const *pszFileName, int iDataType,
-                int iAction, int iCompressFlag, TCSScanResult *pResult)
-{
-    PluginContext *pCtx = (PluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfScanFile == NULL)
-    {
-        return -1;
-    }
-    return (*pCtx->pfScanFile)(pCtx->hLib, pszFileName, iDataType, iAction, iCompressFlag, pResult);
-}
-
-
-static PluginContext *LoadPlugin(void)
-{
-    PluginContext *pCtx = NULL;
-    void *pTmp = dlopen(PLUGIN_PATH, RTLD_LAZY);
-    SLOGD("load plugin");
-    if (pTmp != NULL)
-    {
-        FuncLibraryOpen TmpLibraryOpen;
-        FuncLibraryClose TmpLibraryClose;
-        FuncGetLastError TmpGetLastError;
-        FuncScanData TmpScanData;
-        FuncScanFile TmpScanFile;
-        
-        do
-        {
-            TmpLibraryOpen = dlsym(pTmp, "TCSPLibraryOpen");
-            SLOGD("load api TCSPLibraryOpen");
-            if (TmpLibraryOpen == NULL)
-            {
-                SLOGE("Failed to load TCSPLibraryOpen in %s", PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-            
-            TmpLibraryClose = dlsym(pTmp, "TCSPLibraryClose");
-            if (TmpLibraryClose == NULL)
-            {
-                SLOGE("Failed to load TCSPLibraryClose in %s", PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-            
-            TmpGetLastError = dlsym(pTmp, "TCSPGetLastError");
-            if (TmpGetLastError == NULL)
-            {
-                SLOGE("Failed to load TCSPGetLastError in %s", PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-            
-            TmpScanData = dlsym(pTmp, "TCSPScanData");
-            if (TmpScanData == NULL)
-            {
-                SLOGE("Failed to load TCSPScanData in %s", PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-            
-            TmpScanFile = dlsym(pTmp, "TCSPScanFile");
-            if (TmpScanFile == NULL)
-            {
-                SLOGE("Failed to load TCSPScanFile in %s", PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-            
-            pCtx = (PluginContext *) malloc(sizeof(PluginContext));
-            if (pCtx == NULL)
-            {
-                dlclose(pTmp);
-                break;
-            }
-            pCtx->pPlugin = pTmp;
-            pCtx->pfLibraryOpen = TmpLibraryOpen;
-            pCtx->pfLibraryClose = TmpLibraryClose;
-            pCtx->pfGetLastError = TmpGetLastError;
-            pCtx->pfScanData = TmpScanData;
-            pCtx->pfScanFile = TmpScanFile;
-        } while(0);
-    }
-    else
-    {
-        SLOGE("No plugin found.");
-    }
-
-    return pCtx;
-}
-
-
diff --git a/src/framework/client/TWPImpl.c b/src/framework/client/TWPImpl.c
deleted file mode 100644 (file)
index f945f67..0000000
+++ /dev/null
@@ -1,576 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-
-#include <unistd.h>
-#include <dlfcn.h>
-#include <malloc.h>
-
-#include <tzplatform_config.h>
-
-#include "CsrLog.h"
-#include "TWPImpl.h"
-
-
-#define SITE_PLUGIN_PATH tzplatform_mkpath(TZ_USER_SHARE, "sec_plugin/libwpengine.so")
-
-
-typedef TWP_RESULT (*FuncInitLibrary)(TWPAPIInit *pApiInit);
-typedef void (*FuncUninitLibrary)(void);
-typedef TWP_RESULT (*FuncConfigurationCreate)(TWPConfiguration *pConfigure, TWPConfigurationHandle *phConfigure);
-typedef TWP_RESULT (*FuncConfigurationDestroy)(TWPConfigurationHandle *hConfigure);
-typedef TWP_RESULT (*FuncLookupUrls)(TWPConfigurationHandle hConfigure, TWPRequest *pRequest, int iRedirUrl,
-                                     const char **ppUrls, unsigned int uCount, TWPResponseHandle *phResponse);
-typedef TWP_RESULT (*FuncResponseWrite)(TWPResponseHandle hResponse, const void *pData, unsigned uLength);
-typedef TWP_RESULT (*FuncResponseGetUrlRatingByIndex)(TWPResponseHandle hResponse, unsigned int iIndex,
-                                                      TWPUrlRatingHandle *hRating);
-typedef TWP_RESULT (*FuncResponseGetUrlRatingByUrl)(TWPResponseHandle hResponse, const char *pUrl,
-                                                    unsigned int iUrlLength, TWPUrlRatingHandle *hRating);
-typedef TWP_RESULT (*FuncResponseGetRedirUrlFor)(TWPResponseHandle hResponse, TWPUrlRatingHandle hRating,
-                                                 TWPPolicyHandle hPolicy, char **ppUrl, unsigned int *puLength);
-typedef TWP_RESULT (*FuncResponseGetUrlRatingsCount)(TWPResponseHandle hResponse, unsigned int *puCount);
-typedef TWP_RESULT (*FuncResponseDestroy)(TWPResponseHandle *handle_response);
-typedef TWP_RESULT (*FuncPolicyCreate)(TWPConfigurationHandle hCfg, TWPCategories *pCategories, unsigned int uCount,
-                                       TWPPolicyHandle *phPolicy);
-typedef TWP_RESULT (*FuncPolicyValidate)(TWPPolicyHandle hPolicy, TWPUrlRatingHandle hRating, int *piViolated);
-typedef TWP_RESULT (*FuncPolicyGetViolations)(TWPPolicyHandle hPolicy, TWPUrlRatingHandle hRating,
-                                              TWPCategories **ppViolated, unsigned *puLength);
-typedef TWP_RESULT (*FuncPolicyDestroy)(TWPPolicyHandle *hPolicy);
-typedef TWP_RESULT (*FuncUrlRatingGetScore)(TWPUrlRatingHandle hRating, int *piScore);
-typedef TWP_RESULT (*FuncUrlRatingGetUrl)(TWPUrlRatingHandle hRating, const char **ppUrl,
-                                          unsigned int *puLength);
-typedef TWP_RESULT (*FuncUrlRatingGetDLAUrl)(TWPUrlRatingHandle hRating, const char **ppDlaUrl,
-                                             unsigned int *puLength);
-typedef TWP_RESULT (*FuncUrlRatingHasCategory)(TWPUrlRatingHandle hRating, TWPCategories Category,
-                                               int *piPresent);
-typedef TWP_RESULT (*FuncUrlRatingGetCategories)(TWPUrlRatingHandle hRating, TWPCategories **ppCategories,
-                                                 unsigned int *puLength);
-
-
-typedef struct SitePluginContext_struct
-{
-    void *pPlugin;
-    FuncUninitLibrary pfUninitLibrary;
-    FuncInitLibrary pfInitLibrary;
-    FuncConfigurationCreate pfConfigurationCreate;
-    FuncConfigurationDestroy pfConfigurationDestroy;
-    FuncLookupUrls pfLookupUrls;
-    FuncResponseWrite pfResponseWrite;
-    FuncResponseGetUrlRatingByIndex pfResponseGetUrlRatingByIndex;
-    FuncResponseGetUrlRatingByUrl pfResponseGetUrlRatingByUrl;
-    FuncResponseGetRedirUrlFor pfResponseGetRedirUrlFor;
-    FuncResponseGetUrlRatingsCount pfResponseGetUrlRatingsCount;
-    FuncResponseDestroy pfResponseDestroy;
-    FuncPolicyCreate pfPolicyCreate;
-    FuncPolicyValidate pfPolicyValidate;
-    FuncPolicyGetViolations pfPolicyGetViolations;
-    FuncPolicyDestroy pfPolicyDestroy;
-    FuncUrlRatingGetScore pfUrlRatingGetScore;
-    FuncUrlRatingGetUrl pfUrlRatingGetUrl;
-    FuncUrlRatingGetDLAUrl pfUrlRatingGetDLAUrl;
-    FuncUrlRatingHasCategory pfUrlRatingHasCategory;
-    FuncUrlRatingGetCategories pfUrlRatingGetCategories;
-} SitePluginContext;
-
-
-static SitePluginContext *LoadPlugin(void);
-
-
-TWPLIB_HANDLE TWPInitLibrary(TWPAPIInit *pApiInit)
-{
-    SitePluginContext *pCtx = NULL;
-
-    pCtx = LoadPlugin();
-    if (pCtx != NULL)
-    {
-        if (pCtx->pfInitLibrary != NULL &&
-            (*pCtx->pfInitLibrary)(pApiInit) == TWP_SUCCESS)
-            return (TWPLIB_HANDLE) pCtx;
-
-        TWPUninitLibrary((TWPLIB_HANDLE) pCtx);
-        return INVALID_TWPLIB_HANDLE;
-    }
-
-    return INVALID_TWPLIB_HANDLE;
-}
-
-void TWPUninitLibrary(TWPLIB_HANDLE hLib)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx != NULL)
-    {
-        if (pCtx->pfUninitLibrary != NULL)
-            (*pCtx->pfUninitLibrary)();
-        if (pCtx->pPlugin != NULL)
-            dlclose(pCtx->pPlugin);
-        free(pCtx);
-    }
-}
-
-TWP_RESULT TWPConfigurationCreate(TWPLIB_HANDLE hLib, TWPConfiguration *pConfigure,
-                                  TWPConfigurationHandle *phConfigure)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfConfigurationCreate == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfConfigurationCreate)(pConfigure, phConfigure);
-}
-
-TWP_RESULT TWPConfigurationDestroy(TWPLIB_HANDLE hLib, TWPConfigurationHandle *hConfigure)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfConfigurationDestroy == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfConfigurationDestroy)(hConfigure);
-}
-
-TWP_RESULT TWPLookupUrls(TWPLIB_HANDLE hLib, TWPConfigurationHandle hConfigure, TWPRequest *pRequest,
-                         int iRedirUrl, const char **ppUrls, unsigned int uCount, TWPResponseHandle *phResponse)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfLookupUrls == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfLookupUrls)(hConfigure, pRequest, iRedirUrl, ppUrls, uCount, phResponse);
-}
-
-TWP_RESULT TWPResponseWrite(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, const void *pData, unsigned uLength)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfResponseWrite == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfResponseWrite)(hResponse, pData, uLength);
-}
-
-TWP_RESULT TWPResponseGetUrlRatingByIndex(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, unsigned int uIndex,
-                                          TWPUrlRatingHandle *hRating)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfResponseGetUrlRatingByIndex == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfResponseGetUrlRatingByIndex)(hResponse, uIndex, hRating);
-}
-
-TWP_RESULT TWPResponseGetUrlRatingByUrl(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, const char *pUrl,
-                                        unsigned int uUrlLength, TWPUrlRatingHandle *hRating)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfResponseGetUrlRatingByUrl == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfResponseGetUrlRatingByUrl)(hResponse, pUrl, uUrlLength, hRating);
-}
-
-TWP_RESULT TWPResponseGetRedirUrlFor(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, TWPUrlRatingHandle hRating,
-                                     TWPPolicyHandle hPolicy, char **ppUrl, unsigned int *puLength)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfResponseGetRedirUrlFor == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfResponseGetRedirUrlFor)(hResponse, hRating, hPolicy, ppUrl, puLength);
-}
-
-TWP_RESULT TWPResponseGetUrlRatingsCount(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, unsigned int *puCount)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfResponseGetUrlRatingsCount == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfResponseGetUrlRatingsCount)(hResponse, puCount);
-}
-
-TWP_RESULT TWPResponseDestroy(TWPLIB_HANDLE hLib, TWPResponseHandle *hResponse)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfResponseDestroy == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfResponseDestroy)(hResponse);
-}
-
-TWP_RESULT TWPPolicyCreate(TWPLIB_HANDLE hLib, TWPConfigurationHandle hCfg, TWPCategories *pCategories,
-                           unsigned int uCount, TWPPolicyHandle *phPolicy)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfPolicyCreate == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfPolicyCreate)(hCfg, pCategories, uCount, phPolicy);
-}
-
-TWP_RESULT TWPPolicyValidate(TWPLIB_HANDLE hLib, TWPPolicyHandle hPolicy, TWPUrlRatingHandle hRating, int *piViolated)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfPolicyValidate == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfPolicyValidate)(hPolicy, hRating, piViolated);
-}
-
-TWP_RESULT TWPPolicyGetViolations(TWPLIB_HANDLE hLib, TWPPolicyHandle hPolicy, TWPUrlRatingHandle hRating,
-                                  TWPCategories **ppViolated, unsigned *puLength)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfPolicyGetViolations == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfPolicyGetViolations)(hPolicy, hRating, ppViolated, puLength);
-}
-
-TWP_RESULT TWPPolicyDestroy(TWPLIB_HANDLE hLib, TWPPolicyHandle *hPolicy)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfPolicyDestroy == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfPolicyDestroy)(hPolicy);
-}
-
-TWP_RESULT TWPUrlRatingGetScore(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, int *piScore)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfUrlRatingGetScore == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfUrlRatingGetScore)(hRating, piScore);
-}
-
-TWP_RESULT TWPUrlRatingGetUrl(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, char **ppUrl,
-                              unsigned int *puLength)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfUrlRatingGetUrl == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfUrlRatingGetUrl)(hRating, (const char **) ppUrl, puLength);
-}
-
-TWP_RESULT TWPUrlRatingGetDLAUrl(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, char **ppDlaUrl,
-                                 unsigned int *puLength)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfUrlRatingGetDLAUrl == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfUrlRatingGetDLAUrl)(hRating, (const char **) ppDlaUrl, puLength);
-}
-
-TWP_RESULT TWPUrlRatingHasCategory(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, TWPCategories Category,
-                                   int *piPresent)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfUrlRatingHasCategory == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfUrlRatingHasCategory)(hRating, Category, piPresent);
-}
-
-TWP_RESULT TWPUrlRatingGetCategories(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, TWPCategories **ppCategories,
-                                     unsigned int *puLength)
-{
-    SitePluginContext *pCtx = (SitePluginContext *) hLib;
-
-    if (pCtx == NULL || pCtx->pfUrlRatingGetCategories == NULL)
-        return TWP_NOT_IMPLEMENTED;
-
-    return (*pCtx->pfUrlRatingGetCategories)(hRating, ppCategories, puLength);
-}
-
-static SitePluginContext *LoadPlugin(void)
-{
-    SitePluginContext *pCtx = NULL;
-    void *pTmp = dlopen(SITE_PLUGIN_PATH, RTLD_LAZY);
-    SLOGD("load site plugin");
-    if (pTmp != NULL)
-    {
-        FuncUninitLibrary TmpUninitLibrary;
-        FuncInitLibrary TmpInitLibrary;
-        FuncConfigurationCreate TmpConfigurationCreate;
-        FuncConfigurationDestroy TmpConfigurationDestroy;
-        FuncLookupUrls TmpLookupUrls;
-        FuncResponseWrite TmpResponseWrite;
-        FuncResponseGetUrlRatingByIndex TmpResponseGetUrlRatingByIndex;
-        FuncResponseGetUrlRatingByUrl TmpResponseGetUrlRatingByUrl;
-        FuncResponseGetRedirUrlFor TmpResponseGetRedirUrlFor;
-        FuncResponseGetUrlRatingsCount TmpResponseGetUrlRatingsCount;
-        FuncResponseDestroy TmpResponseDestroy;
-        FuncPolicyCreate TmpPolicyCreate;
-        FuncPolicyValidate TmpPolicyValidate;
-        FuncPolicyGetViolations TmpPolicyGetViolations;
-        FuncPolicyDestroy TmpPolicyDestroy;
-        FuncUrlRatingGetScore TmpUrlRatingGetScore;
-        FuncUrlRatingGetUrl TmpUrlRatingGetUrl;
-        FuncUrlRatingGetDLAUrl TmpUrlRatingGetDLAUrl;
-        FuncUrlRatingHasCategory TmpUrlRatingHasCategory;
-        FuncUrlRatingGetCategories TmpUrlRatingGetCategories;
-        
-        do
-        {
-            TmpInitLibrary = dlsym(pTmp, "TWPPInitLibrary");
-            SLOGD("load api TWPPInitLibrary");
-            if (TmpInitLibrary == NULL)
-            {
-                SLOGE("Failed to load TWPPInitLibrary in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpUninitLibrary = dlsym(pTmp, "TWPPUninitLibrary");
-            SLOGD("load api TWPPUninitLibrary");
-            if (TmpUninitLibrary == NULL)
-            {
-                SLOGE("Failed to load TWPPUninitLibrary in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpConfigurationCreate = dlsym(pTmp, "TWPPConfigurationCreate");
-            SLOGD("load api TWPPConfigurationCreate");
-            if (TmpConfigurationCreate == NULL)
-            {
-                SLOGE("Failed to load TWPPConfigurationCreate in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpConfigurationDestroy = dlsym(pTmp, "TWPPConfigurationDestroy");
-            SLOGD("load api TWPPConfigurationDestroy");
-            if (TmpConfigurationDestroy == NULL)
-            {
-                SLOGE("Failed to load TWPPConfigurationDestroy in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpLookupUrls = dlsym(pTmp, "TWPPLookupUrls");
-            SLOGD("load api TWPPLookupUrls");
-            if (TmpLookupUrls == NULL)
-            {
-                SLOGE("Failed to load TWPPLookupUrls in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpResponseWrite = dlsym(pTmp, "TWPPResponseWrite");
-            SLOGD("load api TWPPResponseWrite");
-            if (TmpResponseWrite == NULL)
-            {
-                SLOGE("Failed to load TWPPResponseWrite in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpResponseGetUrlRatingByIndex = dlsym(pTmp, "TWPPResponseGetUrlRatingByIndex");
-            SLOGD("load api TWPPResponseGetUrlRatingByIndex");
-            if (TmpResponseGetUrlRatingByIndex == NULL)
-            {
-                SLOGE("Failed to load TWPPResponseGetUrlRatingByIndex in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpResponseGetUrlRatingByUrl = dlsym(pTmp, "TWPPResponseGetUrlRatingByUrl");
-            SLOGD("load api TWPPResponseGetUrlRatingByUrl");
-            if (TmpResponseGetUrlRatingByUrl == NULL)
-            {
-                SLOGE("Failed to load TWPPResponseGetUrlRatingByUrl in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpResponseGetRedirUrlFor = dlsym(pTmp, "TWPPResponseGetRedirUrlFor");
-            SLOGD("load api TWPPResponseGetRedirUrlFor");
-            if (TmpResponseGetRedirUrlFor == NULL)
-            {
-                SLOGE("Failed to load TWPPResponseGetRedirUrlFor in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpResponseGetUrlRatingsCount = dlsym(pTmp, "TWPPResponseGetUrlRatingsCount");
-            SLOGD("load api TWPPResponseGetUrlRatingsCount");
-            if (TmpResponseGetUrlRatingsCount == NULL)
-            {
-                SLOGE("Failed to load TWPPResponseGetUrlRatingsCount in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpResponseDestroy = dlsym(pTmp, "TWPPResponseDestroy");
-            SLOGD("load api TWPPResponseDestroy");
-            if (TmpResponseDestroy == NULL)
-            {
-                SLOGE("Failed to load TWPPResponseDestroy in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpPolicyCreate = dlsym(pTmp, "TWPPPolicyCreate");
-            SLOGD("load api TWPPPolicyCreate");
-            if (TmpPolicyCreate == NULL)
-            {
-                SLOGE("Failed to load TWPPPolicyCreate in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpPolicyValidate = dlsym(pTmp, "TWPPPolicyValidate");
-            SLOGD("load api TWPPPolicyValidate");
-            if (TmpPolicyValidate == NULL)
-            {
-                SLOGE("Failed to load TWPPPolicyValidate in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpPolicyGetViolations = dlsym(pTmp, "TWPPPolicyGetViolations");
-            SLOGD("load api TWPPPolicyGetViolations");
-            if (TmpPolicyGetViolations == NULL)
-            {
-                SLOGE("Failed to load TWPPPolicyGetViolations in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpPolicyDestroy = dlsym(pTmp, "TWPPPolicyDestroy");
-            SLOGD("load api TWPPPolicyDestroy");
-            if (TmpPolicyDestroy == NULL)
-            {
-                SLOGE("Failed to load TWPPPolicyDestroy in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpUrlRatingGetScore = dlsym(pTmp, "TWPPUrlRatingGetScore");
-            SLOGD("load api TWPPUrlRatingGetScore");
-            if (TmpUrlRatingGetScore == NULL)
-            {
-                SLOGE("Failed to load TWPPUrlRatingGetScore in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpUrlRatingGetUrl = dlsym(pTmp, "TWPPUrlRatingGetUrl");
-            SLOGD("load api TWPPUrlRatingGetUrl");
-            if (TmpUrlRatingGetUrl == NULL)
-            {
-                SLOGE("Failed to load TWPPUrlRatingGetUrl in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpUrlRatingGetDLAUrl = dlsym(pTmp, "TWPPUrlRatingGetDLAUrl");
-            SLOGD("load api TWPPUrlRatingGetDLAUrl");
-            if (TmpUrlRatingGetDLAUrl == NULL)
-            {
-                SLOGE("Failed to load TWPPUrlRatingGetDLAUrl in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpUrlRatingHasCategory = dlsym(pTmp, "TWPPUrlRatingHasCategory");
-            SLOGD("load api TWPPUrlRatingHasCategory");
-            if (TmpUrlRatingHasCategory == NULL)
-            {
-                SLOGE("Failed to load TWPPUrlRatingHasCategory in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            TmpUrlRatingGetCategories = dlsym(pTmp, "TWPPUrlRatingGetCategories");
-            SLOGD("load api TWPPUrlRatingGetCategories");
-            if (TmpUrlRatingGetCategories == NULL)
-            {
-                SLOGE("Failed to load TWPPUrlRatingGetCategories in %s", SITE_PLUGIN_PATH);
-                dlclose(pTmp);
-                break;
-            }
-
-            pCtx = (SitePluginContext *) malloc(sizeof(SitePluginContext));
-            if (pCtx == NULL)
-            {
-                dlclose(pTmp);
-                break;
-            }
-            
-            pCtx->pPlugin = pTmp;
-            pCtx->pfUninitLibrary = TmpUninitLibrary;
-            pCtx->pfInitLibrary = TmpInitLibrary;
-            pCtx->pfConfigurationCreate = TmpConfigurationCreate;
-            pCtx->pfConfigurationDestroy = TmpConfigurationDestroy;
-            pCtx->pfLookupUrls = TmpLookupUrls;
-            pCtx->pfResponseWrite = TmpResponseWrite;
-            pCtx->pfResponseGetUrlRatingByIndex = TmpResponseGetUrlRatingByIndex;
-            pCtx->pfResponseGetUrlRatingByUrl = TmpResponseGetUrlRatingByUrl;
-            pCtx->pfResponseGetRedirUrlFor = TmpResponseGetRedirUrlFor;
-            pCtx->pfResponseGetUrlRatingsCount = TmpResponseGetUrlRatingsCount;
-            pCtx->pfResponseDestroy = TmpResponseDestroy;
-            pCtx->pfPolicyCreate = TmpPolicyCreate;
-            pCtx->pfPolicyValidate = TmpPolicyValidate;
-            pCtx->pfPolicyGetViolations = TmpPolicyGetViolations;
-            pCtx->pfPolicyDestroy = TmpPolicyDestroy;
-            pCtx->pfUrlRatingGetScore = TmpUrlRatingGetScore;
-            pCtx->pfUrlRatingGetUrl = TmpUrlRatingGetUrl;
-            pCtx->pfUrlRatingGetDLAUrl = TmpUrlRatingGetDLAUrl;
-            pCtx->pfUrlRatingHasCategory = TmpUrlRatingHasCategory;
-            pCtx->pfUrlRatingGetCategories = TmpUrlRatingGetCategories;
-        } while(0);
-    }
-    else
-    {
-        SLOGE("No plugin found.");
-    }
-
-    return pCtx;
-}
diff --git a/src/framework/client/api.cpp b/src/framework/client/api.cpp
new file mode 100644 (file)
index 0000000..d8604c6
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        api.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       csr client C APIs
+ */
+#include "csr/api.h"
+#include "csr/error.h"
+
+#include <functional>
+#include <string>
+#include <exception>
+
+#include "raw-buffer.h"
+#include "message-buffer.h"
+#include "connection.h"
+#include "socket.h"
+#include "command-id.h"
+#include "audit/logger.h"
+
+#define API __attribute__((visibility("default")))
+
+static void init_lib(void) __attribute__((constructor));
+static void init_lib(void)
+{
+       // TODO: set log tag more gently? like singleton
+       Csr::Audit::Logger::setTag("CSR_CLIENT");
+}
+
+namespace {
+
+inline Csr::Connection makeConnection(const std::string &address)
+{
+       return Csr::Connection(Csr::Socket::connect(address));
+}
+
+inline Csr::Connection makeConnection(void)
+{
+       return makeConnection("/tmp/." SERVICE_NAME ".socket");
+}
+
+inline Csr::RawBuffer dispatch(const Csr::Connection &connection, const Csr::RawBuffer &buf)
+{
+       DEBUG("send rawbuf to server. fd: " << connection.getFd());
+       connection.send(buf);
+
+       DEBUG("wait for receive reply from server...");
+       return connection.receive();
+}
+
+using Encoder = std::function<Csr::MessageBuffer(void)>;
+using Decoder = std::function<csr_error_e(Csr::MessageBuffer &&)>;
+
+auto defaultDecoder = [](Csr::MessageBuffer &&msg) {
+       csr_error_e retcode = CSR_ERROR_NONE;
+       msg.Deserialize(retcode);
+       return retcode;
+};
+
+auto post = [](Encoder &&encoder, Decoder &&decoder = defaultDecoder) {
+       try {
+               auto conn = makeConnection();
+
+               INFO("Connection made! Let's dispatch request!");
+
+               auto response = dispatch(conn, encoder().pop());
+
+               DEBUG("Get response!");
+
+               Csr::MessageBuffer msg;
+               msg.push(response);
+
+               return decoder(std::move(msg));
+       } catch (const std::exception &e) {
+               ERROR("std exception occured: " << e.what());
+               /* TODO: divide error codes per exception respectively */
+               return CSR_ERROR_SERVER;
+       } catch (...) {
+               ERROR("Unhandled excpeion occured in post!");
+               return CSR_ERROR_UNKNOWN;
+       }
+};
+
+inline std::string toStlString(const char *cstr)
+{
+       return (cstr == nullptr) ? std::string() : std::string(cstr);
+}
+
+} // namespace anonymous
+
+API
+int csr_file_scan(const char *filepath)
+{
+       DEBUG("csr_file_scan API start!");
+       return post([&]() {
+                       return Csr::MessageBuffer::Serialize(Csr::CommandId::FILE_SCAN, toStlString(filepath));
+               });
+}
+
+API
+int csr_file_judge(const char *filepath, int judge)
+{
+       DEBUG("csr_file_judge API start!");
+       return post([&]() {
+                       return Csr::MessageBuffer::Serialize(Csr::CommandId::FILE_JUDGE, toStlString(filepath), judge);
+               });
+}
diff --git a/src/framework/common/audit/console-sink.cpp b/src/framework/common/audit/console-sink.cpp
new file mode 100644 (file)
index 0000000..2d195d5
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        console-sink.cpp
+ * @author      Jaemin Ryu (jm77.ryu@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "console-sink.h"
+
+#include <iostream>
+
+namespace Csr {
+namespace Audit {
+
+void ConsoleLogSink::sink(
+       LogLevel /*level*/,
+       const std::string &/*tag*/,
+       const std::string &message)
+{
+       std::cout << message;
+}
+
+}
+}
diff --git a/src/framework/common/audit/console-sink.h b/src/framework/common/audit/console-sink.h
new file mode 100644 (file)
index 0000000..6bbf3ff
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        console-sink.h
+ * @author      Jaemin Ryu (jm77.ryu@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+
+#include "audit/log-sink.h"
+#include "audit/logger.h"
+
+namespace Csr {
+namespace Audit {
+
+class ConsoleLogSink : public LogSink {
+public:
+       void sink(LogLevel level, const std::string &tag, const std::string &message) override;
+};
+
+}
+}
diff --git a/src/framework/common/audit/dlog-sink.cpp b/src/framework/common/audit/dlog-sink.cpp
new file mode 100644 (file)
index 0000000..003c620
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        dlog-sink.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "dlog-sink.h"
+
+#include <iostream>
+#include <dlog.h>
+
+namespace Csr {
+namespace Audit {
+
+void DlogLogSink::sink(LogLevel level, const std::string &tag, const std::string &message)
+{
+       switch (level) {
+       case LogLevel::Error:
+               SLOG(LOG_ERROR, tag.c_str(), "%s", message.c_str());
+               return;
+       case LogLevel::Warning:
+               SLOG(LOG_WARN, tag.c_str(), "%s", message.c_str());
+               return;
+       case LogLevel::Debug:
+               SLOG(LOG_DEBUG, tag.c_str(), "%s", message.c_str());
+               return;
+       case LogLevel::Info:
+               SLOG(LOG_INFO, tag.c_str(), "%s", message.c_str());
+               return;
+       case LogLevel::Trace:
+               SLOG(LOG_VERBOSE, tag.c_str(), "%s", message.c_str());
+               return;
+       default:
+               SLOG(LOG_SILENT, tag.c_str(), "%s", message.c_str());
+               return;
+       }
+}
+
+}
+}
diff --git a/src/framework/common/audit/dlog-sink.h b/src/framework/common/audit/dlog-sink.h
new file mode 100644 (file)
index 0000000..40c79ba
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        dlog-sink.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+
+#include "audit/log-sink.h"
+#include "audit/logger.h"
+
+namespace Csr {
+namespace Audit {
+
+class DlogLogSink : public LogSink {
+public:
+       void sink(LogLevel level, const std::string &tag, const std::string &message) override;
+};
+
+}
+}
diff --git a/src/framework/common/audit/log-sink.h b/src/framework/common/audit/log-sink.h
new file mode 100644 (file)
index 0000000..ab39034
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        log-sink.h
+ * @author      Jaemin Ryu (jm77.ryu@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+
+#include "audit/logger.h"
+
+namespace Csr {
+namespace Audit {
+
+class LogSink {
+public:
+       LogSink() {}
+       virtual ~LogSink() {}
+       virtual void sink(
+                       LogLevel level,
+                       const std::string &tag,
+                       const std::string &message) = 0;
+};
+
+}
+}
diff --git a/src/framework/common/audit/logger.cpp b/src/framework/common/audit/logger.cpp
new file mode 100644 (file)
index 0000000..f1f6bb7
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        logger.cpp
+ * @author      Jaemin Ryu (jm77.ryu@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "logger.h"
+
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <stdexcept>
+
+#include "log-sink.h"
+#include "console-sink.h"
+#include "dlog-sink.h"
+
+namespace Csr {
+namespace Audit {
+
+//std::unique_ptr<LogSink> g_backend(new ConsoleLogSink());
+std::unique_ptr<LogSink> g_backend(new DlogLogSink());
+std::string g_tag("CSR");
+
+namespace {
+
+std::string toString(LogLevel level)
+{
+       switch (level) {
+       case LogLevel::Error:   return "ERROR";
+       case LogLevel::Warning: return "WARN";
+       case LogLevel::Debug:   return "DEBUG";
+       case LogLevel::Info:    return "INFO";
+       case LogLevel::Trace:   return "TRACE";
+       default:                return "UNKNOWN";
+       }
+}
+
+} // namespace anonymous
+
+void Logger::log(LogLevel level,
+                               const std::string &file,
+                               unsigned int line,
+                               const std::string &func,
+                               const std::string &message)
+{
+       std::ostringstream buffer;
+
+       buffer << toString(level)
+               << "<" << ::getpid() << ">:"
+               << "[" << file << ":" << line << "]"
+               << " " << func << "() " << message
+               << std::endl;
+
+       g_backend->sink(level, g_tag, buffer.str());
+}
+
+void Logger::setTag(const std::string &tag)
+{
+       g_tag = tag;
+}
+
+}
+}
diff --git a/src/framework/common/audit/logger.h b/src/framework/common/audit/logger.h
new file mode 100644 (file)
index 0000000..f2931b1
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        logger.h
+ * @author      Jaemin Ryu (jm77.ryu@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+#include <memory>
+#include <sstream>
+#include <iostream>
+#include <ios>
+
+#include <cstring>
+
+namespace Csr {
+namespace Audit {
+
+enum class LogLevel : int {
+       Error,
+       Warning,
+       Info,
+       Debug,
+       Trace
+};
+
+class Logger {
+public:
+       static void log(LogLevel level,
+                                       const std::string &file,
+                                       unsigned int line,
+                                       const std::string &func,
+                                       const std::string &message);
+       static void setTag(const std::string &tag);
+
+private:
+       static std::string m_tag;
+};
+
+}
+}
+
+#ifndef __FILENAME__
+#define __FILENAME__ (::strrchr(__FILE__, '/') ? ::strrchr(__FILE__, '/') + 1 : __FILE__)
+#endif
+
+#define FORMAT(ITEMS)                                              \
+       ((dynamic_cast<std::ostringstream &>(                          \
+                       std::ostringstream().seekp(0, std::ios_base::cur) << ITEMS) \
+       ).str())
+
+#define LOG(LEVEL, MESSAGE)               \
+       Csr::Audit::Logger::log(              \
+               Csr::Audit::LogLevel::LEVEL,      \
+               __FILENAME__, __LINE__, __func__, \
+               FORMAT(MESSAGE))
+
+#define ERROR(MESSAGE)  LOG(Error, MESSAGE)
+#define WARN(MESSAGE)   LOG(Warning, MESSAGE)
+
+#if !defined(NDEBUG)
+#define INFO(MESSAGE)   LOG(Info, MESSAGE)
+#define DEBUG(MESSAGE)  LOG(Debug, MESSAGE)
+#define TRACE(MESSAGE)  LOG(Trace, MESSAGE)
+#else
+#define INFO(MESSAGE)  do {} while (false)
+#define DEBUG(MESSAGE) do {} while (false)
+#define TRACE(MESSAGE) do {} while (false)
+#endif //NDEBUG
diff --git a/src/framework/common/binary-queue.cpp b/src/framework/common/binary-queue.cpp
new file mode 100644 (file)
index 0000000..2ccbe23
--- /dev/null
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        binary-queue.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "binary-queue.h"
+
+#include <cstring>
+#include <cstddef>
+#include <algorithm>
+#include <new>
+
+namespace Csr {
+
+BinaryQueue::BinaryQueue() : m_size(0)
+{
+}
+
+BinaryQueue::BinaryQueue(const BinaryQueue &other) : m_size(0)
+{
+       appendCopyFrom(other);
+}
+
+BinaryQueue::~BinaryQueue()
+{
+       // Remove all remainig buckets
+       clear();
+}
+
+const BinaryQueue &BinaryQueue::operator=(const BinaryQueue &other)
+{
+       if (this != &other) {
+               clear();
+               appendCopyFrom(other);
+       }
+
+       return *this;
+}
+
+void BinaryQueue::appendCopyFrom(const BinaryQueue &other)
+{
+       // To speed things up, always copy as one bucket
+       void *bufferCopy = malloc(other.m_size);
+
+       if (bufferCopy == nullptr)
+               throw std::bad_alloc();
+
+       try {
+               other.flatten(bufferCopy, other.m_size);
+               appendUnmanaged(bufferCopy, other.m_size, &bufferDeleterFree, nullptr);
+       } catch (const std::bad_alloc &) {
+               // Free allocated memory
+               free(bufferCopy);
+               throw;
+       }
+}
+
+void BinaryQueue::appendMoveFrom(BinaryQueue &other)
+{
+       // Copy all buckets
+       std::copy(other.m_buckets.begin(),
+                         other.m_buckets.end(), std::back_inserter(m_buckets));
+       m_size += other.m_size;
+
+       // Clear other, but do not free memory
+       other.m_buckets.clear();
+       other.m_size = 0;
+}
+
+void BinaryQueue::appendCopyTo(BinaryQueue &other) const
+{
+       other.appendCopyFrom(*this);
+}
+
+void BinaryQueue::appendMoveTo(BinaryQueue &other)
+{
+       other.appendMoveFrom(*this);
+}
+
+void BinaryQueue::clear()
+{
+       std::for_each(m_buckets.begin(), m_buckets.end(), &deleteBucket);
+       m_buckets.clear();
+       m_size = 0;
+}
+
+void BinaryQueue::appendCopy(const void* buffer, size_t size)
+{
+       // Create data copy with malloc/free
+       void *bufferCopy = malloc(size);
+
+       // Check if allocation succeded
+       if (bufferCopy == nullptr)
+               throw std::bad_alloc();
+
+       // Copy user data
+       memcpy(bufferCopy, buffer, size);
+
+       try {
+               // Try to append new bucket
+               appendUnmanaged(bufferCopy, size, &bufferDeleterFree, nullptr);
+       } catch (const std::bad_alloc &) {
+               // Free allocated memory
+               free(bufferCopy);
+               throw;
+       }
+}
+
+void BinaryQueue::appendUnmanaged(const void* buffer,
+                                                                 size_t size,
+                                                                 BufferDeleter deleter,
+                                                                 void* userParam)
+{
+       // Do not attach empty buckets
+       if (size == 0) {
+               deleter(buffer, size, userParam);
+               return;
+       }
+
+       // Just add new bucket with selected deleter
+       Bucket *bucket = new Bucket(buffer, size, deleter, userParam);
+       try {
+               m_buckets.push_back(bucket);
+       } catch (const std::bad_alloc &) {
+               delete bucket;
+               throw;
+       }
+
+       // Increase total queue size
+       m_size += size;
+}
+
+size_t BinaryQueue::size() const
+{
+       return m_size;
+}
+
+bool BinaryQueue::empty() const
+{
+       return m_size == 0;
+}
+
+void BinaryQueue::consume(size_t size)
+{
+       if (size > m_size)
+               throw std::range_error("protocol broken. no more binary to consume in queue");
+
+       size_t bytesLeft = size;
+
+       // Consume data and/or remove buckets
+       while (bytesLeft > 0) {
+               // Get consume size
+               size_t count = std::min(bytesLeft, m_buckets.front()->left);
+
+               m_buckets.front()->ptr =
+                       static_cast<const char *>(m_buckets.front()->ptr) + count;
+               m_buckets.front()->left -= count;
+               bytesLeft -= count;
+               m_size -= count;
+
+               if (m_buckets.front()->left == 0) {
+                       deleteBucket(m_buckets.front());
+                       m_buckets.pop_front();
+               }
+       }
+}
+
+void BinaryQueue::flatten(void *buffer, size_t size) const
+{
+       if (size == 0)
+               return;
+
+       if (size > m_size)
+               throw std::range_error("protocol broken. no more binary to flatten in queue");
+
+       size_t bytesLeft = size;
+       void *ptr = buffer;
+       BucketList::const_iterator bucketIterator = m_buckets.begin();
+       /* TODO: Assert(m_buckets.end() != bucketIterator); */
+
+       // Flatten data
+       while (bytesLeft > 0) {
+               // Get consume size
+               size_t count = std::min(bytesLeft, (*bucketIterator)->left);
+
+               // Copy data to user pointer
+               memcpy(ptr, (*bucketIterator)->ptr, count);
+
+               // Update flattened bytes count
+               bytesLeft -= count;
+               ptr = static_cast<char *>(ptr) + count;
+
+               // Take next bucket
+               ++bucketIterator;
+       }
+}
+
+void BinaryQueue::flattenConsume(void *buffer, size_t size)
+{
+       // FIXME: Optimize
+       flatten(buffer, size);
+       consume(size);
+}
+
+void BinaryQueue::deleteBucket(BinaryQueue::Bucket *bucket)
+{
+       delete bucket;
+}
+
+void BinaryQueue::bufferDeleterFree(const void *data,
+                                                                       size_t /*dataSize*/,
+                                                                       void */*userParam*/)
+{
+       // Default free deleter
+       free(const_cast<void *>(data));
+}
+
+BinaryQueue::Bucket::Bucket(const void* data,
+                                                       size_t dataSize,
+                                                       BufferDeleter dataDeleter,
+                                                       void* userParam) :
+       buffer(data),
+       ptr(data),
+       size(dataSize),
+       left(dataSize),
+       deleter(dataDeleter),
+       param(userParam)
+{
+       if (data == nullptr || dataDeleter == nullptr)
+               throw std::invalid_argument("Bucket construct failed.");
+}
+
+BinaryQueue::Bucket::~Bucket()
+{
+       // Invoke deleter on bucket data
+       deleter(buffer, size, param);
+}
+
+BinaryQueue::BucketVisitor::~BucketVisitor()
+{
+}
+
+BinaryQueue::BucketVisitorCall::BucketVisitorCall(BucketVisitor *visitor) :
+       m_visitor(visitor)
+{
+}
+
+BinaryQueue::BucketVisitorCall::~BucketVisitorCall()
+{
+}
+
+void BinaryQueue::BucketVisitorCall::operator()(Bucket *bucket) const
+{
+       m_visitor->OnVisitBucket(bucket->ptr, bucket->left);
+}
+
+void BinaryQueue::visitBuckets(BucketVisitor *visitor) const
+{
+       throw std::invalid_argument("visitBuckets func failed");
+
+       // Visit all buckets
+       std::for_each(m_buckets.begin(), m_buckets.end(), BucketVisitorCall(visitor));
+}
+
+}
diff --git a/src/framework/common/binary-queue.h b/src/framework/common/binary-queue.h
new file mode 100644 (file)
index 0000000..12de247
--- /dev/null
@@ -0,0 +1,279 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        binary-queue.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the header file of binary queue
+ */
+#pragma once
+
+#include <memory>
+#include <list>
+#include <functional>
+
+namespace Csr {
+/**
+ * Binary stream implemented as constant size bucket list
+ *
+ * @todo Add optimized implementation for flattenConsume
+ */
+class BinaryQueue {
+public:
+       using BufferDeleter = std::function<void(const void *buffer, size_t size, void *userParam)>;
+       static void bufferDeleterFree(const void *buffer,
+                                                                 size_t size,
+                                                                 void *userParam);
+
+       class BucketVisitor {
+       public:
+               /**
+                * Destructor
+                */
+               virtual ~BucketVisitor();
+
+               /**
+                * Visit bucket
+                *
+                * @return none
+                * @param[in] buffer Constant pointer to bucket data buffer
+                * @param[in] size Number of bytes in bucket
+                */
+               virtual void OnVisitBucket(const void *buffer, size_t size) = 0;
+       };
+
+private:
+       struct Bucket {
+               Bucket(const Bucket &) = delete;
+               Bucket &operator=(const Bucket &) = delete;
+
+               const void *buffer;
+               const void *ptr;
+               size_t size;
+               size_t left;
+
+               BufferDeleter deleter;
+               void *param;
+
+               Bucket(const void *buffer,
+                          size_t size,
+                          BufferDeleter deleter,
+                          void *userParam);
+               virtual ~Bucket();
+       };
+
+       typedef std::list<Bucket *> BucketList;
+       BucketList m_buckets;
+       size_t m_size;
+
+       static void deleteBucket(Bucket *bucket);
+
+       class BucketVisitorCall {
+       private:
+               BucketVisitor *m_visitor;
+
+       public:
+               BucketVisitorCall(BucketVisitor *visitor);
+               virtual ~BucketVisitorCall();
+
+               void operator()(Bucket *bucket) const;
+       };
+
+public:
+       /**
+        * Construct empty binary queue
+        */
+       BinaryQueue();
+
+       /**
+        * Construct binary queue via bare copy of other binary queue
+        *
+        * @param[in] other Other binary queue to copy from
+        * @warning One cannot assume that bucket structure is preserved during copy
+        */
+       BinaryQueue(const BinaryQueue &other);
+
+       /**
+        * Construct binary queue by moving data from other binary queue
+        *
+        * @param[in] other Other binary queue to move from
+        */
+       BinaryQueue(BinaryQueue&&) = default;
+
+       /**
+        * Destructor
+        */
+       virtual ~BinaryQueue();
+
+       /**
+        * Construct binary queue via bare copy of other binary queue
+        *
+        * @param[in] other Other binary queue to copy from
+        * @warning One cannot assume that bucket structure is preserved during copy
+        */
+       const BinaryQueue &operator=(const BinaryQueue &other);
+
+       /**
+        * Assign data from other binary queue using move semantics
+        *
+        * @param[in] other Other binary queue to move from
+        */
+       BinaryQueue &operator=(BinaryQueue&&) = default;
+
+       /**
+        * Append copy of @a size bytes from memory pointed by @a buffer
+        * to the end of binary queue. Uses default deleter based on free.
+        *
+        * @return none
+        * @param[in] buffer Pointer to buffer to copy data from
+        * @param[in] size Number of bytes to copy
+        * @exception std::bad_alloc Cannot allocate memory to hold additional data
+        * @see BinaryQueue::BufferDeleterFree
+        */
+       void appendCopy(const void *buffer, size_t size);
+
+       /**
+        * Append @a size bytes from memory pointed by @a buffer
+        * to the end of binary queue. Uses custom provided deleter.
+        * Responsibility for deleting provided buffer is transfered to BinaryQueue.
+        *
+        * @return none
+        * @param[in] buffer Pointer to data buffer
+        * @param[in] size Number of bytes available in buffer
+        * @param[in] deleter Pointer to deleter procedure used to free provided
+        * buffer
+        * @param[in] userParam User parameter passed to deleter routine
+        * @exception std::bad_alloc Cannot allocate memory to hold additional data
+        */
+       void appendUnmanaged(
+               const void *buffer,
+               size_t size,
+               BufferDeleter deleter = &BinaryQueue::bufferDeleterFree,
+               void *userParam = nullptr);
+
+       /**
+        * Append copy of other binary queue to the end of this binary queue
+        *
+        * @return none
+        * @param[in] other Constant reference to other binary queue to copy data
+        * from
+        * @exception std::bad_alloc Cannot allocate memory to hold additional data
+        * @warning One cannot assume that bucket structure is preserved during copy
+        */
+       void appendCopyFrom(const BinaryQueue &other);
+
+       /**
+        * Move bytes from other binary queue to the end of this binary queue.
+        * This also removes all bytes from other binary queue.
+        * This method is designed to be as fast as possible (only pointer swaps)
+        * and is suggested over making copies of binary queues.
+        * Bucket structure is preserved after operation.
+        *
+        * @return none
+        * @param[in] other Reference to other binary queue to move data from
+        * @exception std::bad_alloc Cannot allocate memory to hold additional data
+        */
+       void appendMoveFrom(BinaryQueue &other);
+
+       /**
+        * Append copy of binary queue to the end of other binary queue
+        *
+        * @return none
+        * @param[in] other Constant reference to other binary queue to copy data to
+        * @exception std::bad_alloc Cannot allocate memory to hold additional data
+        * @warning One cannot assume that bucket structure is preserved during copy
+        */
+       void appendCopyTo(BinaryQueue &other) const;
+
+       /**
+        * Move bytes from binary queue to the end of other binary queue.
+        * This also removes all bytes from binary queue.
+        * This method is designed to be as fast as possible (only pointer swaps)
+        * and is suggested over making copies of binary queues.
+        * Bucket structure is preserved after operation.
+        *
+        * @return none
+        * @param[in] other Reference to other binary queue to move data to
+        * @exception std::bad_alloc Cannot allocate memory to hold additional data
+        */
+       void appendMoveTo(BinaryQueue &other);
+
+       /**
+        * Retrieve total size of all data contained in binary queue
+        *
+        * @return Number of bytes in binary queue
+        */
+       size_t size() const;
+
+       /**
+        * Remove all data from binary queue
+        *
+        * @return none
+        */
+       void clear();
+
+       /**
+        * Check if binary queue is empty
+        *
+        * @return true if binary queue is empty, false otherwise
+        */
+       bool empty() const;
+
+       /**
+        * Remove @a size bytes from beginning of binary queue
+        *
+        * @return none
+        * @param[in] size Number of bytes to remove
+        * @exception BinaryQueue::Exception::OutOfData Number of bytes is larger
+        *            than available bytes in binary queue
+        */
+       void consume(size_t size);
+
+       /**
+        * Retrieve @a size bytes from beginning of binary queue and copy them
+        * to user supplied buffer
+        *
+        * @return none
+        * @param[in] buffer Pointer to user buffer to receive bytes
+        * @param[in] size Size of user buffer pointed by @a buffer
+        * @exception BinaryQueue::Exception::OutOfData Number of bytes to flatten
+        *            is larger than available bytes in binary queue
+        */
+       void flatten(void *buffer, size_t size) const;
+
+       /**
+        * Retrieve @a size bytes from beginning of binary queue, copy them
+        * to user supplied buffer, and remove from binary queue
+        *
+        * @return none
+        * @param[in] buffer Pointer to user buffer to receive bytes
+        * @param[in] size Size of user buffer pointed by @a buffer
+        * @exception BinaryQueue::Exception::OutOfData Number of bytes to flatten
+        *            is larger than available bytes in binary queue
+        */
+       void flattenConsume(void *buffer, size_t size);
+
+       /**
+        * Visit each buffer with data using visitor object
+        *
+        * @return none
+        * @param[in] visitor Pointer to bucket visitor
+        * @see BinaryQueue::BucketVisitor
+        */
+       void visitBuckets(BucketVisitor *visitor) const;
+};
+
+}
diff --git a/src/framework/common/command-id.h b/src/framework/common/command-id.h
new file mode 100644 (file)
index 0000000..419998c
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        command-id.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+namespace Csr {
+
+enum class CommandId : int {
+       FILE_SCAN  = 0x01,
+       FILE_JUDGE = 0x02
+};
+
+}
diff --git a/src/framework/common/connection.cpp b/src/framework/common/connection.cpp
new file mode 100644 (file)
index 0000000..e283e94
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        connection.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "connection.h"
+
+#include <utility>
+
+namespace Csr {
+
+Connection::Connection(Socket &&socket) : m_socket(std::move(socket))
+{
+}
+
+Connection::~Connection()
+{
+}
+
+Connection::Connection(Connection &&other) : m_socket(std::move(other.m_socket))
+{
+}
+
+Connection &Connection::operator=(Connection &&other)
+{
+       if (this == &other)
+               return *this;
+
+       m_socket = std::move(other.m_socket);
+       return *this;
+}
+
+void Connection::send(const RawBuffer &buf) const
+{
+       /* TODO: scoped-lock ? */
+       m_socket.write(buf);
+}
+
+RawBuffer Connection::receive() const
+{
+       /* TODO: scoped-lock ? */
+       return m_socket.read();
+}
+
+int Connection::getFd() const
+{
+       return m_socket.getFd();
+}
+
+}
diff --git a/src/framework/common/connection.h b/src/framework/common/connection.h
new file mode 100644 (file)
index 0000000..b236d54
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        connection.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+#include <functional>
+#include <memory>
+
+#include "socket.h"
+#include "raw-buffer.h"
+
+namespace Csr {
+
+class Connection {
+public:
+       explicit Connection(Socket &&socket);
+       virtual ~Connection();
+
+       Connection(const Connection &) = delete;
+       Connection &operator=(const Connection &) = delete;
+
+       Connection(Connection &&);
+       Connection &operator=(Connection &&);
+
+       void send(const RawBuffer &) const;
+       RawBuffer receive(void) const;
+       int getFd(void) const;
+
+private:
+       Socket m_socket;
+};
+
+using ConnShPtr = std::shared_ptr<Connection>;
+
+}
diff --git a/src/framework/common/message-buffer.cpp b/src/framework/common/message-buffer.cpp
new file mode 100644 (file)
index 0000000..328ca98
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        message-buffer.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of MessageBuffer.
+ */
+#include "message-buffer.h"
+
+#include <exception>
+#include <cstring>
+
+namespace Csr {
+
+MessageBuffer::MessageBuffer() : m_bytesLeft(0)
+{
+}
+
+void MessageBuffer::push(const RawBuffer &data)
+{
+       m_buffer.appendCopy(data.data(), data.size());
+}
+
+RawBuffer MessageBuffer::pop()
+{
+       size_t size = m_buffer.size();
+
+       RawBuffer buffer(size + sizeof(size_t));
+
+       memcpy(buffer.data(), &size, sizeof(size_t));
+       m_buffer.flattenConsume(buffer.data() + sizeof(size_t), size);
+
+       return buffer;
+}
+
+bool MessageBuffer::ready()
+{
+       countBytesLeft();
+
+       return (m_bytesLeft != 0 && m_bytesLeft <= m_buffer.size());
+}
+
+void MessageBuffer::read(size_t num, void *bytes)
+{
+       countBytesLeft();
+       if (num > m_bytesLeft)
+               throw std::range_error("protocol broken. message buffer overreaded");
+
+       m_buffer.flattenConsume(bytes, num);
+       m_bytesLeft -= num;
+}
+
+void MessageBuffer::write(size_t num, const void *bytes)
+{
+       m_buffer.appendCopy(bytes, num);
+}
+
+void MessageBuffer::countBytesLeft()
+{
+       if (m_bytesLeft > 0 || m_buffer.size() < sizeof(size_t))
+               return;
+
+       m_buffer.flattenConsume(&m_bytesLeft, sizeof(size_t));
+}
+
+}
diff --git a/src/framework/common/message-buffer.h b/src/framework/common/message-buffer.h
new file mode 100644 (file)
index 0000000..0deb2bf
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        message-buffer.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementatin of MessageBuffer.
+ */
+#pragma once
+
+#include "raw-buffer.h"
+#include "binary-queue.h"
+#include "serialization.h"
+
+namespace Csr {
+
+class MessageBuffer : public IStream {
+public:
+       MessageBuffer();
+
+       MessageBuffer(MessageBuffer&&) = default;
+       MessageBuffer &operator=(MessageBuffer&&) = default;
+
+       void push(const RawBuffer &data);
+       RawBuffer pop();
+
+       bool ready();
+
+       virtual void read(size_t num, void *bytes);
+       virtual void write(size_t num, const void *bytes);
+
+       // generic serialization
+       template <typename... Args>
+       static MessageBuffer Serialize(const Args&... args)
+       {
+               MessageBuffer buffer;
+               Serializer<Args...>::Serialize(buffer, args...);
+               return buffer;
+       }
+
+       // generic deserialization
+       template <typename... Args>
+       void Deserialize(Args&... args)
+       {
+               Deserializer<Args...>::Deserialize(*this, args...);
+       }
+
+protected:
+       void countBytesLeft(void);
+
+       size_t m_bytesLeft;
+       BinaryQueue m_buffer;
+};
+
+}
diff --git a/src/framework/common/raw-buffer.h b/src/framework/common/raw-buffer.h
new file mode 100644 (file)
index 0000000..8700300
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        raw-buffer.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <vector>
+
+namespace Csr {
+
+using RawBuffer = std::vector<unsigned char>;
+
+}
diff --git a/src/framework/common/serialization.h b/src/framework/common/serialization.h
new file mode 100644 (file)
index 0000000..d68066d
--- /dev/null
@@ -0,0 +1,518 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    serialization.h
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   Interfaces and templates used for data serialization.
+ */
+#pragma once
+
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+#include <list>
+#include <map>
+#include <memory>
+
+#include "command-id.h"
+#include "csr/error.h"
+
+namespace Csr {
+
+// Abstract data stream buffer
+class IStream {
+  public:
+       virtual void read(size_t num, void * bytes) = 0;
+       virtual void write(size_t num, const void * bytes) = 0;
+       virtual ~IStream(){}
+};
+
+// Serializable interface
+class ISerializable {
+  public:
+       /*    ISerializable(){};
+        *    ISerializable(IStream&){}; */
+       virtual void Serialize(IStream &) const = 0;
+       virtual ~ISerializable(){}
+};
+
+struct Serialization {
+       // serialization
+       // normal functions
+
+       // ISerializable objects
+       static void Serialize(IStream& stream, const ISerializable& object)
+       {
+               object.Serialize(stream);
+       }
+
+       static void Serialize(IStream& stream, const ISerializable* const object)
+       {
+               object->Serialize(stream);
+       }
+
+       // char
+       static void Serialize(IStream& stream, const char value)
+       {
+               stream.write(sizeof(value), &value);
+       }
+       static void Serialize(IStream& stream, const char* const value)
+       {
+               stream.write(sizeof(*value), value);
+       }
+
+       // unsigned char
+       static void Serialize(IStream& stream, const unsigned char value)
+       {
+               stream.write(sizeof(value), &value);
+       }
+       static void Serialize(IStream& stream, const unsigned char* const value)
+       {
+               stream.write(sizeof(*value), value);
+       }
+
+       // unsigned int32
+       static void Serialize(IStream& stream, const uint32_t value)
+       {
+               stream.write(sizeof(value), &value);
+       }
+       static void Serialize(IStream& stream, const uint32_t* const value)
+       {
+               stream.write(sizeof(*value), value);
+       }
+
+       // int32
+       static void Serialize(IStream& stream, const int32_t value)
+       {
+               stream.write(sizeof(value), &value);
+       }
+       static void Serialize(IStream& stream, const int32_t* const value)
+       {
+               stream.write(sizeof(*value), value);
+       }
+
+       // unsigned int64
+       static void Serialize(IStream& stream, const uint64_t value)
+       {
+               stream.write(sizeof(value), &value);
+       }
+       static void Serialize(IStream& stream, const uint64_t* const value)
+       {
+               stream.write(sizeof(*value), value);
+       }
+
+       // int64
+       static void Serialize(IStream& stream, const int64_t value)
+       {
+               stream.write(sizeof(value), &value);
+       }
+       static void Serialize(IStream& stream, const int64_t* const value)
+       {
+               stream.write(sizeof(*value), value);
+       }
+
+       // bool
+       static void Serialize(IStream& stream, const bool value)
+       {
+               stream.write(sizeof(value), &value);
+       }
+       static void Serialize(IStream& stream, const bool* const value)
+       {
+               stream.write(sizeof(*value), value);
+       }
+
+       static void Serialize(IStream& stream, const CommandId value)
+       {
+               Serialize(stream, static_cast<int>(value));
+       }
+
+       static void Serialize(IStream& stream, const csr_error_e value)
+       {
+               Serialize(stream, static_cast<int>(value));
+       }
+
+       // std::string
+       template <typename T, typename R, typename A>
+       static void Serialize(IStream& stream, const std::basic_string<T, R, A>& str)
+       {
+               int length = str.size();
+               stream.write(sizeof(length), &length);
+               stream.write(length*sizeof(T), str.data());
+       }
+
+       template<typename T, typename R, typename A>
+       static void Serialize(IStream& stream, const std::basic_string<T, R, A>* const str)
+       {
+               int length = str->size();
+               stream.write(sizeof(length), &length);
+               stream.write(length*sizeof(T), str->data());
+       }
+
+       // STL templates
+
+       // std::list
+       template <typename T>
+       static void Serialize(IStream& stream, const std::list<T>& list)
+       {
+               int length = list.size();
+               stream.write(sizeof(length), &length);
+               for (typename std::list<T>::const_iterator list_iter = list.begin();
+                        list_iter != list.end(); list_iter++)
+                       Serialize(stream, *list_iter);
+       }
+       template <typename T>
+       static void Serialize(IStream& stream, const std::list<T>* const list)
+       {
+               Serialize(stream, *list);
+       }
+
+       // RawBuffer
+       template <typename A>
+       static void Serialize(IStream& stream, const std::vector<unsigned char, A>& vec)
+       {
+               int length = vec.size();
+               stream.write(sizeof(length), &length);
+               stream.write(length, vec.data());
+       }
+
+       template <typename A>
+       static void Serialize(IStream& stream, const std::vector<unsigned char, A>* const vec)
+       {
+               Serialize(stream, *vec);
+       }
+
+       // std::vector
+       template <typename T, typename A>
+       static void Serialize(IStream& stream, const std::vector<T, A>& vec)
+       {
+               int length = vec.size();
+               stream.write(sizeof(length), &length);
+               for (const auto &i : vec)
+                       Serialize(stream, i);
+       }
+       template <typename T, typename A>
+       static void Serialize(IStream& stream, const std::vector<T, A>* const vec)
+       {
+               Serialize(stream, *vec);
+       }
+
+       // std::pair
+       template <typename A, typename B>
+       static void Serialize(IStream& stream, const std::pair<A, B>& p)
+       {
+               Serialize(stream, p.first);
+               Serialize(stream, p.second);
+       }
+       template <typename A, typename B>
+       static void Serialize(IStream& stream, const std::pair<A, B>* const p)
+       {
+               Serialize(stream, *p);
+       }
+
+       // std::map
+       template <typename K, typename T>
+       static void Serialize(IStream& stream, const std::map<K, T>& map)
+       {
+               int length = map.size();
+               stream.write(sizeof(length), &length);
+               typename std::map<K, T>::const_iterator it;
+               for (it = map.begin(); it != map.end(); ++it) {
+                       Serialize(stream, (*it).first);
+                       Serialize(stream, (*it).second);
+               }
+       }
+       template <typename K, typename T>
+       static void Serialize(IStream& stream, const std::map<K, T>* const map)
+       {
+               Serialize(stream, *map);
+       }
+
+       // std::unique_ptr
+       template <typename T>
+       static void Serialize(IStream& stream, const std::unique_ptr<T>& p)
+       {
+               Serialize(stream, *p);
+       }
+}; // struct Serialization
+
+struct Deserialization {
+       // deserialization
+       // normal functions
+
+       // ISerializable objects
+       // T instead of ISerializable is needed to call proper constructor
+       template <typename T>
+       static void Deserialize(IStream& stream, T& object)
+       {
+               object = T(stream);
+       }
+       template <typename T>
+       static void Deserialize(IStream& stream, T*& object)
+       {
+               object = new T(stream);
+       }
+
+       // char
+       static void Deserialize(IStream& stream, char& value)
+       {
+               stream.read(sizeof(value), &value);
+       }
+       static void Deserialize(IStream& stream, char*& value)
+       {
+               value = new char;
+               stream.read(sizeof(*value), value);
+       }
+
+       // unsigned char
+       static void Deserialize(IStream& stream, unsigned char& value)
+       {
+               stream.read(sizeof(value), &value);
+       }
+       static void Deserialize(IStream& stream, unsigned char*& value)
+       {
+               value = new unsigned char;
+               stream.read(sizeof(*value), value);
+       }
+
+       // unsigned int32
+       static void Deserialize(IStream& stream, uint32_t& value)
+       {
+               stream.read(sizeof(value), &value);
+       }
+       static void Deserialize(IStream& stream, uint32_t*& value)
+       {
+               value = new uint32_t;
+               stream.read(sizeof(*value), value);
+       }
+
+       // int32
+       static void Deserialize(IStream& stream, int32_t& value)
+       {
+               stream.read(sizeof(value), &value);
+       }
+       static void Deserialize(IStream& stream, int32_t*& value)
+       {
+               value = new int32_t;
+               stream.read(sizeof(*value), value);
+       }
+
+       // unsigned int64
+       static void Deserialize(IStream& stream, uint64_t& value)
+       {
+               stream.read(sizeof(value), &value);
+       }
+       static void Deserialize(IStream& stream, uint64_t*& value)
+       {
+               value = new uint64_t;
+               stream.read(sizeof(*value), value);
+       }
+
+       // int64
+       static void Deserialize(IStream& stream, int64_t& value)
+       {
+               stream.read(sizeof(value), &value);
+       }
+       static void Deserialize(IStream& stream, int64_t*& value)
+       {
+               value = new int64_t;
+               stream.read(sizeof(*value), value);
+       }
+
+       // bool
+       static void Deserialize(IStream& stream, bool& value)
+       {
+               stream.read(sizeof(value), &value);
+       }
+       static void Deserialize(IStream& stream, bool*& value)
+       {
+               value = new bool;
+               stream.read(sizeof(*value), value);
+       }
+
+       static void Deserialize(IStream& stream, CommandId& value)
+       {
+               int val;
+               Deserialize(stream, val);
+               value = static_cast<CommandId>(val);
+       }
+
+       static void Deserialize(IStream& stream, csr_error_e& value)
+       {
+               int val;
+               Deserialize(stream, val);
+               value = static_cast<csr_error_e>(val);
+       }
+
+       template <typename T, typename R, typename A>
+       static void Deserialize(IStream& stream, std::basic_string<T, R, A>& str)
+       {
+               int length;
+               stream.read(sizeof(length), &length);
+               std::vector<T> buf(length);
+               stream.read(length*sizeof(T), buf.data());
+               str = std::basic_string<T, R, A>(buf.data(), buf.data() + length);
+       }
+
+       template <typename T, typename R, typename A>
+       static void Deserialize(IStream& stream, std::basic_string<T, R, A>*& str)
+       {
+               int length;
+               stream.read(sizeof(length), &length);
+               std::vector<T> buf(length);
+               stream.read(length*sizeof(T), buf.data());
+               str = new std::basic_string<T, R, A>(buf.data(), buf.data() + length);
+       }
+
+       // STL templates
+
+       // std::list
+       template <typename T>
+       static void Deserialize(IStream& stream, std::list<T>& list)
+       {
+               int length;
+               stream.read(sizeof(length), &length);
+               for (int i = 0; i < length; ++i) {
+                       T obj;
+                       Deserialize(stream, obj);
+                       list.push_back(std::move(obj));
+               }
+       }
+       template <typename T>
+       static void Deserialize(IStream& stream, std::list<T>*& list)
+       {
+               list = new std::list<T>;
+               Deserialize(stream, *list);
+       }
+
+       // RawBuffer
+       template <typename A>
+       static void Deserialize(IStream& stream, std::vector<unsigned char, A>& vec)
+       {
+               int length;
+               stream.read(sizeof(length), &length);
+               vec.resize(length);
+               stream.read(length, vec.data());
+       }
+
+       template <typename A>
+       static void Deserialize(IStream& stream, std::vector<unsigned char, A>*& vec)
+       {
+               vec = new std::vector<unsigned char, A>;
+               Deserialize(stream, *vec);
+       }
+
+       // std::vector
+       template <typename T, typename A>
+       static void Deserialize(IStream& stream, std::vector<T, A>& vec)
+       {
+               int length;
+               stream.read(sizeof(length), &length);
+               for (int i = 0; i < length; ++i) {
+                       T obj;
+                       Deserialize(stream, obj);
+                       vec.push_back(std::move(obj));
+               }
+       }
+       template <typename T, typename A>
+       static void Deserialize(IStream& stream, std::vector<T, A>*& vec)
+       {
+               vec = new std::vector<T, A>;
+               Deserialize(stream, *vec);
+       }
+
+       // std::pair
+       template <typename A, typename B>
+       static void Deserialize(IStream& stream, std::pair<A, B>& p)
+       {
+               Deserialize(stream, p.first);
+               Deserialize(stream, p.second);
+       }
+       template <typename A, typename B>
+       static void Deserialize(IStream& stream, std::pair<A, B>*& p)
+       {
+               p = new std::pair<A, B>;
+               Deserialize(stream, *p);
+       }
+
+       // std::map
+       template <typename K, typename T>
+       static void Deserialize(IStream& stream, std::map<K, T>& map)
+       {
+               int length;
+               stream.read(sizeof(length), &length);
+               for (int i = 0; i < length; ++i) {
+                       K key;
+                       T obj;
+                       Deserialize(stream, key);
+                       Deserialize(stream, obj);
+                       map[key] = std::move(obj);
+               }
+       }
+       template <typename K, typename T>
+       static void Deserialize(IStream& stream, std::map<K, T>*& map)
+       {
+               map = new std::map<K, T>;
+               Deserialize(stream, *map);
+       }
+}; // struct Deserialization
+
+// generic serialization
+template <typename... Args>
+struct Serializer;
+
+template <typename First, typename... Args>
+struct Serializer<First, Args...> : public Serializer<Args...> {
+       static void Serialize(IStream& stream, const First& f, const Args&... args)
+       {
+               Serialization::Serialize(stream, f);
+               Serializer<Args...>::Serialize(stream, args...);
+       }
+};
+
+// end of recursion
+template <>
+struct Serializer<> {
+       static void Serialize(IStream&)
+       {
+               return;
+       }
+};
+
+// generic deserialization
+template <typename... Args>
+struct Deserializer;
+
+template <typename First, typename... Args>
+struct Deserializer<First, Args...> : public Deserializer<Args...> {
+       static void Deserialize(IStream& stream, First& f, Args&... args)
+       {
+               Deserialization::Deserialize(stream, f);
+               Deserializer<Args...>::Deserialize(stream, args...);
+       }
+};
+
+// end of recursion
+template <>
+struct Deserializer<> {
+       static void Deserialize(IStream&)
+       {
+               return;
+       }
+};
+
+}
diff --git a/src/framework/common/socket.cpp b/src/framework/common/socket.cpp
new file mode 100644 (file)
index 0000000..ef03722
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        socket.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "socket.h"
+
+#include <exception>
+#include <system_error>
+
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <unistd.h>
+
+#include <systemd/sd-daemon.h>
+
+#include "audit/logger.h"
+
+namespace {
+
+int createSystemdSocket(const std::string &path)
+{
+       int n = ::sd_listen_fds(-1);
+       if (n < 0)
+               throw std::system_error(std::error_code(), "failed to sd_listen_fds");
+
+       for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; ++fd) {
+               if (::sd_is_socket_unix(fd, SOCK_STREAM, 1, path.c_str(), 0) > 0) {
+                       INFO("service's systemd socket found with fd: " << fd);
+                       return fd;
+               }
+       }
+
+       throw std::system_error(std::error_code(), "get systemd socket failed!");
+}
+
+}
+
+namespace Csr {
+
+Socket::Socket(int fd) : m_fd(fd)
+{
+       if (m_fd < 0)
+               throw std::logic_error("Socket fd from constructor is invalid!!");
+}
+
+Socket::Socket(const std::string &path) : m_fd(createSystemdSocket(path))
+{
+}
+
+Socket::Socket(Socket &&other)
+{
+       if (other.m_fd < 0)
+               throw std::logic_error("Socket fd from move constructor is invalid!!");
+
+       m_fd = other.m_fd;
+       other.m_fd = 0;
+}
+
+Socket &Socket::operator=(Socket &&other)
+{
+       if (this == &other)
+               return *this;
+
+       if (other.m_fd < 0)
+               throw std::logic_error("Socket fd from move assignment is invalid!!");
+
+       m_fd = other.m_fd;
+       other.m_fd = 0;
+
+       return *this;
+}
+
+Socket::~Socket()
+{
+       if (m_fd == 0)
+               return;
+
+       INFO("Close socket of fd: " << m_fd);
+       ::close(m_fd);
+}
+
+Socket Socket::accept() const
+{
+       int fd = ::accept(m_fd, nullptr, nullptr);
+       if (fd < 0)
+               throw std::system_error(
+                       std::error_code(errno, std::generic_category()),
+                       "socket accept failed!");
+
+       INFO("Accept client success with fd: " << fd);
+
+       return Socket(fd);
+}
+
+Socket Socket::connect(const std::string &path)
+{
+       if (path.size() >= sizeof(sockaddr_un::sun_path))
+               throw std::invalid_argument("socket path size too long!");
+
+       int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
+       if (fd < 0)
+               throw std::system_error(
+                       std::error_code(errno, std::generic_category()),
+                       "socket create failed!");
+
+       sockaddr_un addr;
+       addr.sun_family = AF_UNIX;
+
+       strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path));
+
+       if (::connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(sockaddr_un)) == -1)
+               throw std::system_error(
+                       std::error_code(errno, std::generic_category()),
+                       "socket connect failed!");
+
+       INFO("Connect to CSR server success with fd:" << fd);
+
+       return Socket(fd);
+}
+
+int Socket::getFd() const
+{
+       return m_fd;
+}
+
+RawBuffer Socket::read(void) const
+{
+       size_t total = 0;
+
+       RawBuffer data(1024, 0);
+       auto buf = reinterpret_cast<char *>(data.data());
+       auto size = data.size();
+
+       DEBUG("Read data from stream on socket fd[" << m_fd << "]");
+
+       while (total < size) {
+               int bytes = ::read(m_fd, buf + total, size - total);
+               if (bytes < 0) {
+                       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
+                               continue;
+                       else
+                               throw std::system_error(
+                                       std::error_code(errno, std::generic_category()),
+                                       "socket read failed!");
+               }
+
+               /* TODO: handle the case of more bytes in stream to read than buffer size */
+               total += bytes;
+               break;
+       }
+
+       data.resize(total);
+
+       DEBUG("Read data of size[" << total
+               << "] from stream on socket fd[" << m_fd << "] done.");
+
+       return data;
+}
+
+void Socket::write(const RawBuffer &data) const
+{
+       size_t total = 0;
+
+       auto buf = reinterpret_cast<const char *>(data.data());
+       auto size = data.size();
+
+       DEBUG("Write data to stream on socket fd[" << m_fd << "]");
+
+       while (total < size) {
+               int bytes = ::write(m_fd, buf + total, size - total);
+               if (bytes < 0) {
+                       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
+                               continue;
+                       else
+                               throw std::system_error(
+                                       std::error_code(errno, std::generic_category()),
+                                       "socket write failed!");
+               }
+
+               total += bytes;
+       }
+
+       DEBUG("Write data of size[" << total
+               << "] to stream on socket fd[" << m_fd << "] done.");
+}
+
+}
diff --git a/src/framework/common/socket.h b/src/framework/common/socket.h
new file mode 100644 (file)
index 0000000..c8c24d0
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        socket.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+
+#include "raw-buffer.h"
+
+namespace Csr {
+
+class Socket {
+public:
+       Socket(int fd = 0);
+       Socket(const std::string &path); /* Construct with systemd socket from path */
+
+       Socket(const Socket &) = delete;
+       Socket &operator=(const Socket &) = delete;
+
+       Socket(Socket &&);
+       Socket &operator=(Socket &&);
+
+       virtual ~Socket();
+
+       Socket accept(void) const;
+       int getFd(void) const;
+
+       RawBuffer read(void) const;
+       void write(const RawBuffer &data) const;
+
+       static Socket connect(const std::string &path); /* TODO: can it be constructor? */
+
+private:
+       int m_fd;
+
+};
+
+}
diff --git a/src/framework/main/csr-main.cpp b/src/framework/main/csr-main.cpp
new file mode 100644 (file)
index 0000000..9bb89e1
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        csr-main.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Main of csr daemon
+ */
+#include "service.h"
+
+#include "audit/logger.h"
+
+int main(void)
+{
+       try {
+               INFO("Start csr-server main!");
+
+               Csr::Service service("/tmp/." SERVICE_NAME ".socket");
+
+               INFO("Let's start csr-server service!");
+
+               service.start();
+
+               return 0;
+       } catch (const std::exception &e) {
+               ERROR("std exception occured in csr-server main! what: " << e.what());
+               return -1;
+       } catch (...) {
+               ERROR("Unhandled exception occured in csr-server main!");
+               return -1;
+       }
+}
diff --git a/src/framework/main/mainloop.cpp b/src/framework/main/mainloop.cpp
new file mode 100644 (file)
index 0000000..ec17726
--- /dev/null
@@ -0,0 +1,135 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        mainloop.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Mainloop of csr-server with epoll
+ */
+#include "mainloop.h"
+
+#include <exception>
+#include <stdexcept>
+#include <system_error>
+#include <sys/epoll.h>
+#include <unistd.h>
+
+#include "audit/logger.h"
+
+namespace Csr {
+
+Mainloop::Mainloop() :
+       m_pollfd(::epoll_create1(EPOLL_CLOEXEC))
+{
+       if (m_pollfd == -1)
+               throw std::system_error(
+                       std::error_code(errno, std::generic_category()),
+                       "Failed to epoll_create1");
+}
+
+Mainloop::~Mainloop()
+{
+       if (!m_callbacks.empty())
+               throw std::logic_error("m_callbacks shouldn't be empty");
+
+       ::close(m_pollfd);
+}
+
+void Mainloop::run()
+{
+       while (true) {
+               dispatch(-1);
+       }
+}
+
+void Mainloop::addEventSource(int fd, uint32_t event, Callback &&callback)
+{
+       /* TODO: use scoped-lock to thread safe on member variables */
+       if (m_callbacks.count(fd) != 0)
+               throw std::logic_error(FORMAT("event source on fd[" << fd << "] already added!"));
+
+       DEBUG("Add event[" << event << "] source on fd[" << fd << "]");
+
+       epoll_event e;
+
+       e.events = event;
+       e.data.fd = fd;
+
+       if (::epoll_ctl(m_pollfd, EPOLL_CTL_ADD, fd, &e) == -1)
+               throw std::system_error(
+                       std::error_code(errno, std::generic_category()),
+                       "epoll_ctl failed to EPOLL_CTL_ADD.");
+
+       m_callbacks[fd] = std::move(callback);
+}
+
+void Mainloop::removeEventSource(int fd)
+{
+       /* TODO: use scoped-lock to thread safe on member variables */
+       if (m_callbacks.count(fd) == 0)
+               throw std::logic_error(FORMAT("event source on fd[" << fd << "] isn't added at all"));
+
+       DEBUG("Remove event source on fd[" << fd << "]");
+
+       do {
+               m_callbacks.erase(fd);
+               if (::epoll_ctl(m_pollfd, EPOLL_CTL_DEL, fd, nullptr) == -1) {
+                       if (errno == ENOENT)
+                               throw std::logic_error("Tried to delete epoll item which wasn't added");
+                       else
+                               throw std::system_error(
+                                       std::error_code(errno, std::generic_category()),
+                                       "epoll_ctl failed to EPOLL_CTL_DEL.");
+               }
+       } while (false);
+}
+
+void Mainloop::dispatch(int timeout)
+{
+       int nfds = -1;
+       epoll_event event[MAX_EPOLL_EVENTS];
+
+       DEBUG("Mainloop dispatched with timeout: " << timeout);
+
+       do {
+               nfds = ::epoll_wait(m_pollfd, event, MAX_EPOLL_EVENTS, timeout);
+       } while ((nfds == -1) && (errno == EINTR));
+
+       if (nfds < 0)
+               throw std::system_error(
+                       std::error_code(errno, std::generic_category()),
+                       "epoll_wait failed!");
+
+       for (int i = 0; i < nfds; i++) {
+               /* TODO: use scoped-lock to thread safe on member variables */
+               int fd = event[i].data.fd;
+
+               if (m_callbacks.count(fd) == 0)
+                       throw std::logic_error(FORMAT(
+                               "event in on fd[" << fd << "] but associated callback isn't exist!"));
+
+               if (event[i].events & (EPOLLHUP | EPOLLRDHUP)) {
+                       INFO("peer connection closed on fd[" << fd << "]");
+                       event[i].events &= ~EPOLLIN;
+               }
+
+               DEBUG("event[" << event[i].events << "] polled on fd[" << fd << "]");
+
+               m_callbacks[fd](event[i].events);
+       }
+}
+
+}
diff --git a/src/framework/main/mainloop.h b/src/framework/main/mainloop.h
new file mode 100644 (file)
index 0000000..ead51ff
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        mainloop.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Manageloop of csr-server with epoll
+ */
+#pragma once
+
+#include <functional>
+#include <mutex>
+#include <unordered_map>
+
+namespace Csr {
+
+class Mainloop {
+public:
+       typedef std::function<void(uint32_t event)> Callback;
+
+       Mainloop();
+       virtual ~Mainloop();
+
+       Mainloop(const Mainloop &) = delete;
+       Mainloop &operator=(const Mainloop &) = delete;
+       Mainloop(Mainloop &&) = delete;
+       Mainloop &operator=(Mainloop &&) = delete;
+
+       void run(void);
+
+       void addEventSource(int fd, uint32_t event, Callback &&callback);
+       void removeEventSource(int fd);
+
+private:
+       void dispatch(int timeout);
+
+       int m_pollfd;
+       std::mutex m_mutex;
+       std::unordered_map<int, Callback> m_callbacks;
+
+       constexpr static size_t MAX_EPOLL_EVENTS = 32;
+};
+
+}
diff --git a/src/framework/service/logic.cpp b/src/framework/service/logic.cpp
new file mode 100644 (file)
index 0000000..e7abadb
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        logic.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "logic.h"
+
+#include <string>
+#include <utility>
+#include <iostream>
+
+#include "audit/logger.h"
+#include "csr/error.h"
+
+namespace Csr {
+
+Logic::Logic()
+{
+}
+
+Logic::~Logic()
+{
+}
+
+RawBuffer Logic::dispatch(const RawBuffer &in)
+{
+       auto info = getRequestInfo(in);
+
+       INFO("Request dispatch! CommandId: " << static_cast<int>(info.first));
+
+       switch (info.first) {
+       case CommandId::FILE_SCAN: {
+               std::string filepath;
+               info.second.Deserialize(filepath);
+               return fileScan(filepath);
+       }
+
+       case CommandId::FILE_JUDGE: {
+               std::string filepath;
+               int judge;
+               info.second.Deserialize(filepath, judge);
+               return fileJudge(filepath, judge);
+       }
+
+       default:
+               /* TODO: throw request info broken exception */
+               return RawBuffer();
+       }
+}
+
+std::pair<CommandId, MessageBuffer> Logic::getRequestInfo(const RawBuffer &data)
+{
+       CommandId id;
+
+       MessageBuffer msgbuffer;
+       msgbuffer.push(data);
+       msgbuffer.Deserialize(id);
+
+       return std::make_pair(id, std::move(msgbuffer));
+}
+
+RawBuffer Logic::fileScan(const std::string &filepath)
+{
+       DEBUG("Do filescan through engine with filepath: " << filepath);
+
+       return MessageBuffer::Serialize(CSR_ERROR_NONE).pop();
+}
+
+RawBuffer Logic::fileJudge(const std::string &filepath, int judge)
+{
+       DEBUG("Do filejudge through engine with filepath: " << filepath
+               << " and judge: " << judge);
+
+       return MessageBuffer::Serialize(CSR_ERROR_NONE).pop();
+}
+
+}
diff --git a/src/framework/service/logic.h b/src/framework/service/logic.h
new file mode 100644 (file)
index 0000000..9baecd2
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        logic.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+#include <utility>
+
+#include "command-id.h"
+#include "raw-buffer.h"
+#include "message-buffer.h"
+
+namespace Csr {
+
+class Logic {
+public:
+       Logic();
+       virtual ~Logic();
+
+       RawBuffer dispatch(const RawBuffer &);
+
+private:
+       std::pair<CommandId, MessageBuffer> getRequestInfo(const RawBuffer &);
+
+       RawBuffer fileScan(const std::string &filepath);
+       RawBuffer fileJudge(const std::string &filepath, int judge);
+};
+
+}
diff --git a/src/framework/service/service.cpp b/src/framework/service/service.cpp
new file mode 100644 (file)
index 0000000..657754b
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        service.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include "service.h"
+
+#include <sys/types.h>
+#include <sys/epoll.h>
+
+#include "audit/logger.h"
+
+namespace Csr {
+
+Service::Service(const std::string &address) :
+       m_loop(),
+       m_address(address)
+{
+       DEBUG("Service constructed with address[" << address << "]");
+
+       setNewConnectionCallback(nullptr);
+       setCloseConnectionCallback(nullptr);
+}
+
+Service::~Service()
+{
+}
+
+void Service::start()
+{
+       INFO("Service start!");
+
+       Socket socket(m_address);
+
+       DEBUG("Get server socket[" << socket.getFd()
+               << "] with address[" << m_address << "]");
+
+       m_loop.addEventSource(socket.getFd(), EPOLLIN | EPOLLHUP | EPOLLRDHUP,
+               [&](uint32_t event) {
+                       if (event != EPOLLIN)
+                               return;
+
+                       m_onNewConnection(std::make_shared<Connection>(socket.accept()));
+               });
+
+       m_loop.run();
+}
+
+void Service::stop()
+{
+       INFO("Service stop!");
+}
+
+void Service::setNewConnectionCallback(const ConnCallback &/*callback*/)
+{
+       /* TODO: scoped-lock */
+       m_onNewConnection = [&](const ConnShPtr &connection) {
+               if (!connection)
+                       throw std::logic_error("onNewCOnnection called but ConnShPtr is nullptr.");
+
+               int fd = connection->getFd();
+
+               INFO("welcome! accepted client socket fd[" << fd << "]");
+
+/*
+               // TODO: disable temporarily
+               if (callback)
+                       callback(connection);
+*/
+
+               m_loop.addEventSource(fd, EPOLLIN | EPOLLHUP | EPOLLRDHUP,
+                       [&, fd](uint32_t event) {
+                               DEBUG("read event comes in to fd[" << fd << "]");
+
+                               if (m_connectionRegistry.count(fd) == 0)
+                                       throw std::logic_error(FORMAT("get event on fd[" << fd
+                                               << "] but no associated connection exist"));
+
+                               auto &conn = m_connectionRegistry[fd];
+
+                               if (event & (EPOLLHUP | EPOLLRDHUP)) {
+                                       DEBUG("event of epoll hup. close connection on fd[" << fd << "]");
+                                       m_onCloseConnection(conn);
+                                       return;
+                               }
+
+                               DEBUG("Start message process on fd[" << fd << "]");
+
+                               onMessageProcess(conn);
+                       });
+
+               m_connectionRegistry[fd] = connection;
+       };
+}
+
+void Service::setCloseConnectionCallback(const ConnCallback &/*callback*/)
+{
+       /* TODO: scoped-lock */
+       m_onCloseConnection = [&](const ConnShPtr &connection) {
+               if (!connection)
+                       throw std::logic_error("no connection to close");
+
+               int fd = connection->getFd();
+
+               if (m_connectionRegistry.count(fd) == 0)
+                       throw std::logic_error(FORMAT("no connection in registry to remove "
+                               "associated to fd[" << fd << "]"));
+
+               INFO("good-bye! close socket fd[" << fd << "]");
+
+               m_loop.removeEventSource(fd);
+               m_connectionRegistry.erase(fd); /* scoped-lock needed? */
+
+/*
+               // TODO: disable temporarily
+               if (callback)
+                       callback(connection);
+*/
+       };
+}
+
+void Service::onMessageProcess(const ConnShPtr &connection)
+{
+       DEBUG("let's dispatch it to worker threads.");
+
+       auto process = [&]() {
+               auto reply = m_logic.dispatch(connection->receive());
+
+               connection->send(reply);
+       };
+
+       /* TODO: submit to workqueue */
+       process();
+}
+
+}
diff --git a/src/framework/service/service.h b/src/framework/service/service.h
new file mode 100644 (file)
index 0000000..aaa7d5d
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        service.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+#include <memory>
+#include <functional>
+
+#include "connection.h"
+#include "mainloop.h"
+#include "logic.h"
+
+namespace Csr {
+
+using ConnCallback = std::function<void(const ConnShPtr &)>;
+
+class Service {
+public:
+       Service(const std::string &address);
+       virtual ~Service();
+
+       void start(void);
+       void stop(void);
+
+       /* ConnCallback param should throw exception to handle error */
+       void setNewConnectionCallback(const ConnCallback &);
+       void setCloseConnectionCallback(const ConnCallback &);
+
+private:
+       void onMessageProcess(const ConnShPtr &);
+
+       ConnCallback m_onNewConnection;
+       ConnCallback m_onCloseConnection;
+
+       std::unordered_map<int, ConnShPtr> m_connectionRegistry;
+       Mainloop m_loop;
+       std::string m_address;
+
+       Logic m_logic;
+};
+
+}
index 5b8817b..db25033 100644 (file)
 # @brief       install headers to be built with clients
 #
 INSTALL(
-    FILES
-        csr/TCSErrorCodes.h
-        csr/TCSImpl.h
-        csr/TWPImpl.h
-    DESTINATION
-        ${INCLUDE_INSTALL_DIR}
+       FILES
+               csr/api.h
+               csr/error.h
+       DESTINATION
+               ${INCLUDE_INSTALL_DIR}/csr/csr
 )
diff --git a/src/include/csr/TCSErrorCodes.h b/src/include/csr/TCSErrorCodes.h
deleted file mode 100644 (file)
index 963cebb..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef TCSERRORCODES_H
-#define TCSERRORCODES_H
-
-#ifdef __cplusplus 
-extern "C" {
-#endif
-
-/**
- * @file TCSErrorCodes.h
- * @brief TCS Error Code Header File
- *  
- * This file provides the TCS error code definition.
- */
-
-/**
- * @addtogroup CAPI_CSRFW_TCS_MODULE
- * @{
- */
-
-
-/**
- * @brief A generic error code.
- * @since_tizen 2.3
- */
-#define TCS_ERROR_MODULE_GENERIC 1
-
-/**
- * @brief Operations cancelled.
- * @since_tizen 2.3
- */
-#define TCS_ERROR_CANCELLED 1
-
-/**
- * @brief Unable to access data.
- * @since_tizen 2.3
- */
-#define TCS_ERROR_DATA_ACCESS 2
-
-/**
- * @brief Invalid parameter.
- * @since_tizen 2.3
- */
-#define TCS_ERROR_INVALID_PARAM 3
-
-/**
- * @brief Insufficient resource.
- * @since_tizen 2.3
- */
-#define TCS_ERROR_INSUFFICIENT_RES 4
-
-/**
- * @brief Unexpected internal error.
- * @since_tizen 2.3
- */
-#define TCS_ERROR_INTERNAL 5
-
-/**
- * @brief Invalid handle.
- * @since_tizen 2.3
- */
-#define TCS_ERROR_INVALID_HANDLE 6
-
-/**
- * @brief Specified functionality is not implemented in the TCS plug-in. (e.g. repair)
- * @since_tizen 2.3
- */
-#define TCS_ERROR_NOT_IMPLEMENTED 7
-
-/**
- * @}
- */
-
-#ifdef __cplusplus
-}
-#endif 
-
-#endif /* TCSERRORCODES_H */
diff --git a/src/include/csr/TCSImpl.h b/src/include/csr/TCSImpl.h
deleted file mode 100644 (file)
index 03a0af8..0000000
+++ /dev/null
@@ -1,532 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef TCSIMPL_H
-#define TCSIMPL_H
-
-#ifdef __cplusplus 
-extern "C" {
-#endif
-
-/**
- * @addtogroup CAPI_CSRFW_TCS_MODULE
- * @{
- */
-
-/**
- * @brief Instructs the scan functions to perform scanning only.
- * @since_tizen 2.3
- * */
-#define TCS_SA_SCANONLY 1
-
-/**
- * @brief Instructs the scan functions to carry out both scanning and repair/removal of detected malware.
- * @since_tizen 2.3
- */
-#define TCS_SA_SCANREPAIR 2
-
-/**
- * @brief Informs the caller a malicious code has been detected in the scan target. \n
- * The callback data argument pParam is set to point to a TCSDetected structure.
- * @since_tizen 2.3
- */
-#define TCS_CB_DETECTED 1
-
-/**
- * @brief Scan for malicious content in an unknown data type. \n
- * This data type should be used when the other types are not appropriate.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_UNKNOWN 0
-
-/**
- * @brief Scan for malicious content in HTML.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_HTML 1
-
-/**
- * @brief Scan for URL with malicious content. url-string format should conform to the \n
- * Uniform Resource Locators (RFC 1738) specification.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_URL 2
-
-/**
- * @brief Scan for email-address with malicious intent. \n
- * email-string format should conform with the Internet E-mail address format \n
- * (RFC 822) specification.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_EMAIL 3
-
-/**
- * @brief Scan for phone number with malicious intent.\n
- * phone-number string consists of the numeric characters '0' through '9', \n
- * and the '#' and '*' characters.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_PHONE 4
-
-/**
- * @brief Scan for malicious Java code.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_JAVA 5
-
-/**
- * @brief Scan for malicious Java code.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_JAVAS 6
-
-/**
- * @brief Scan text data for malicious content.
- * @since_tizen 2.3
- */
-#define TCS_DTYPE_TEXT 7
-
-/**
- * @brief  Malware type.
- * @since_tizen 2.3
- */
-#define TCS_VTYPE_MALWARE 1
-
-/**
- * @brief Detected malware is harmful to the user.
- * @since_tizen 2.3
- */
-#define TCS_SC_USER 1
-
-/**
- * @brief Detected malware is harmful to the terminal.
- * @since_tizen 2.3
- */
-#define TCS_SC_TERMINAL 2
-
-/**
- * @brief Process with a warning. This severity level may be assigned to data previously considered malicious.
- * @since_tizen 2.3
- */
-#define TCS_BC_LEVEL0 0
-
-/**
- * @brief Prompt the user before processing. Ask the user if they want the application to process the data.
- * @since_tizen 2.3
- */
-#define TCS_BC_LEVEL1 1
-/**
- * @brief Do not process the data.
- * @since_tizen 2.3
- */
-#define TCS_BC_LEVEL2 2
-
-/**
- * @brief SDo not process the data and prompt user for removal.\n
- * If the content is stored on the terminal, prompt the user for permission before removal.
- * @since_tizen 2.3
- */
-#define TCS_BC_LEVEL3 3
-/**
- * @brief Do not process the data and automatically remove if stored.
- * @since_tizen 2.3
- */
-#define TCS_BC_LEVEL4 4
-
-
-/*==================================================================================================
-                                            MACROS
-==================================================================================================*/
-
-/**
- * @brief Helper macro to get error module.
- * @since_tizen 2.3
- */
-#define TCS_ERRMODULE(e) (((e) >> 24) & 0xff)
-
-/**
- * @brief Helper macro to get error code.
- * @since_tizen 2.3
- */
-#define TCS_ERRCODE(e) ((e) & 0x00ffffff)
-
-/*==================================================================================================
-                                 STRUCTURES AND OTHER TYPEDEFS
-==================================================================================================*/
-
-/**
- * @brief Dummy data structure to avoid unexpected data type casting.
- * @since_tizen 2.3
- */
-struct TCSLibHandle_struct {int iDummy;};
-
-/**
- * @brief TCS library handle type.
- * @since_tizen 2.3
- */
-typedef struct TCSLibHandle_struct *TCSLIB_HANDLE;
-
-/**
- * @brief Invalid Content Screening library interface handle.
- * @since_tizen 2.3
- */
-#define INVALID_TCSLIB_HANDLE ((TCSLIB_HANDLE) 0)
-
-/**
- * @brief error code type.
- * @since_tizen 2.3
- */
-typedef unsigned long TCSErrorCode;
-
-/**
- * @brief Support 64 bits data / file locating
- * @since_tizen 2.3
- */
-typedef long long TCSOffset;
-
-/**
- * @brief The calling application specifies scan
- * parameters using the TCSScanParam structure. The information
- * contained in the structure provides the scan functions with:
- * - scan action type (iAction)
- * - the scan data type (iDataType)
- * - data pointer to the scan target (pPrivate)
- * - callback function to retrieve the data size in bytes (pfGetSize)
- * - callback function to resize the scan data (pfSetSize)
- * - callback function used by the scan functions to retrieve a
- *     block of scan data (pfRead)
- * - callback function used to write to the scan data (pfWrite)
- * - callback function for status/progress reporting (pfCallBack)
- * @since_tizen 2.3
- */
-typedef struct TCSScanParam_struct
-{
-    int iAction; /**< The scan-action specifies the type of scanning to be performed on supplied scan data. */
-
-    int iDataType; /**< The calling application specifies the data type/format of the data to be scanned using this variable. */
-
-    int iCompressFlag; /**< 0 - decompression disabled, 1 - decompression enabled. */
-
-    void *pPrivate; /**< Pointer (or handle) to an application object being scanned.
-                       The scan functions do not perform direct memory I/O using this data
-                       pointer/handle. The data pointer/handle is simply passed back to the caller when
-                       performing data read/write using caller specified I/O functions. Also the private
-                       data is passed back to the caller using the pfCallback function if it is set. */
-
-    TCSOffset (*pfGetSize)(void *pPrivate); /**< Used by the scan functions
-                                               to obtain the scan target data size (in bytes) from the caller.
-                                                                                                            
-                                               This is a synchronous API.
-                                               [in] pPrivate Pointer (or handle) to an application object being scanned.
-
-                                               return - Return Type (int)
-                                               The size (in bytes) of the data to be scanned.
-                                               */
-
-    int (*pfSetSize)(void *pPrivate, TCSOffset uSize); /**< Called by the scan
-                                                          functions to resize the scanned data to a given size (in bytes) during
-                                                          repair/clean. The resize function pointer needs to be set if the scan-action
-                                                          (iAction) is set to TCS_SA_SCANREPAIR.
-
-                                                          This is a synchronous API.
-
-                                                          @param[in] pPrivate Pointer (or handle) to an application object being scanned.
-                                                          @param[in] uSize The size (in bytes) of the repaired data.
-
-                                                          @return Return Type (int)
-                                                          The size (in bytes) of the application data.
-                                                          Not equal to the value of uSize indicating this call fails.
-                                                          */
-
-    unsigned int (*pfRead)(void *pPrivate, TCSOffset uOffset, void *pBuffer,
-                           unsigned int uCount); /**< Used for reading a specified
-                                                    amount of application data during scanning/analysis.
-                                                                                                                    
-                                                    This is a synchronous API.
-
-                                                    @param[in] pPrivate Pointer (or handle) to an application object being scanned.
-                                                    @param[in] uOffset Read from the offset in the application data.
-                                                    @param[out] pBuffer The buffer used to store the read data.
-                                                    @param[in] uCount The size (in bytes) of the data to be read.
-
-                                                    @return Return Type (int) 
-                                                    The size (in bytes) of the read data. 
-                                                    Not equal to the value of uCount indicating this call fails.
-                                                    */
-
-    unsigned int (*pfWrite)(void *pPrivate, TCSOffset uOffset, void const *pBuffer,
-                            unsigned int uCount); /**< The scan functions use the
-                                                     given function to write a specified amount of data to the scanned object as a part
-                                                     of the repair process. The function pointer needs to be set if the scan action
-                                                     (iAction) is set to TCS_SA_SCANREPAIR.
-                                                                                                                    
-                                                     This is a synchronous API.
-
-                                                     @param[in] pPrivate Pointer (or handle) to an application object being scanned.
-                                                     @param[in] uOffset Write data from the offset in the application data.
-                                                     @param[in] pBuffer The buffer hold the data to be written.
-                                                     @param[in] uCount The size (in bytes) of the data to be written.
-
-                                                     @return Return Type (int)
-                                                     The size (in bytes) of the written data.
-                                                     Not equal to the value of uCount indicating this call fails.
-                                                     */
-
-    int (*pfCallBack)(void *pPrivate, int iReason, void *pParam); /**< This callback
-                                                                     function is set by the caller to be notified to each detected malware while
-                                                                     scanning is in process. If specified (not NULL), the scan functions call the
-                                                                     specified function with the information (e.g. TCS_CB_DETECTED) for each malware
-                                                                     detected in the content/data during scanning.
-                                                                                                                                                        
-                                                                     This is a synchronous API.
-                                                                                                                                                    
-                                                                     @param[in] pPrivate Pointer (or handle) to an application object being scanned.
-                                                                     @param[in] iReason Reason of this callback.
-                                                                     @param[in] pParam The data for specified callback reason respectively.
-                                                                                                                                                    
-                                                                     @return Return Type (int) 
-                                                                     The scanning process continues if the callback function returns 0. If a negative
-                                                                     value (e.g. -1) is returned, the scanning process is aborted and control is
-                                                                     returned to the caller.
-                                                                     */
-} TCSScanParam;
-
-/**
- * @brief Detected malicious code/content information structure.
- * @since_tizen 2.3
- */
-typedef struct TCSDetected_struct
-{
-    struct TCSDetected_struct *pNext; /**< Pointer to next malware found, NULL if at the end of list. */
-
-    char const *pszName; /**< Detected malware name. */
-    char const *pszVariant; /**< Detected malware's variant name. pszName and
-                               pszVariant report detected malicious code/content and variant names. The maximum
-                               string length for both strings is 64 characters and each is terminated by a null
-                               character ('\\0') - the maximum buffer size for both strings is 65 bytes.
-
-                               pszVariant is set to an empty string ("\0") if the detected malware is not a
-                               variant. */
-
-    unsigned int uType; /**< Detected malware type. \see TCS_VTYPE_MALWARE */
-    unsigned int uAction; /**< Bit-field specifying severity, class and behavior level.
-
-                             Included in the TCSDetected structure is a bit-field variable containing malware
-                             severity flags and client application behavior levels.
-
-                             The scan functions set the TCS_SC_USER flag if the scanned object/data contains
-                             malware harmful to the user. TCS_SC_TERMINAL flag is set if the malware is
-                             harmful to the terminal itself. Both TCS_SC_USER and TCS_SC_TERMINAL flags are
-                             set if the malware is harmful to both the user and the terminal.
-
-                             The application behavior level specifies what to do with the data/object
-                             containing the detected malware.
-
-                             When multiple behavior level codes are found in a scanned data/object, the
-                             calling application would be expected to act with the highest behavior level.
-                             For example, if both TCS_BC_LEVEL0 and TCS_BC_LEVEL3 were reported, the application
-                             would need to take on TCS_BC_LEVEL3 action. */
-
-    char const *pszFileName; /**< Path of the infected file. The pszFileName field
-                                report, if not NULL, the complete file path of the infected content. If the scan
-                                functions have the ability to scan/analyze inside archives, then the path
-                                reported in pszFileName would be composed of multiple paths separated by the '|'
-                                character. The first path of the sequence is the real file system path of the
-                                currently scanned file, for TCSScanFile(), or empty for TCSScanData(). No
-                                assumption should be made on the path name separator used for the archive
-                                components of the path (the ones following the first). Only the first component,
-                                if not empty, is the real file path of the currently scanned content. */
-} TCSDetected;
-
-/**
- * @brief Detected malware information is returned to the caller in the TCSScanResult
- * structure provided by the caller. The TCSScanResult structure contains a pointer 
- * to a structure that contains scan result information and a pointer to a function 
- * used to remove the scan result resource. The memory used to hold the scan result 
- * is allocated by the scan functions and freed by calling the function pointed by the 
- * pfFreeResult pointer. The detected malware information includes the malware
- * information which had been reported via the callback (pfCallback) function during
- * scanning.
- *
- * @since_tizen 2.3
- * @code
- * int ScanAppData( ... )
- * {
- *     TCSScanResult scanResult;
- *     .
- *     .
- *     if (TCSScanData(hScanner, &scanParam, &scanResult) == 0)
- *     {
- *         .
- *         .
- *         scanResult.pfFreeResult( &scanResult );
- *     }
- *     .
- *     .
- * }
- * @endcode
- */
-typedef struct TCSScanResult_struct
-{
-    int iNumDetected; /**< Number of malware found. */
-    TCSDetected *pDList; /**< Detected malware list. */
-    void (*pfFreeResult)(struct TCSScanResult_struct *pResult); /**< Function pointer
-                                                                   used to free reported scan result.
-                                                                                                                                                
-                                                                   This is a synchronous API.
-                                                                   @param[in] pResult Pointer to data structure in which detected scan result
-                                                                   information is stored.
-
-                                                                   @return None
-                                                                   */
-} TCSScanResult;
-
-/*==================================================================================================
-                                     FUNCTION PROTOTYPES
-==================================================================================================*/
-
-/**
- * @brief Initializes and returns a Tizen Content Screening library interface handle.
- * @details A Content Screening library interface handle (or TCS library handle) is \n
- * obtained using the TCSLibraryOpen() function. The library handle is required for \n
- * subsequent TCS API calls. The TCSLibraryClose() function releases/closes the library \n
- * handle. Multiple library handles can be obtained using TCSLibraryOpen(). \n
- *  \n
- * This is a synchronous API.
- *
- * @since_tizen 2.3
- *
- * @return TCS library interface handle on success, otherwise #INVALID_TCSLIB_HANDLE.
- * @see TCSLibraryClose()
- */
-TCSLIB_HANDLE TCSLibraryOpen(void);
-
-/**
- * @brief Releases system resources associated with an TCS API library
- * @details handle returned by the TCSLibraryOpen() function. \n
- * \n
- * This is a synchronous API. \n
- *
- * @since_tizen 2.3
- *
- * @param[in] hLib TCS library handle returned by TCSLibraryOpen().
- *
- * @return 0 on success, otherwise -1.
- * @see TCSLibraryOpen()
- */
-int TCSLibraryClose(TCSLIB_HANDLE hLib);
-
-/**
- * @brief Returns the last error code associated with the given TCS library handle.
- * @details Once the TCS library handle has been successfully obtained from TCSLibraryOpen(), \n
- * TCSGetLastError() can be used to retrieve the last TCS error that occurred. All TCS \n
- * API functions return zero (= 0) or a valid object pointer if successful, and -1 \n
- * or a null object handle (e.g. INVALID_TCSSCAN_HANDLE) in case of an error. The \n
- * TCSGetLastError() function is used to retrieve error information when a TCS \n
- * function fails. \n
- * \n
- * This is a synchronous API. \n
- *
- * @since_tizen 2.3
- *
- * @param[in] hLib TCS library handle returned by TCSLibraryOpen().
- *
- * @return Last error code set by the TCS library. The TCSErrorCode data type is defined as a \n
- * 32-bit unsigned integer which contains both component and an error code (see \n
- * Figure about TCS Error Code Format). Two macros are available to extract the error \n
- * module and the error code. Call TCS_ERRMODULE(error-code) to get the error module, \n
- * and TCS_ERRCODE(error-code) to get the error code (where error-code is the value \n
- * returned by TCSGetLastError()). \n
- * \n
- * TCS library call sequence with a call to the TCSGetLastError() function: \n
- * @see TCSErrorCodes.h
- */
-TCSErrorCode TCSGetLastError(TCSLIB_HANDLE hLib);
-
-/**
- * @brief TCSScanData() is used to scan a data buffer for malware.
- * @details The caller specifies a scanner action, scan target data type, set I/O functions to access \n
- * the data, and an optional callback function for information retrieval. The result \n
- * of the data scanning is returned in a caller provided data structure. \n
- * \n
- * This is a synchronous API. \n
- *
- * @since_tizen 2.3
- * @param[in] hLib instance handle obtained from a call to the TCSLibraryOpen() \n
- * function.
- * @param[in] pParam Pointer to a structure containing data scan parameters.
- * @param[out] pResult Pointer to a structure containing data scan results.
- *
- * @return 0 on success, otherwise -1 and error code is set.
- * @see #TCSScanParam
- * @see #TCSScanResult
- * @see #TCSDetected
- * @see TCSScanFile()
- * @see TCSLibraryClose()
- */
-int TCSScanData(TCSLIB_HANDLE hLib, TCSScanParam *pParam, TCSScanResult *pResult);
-
-/**
- * @brief TCSScanFile() is used to scan a file for malware.
- * @details The caller specifies a file name, a scanner action, and scan target data type. The scan result is \n
- * returned in a caller provided data structure. \n
- * \n
- * This is a synchronous API. \n
- *
- * @since_tizen 2.3
- * @param[in] hLib instance handle obtained from a call to the  \n
- * TCSLibraryOpen() function.
- * @param[in] pszFileName Name of file to scan. The file name must include the \n
- * absolute path.
- * @param[in] iDataType Type of data contained in the file. This is used to \n
- * perform data type specific scans on files.
- * @param[in] iAction Type of scanning to perform on file.
- * @param[in] iCompressFlag Flag of decompression
- * @param[out] pResult Pointer to a structure containing data scan results.
- *
- * @return 0 on success, otherwise -1 and error code is set.
- * @see #TCSScanResult
- * @see #TCSDetected
- * @see TCSScanData()
- * @see TCSLibraryClose()
- */
-int TCSScanFile(TCSLIB_HANDLE hLib, char const *pszFileName, int iDataType, int iAction, int iCompressFlag, TCSScanResult *pResult);
-
-/**
- * @}
- */
-
-
-#ifdef __cplusplus
-}
-#endif 
-
-#endif  /* TCSIMPL_H */
diff --git a/src/include/csr/TWPImpl.h b/src/include/csr/TWPImpl.h
deleted file mode 100644 (file)
index d04dd42..0000000
+++ /dev/null
@@ -1,841 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef TWPIMPL_H
-#define TWPIMPL_H
-
-
-#ifdef __cplusplus 
-extern "C" {
-#endif
-
-/**
- * @addtogroup CAPI_CSRFW_TWP_MODULE
- * @{
- */
-
-
-/**
- * @brief Size unit
- * @since_tizen 2.3
- */
-typedef long unsigned int TWPMallocSizeT;
-
-/**
- * @brief Dummy data structure to avoid unexpected data type casting.
- * @since_tizen 2.3
- */
-struct TWPLibHandle_struct {int iDummy;};
-
-/**
- * @brief TWP library handle type.
- * @since_tizen 2.3
- */
-typedef struct TWPLibHandle_struct *TWPLIB_HANDLE;
-
-/**
- * @brief SDK version.
- * @since_tizen 2.3
- */
-#define TWPAPI_VERSION 1
-
-/**
- * @brief Configure version.
- * @since_tizen 2.3
- */
-#define TWPCONFIG_VERSION 1
-
-/**
- * @brief Request version.
- * @since_tizen 2.3
- */
-#define TWPREQUEST_VERSION 1
-
-/**
- * @brief Invalid web protection library interface handle.
- * @since_tizen 2.3
- */
-#define INVALID_TWPLIB_HANDLE ((TWPLIB_HANDLE) 0)
-       
-/**
- * @brief Result code used by TWP_RESULT
- * @since_tizen 2.3
- */
-typedef enum
-{
-       TWP_SUCCESS = 0, /**< Success */
-       TWP_ERROR = 1, /**< Generic error */
-       TWP_NOMEM = 2,  /**< Function failed to allocate required memory */
-       TWP_INVALID_HANDLE = 3, /**< The given handle is invalid */
-       TWP_INVALID_PARAMETER = 4, /**< The given parameter other than handle is invalid */
-       TWP_INVALID_VERSION = 5, /**< The version of the structure is incorrect */
-       TWP_INVALID_RESPONSE = 6, /**< The server response is invalid */
-       TWP_NO_DATA = 7, /**< Requested data is not available.  This error code is
-                         usually returned when necessity data is not passed */
-       TWP_NOT_IMPLEMENTED = 500 /**< Tizen Web Protection APIs are not implemented on system
-                               Or the APIs are called while CSR framework fails to load */
-} TWP_RESULT;
-
-/**
- * @brief Web site category definitions. \n
- * See "Categories definitions" section in "Tizen Web Protection API Specification" \n
- * docoument for more detail.
- * @since_tizen 2.3
- */
-typedef enum 
-{
-    TWP_Artcultureheritage, /**< Artculture and heritage */
-    TWP_Alcohol, /**< Alcohol */
-    TWP_Anonymizers, /**< Anonymizers */
-    TWP_Anonymizingutilities, /**< Anonymizingutilities */
-    TWP_Business, /**< Business */
-    TWP_Chat, /**< Chat */
-    TWP_Publicinformation, /**< Publicinformation */
-    TWP_Potentialcriminalactivities, /**< Potentialcriminalactivities */
-    TWP_Drugs, /**< Drugs */
-    TWP_Educationreference, /**< Educationreference */
-    TWP_Entertainment, /**< Entertainment */
-    TWP_Extreme, /**< Extreme */
-    TWP_Financebanking, /**< Finance banking */
-    TWP_Gambling, /**< Gambling */
-    TWP_Games, /**< Games */
-    TWP_Governmentmilitary, /**< Governmentmilitary */
-    TWP_Potentialhackingcomputercrime, /**< Potential hacking and computer crime */
-    TWP_Health, /**< Health */
-    TWP_Humorcomics, /**< Humorcomics */
-    TWP_Discrimination, /**< Discrimination */
-    TWP_Instantmessaging, /**< Instantmessaging */
-    TWP_Stocktrading, /**< Stocktrading */
-    TWP_Internetradiotv, /**< Internet radio and tv */
-    TWP_Jobsearch, /**< Jobsearch */
-    TWP_Informationsecurity, /**< Information security */
-    TWP_E_RESERVED_1, /**< Reserved */
-    TWP_Mobilephone, /**< Mobilephone */
-    TWP_Mediadownloads, /**< Media downloads */
-    TWP_Malicioussites, /**< Maliciouss ites */
-    TWP_E_RESERVED_2, /**< REserved */
-    TWP_Nudity, /**< Nudity */
-    TWP_Nonprofitadvocacyngo, /**< Non profit advocacy ngo */
-    TWP_Generalnews, /**< General news */
-    TWP_Onlineshopping, /**< Online shopping */
-    TWP_Provocativeattire, /**< Provocative attire */
-    TWP_P2pfilesharing, /**< P2p file sharing */
-    TWP_Politicsopinion, /**< Politics opinion */
-    TWP_Personalpages, /**< Personal pages */
-    TWP_Portalsites, /**< Portal sites */
-    TWP_Remoteaccess, /**< Remote access */
-    TWP_Religionideology, /**< Religionideology */
-    TWP_Resourcesharing, /**< Resource sharing */
-    TWP_Searchengines, /**< Search engines */
-    TWP_Sports, /**< Sports */
-    TWP_Streamingmedia, /**< Streaming media */
-    TWP_Sharewarefreeware, /**< Shareware and freeware */
-    TWP_Pornography, /**< Pornography */
-    TWP_Spywareadwarekeyloggers, /**< Spyware and adware and keyloggers */
-    TWP_Tobacco, /**< Tobacco */
-    TWP_Travel, /**< Travel */
-    TWP_Violence, /**< Violence */
-    TWP_Webads, /**< Webads */
-    TWP_Weapons, /**< Weapons */
-    TWP_Webmail, /**< Webmail */
-    TWP_Webphone, /**< Webphone */
-    TWP_Auctionsclassifieds, /**< Auctions and classifieds */
-    TWP_Forumbulletinboards, /**< Forum and bulletinboards */
-    TWP_Profanity, /**< Profanity */
-    TWP_Schoolcheatinginformation, /**< Schoolcheating information */
-    TWP_Sexualmaterials, /**< Sexual materials */
-    TWP_Gruesomecontent, /**< Gruesomecontent */
-    TWP_Visualsearchengine, /**< Visual search engine */
-    TWP_Technicalbusinessforums, /**< Technical business forums */
-    TWP_Gamblingrelated, /**< Gambling related */
-    TWP_Messaging, /**< Messaging */
-    TWP_Gamecartoonviolence, /**< Game and cartoon violence */
-    TWP_Phishing, /**< Phishing */
-    TWP_Personalnetworkstorage, /**< Personal network storage */
-    TWP_Spamurls, /**< Spamurls */
-    TWP_Interactivewebapplications, /**< Interactive webapplications */
-    TWP_Fashionbeauty, /**< Fashionbeauty */
-    TWP_Softwarehardware, /**< Softwarehardware */
-    TWP_Potentialillegalsoftware, /**< Potentialillegalsoftware */
-    TWP_Contentserver, /**< Contentserver */
-    TWP_Internetservices, /**< Internetservices */
-    TWP_Mediasharing, /**< Mediasharing */
-    TWP_Incidentalnudity, /**< Incidentalnudity */
-    TWP_Marketingmerchandising, /**< Marketing merchandising */
-    TWP_Parkeddomain, /**< Parkeddomain */
-    TWP_Pharmacy, /**< Pharmacy */
-    TWP_Restaurants, /**< Restaurants */
-    TWP_Realestate, /**< Realestate */
-    TWP_Recreationhobbies, /**< Recreation hobbies */
-    TWP_Blogswiki, /**< Blogs wiki */
-    TWP_Digitalpostcards, /**< Digital postcards */
-    TWP_Historicalrevisionism, /**< Historical revisionism */
-    TWP_Technicalinformation, /**< Technical information */
-    TWP_Datingpersonals, /**< Dating personals */
-    TWP_Motorvehicles, /**< Motor vehicles */
-    TWP_Professionalnetworking, /**< Professional networking */
-    TWP_Socialnetworking, /**< Socialnetworking */
-    TWP_Texttranslators, /**< Text translators */
-    TWP_Webmeetings, /**< Web meetings */
-    TWP_Forkids, /**< For kids */
-    TWP_E_RESERVED_3, /**< Reserved */
-    TWP_Moderated, /**< Moderated */
-    TWP_Textspokenonly, /**< Text spoken only */
-    TWP_Controversialopinions, /**< Controversial opinions */
-    TWP_Residentialipaddresses, /**< Residential ip addresses */
-    TWP_Browserexploits, /**< Browser exploits */
-    TWP_Consumerprotection, /**< Consumer protection */
-    TWP_Illegaluk, /**< Illegal site in uk */
-    TWP_Majorglobalreligions, /**< Major global religions */
-    TWP_Maliciousdownloads, /**< Malicious downloads */
-    TWP_Potentiallyunwantedprograms, /**< Potentially unwanted programs */
-
-    TWP_LastCategoryPlaceholder = 128, /**< LastCategory Placeholder */
-    TWP_OverallPhishing = 129, /**< Overall Phishing site*/
-    TWP_OverallRiskHigh = 130, /**< Overall RiskHigh */
-    TWP_OverallRiskMedium = 131, /**< Overall RiskMedium */
-    TWP_OverallRiskMinimal = 132, /**< Overall RiskMinimal */
-    TWP_OverallRiskUnverified = 137, /**< Overall risk unverified */
-    TWP_LastAttributePlaceholder = 160, /**< LastAttribute Placeholder */
-} TWPCategories;
-
-/**
- * @brief Risk level
- * @since_tizen 2.3
- */
-typedef enum
-{
-       TWP_Minimal, /**< Risk minimal */
-       TWP_Unverified, /**< Risk unverified  */
-       TWP_Medium, /**< Risk medium */
-       TWP_High, /**< Risk High */
-} TWPRiskLevel;
-
-/**
- * @brief Score range
- * @since_tizen 2.3
- */
-typedef enum 
-{
-       TWP_MinimalLow = 0, /**< Lowest score coresponding to the minimal level */
-       TWP_MinimalHigh = 14, /**< Highest score coresponding to the minimal level */
-       TWP_UnverifiedLow = 15, /**< Lowest score coresponding to the unverified level */
-       TWP_UnverifiedHigh = 29, /**< Highest score coresponding to the unverified level */
-       TWP_MediumLow = 30, /**< Lowest score coresponding to the medium level */
-       TWP_MediumHigh = 49, /**< Highest score coresponding to the medium level */
-       TWP_HighLow= 50, /**< Lowest score coresponding to the high level */
-       TWP_HighHigh = 127 /**< Highest score coresponding to the high level */
-} TWPScoreRange;
-
-/**
- * @brief HTTP submit method
- * @since_tizen 2.3
- */
-typedef enum
-{
-       TWPPOST, /**< HTTP Post method */
-} TWPSubmitMethod;
-       
-/* forward declaration */
-struct TWPRequest;     
-
-/**
- * @brief typedef declaration of the pointer to TWPConfiguration structure
- * @since_tizen 2.3
- */
-typedef struct TWPConfiguration *TWPConfigurationHandle;
-
-/**
- * @brief typedef declaration of the pointer to TWPResponse structure
- * @since_tizen 2.3
- */
-typedef struct TWPResponse*    TWPResponseHandle;
-
-/**
- * @brief typedef declaration of the pointer to TWPUrlRating structure
- * @since_tizen 2.3
- */
-typedef struct TWPUrlRating *TWPUrlRatingHandle;
-
-/**
- * @brief typedef declaration of the pointer to TWPPolicy structure
- * @since_tizen 2.3
- */
-typedef struct TWPPolicy *TWPPolicyHandle;
-
-/**
- * @brief typedef declaration of the pointer to memory allocation function
- *
- * @since_tizen 2.3
- * @param[in] size allocation size
- * @return pointer to the allocated memory. NULL if failed to allocate
- * @see #TWPAPIInit
- */
-typedef void *(*TWPFnMemAlloc)(TWPMallocSizeT size);
-
-/**
- * @brief typedef declaration of the pointer to memory release function
- *
- * @since_tizen 2.3
- * @param[in] address an address of memroy region which is returned by void *(*TWPFnMemAlloc)(TWPMallocSizeT size);
- * @see #TWPAPIInit
- */
-typedef void (*TWPFnMemFree)(void *address);
-
-/**
- * @brief typedef declaration of the pointer to random number generation function
- *
- * @since_tizen 2.3
- * @return random number in the range of 'long' type size
- * @see #TWPConfiguration
- */
-typedef long (*TWPFnRandom)(void);
-
-/**
- * @brief typedef declaration of the pointer to the function which sets request URL
- *
- * @since_tizen 2.3
- * @param[in] request Pointer to struct TWPRequest which was passed to TWPLookupUrl()
- * @param[in] url Url to be set
- * @param[in] length The string length of the Url
- * @return #TWP_RESULT
- * @retval #TWP_SUCCESS Url is set successfuly
- * @see #TWPRequest
- * @see TWPLookupUrl()
- */
-typedef TWP_RESULT (*TWPFnRequestSetUrl)(struct TWPRequest *request, const char *url,
-                                         unsigned int length);
-
-/**
- * @brief typedef declaration of the function of request method
- *
- * @since_tizen 2.3
- * @param[in] request Pointer to struct TWPRequest which was passed to TWPLookupUrl()
- * @param[in] only WP_POST is passed
- * @return #TWP_RESULT
- * @retval #TWP_SUCCESS Method was successfuly set
- * @see #TWPRequest 
- * @see TWPLookupUrl()
- */
-typedef TWP_RESULT (*TWPFnRequestSetMethod)(struct TWPRequest *request, TWPSubmitMethod method);
-
-/**
- * @brief typedef declaration of the function to send request
- *
- * @since_tizen 2.3
- * @param[in] request Pointer to struct TWPRequest which was passed to TWPLookupUrl()
- * @param[in] response TWPResponseHandle. Set NULL for synchronous request.\n
- *            uninitialized response object for asynchronous request            
- * @param[in] data request body to send to the server
- * @param[in] length the lengh of the reqest body
- * @return #TWP_RESULT 
- * @retval #TWP_SUCCESS if request is successfully sent
- * @see #TWPRequest
- * @see TWPLookupUrl()
- */
-typedef TWP_RESULT (*TWPFnRequestSend)(struct TWPRequest *request, TWPResponseHandle response,
-                                       const void *data, unsigned int length);
-
-/**
- * @brief typedef declaration of the function to receive request
- *
- * @since_tizen 2.3
- * @param[in] request Pointer to struct TWPRequest which was passed to TWPLookupUrl()
- * @param[in] buffer Buffer to store response 
- * @param[in] buffer_length The length of the buffer in byte 
- * @param[in] length number of bytes that is acutualy stored in the buffer
- * @return #TWP_RESULT
- * @retval #TWP_SUCCESS if response is successfully stored in the buffer
- * @see #TWPRequest
- * @see TWPLookupUrl()
- */
-typedef TWP_RESULT (*TWPFnRequestReceive)(struct TWPRequest *request, void *buffer,
-                                          unsigned int buffer_length, unsigned int *length);   
-
-/**
- * @brief Initialize data requested by SDK initialization
- * @since_tizen 2.3
- */
-typedef struct TWPAPIInit
-{
-    int api_version; /**< Version of this structure */
-    TWPFnMemAlloc memallocfunc; /**< Pointer to malloc function */
-    TWPFnMemFree memfreefunc; /**< Pointer to free function */
-} TWPAPIInit;
-
-/**
- * @brief Configuration which enable caller to customize the SDK
- * @since_tizen 2.3
- */
-typedef struct TWPConfiguration
-{
-       int config_version; /**< Configuration version */
-       const char *client_id; /**< Client id for cloud to qualify */
-       const char *client_key; /**< Corresponding key for specific client for validation from cloud */
-       const char *host; /**< Host name for cloud where SDK send request to, set to NULL for SDK to use default settings in plug-in */
-       int     secure_connection; /**< 1 - use secured connection (HTTPS), 0 - not secured connection. */
-       int     skip_dla; /**< 1 - disable DLA lookup, 0 - enable DLA lookup */
-       int     obfuscate_request; /**< 1 - obfuscate request data, 0 - do not obfuscate request data */
-       TWPFnRandom randomfunc; /**< Caller customized random function */
-} TWPConfiguration;
-
-/**
- * @brief Request for SDK to check URL against cloud database
- * @since_tizen 2.3
- */
-typedef struct TWPRequest
-{
-       int request_version; /**< Request version */
-       TWPFnRequestSetUrl seturlfunc; /**< Callback for SDK to set URL from SDK */
-       TWPFnRequestSetMethod setmethodfunc; /**< Callback for SDK to set HTTP request method */
-       TWPFnRequestSend sendfunc; /**< Callback for SDK to send HTTP request */
-       TWPFnRequestReceive receivefunc; /**< Callback for SDK to receive HTTP response, if caller set it to be NULL,
-                                        SDK will assume the HTTP request will be handled in a-synchronized manner */
-} TWPRequest;
-       
-/**
- * @brief Initialize SDK.
- * @details This is a synchronized API
- *
- * @since_tizen 2.3
- * @param[in] pApiInit API initialization data structure.
- *
- * @return TWP library interface handle on success, otherwise #INVALID_TWPLIB_HANDLE.
- * @see TWPLibraryClose()
- */
-TWPLIB_HANDLE TWPInitLibrary(TWPAPIInit *pApiInit);
-
-/**
- * @brief Uninitialize SDK.
- * @details This is a synchronized API
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @see TWPLibraryOpen()
- */
-void TWPUninitLibrary(TWPLIB_HANDLE hLib);
-
-/**
- * @brief Create TWP configuration to customize SDK.
- * @details This is a synchronized API.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen(). 
- * @param[in] pConfigure caller configurations
- * @param[out] phConfigure created configuration for SDK
- *
- * @return #TWP_RESULT
- * @retval #TWP_SUCCESS - on success.
- * @retval #TWP_INVALID_PARAMETER - if any of the following errors occur:
- *           - pConfigure is NULL \n
- *           - phConfigure is NULL \n
- *           - TWPConfigration.randomfunc is NULL and TWPConfiguration.obfuscate_request is not NULL
- * @retval #TWP_INVALID_VERSION - TWPConfiguration.config_version is not TWP_CONFIG_VERSION
- * @retval #TWP_NOMEM - The function failed to allocate memory required to complete initialization of the configuration object
- * @see #TWPConfiguration
- * @see TWPConfigurationDestroy()
- */
-TWP_RESULT TWPConfigurationCreate(TWPLIB_HANDLE hLib, TWPConfiguration *pConfigure, TWPConfigurationHandle *phConfigure);
-
-/**
- * @brief Release the configuration resources allocated by TWPConfigurationCreate().
- * @details This is a synchronized API.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen(). 
- * @param[in] phConfigure configuration to be destroyed
- * @return #TWP_RESULT
- * @retval #TWP_SUCCESS - on success. 
- * @retval #TWP_INVALID_HANDLE - the value that is pointed to by phConfigure is invalid
- * @see TWPConfigurationCreate()
- */
-TWP_RESULT TWPConfigurationDestroy(TWPLIB_HANDLE hLib, TWPConfigurationHandle *phConfigure);
-
-/**
- * @brief Main function for caller to check URL reputation against the cloud database.
- * @details This can be a synchronized API or a-synchronized API depends on the configuration from caller. \n
- * \n
- * Synchronous mode \n
- *      In this synchronous operation mode, the function invokes TWPRequest::sendfunc and \n
- *      TWPRequest::receivefunc, one right after the other, expecting the entire HTTP \n
- *      transaction to be completed between the calls. Upon successful completion, the \n
- *      phResponse will point to a valid response handle that can be used to analyze results. \n
- * \n
- * Asynchronous mode \n
- *      In the asynchronous mode, the function invokes TWPRequest::sendfunc and returns \n
- *      immediately with TWP_SUCCESS. Upon completion, phResponse is NULL. The application \n
- *      is supposed to complete the HTTP transaction while calling TWPResponseWrite as \n
- *      response data becomes available. When all data was read, TWPResponseWrite must \n
- *      be called again with zero data length to signal the end transaction. \n
- * \n
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen(). 
- * @param[in] hConfigure Configuration of caller
- * @param[in] pRequest Request data structure for SDK to check with cloud
- * @param[in] iRedirUrl 1 indicating instruct the cloud server to provide a landing page \n
- *            URL to which blocked URLs can be redirected. 
- * @param[in] ppUrls An array of 7 bit ASCII character strings representing URLs to obtain \n
- *            the rating for. \n
- * \n
- *            Note: All URLs have to be normalized before submission (see RFC 3986) and \n
- *            pynicoded if required. 
- * @param[in] uCount Length of the ppUrls array.
- * @param[out] phResponse For synchronous requests, a pointer to the location where the \n
- *             response object handle will be stored upon completion. It can be NULL for \n
- *             asynchronous requests.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE - hConfigure is not a valid configuraiton handle
- * @retval #TWP_INVALID_PARAMETER - if any of the following errors occur:
- *           - ppUrls is NULL \n
- *           - any string in the ppUrls array is NULL or has zero length \n
- *           - uCount is 0 \n
- *           - pRequest is NULL \n
- *           - TWPRequest.receivefunc is not NULL and TWPRequest.phResponse is NULL (if TWPRequest.receivefunc is NULL, hResponse can be NULL)
- * @retval #TWP_INVALID_VERSION - TWPConfiguration.config_version is not TWP_CONFIG_VERSION
- * @retval #TWP_NOMEM - The function failed to allocate memory required to complete initialization of the configuration object
- * @retval #TWP_SUCCESS - on success. 
- * @retval other - Any integer value other than TWP_SUCCESS is returned by TWPRequest::setmethodfunc, TWPRequest::seturlfunc and TWPRequest::sendfunc functions
- * @see #TWPRequest
- * @see TWPLookupUrls()
- * @see TWPResponseDestory()
- */
-TWP_RESULT TWPLookupUrls(TWPLIB_HANDLE hLib, TWPConfigurationHandle hConfigure, TWPRequest *pRequest,
-                         int iRedirUrl, const char **ppUrls, unsigned int uCount, TWPResponseHandle *phResponse);
-
-/**
- * @brief In asynchronous mode, caller will call this API to write received HTTP response data to SDK.
- * @details Writing with zero data length will be taken as end of HTTP transaction for SDK. \n
- * This is a synchronized API.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen(). 
- * @param[in] hResponse Response handle for SDK to keep track on HTTP transaction.
- * @param[in] pData Received HTTP response data chunk.
- * @param[in] uLength Length of the HTTP response data.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE - hResponse is not a valid handle
- * @retval #TWP_ERROR - Internal error occured
- * @retval #TWP_INVALID_RESPONSE - Server response is invalid. This can usually happen when the entire response \n
- *                                was not passed to the SDK
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPLookupUrls()
- * @see TWPResponseDestory()
- */
-TWP_RESULT TWPResponseWrite(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, const void *pData, unsigned uLength);
-
-/**
- * @brief Get web site rating by its index in URL list in the response which comply to the URL list order passed by caller in TWPLookupUrls().
- * @details This is a synchronized API.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen(). 
- * @param[in] hResponse Response handle created based on cloud response.
- * @param[in] uIndex Index of the web site in request list.
- * @param[out] phRating Rating of the specified web site.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE - hResponse is not a valid handle
- * @retval #TWP_INVALID_PARAMETER - phRating is NULL 
- * @retval #TWP_NO_DATA - Index is out of bound
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPLookupUrls()
- * @see TWPResponseDestory()
- */
-TWP_RESULT TWPResponseGetUrlRatingByIndex(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, unsigned int uIndex,
-                                          TWPUrlRatingHandle *phRating);
-
-/**
- * @brief Get web site rating by its URL string.
- * @details This is a synchronized API.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen(). 
- * @param[in] hResponse Response handle created based on cloud response.
- * @param[in] pUrl URL string
- * @param[in] uUrlLength URL string length
- * @param[out] phRating Rating of the specified web site
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE - hResponse is not a valid handle
- * @retval #TWP_INVALID_PARAMETER - phRating is NULL 
- * @retval #TWP_NO_DATA - pUrl does not corespond to an existing URL rating object
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPLookupUrls()
- * @see TWPResponseDestory()
- */
-TWP_RESULT TWPResponseGetUrlRatingByUrl(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, const char *pUrl,
-                                        unsigned int uUrlLength, TWPUrlRatingHandle *phRating);
-
-/**
- * @brief Get the redirection URL for blocked URL to display to user.
- * @details Blocking pages can be used by application that want to block users \n
- * from navigating to a URL that violates one of the defined policies. \n
- * The returned string must be deallocated by the application using \n
- * TWPAPIInit::TWPFnMemFree function. \n
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hResponse Response handle created based on cloud response.
- * @param[in] hRating Rating handle resolved from cloud response.
- * @param[in] hPolicy Policy handle created by caller.
- * @param[out] ppUrl Redirection URL.
- * @param[out] puLength Length of redirection URL
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE - One of hResponse, hRating and hPolicy is not a valid handle
- * @retval #TWP_INVALID_PARAMETER - ppUrl is NULL 
- * @retval #TWP_NO_DATA - The URL rating does not violate the policy (if TWPPolicyValidate() called with HPolicy and hRating would indicate no violations)
- * @retval #TWP_ERROR - An internal error occurs
- * @retval #TWP_NOMEM - Memory for the URL can not be allocated
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPLookupUrls()
- * @see TWPResponseDestory()
- */
-TWP_RESULT TWPResponseGetRedirUrlFor(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, TWPUrlRatingHandle hRating,
-                                     TWPPolicyHandle hPolicy, char **ppUrl, unsigned int *puLength);
-
-/**
- * @brief Get the rating count of specified response.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hResponse Response handle created based on cloud response.
- * @param[out] puCount Rating count.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE - hResponse is not valid
- * @retval #TWP_INVALID_PARAMETER - puCount is NULL 
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPLookupUrls()
- * @see TWPResponseDestory()
- */
-TWP_RESULT TWPResponseGetUrlRatingsCount(TWPLIB_HANDLE hLib, TWPResponseHandle hResponse, unsigned int *puCount);      
-
-/**
- * @brief Release resource for response handle.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] phResponse Response handle created based on cloud response.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE - phResponse is not valid
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPLookupUrls()
- */
-TWP_RESULT TWPResponseDestroy(TWPLIB_HANDLE hLib, TWPResponseHandle *phResponse);
-
-/**
- * @brief Create the policy (set of web site categories) caller want to check.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hCfg configuration handle
- * @param[in] pCategories Web site category list
- * @param[in] uCount Category list length.
- * @param[out] phPolicy Policy handle.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_PARAMETER - if one of the following errors occur:
- *                                  - uCount is 0
- *                                  - phPolicy is NULL 
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPPolicyDestroy()
- */
-TWP_RESULT TWPPolicyCreate(TWPLIB_HANDLE hLib, TWPConfigurationHandle hCfg, TWPCategories *pCategories, unsigned int uCount, TWPPolicyHandle *phPolicy);
-
-/**
- * @brief Compare the categories assigned by security vendor to the URL represented 
- * by hRating with the categories assigned to the policy handle.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hPolicy Polcy handle
- * @param[in] hRating Rating for specific URL
- * @param[out] piViolated non-zero if intersection found between the policy and URL rating categories.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if hPolicy or hRating does not correspond to a valid handle
- * @retval #TWP_INVALID_PARAMETER - piViolated is NULL
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPResponseGetUrlRatingByUrl()
- * @see TWPResponseGetUrlRatingByIndex()
- */
-TWP_RESULT TWPPolicyValidate(TWPLIB_HANDLE hLib, TWPPolicyHandle hPolicy, TWPUrlRatingHandle hRating, int *piViolated);
-
-/**
- * @brief Retrieves all categories common between the policy and URL rating.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hPolicy Policy handle.
- * @param[in] hRating URL rating handle.
- * @param[out] ppViolated An array of all common categories. This array is allocated by using \n
- *             TWPAPIInit::memallocfunc and has to be deallocated by the caller.
- * @param[out] puLength Length of violation array.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if hPolicy or hRating does not correspond to a valid handle
- * @retval #TWP_INVALID_PARAMETER - piViolated or piLength is NULL
- * @retval #TWP_NOMEM - ppViolated can not be allocated
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPResponseGetUrlRatingByUrl()
- * @see TWPResponseGetUrlRatingByIndex()
- */
-TWP_RESULT TWPPolicyGetViolations(TWPLIB_HANDLE hLib, TWPPolicyHandle hPolicy, TWPUrlRatingHandle hRating,
-                                  TWPCategories **ppViolated, unsigned *puLength);
-
-/**
- * @brief Release resource for policy handle.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] phPolicy Pointer to policy handle.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if phPolicy does not correspond to a valid handle
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPPolicyCreate()
- */
-TWP_RESULT TWPPolicyDestroy(TWPLIB_HANDLE hLib, TWPPolicyHandle *phPolicy);
-
-/**
- * @brief Get score from URL rating data structure which is assigned by security vendor.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hRating Rating handle.
- * @param[out] piScore URL score.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if hRating does not correspond to a valid handle
- * @retval #TWP_INVALID_PARAMETER - piScore is NULL
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPResponseGetUrlRatingByUrl()
- * @see TWPResponseGetUrlRatingByIndex()
- */
-TWP_RESULT TWPUrlRatingGetScore(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, int *piScore);
-
-/**
- * @brief Get corresponding URL from rating handle.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hRating Rating handle and the handle should have been obtained using TWPResponseGetUrlRatingByUrl() \n 
- * TWPResponseGetUrlRatingByIndex()
- * @param[out] ppUrl A pointer to a NULL terminated string representing \n
- *             the URL. The string is valid as long as the URL rating \n
- *             handle is valid. \n
- * @param[out] puLength An optional pointer to the length of URL string.
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if hRating does not correspond to a valid handle
- * @retval #TWP_INVALID_PARAMETER - ppUrl is NULL
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPResponseGetUrlRatingByUrl()
- * @see TWPResponseGetUrlRatingByIndex()
- */
-TWP_RESULT TWPUrlRatingGetUrl(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, char **ppUrl,
-                              unsigned int *puLength);
-
-/**
- * @brief Get DLA (Deep Link Analysis) URL
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hRating Rating handle and the handle should have been obtained using TWPResponseGetUrlRatingByUrl() \n 
- * TWPResponseGetUrlRatingByIndex()
- * @param[out] ppDlaUrl A ponit to a NULL terminated string representing \n
- *             the DLA URL. This string is valid as long as the URL rating \n
- *             handle is valid. \n
- * @param[out] puLength Length of DLA URL string.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if hRating does not correspond to a valid handle
- * @retval #TWP_INVALID_PARAMETER - ppDlaUrl is NULL
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPResponseGetUrlRatingByUrl()
- * @see TWPResponseGetUrlRatingByIndex()
- */
-TWP_RESULT TWPUrlRatingGetDLAUrl(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, char **ppDlaUrl,
-                                 unsigned int *puLength);
-
-/**
- * @brief Determine whether the URL rating object has the specified category.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hRating Rating handle and the handle should have been obtained using TWPResponseGetUrlRatingByUrl() \n 
- * TWPResponseGetUrlRatingByIndex()
- * @param[in] Category Category enum value.
- * @param[out] piPresent Non-zero value indicating exists.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if hRating does not correspond to a valid handle
- * @retval #TWP_INVALID_PARAMETER - piPresent is NULL
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPResponseGetUrlRatingByUrl()
- * @see TWPResponseGetUrlRatingByIndex()
- */
-TWP_RESULT TWPUrlRatingHasCategory(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, TWPCategories Category,
-                                   int *piPresent);
-
-/**
- * @brief Retrives categories assigned by security vendor for the rated URL.
- *
- * @since_tizen 2.3
- * @param[in] hLib TWP library handle returned by TWPLibraryOpen().
- * @param[in] hRating Rating handle and the handle should have been obtained using TWPResponseGetUrlRatingByUrl() \n 
- * TWPResponseGetUrlRatingByIndex()
- * @param[out] ppCategories The pointer to a variable that contains the address \n
- *             of the category list. \n
- * @param[out] puLength Length of category list.
- *
- * @return #TWP_RESULT
- * @retval #TWP_INVALID_HANDLE if hPolicy or hRating does not correspond to a valid handle
- * @retval #TWP_INVALID_PARAMETER - piViolated or piLength is NULL
- * @retval #TWP_NOMEM - ppViolated can not be allocated
- * @retval #TWP_SUCCESS - on success. 
- * @see TWPResponseGetUrlRatingByUrl()
- * @see TWPResponseGetUrlRatingByIndex()
- */
-TWP_RESULT TWPUrlRatingGetCategories(TWPLIB_HANDLE hLib, TWPUrlRatingHandle hRating, TWPCategories **ppCategories,
-                                     unsigned int *puLength);
-       
-#ifdef __cplusplus
-}
-#endif
-#endif
-
-/**
- @}
- */
diff --git a/src/include/csr/api.h b/src/include/csr/api.h
new file mode 100644 (file)
index 0000000..da9a3da
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        api.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#ifndef __CSR_API_H_
+#define __CSR_API_H_
+
+#include "csr/error.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int csr_file_scan(const char *filepath);
+
+int csr_file_judge(const char *filepath, int judge);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/include/csr/error.h b/src/include/csr/error.h
new file mode 100644 (file)
index 0000000..68e4d6e
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        error.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       csr error codes
+ */
+#ifndef __TIZEN_CORE_CSR_ERROR_H_
+#define __TIZEN_CORE_CSR_ERROR_H_
+
+#include <tizen.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define TIZEN_ERROR_CSR 0x60 // 0110 0000
+
+typedef enum {
+       CSR_ERROR_NONE              = TIZEN_ERROR_NONE,              /**< Success */
+       CSR_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER, /**< Invalid function parameter */
+       CSR_ERROR_OUT_OF_MEMORY     = TIZEN_ERROR_OUT_OF_MEMORY,     /**< Out of memory */
+       CSR_ERROR_PERMISSION_DEINED = TIZEN_ERROR_PERMISSION_DENIED, /**< Permission denied */
+       CSR_ERROR_SOCKET            = TIZEN_ERROR_CSR | 0x01,        /**< Socket error between client and csr-server */
+       CSR_ERROR_BAD_REQUEST       = TIZEN_ERROR_CSR | 0x02,        /**< Invalid request from client */
+       CSR_ERROR_BAD_RESPONSE      = TIZEN_ERROR_CSR | 0x03,        /**< Invalid response from csr-server */
+       CSR_ERROR_SEND_FAILED       = TIZEN_ERROR_CSR | 0x04,        /**< Transmitting request failed */
+       CSR_ERROR_RECV_FAILED       = TIZEN_ERROR_CSR | 0x05,        /**< Receiving response failed */
+       CSR_ERROR_SERVER            = TIZEN_ERROR_CSR | 0x06,        /**< csr-server has been failed for some reason */
+       CSR_ERROR_UNKNOWN           = TIZEN_ERROR_CSR | 0xFF         /**< Unknown reason */
+} csr_error_e;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/systemd/CMakeLists.txt b/systemd/CMakeLists.txt
new file mode 100644 (file)
index 0000000..76d6dd3
--- /dev/null
@@ -0,0 +1,10 @@
+CONFIGURE_FILE(${SERVICE_NAME}.service.in ${SERVICE_NAME}.service @ONLY)
+CONFIGURE_FILE(${SERVICE_NAME}.socket.in ${SERVICE_NAME}.socket @ONLY)
+
+INSTALL(
+       FILES
+               ${SERVICE_NAME}.service
+               ${SERVICE_NAME}.socket
+       DESTINATION ${SYSTEMD_UNIT_DIR}
+)
+
diff --git a/systemd/csr.service.in b/systemd/csr.service.in
new file mode 100644 (file)
index 0000000..9590ef0
--- /dev/null
@@ -0,0 +1,13 @@
+[Unit]
+Description=Content Screening and Reputation service
+Requires=@SERVICE_NAME@.socket
+
+[Service]
+User=system
+Group=system
+SmackProcessLabel=@SERVICE_NAME@
+ExecStart=@BIN_DIR@/@SERVICE_NAME@-server
+Sockets=@SERVICE_NAME@.socket
+
+[Install]
+WantedBy=multi-user.target
diff --git a/systemd/csr.socket.in b/systemd/csr.socket.in
new file mode 100644 (file)
index 0000000..c2e2187
--- /dev/null
@@ -0,0 +1,16 @@
+[Unit]
+Description=Csr framework socket
+Wants=@SERVICE_NAME@.service
+Before=@SERVICE_NAME@.service
+
+[Socket]
+ListenStream=/tmp/.@SERVICE_NAME@.socket
+Service=@SERVICE_NAME@.service
+SocketMode=0777
+# smack access control on socket disabled shortly to fast development
+#SmackLabelIPIn=@SERVICE_NAME@::api
+SmackLabelIPIn=*
+SmackLabelIPOut=@
+
+[Install]
+WantedBy=sockets.target
index 33e2f8c..743fb5c 100644 (file)
@@ -1,29 +1,47 @@
-# Make test binary
+# Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Kyungwook Tak (k.tak@samsung.com)
+# @brief       build test program of csr-framework
+#
+FIND_PACKAGE(Threads REQUIRED)
+ADD_DEFINITIONS("-DBOOST_TEST_DYN_LINK")
+
 PKG_CHECK_MODULES(${TARGET_CSR_TEST}_DEP
-    REQUIRED
+       REQUIRED
 )
 
-# TODO: Integrate TCS test and TWP test into one binary
 SET(${TARGET_CSR_TEST}_SRCS
-    SampleInfo.c
-    TCSTest.c
-    TCSTestUtils.c
-    TWPTest.c
-    TWPTestUtils.c
-    XMHttp.c
-    XMPHttp.c
+       test-main.cpp
+       test-api.cpp
+       colour_log_formatter.cpp
 )
 
 INCLUDE_DIRECTORIES(
-    ${PROJECT_SOURCE_DIR}/include/csr
-    ${${TARGET_CSR_TEST}_DEP_INCLUDE_DIRS}
+       ${PROJECT_SOURCE_DIR}/src/include
+       ./
+       ${${TARGET_CSR_TEST}_DEP_INCLUDE_DIRS}
 )
 
 ADD_EXECUTABLE(${TARGET_CSR_TEST} ${${TARGET_CSR_TEST}_SRCS})
 
 TARGET_LINK_LIBRARIES(${TARGET_CSR_TEST}
-    ${TARGET_CSR_CLIENT}
-    ${${TARGET_CSR_TEST}_DEP_LIBRARIES}
+       ${TARGET_CSR_CLIENT}
+       ${${TARGET_CSR_TEST}_DEP_LIBRARIES}
+       boost_unit_test_framework
+       -ldl
 )
 
 INSTALL (TARGETS ${TARGET_CSR_TEST} DESTINATION ${BIN_DIR})
diff --git a/test/SampleInfo.c b/test/SampleInfo.c
deleted file mode 100644 (file)
index 266593f..0000000
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "stdlib.h"
-#include "TCSTest.h"
-#include "TCSImpl.h"
-
-#include "SampleInfo.h"
-
-
-/*
- * Maximum sample file name length.
- */
-#define MAX_SAMPLE_NAME_LEN 128
-
-#define MAX_INFECTED_NUM 3
-
-
-typedef struct SampleInfo_struct
-{
-    enum ENUM_MALWARE_TEST_TYPES eTestType;
-    char szName[TCS_MAX_MALWARE_NAME_LEN];
-    char szVariant[TCS_MAX_MALWARE_NAME_LEN];
-    unsigned int uSeverity;
-    unsigned int uBehavior;
-    unsigned int uType;
-    char szInfectedFileName[MAX_SAMPLE_NAME_LEN];
-    char szBenignFileName[MAX_SAMPLE_NAME_LEN];
-} SampleInfo;
-
-
-static SampleInfo Samples[][MAX_INFECTED_NUM] =
-{
-    {
-        {
-            MALWARE_TTYPE_BUFFER,
-            BUFFER_MALWARE_NAME,
-            BUFFER_VARIANT_NAME,
-            BUFFER_SEVERITY_CLASS,
-            BUFFER_BEHAVIOR_CLASS,
-            BUFFER_MALWARE_TYPE,
-            BUFFER_FILE_NAME_1,
-            BUFFER_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_HTML,
-            HTML_MALWARE_NAME,
-            HTML_VARIANT_NAME,
-            HTML_SEVERITY_CLASS,
-            HTML_BEHAVIOR_CLASS,
-            HTML_MALWARE_TYPE,
-            HTML_FILE_NAME_1,
-            HTML_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_URL,
-            URL_MALWARE_NAME,
-            URL_VARIANT_NAME,
-            URL_SEVERITY_CLASS,
-            URL_BEHAVIOR_CLASS,
-            URL_MALWARE_TYPE,
-            URL_FILE_NAME_1,
-            URL_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_EMAIL,
-            EMAIL_MALWARE_NAME,
-            EMAIL_VARIANT_NAME,
-            EMAIL_SEVERITY_CLASS,
-            EMAIL_BEHAVIOR_CLASS,
-            EMAIL_MALWARE_TYPE,
-            EMAIL_FILE_NAME_1,
-            EMAIL_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_PHONE,
-            PHONE_MALWARE_NAME,
-            PHONE_VARIANT_NAME,
-            PHONE_SEVERITY_CLASS,
-            PHONE_BEHAVIOR_CLASS,
-            PHONE_MALWARE_TYPE,
-            PHONE_FILE_NAME_1,
-            PHONE_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_TEXT,
-            TEXT_MALWARE_NAME,
-            TEXT_VARIANT_NAME,
-            TEXT_SEVERITY_CLASS,
-            TEXT_BEHAVIOR_CLASS,
-            TEXT_MALWARE_TYPE,
-            TEXT_FILE_NAME_1,
-            TEXT_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_JAVA,
-            JAVA_MALWARE_NAME,
-            JAVA_VARIANT_NAME,
-            JAVA_SEVERITY_CLASS,
-            JAVA_BEHAVIOR_CLASS,
-            JAVA_MALWARE_TYPE,
-            JAVA_FILE_NAME_1,
-            JAVA_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_MULTIPLE,
-            MULTIPLE0_MALWARE_NAME,
-            MULTIPLE0_VARIANT_NAME,
-            MULTIPLE0_SEVERITY_CLASS,
-            MULTIPLE0_BEHAVIOR_CLASS,
-            MULTIPLE0_MALWARE_TYPE,
-            MULTIPLE0_FILE_NAME_1,
-            MULTIPLE0_FILE_NAME_0
-        },
-        {
-            MALWARE_TTYPE_MULTIPLE,
-            MULTIPLE1_MALWARE_NAME,
-            MULTIPLE1_VARIANT_NAME,
-            MULTIPLE1_SEVERITY_CLASS,
-            MULTIPLE1_BEHAVIOR_CLASS,
-            MULTIPLE1_MALWARE_TYPE,
-            MULTIPLE1_FILE_NAME_1,
-            MULTIPLE1_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_JAVAS,
-            JAVAS_MALWARE_NAME,
-            JAVAS_VARIANT_NAME,
-            JAVAS_SEVERITY_CLASS,
-            JAVAS_BEHAVIOR_CLASS,
-            JAVAS_MALWARE_TYPE,
-            JAVAS_FILE_NAME_1,
-            JAVAS_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    },
-    {
-        {
-            MALWARE_TTYPE_COMPRESS,
-            COMPRESS_MALWARE_NAME,
-            COMPRESS_VARIANT_NAME,
-            COMPRESS_SEVERITY_CLASS,
-            COMPRESS_BEHAVIOR_CLASS,
-            COMPRESS_MALWARE_TYPE,
-            COMPRESS_FILE_NAME_1,
-            COMPRESS_FILE_NAME_0
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        },
-        {
-            -1, "", "", 0, 0, 0, "", ""
-        }
-    }
-};
-
-
-static SampleInfo *SampleGetInfo(int iType, int iIndex)
-{
-    int i;
-    int n = (int) (sizeof(Samples) / (sizeof(SampleInfo) * MAX_INFECTED_NUM));
-
-    for (i = 0; i < n; i++)
-    {
-        if (Samples[i][0].eTestType == iType)
-            return &Samples[i][iIndex];
-    }
-
-    return NULL;
-}
-
-
-const char *SampleGetMalName(int iType, int iIndex)
-{
-
-    return SampleGetInfo(iType, iIndex)->szName;
-}
-
-
-const char *SampleGetVarName(int iType, int iIndex)
-{
-
-    return SampleGetInfo(iType, iIndex)->szVariant;
-}
-
-
-unsigned int SampleGetSeverity(int iType, int iIndex)
-{
-
-    return SampleGetInfo(iType, iIndex)->uSeverity;
-}
-
-
-unsigned int SampleGetMalType(int iType, int iIndex)
-{
-
-    return SampleGetInfo(iType, iIndex)->uType;
-}
-
-
-unsigned int SampleGetBehavior(int iType, int iIndex)
-{
-
-    return SampleGetInfo(iType, iIndex)->uBehavior;
-}
-
-
-const char *SampleGetInfectedFileName(int iType)
-{
-
-    return SampleGetInfo(iType, 0)->szInfectedFileName;
-}
-
-
-const char *SampleGetBenignFileName(int iType)
-{
-
-    return SampleGetInfo(iType, 0)->szBenignFileName;
-}
-
-
-int SampleGetCount(int iType)
-{
-    int i = 0;
-
-    while (SampleGetInfo(iType, i)->eTestType == iType)
-        i++;
-
-    return i;
-}
-
diff --git a/test/SampleInfo.h b/test/SampleInfo.h
deleted file mode 100644 (file)
index e5438b1..0000000
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef SAMPLE_INFO_H
-#define SAMPLE_INFO_H
-
-#ifdef __cplusplus 
-extern "C" {
-#endif
-
-#define TCS_MAX_MALWARE_NAME_LEN 64
-
-#define MALWARE_1_0_0 "Malware-fortest-1.0.0"
-#define MALWARE_1_1_0 "Malware-fortest-1.1.0"
-#define MALWARE_1_2_0 "Malware-fortest-1.2.0"
-#define MALWARE_1_3_0 "Malware-fortest-1.3.0"
-#define MALWARE_1_4_0 "Malware-fortest-1.4.0"
-#define MALWARE_1_5_0 "Malware-fortest-1.5.0"
-#define MALWARE_1_6_0 "Malware-fortest-1.6.0"
-#define MALWARE_1_7_0 "Malware-fortest-1.7.0"
-#define MALWARE_1_8_0 "Malware-fortest-1.8.0"
-#define MALWARE_1_9_0 "Malware-fortest-1.9.0"
-
-#define VARIANT_1_0_0 "Variant-fortest-1.0.0"
-#define VARIANT_1_1_0 "Variant-fortest-1.1.0"
-#define VARIANT_1_2_0 "Variant-fortest-1.2.0"
-#define VARIANT_1_3_0 "Variant-fortest-1.3.0"
-#define VARIANT_1_4_0 "Variant-fortest-1.4.0"
-#define VARIANT_1_5_0 "Variant-fortest-1.5.0"
-#define VARIANT_1_6_0 "Variant-fortest-1.6.0"
-#define VARIANT_1_7_0 "Variant-fortest-1.7.0"
-#define VARIANT_1_8_0 "Variant-fortest-1.8.0"
-#define VARIANT_1_9_0 "Variant-fortest-1.9.0"
-
-#define BUFFER_MALWARE_NAME MALWARE_1_6_0
-#define BUFFER_VARIANT_NAME VARIANT_1_6_0
-#define BUFFER_SEVERITY_CLASS TCS_SC_USER
-#define BUFFER_BEHAVIOR_CLASS TCS_BC_LEVEL1
-#define BUFFER_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define BUFFER_FILE_NAME_1 "tcs-testfile-1.buf"
-#define BUFFER_FILE_NAME_0 "tcs-testfile-0.buf"
-
-#define HTML_MALWARE_NAME MALWARE_1_0_0
-#define HTML_VARIANT_NAME VARIANT_1_0_0
-#define HTML_SEVERITY_CLASS TCS_SC_USER
-#define HTML_BEHAVIOR_CLASS TCS_BC_LEVEL0
-#define HTML_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define HTML_FILE_NAME_1 "tcs-testfile-1.html"
-#define HTML_FILE_NAME_0 "tcs-testfile-0.html"
-
-#define URL_MALWARE_NAME MALWARE_1_1_0
-#define URL_VARIANT_NAME VARIANT_1_1_0
-#define URL_SEVERITY_CLASS TCS_SC_USER
-#define URL_BEHAVIOR_CLASS TCS_BC_LEVEL1
-#define URL_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define URL_FILE_NAME_1 "tcs-testfile-1.url"
-#define URL_FILE_NAME_0 "tcs-testfile-0.url"
-
-#define EMAIL_MALWARE_NAME MALWARE_1_2_0
-#define EMAIL_VARIANT_NAME VARIANT_1_2_0
-#define EMAIL_SEVERITY_CLASS TCS_SC_TERMINAL
-#define EMAIL_BEHAVIOR_CLASS TCS_BC_LEVEL2
-#define EMAIL_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define EMAIL_FILE_NAME_1 "tcs-testfile-1.email"
-#define EMAIL_FILE_NAME_0 "tcs-testfile-0.email"
-
-#define PHONE_MALWARE_NAME MALWARE_1_3_0
-#define PHONE_VARIANT_NAME VARIANT_1_3_0
-#define PHONE_SEVERITY_CLASS TCS_SC_TERMINAL
-#define PHONE_BEHAVIOR_CLASS TCS_BC_LEVEL3
-#define PHONE_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define PHONE_FILE_NAME_1 "tcs-testfile-1.phone"
-#define PHONE_FILE_NAME_0 "tcs-testfile-0.phone"
-
-#define TEXT_MALWARE_NAME MALWARE_1_4_0
-#define TEXT_VARIANT_NAME VARIANT_1_4_0
-#define TEXT_SEVERITY_CLASS TCS_SC_TERMINAL
-#define TEXT_BEHAVIOR_CLASS TCS_BC_LEVEL4
-#define TEXT_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define TEXT_FILE_NAME_1 "tcs-testfile-1.txt"
-#define TEXT_FILE_NAME_0 "tcs-testfile-0.txt"
-
-#define JAVA_MALWARE_NAME MALWARE_1_7_0
-#define JAVA_VARIANT_NAME VARIANT_1_7_0
-#define JAVA_SEVERITY_CLASS TCS_SC_USER
-#define JAVA_BEHAVIOR_CLASS TCS_BC_LEVEL0
-#define JAVA_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define JAVA_FILE_NAME_1 "tcs-testfile-1.class"
-#define JAVA_FILE_NAME_0 "tcs-testfile-0.class"
-
-#define MULTIPLE0_MALWARE_NAME MALWARE_1_5_0
-#define MULTIPLE0_VARIANT_NAME VARIANT_1_5_0
-#define MULTIPLE0_SEVERITY_CLASS TCS_SC_USER
-#define MULTIPLE0_BEHAVIOR_CLASS TCS_BC_LEVEL0
-#define MULTIPLE0_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define MULTIPLE0_FILE_NAME_1 "tcs-testfile-1.multiple"
-#define MULTIPLE0_FILE_NAME_0 "tcs-testfile-0.multiple"
-
-#define MULTIPLE1_MALWARE_NAME MALWARE_1_6_0
-#define MULTIPLE1_VARIANT_NAME VARIANT_1_6_0
-#define MULTIPLE1_SEVERITY_CLASS TCS_SC_USER
-#define MULTIPLE1_BEHAVIOR_CLASS TCS_BC_LEVEL1
-#define MULTIPLE1_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define MULTIPLE1_FILE_NAME_1 "tcs-testfile-1.multiple"
-#define MULTIPLE1_FILE_NAME_0 "tcs-testfile-0.multiple"
-
-#define JAVAS_MALWARE_NAME MALWARE_1_8_0
-#define JAVAS_VARIANT_NAME VARIANT_1_8_0
-#define JAVAS_SEVERITY_CLASS TCS_SC_USER
-#define JAVAS_BEHAVIOR_CLASS TCS_BC_LEVEL2
-#define JAVAS_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define JAVAS_FILE_NAME_1 "tcs-testfile-1.js"
-#define JAVAS_FILE_NAME_0 "tcs-testfile-0.js"
-
-#define COMPRESS_MALWARE_NAME MALWARE_1_9_0
-#define COMPRESS_VARIANT_NAME VARIANT_1_9_0
-#define COMPRESS_SEVERITY_CLASS TCS_SC_USER
-#define COMPRESS_BEHAVIOR_CLASS TCS_BC_LEVEL2
-#define COMPRESS_MALWARE_TYPE TCS_VTYPE_MALWARE
-#define COMPRESS_FILE_NAME_1 "tcs-testfile-1.z"
-#define COMPRESS_FILE_NAME_0 "tcs-testfile-0.z"
-
-#ifdef __cplusplus 
-}
-#endif
-
-#endif /* SAMPLE_INFO_H */
-
diff --git a/test/TCSTest.c b/test/TCSTest.c
deleted file mode 100644 (file)
index dbd6ade..0000000
+++ /dev/null
@@ -1,1101 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <errno.h>
-#include <string.h>
-#include <assert.h>
-#include "TCSImpl.h"
-#include "TCSErrorCodes.h"
-
-#include "TCSTest.h"
-
-
-/* Test cases. */
-static void TCSStartup(void);
-static void TCSCleanup(void);
-static void TCSLibraryOpen_0001(void);
-static void TCSLibraryOpen_0002(void);
-static void TCSLibraryOpen_0003(void);
-static void TCSLibraryOpen_0004(void);
-static void TCSGetLastError_0001(void);
-static void TCSLibraryClose_0001(void);
-
-static void TCSScanData_0001(void);
-static void TCSScanData_0002(void);
-static void TCSScanData_0003(void);
-static void TCSScanData_0004(void);
-static void TCSScanData_0005(void);
-static void TCSScanData_0006(void);
-static void TCSScanData_0007(void);
-static void TCSScanData_0008(void);
-static void TCSScanData_0009(void);
-static void TCSScanData_0010(void);
-static void TCSScanData_0011(void);
-static void TCSScanData_0012(void);
-static void TCSScanData_0013(void);
-static void TCSScanData_0014(void);
-static void TCSScanData_0015(void);
-static void TCSScanData_0016(void);
-static void TCSScanData_0017(void);
-static void TCSScanData_0018(void);
-static void TCSScanData_0019(void);
-static void TCSScanData_0020(void);
-static void TCSScanData_0021(void);
-static void TCSScanData_0022(void);
-static void TCSScanData_0023(void);
-static void TCSScanData_0024(void);
-static void TCSScanData_0025(void);
-static void TCSScanData_0026(void);
-static void TCSScanData_0027(void);
-static void TCSScanData_0028(void);
-static void TCSScanData_0029(void);
-static void TCSScanData_0030(void);
-static void TCSScanData_0031(void);
-static void TCSScanData_0032(void);
-static void TCSScanData_0033(void);
-static void TCSScanData_0034(void);
-static void TCSScanData_0035(void);
-static void TCSScanData_0036(void);
-static void TCSScanData_0037(void);
-static void TCSScanData_0038(void);
-static void TCSScanData_0039(void);
-static void TCSScanData_0040(void);
-static void TCSScanData_0041(void);
-static void TCSScanData_0042(void);
-static void TCSScanData_0043(void);
-static void TCSScanData_0044(void);
-static void TCSScanData_0045(void);
-static void TCSScanData_0046(void);
-static void TCSScanData_0047(void);
-static void TCSScanData_0048(void);
-static void TCSScanData_0049(void);
-static void TCSScanData_0050(void);
-static void TCSScanData_0051(void);
-static void TCSScanData_0052(void);
-
-static void TCSScanFile_0001(void);
-static void TCSScanFile_0002(void);
-static void TCSScanFile_0003(void);
-static void TCSScanFile_0004(void);
-static void TCSScanFile_0005(void);
-static void TCSScanFile_0006(void);
-static void TCSScanFile_0007(void);
-static void TCSScanFile_0008(void);
-static void TCSScanFile_0009(void);
-static void TCSScanFile_0010(void);
-static void TCSScanFile_0011(void);
-static void TCSScanFile_0012(void);
-static void TCSScanFile_0013(void);
-static void TCSScanFile_0014(void);
-static void TCSScanFile_0015(void);
-static void TCSScanFile_0016(void);
-static void TCSScanFile_0017(void);
-static void TCSScanFile_0018(void);
-static void TCSScanFile_0019(void);
-static void TCSScanFile_0020(void);
-static void TCSScanFile_0021(void);
-static void TCSScanFile_0022(void);
-static void TCSScanFile_0023(void);
-static void TCSScanFile_0024(void);
-static void TCSScanFile_0025(void);
-static void TCSScanFile_0026(void);
-static void TCSScanFile_0027(void);
-static void TCSScanFile_0028(void);
-static void TCSScanFile_0029(void);
-static void TCSScanFile_0030(void);
-static void TCSScanFile_0031(void);
-static void TCSScanFile_0032(void);
-static void TCSScanFile_0033(void);
-static void TCSScanFile_0034(void);
-
-static void TestCases(void);
-
-
-extern int TestCasesCount;
-extern int Success;
-extern int Failures;
-
-
-int main(int argc, char **argv)
-{
-
-    TCSStartup();
-    TestCases();
-    TCSCleanup();
-
-    return 0;
-}
-
-
-static void TestCases(void)
-{
-    TCSLibraryOpen_0001();
-    TCSLibraryOpen_0002();
-    TCSLibraryOpen_0003();
-    TCSLibraryOpen_0004();
-
-    TCSGetLastError_0001();
-
-    TCSLibraryClose_0001();
-
-    TCSScanData_0001();
-    TCSScanData_0002();
-    TCSScanData_0003();
-    TCSScanData_0004();
-    TCSScanData_0005();
-    TCSScanData_0006();
-    TCSScanData_0007();
-    TCSScanData_0008();
-    TCSScanData_0009();
-    TCSScanData_0010();
-    TCSScanData_0011();
-    TCSScanData_0012();
-    TCSScanData_0013();
-    TCSScanData_0014();
-    TCSScanData_0015();
-    TCSScanData_0016();
-    TCSScanData_0017();
-    TCSScanData_0018();
-    TCSScanData_0019();
-    TCSScanData_0020();
-    TCSScanData_0021();
-    TCSScanData_0022();
-    TCSScanData_0023();
-    TCSScanData_0024();
-    TCSScanData_0025();
-    TCSScanData_0026();
-    TCSScanData_0027();
-    TCSScanData_0028();
-    TCSScanData_0029();
-    TCSScanData_0030();
-    TCSScanData_0031();
-    TCSScanData_0032();
-    TCSScanData_0033();
-    TCSScanData_0034();
-    TCSScanData_0035();
-    TCSScanData_0036();
-    TCSScanData_0037();
-    TCSScanData_0038();
-    TCSScanData_0039();
-    TCSScanData_0040();
-    TCSScanData_0041();
-    TCSScanData_0042();
-    TCSScanData_0043();
-    TCSScanData_0044();
-    TCSScanData_0045();
-    TCSScanData_0046();
-    TCSScanData_0047();
-    TCSScanData_0048();
-    TCSScanData_0049();
-    TCSScanData_0050();
-    TCSScanData_0051();
-    TCSScanData_0052();
-
-    TCSScanFile_0001();
-    TCSScanFile_0002();
-    TCSScanFile_0003();
-    TCSScanFile_0004();
-    TCSScanFile_0005();
-    TCSScanFile_0006();
-    TCSScanFile_0007();
-    TCSScanFile_0008();
-    TCSScanFile_0009();
-    TCSScanFile_0010();
-    TCSScanFile_0011();
-    TCSScanFile_0012();
-    TCSScanFile_0013();
-    TCSScanFile_0014();
-    TCSScanFile_0015();
-    TCSScanFile_0016();
-    TCSScanFile_0017();
-    TCSScanFile_0018();
-    TCSScanFile_0019();
-    TCSScanFile_0020();
-    TCSScanFile_0021();
-    TCSScanFile_0022();
-    TCSScanFile_0023();
-    TCSScanFile_0024();
-    TCSScanFile_0025();
-    TCSScanFile_0026();
-    TCSScanFile_0027();
-    TCSScanFile_0028();
-    TCSScanFile_0029();
-    TCSScanFile_0030();
-    TCSScanFile_0031();
-    TCSScanFile_0032();
-    TCSScanFile_0033();
-    TCSScanFile_0034();
-}
-
-
-static void TCSRemovePlugin(void)
-{
-    char *pszCommand;
-
-    asprintf(&pszCommand, "rm -f %s", PLUGIN_PATH);
-//    CallSys(pszCommand);
-    free(pszCommand);
-}
-
-
-static void TCSLibraryOpen_0001(void)
-{
-    TestCase TestCtx;
-    TCSLIB_HANDLE hLib;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    TEST_ASSERT((hLib = TCSLibraryOpen()) != INVALID_TCSLIB_HANDLE);
-    TESTCASEDTOR(&TestCtx);
-    TCSLibraryClose(hLib);
-}
-
-
-static void TCSLibraryOpen_0002(void)
-{
-    int iErr;
-    TestCase TestCtx;
-    TCSLIB_HANDLE hLib;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-
-    BackupEngine();
-    TCSRemovePlugin();
-
-    TEST_ASSERT((hLib = TCSLibraryOpen()) == INVALID_TCSLIB_HANDLE);
-    iErr = TCSGetLastError(hLib);
-    TEST_ASSERT(TCS_ERRMODULE(iErr) == TCS_ERROR_MODULE_GENERIC);
-    TEST_ASSERT(TCS_ERRCODE(iErr) == TCS_ERROR_NOT_IMPLEMENTED);
-    TESTCASEDTOR(&TestCtx);
-
-    RestoreEngine();
-}
-
-
-static void TCSGetLastError_0001(void)
-{
-    int iErr;
-    TestCase TestCtx;
-
-    BackupEngine();
-    TCSRemovePlugin();
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    iErr = TCSGetLastError(INVALID_TCSLIB_HANDLE);
-    TEST_ASSERT(TCS_ERRMODULE(iErr) == TCS_ERROR_MODULE_GENERIC);
-    TEST_ASSERT(TCS_ERRCODE(iErr) == TCS_ERROR_NOT_IMPLEMENTED);
-    TESTCASEDTOR(&TestCtx);
-
-    RestoreEngine();
-}
-
-
-static void TCSScanData_0052(void)
-{
-    TestCase TestCtx;
-    TCSScanParam SP = {0};
-    TCSScanResult SR= {0};
-
-    BackupEngine();
-    TCSRemovePlugin();
-
-    SP.iAction = TCS_SA_SCANONLY;
-    SP.iDataType = TCS_DTYPE_UNKNOWN;
-    SP.iCompressFlag = 1;
-    SP.pPrivate = NULL;
-    SP.pfGetSize = NULL;
-    SP.pfSetSize = NULL;
-    SP.pfRead = NULL;
-    SP.pfWrite = NULL;
-    SP.pfCallBack = NULL;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    TEST_ASSERT(TCSScanData(INVALID_TCSLIB_HANDLE, &SP, &SR) == -1);
-    TESTCASEDTOR(&TestCtx);
-
-    RestoreEngine();
-}
-
-
-static void TCSScanFile_0034(void)
-{
-    TestCase TestCtx;
-    TCSScanResult SR = {0};
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    TEST_ASSERT(TCSScanFile(INVALID_TCSLIB_HANDLE, "file",
-                            TCS_DTYPE_UNKNOWN, TCS_SA_SCANONLY, 1, &SR) == -1);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSLibraryClose_0001(void)
-{
-    TestCase TestCtx;
-    TCSLIB_HANDLE hLib;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    TEST_ASSERT((hLib = TCSLibraryOpen()) != INVALID_TCSLIB_HANDLE)
-    TEST_ASSERT(TCSLibraryClose(hLib) == 0);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSScanData_0001(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_BUFFER, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0002(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_BUFFER, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0003(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0004(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0005(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_HTML, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0006(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_HTML, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0007(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_HTML, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0008(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_HTML, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0009(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_URL, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0010(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_URL, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0011(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_URL, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0012(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_URL, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0013(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_EMAIL, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0014(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_EMAIL, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0015(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_EMAIL, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0016(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_EMAIL, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0017(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_PHONE, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0018(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_PHONE, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0019(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_PHONE, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0020(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_PHONE, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0021(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVA, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0022(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVA, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0023(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVA, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0024(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVA, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0025(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVAS, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0026(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVAS, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0027(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVAS, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0028(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVAS, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0029(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_TEXT, BENIGN_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0030(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_TEXT, BENIGN_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0031(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_TEXT, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0032(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_TEXT, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0033(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_MULTIPLE, INFECTED_DATA,
-                 TCS_SA_SCANONLY, NULL);
-}
-
-
-static void TCSScanData_0034(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_MULTIPLE, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbScanCallback);
-}
-
-
-static void TCSScanData_0035(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0036(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_HTML, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0037(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_URL, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0038(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_EMAIL, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0039(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_PHONE, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0040(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_JAVA, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0041(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_TEXT, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0042(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_MULTIPLE, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0043(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA,
-                 TCS_SA_SCANONLY, &CbAbortCallback);
-}
-
-
-static void TCSScanData_0044(void)
-{
-
-    TestScanData(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR, &CbScanCallback);
-}
-
-
-static void TCSScanData_0045(void)
-{
-    TestCase TestCtx;
-    TCSScanParam SP = {0};
-    TCSScanResult SR= {0};
-
-    SP.iAction = TCS_SA_SCANONLY;
-    SP.iDataType = TCS_DTYPE_UNKNOWN;
-    SP.iCompressFlag = 1;
-    SP.pPrivate = NULL;
-    SP.pfGetSize = NULL;
-    SP.pfSetSize = NULL;
-    SP.pfRead = NULL;
-    SP.pfWrite = NULL;
-    SP.pfCallBack = NULL;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    TEST_ASSERT(TCSScanData(INVALID_TCSLIB_HANDLE, &SP, &SR) == -1);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSScanData_0046(void)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    ConScanData(&TestCtx, TCS_SA_SCANONLY);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSScanData_0047(void)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    ConScanData(&TestCtx, TCS_SA_SCANREPAIR);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSScanData_0048(void)
-{
-
-    TestScanDataEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, BENIGN_DATA,
-                   TCS_SA_SCANONLY, 1, &CbScanCallback);
-}
-
-
-static void TCSScanData_0049(void)
-{
-
-    TestScanDataEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, BENIGN_DATA,
-                   TCS_SA_SCANONLY, 0, &CbScanCallback);
-}
-
-
-static void TCSScanData_0050(void)
-{
-
-    TestScanDataEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, INFECTED_DATA,
-                   TCS_SA_SCANONLY, 1, &CbScanCallback);
-}
-
-
-static void TCSScanData_0051(void)
-{
-
-    TestScanDataEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, INFECTED_DATA,
-                   TCS_SA_SCANONLY, 0, &CbScanCallback);
-}
-
-
-static void TCSScanFile_0001(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_BUFFER, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0002(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0003(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_HTML, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0004(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_HTML, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0005(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_URL, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0006(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_URL, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0007(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_EMAIL, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0008(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_EMAIL, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0009(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_PHONE, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0010(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_PHONE, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0011(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_JAVA, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0012(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_JAVA, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0013(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_TEXT, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0014(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_TEXT, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0015(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_MULTIPLE, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0016(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0017(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_HTML, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0018(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_URL, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0019(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_EMAIL, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0020(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_PHONE, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0021(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_JAVA, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0022(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_TEXT, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0023(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_MULTIPLE, INFECTED_DATA,
-                 TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0024(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_BUFFER, INFECTED_DATA, TCS_SA_SCANREPAIR);
-}
-
-
-static void TCSScanFile_0025(void)
-{
-    TestCase TestCtx;
-    TCSScanResult SR = {0};
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    TEST_ASSERT(TCSScanFile(INVALID_TCSLIB_HANDLE, "file",
-                            TCS_DTYPE_UNKNOWN, TCS_SA_SCANONLY, 1, &SR) == -1);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSScanFile_0026(void)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    ConScanFile(&TestCtx, TCS_SA_SCANONLY);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSScanFile_0027(void)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    ConScanFile(&TestCtx, TCS_SA_SCANREPAIR);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSScanFile_0028(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_JAVAS, BENIGN_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0029(void)
-{
-
-    TestScanFile(__FUNCTION__, MALWARE_TTYPE_JAVAS, INFECTED_DATA, TCS_SA_SCANONLY);
-}
-
-
-static void TCSScanFile_0030(void)
-{
-
-    TestScanFileEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, BENIGN_DATA, TCS_SA_SCANONLY, 1);
-}
-
-
-static void TCSScanFile_0031(void)
-{
-
-    TestScanFileEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, INFECTED_DATA, TCS_SA_SCANONLY, 1);
-}
-
-
-static void TCSScanFile_0032(void)
-{
-
-    TestScanFileEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, BENIGN_DATA, TCS_SA_SCANONLY, 0);
-}
-
-
-static void TCSScanFile_0033(void)
-{
-
-    TestScanFileEx(__FUNCTION__, MALWARE_TTYPE_COMPRESS, INFECTED_DATA, TCS_SA_SCANONLY, 0);
-}
-
-
-static void TCSStartup(void)
-{
-    extern int TestCasesCount;
-    extern int Success;
-    extern int Failures;
-
-    TestCasesCount = 0;
-    Success = 0;
-    Failures = 0;
-    CreateTestDirs();
-}
-
-
-static void TCSCleanup(void)
-{
-    LOG_OUT("@@@@@@@@@@@@@@@@@@@@@@@@\n");
-    LOG_OUT("Test done: %d executed, %d passed, %d failure\n", TestCasesCount, Success, Failures);
-    DestoryTestDirs();
-}
-
-
-static void TCSLibraryOpen_0003(void)
-{
-    TCSLIB_HANDLE hLib = INVALID_TCSLIB_HANDLE;
-    TestCase TestCtx;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-    /* pre-condition is stub library */
-    BackupEngine();
-    TCSRemovePlugin();
-
-    TEST_ASSERT((hLib = TCSLibraryOpen()) == INVALID_TCSLIB_HANDLE);
-    RestoreEngine();
-
-    TEST_ASSERT((hLib = TCSLibraryOpen()) != INVALID_TCSLIB_HANDLE);
-    TCSLibraryClose(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TCSLibraryOpen_0004(void)
-{
-    TCSLIB_HANDLE hLib = INVALID_TCSLIB_HANDLE;
-    TestCase TestCtx;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__, 0, 0, 0, NULL);
-
-    TEST_ASSERT((hLib = TCSLibraryOpen()) != INVALID_TCSLIB_HANDLE);
-
-    BackupEngine();
-    TCSRemovePlugin();
-    TCSLibraryClose(hLib);
-
-    TEST_ASSERT((hLib = TCSLibraryOpen()) == INVALID_TCSLIB_HANDLE);
-
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
diff --git a/test/TCSTest.h b/test/TCSTest.h
deleted file mode 100644 (file)
index 7d90d60..0000000
+++ /dev/null
@@ -1,176 +0,0 @@
-#ifndef TCSTEST_H
-#define TCSTEST_H
-
-
-#include <setjmp.h>
-
-
-/* For multi-user support */
-#include <tzplatform_config.h>
-
-#ifdef __cplusplus 
-extern "C" {
-#endif
-
-#define TEST_SUITE_VERSION "0.0.1"
-
-/* Immediate value definitions. */
-#define MAX_TEST_NUM 128
-
-/* Test content polarities */
-#define BENIGN_DATA 0
-#define INFECTED_DATA 1
-
-/* Maximum CS API name length. */
-#define MAX_TCS_API_NAME_LEN 128
-
-/* Content backup directory before repairing test. */
-#define TCS_BACKUP_CONTENT_DIR "contents_bak"
-
-/* Content directory for testing. */
-#define TCS_TEST_CONTENT_DIR "contents_test"
-
-/* Default maximum number of threads for concurrency test. */
-#define MAX_TEST_THREADS 10
-
-/* Default maximum concurrency test timeout (in seconds). */
-#define DEFAULT_CONCURRENCY_TEST_TIMEOUT 30
-
-/* Sleep interval for thread context switch. */
-#define SLEEP_INTERVAL 500
-
-
-/* Output methods. */
-#define LOG_OUT(fmt, x...) printf("Log:"fmt, ##x)
-
-#define TRY_TEST { \
-    int _ret_ = setjmp(JmpBuf); \
-    if (_ret_ == 1) { \
-        Failures++; \
-    } else { \
-
-#define FAIL_TEST longjmp(JmpBuf, 1);
-
-#define TESTCASECTOR(_ctx_, _api_, _testtype_, _polarity_, _action_, _callback_) \
-        TRY_TEST \
-        TestCaseCtor(_ctx_, _api_, _testtype_, _polarity_, _action_, _callback_);
-
-#define TESTCASECTOREX(_ctx_, _api_, _testtype_, _polarity_, _action_, _flag_, _callback_) \
-        TRY_TEST \
-        TestCaseCtorEx(_ctx_, _api_, _testtype_, _polarity_, _action_, _flag_, _callback_);
-
-#define TESTCASEDTOR(_ctx_) \
-        TestCaseDtor(_ctx_); \
-    } \
-} \
-
-/* Test assert method. */
-#define TEST_ASSERT(cond) if (!(cond)) {LOG_OUT("Test failed!! at : %s, %d\n", __FILE__, __LINE__); FAIL_TEST}
-
-#define ELEMENT_NUM(ary) (sizeof(ary) / sizeof((ary)[0]))
-
-#define TEST_CONSTRUCT_ERRCODE(m, e) (((m) << 24) | (e))
-
-#define PLUGIN_PATH tzplatform_mkpath(TZ_USER_SHARE, "sec_plugin/libengine.so")
-#define PLUGIN_DIR tzplatform_mkpath(TZ_USER_SHARE, "sec_plugin/")
-
-/* Test content file types */
-enum ENUM_MALWARE_TEST_TYPES
-{
-    MALWARE_TTYPE_BUFFER = 0,
-    MALWARE_TTYPE_HTML,
-    MALWARE_TTYPE_URL,
-    MALWARE_TTYPE_EMAIL,
-    MALWARE_TTYPE_PHONE,
-    MALWARE_TTYPE_TEXT,
-    MALWARE_TTYPE_JAVA,
-    MALWARE_TTYPE_MULTIPLE,
-    MALWARE_TTYPE_JAVAS,
-    MALWARE_TTYPE_COMPRESS,
-    MALWARE_TTYPE_MAX
-};
-
-typedef int (*PFScan)(void *pPrivate, int nReason, void *pParam);
-
-/**
- * Test case information data
- */
-typedef struct TestCase_struct
-{
-    char szAPIName[MAX_TCS_API_NAME_LEN]; /* TCS API names */
-    int iInfected; /* Index of infected malware passed in pfCallback. */
-    int iTestType; /* Sample type. */
-    int iPolarity; /* INFECTED_DATA - Infected, BENIGN_DATA - Benign
-                      otherwise undefined. */
-    int iAction;
-    int iCompressFlag;
-    int iNotImplTestFlag; /* 1 - repair not implemented test flag, otherwise not. */
-    int *pFlags;
-    PFScan pfCallback;
-
-    pthread_mutex_t MutexCon; /* Concurrency test communication stuff. */
-    pthread_cond_t CondCon; /* Concurrency test communication stuff. */
-} TestCase;
-
-/**
- * Concurrency test data
- */
-typedef struct ConTestContext_struct
-{
-    TestCase *pTestCtx;
-    int iCid; /* Concurrency test id. */
-
-    /* Report concurrency test status. 1 - success, -1 - failure, 0 - running. */
-    int iConTestRet;
-} ConTestContext;
-
-
-/*
- * Very simple/thin porting layer
- *
- * Test malware informations. Malware names to be tested should be
- * prepared in compiling time. Please see the porting guide for test
- * suite.
- */
-extern const char *SampleGetMalName(int iType, int iIndex);
-extern const char *SampleGetVarName(int iType, int iIndex);
-extern const char *SampleGetBenignFileName(int iType);
-extern const char *SampleGetInfectedFileName(int iType);
-extern unsigned int SampleGetSeverity(int iType, int iIndex);
-extern unsigned int SampleGetBehavior(int iType, int iIndex);
-extern unsigned int SampleGetMalType(int iType, int iIndex);
-extern int SampleGetCount(int iType);
-
-/* Test framework */
-extern int CbScanCallback(void *pPrivate, int nReason, void *pParam);
-extern int CbAbortCallback(void *pPrivate, int nReason, void *pParam);
-extern void TestCaseCtor(TestCase *pCtx, const char *pszAPI, int iTestType,
-                         int iPolarity, int iAction, PFScan pfCallback);
-extern void TestCaseDtor(TestCase *pCtx);
-extern void TestScanFile(const char *pszFunc, int iTType, int iPolarity,
-                         int iAction);
-extern void TestScanData(const char *pszFunc, int iTType, int iPolarity,
-                         int iAction, PFScan pfCallback);
-extern void TestScanFileEx(const char *pszFunc, int iTType, int iPolarity,
-                           int iAction, int iCompressFlag);
-extern void TestScanDataEx(const char *pszFunc, int iTType, int iPolarity,
-                           int iAction, int iCompressFlag, PFScan pfCallback);
-extern void ConScanFile(TestCase *pCtx, int iAction);
-extern void ConScanData(TestCase *pCtx, int iAction);
-extern int DetectRepairFunc(void);
-extern int CreateTestDirs(void);
-extern void DestoryTestDirs(void);
-extern int DetectStubLibrary(void);
-extern int IsStubTest();
-extern int IsTestRepair();
-extern void RestoreEngine();
-extern void BackupEngine();
-extern void CallSys(const char *pszCmd);
-
-extern jmp_buf JmpBuf;
-
-#ifdef __cplusplus 
-}
-#endif
-
-#endif /* TCSTEST_H */
diff --git a/test/TCSTestUtils.c b/test/TCSTestUtils.c
deleted file mode 100644 (file)
index 615a29d..0000000
+++ /dev/null
@@ -1,2106 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#define _GNU_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <pthread.h>
-#include <sys/time.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include "TCSErrorCodes.h"
-#include "TCSImpl.h"
-#include "TCSTest.h"
-
-/* Concurrency test macros. */
-#define CONTEST_START \
-{\
-    int iTestRet = 1;
-
-#define CONTEST_ERROR \
-    CONTEST_ASSERT(0)
-
-#define CONTEST_ASSERT(condition) \
-if (!(condition)) \
-{ \
-    LOG_OUT("test failed: %s,%d\n", __FILE__, __LINE__); \
-    iTestRet = -1; \
-}
-
-#define CONTEST_RETURN(ret) \
-    ret = iTestRet; \
-}
-
-#define CONTEST_RELEASE(con_test_ctx) \
-    ReleaseTestObject(con_test_ctx, iTestRet);\
-}
-
-#define TCS_ACTION_CLASS(a) ((a) & 0xff)
-#define TCS_ACTION_BEHAVIOR(a) (((a) >> 8) & 0xff)
-
-#ifndef MAX
-#define MAX(a, b) ((a) > (b) ? (a) : (b))
-#endif
-
-#define CONTENTS_ROOT "contents"
-#define CONTENTS_TMP "tmp"
-
-
-/**
- * Scan context
- */
-typedef struct ScanContext_struct
-{
-    /* Test status */
-    TestCase *pCurrentTestCase;
-    char *pData;
-    unsigned int uSize;
-} ScanContext;
-
-
-/**
- * Concurrency Scan context
- */
-typedef struct ConScanContext_struct
-{
-    /* Test status */
-    int iTestType;
-    int iInfected;
-    int iPolarity;
-    int iTestRet;
-    int *pFlags;
-    char *pData;
-    unsigned int uSize;
-} ConScanContext;
-
-
-pthread_mutex_t g_Mutex = PTHREAD_MUTEX_INITIALIZER;
-pthread_cond_t g_Cond = PTHREAD_COND_INITIALIZER;
-
-
-static int ScanBufferProc(TestCase *pCtx, char *pData, int iDataLen);
-static int SaveTestContents(void);
-static int LoadTestContents(void);
-static char *GetBackupDir(void);
-static void PutBackupDir(char *pszBackupDir);
-static char *GetSamplePath(TestCase *pCtx);
-static void PutSamplePath(char *pszSamplePath);
-static int GetSampleDataType(int iTType);
-static char *LoadFile(char const *pszFileName, int *piSize);
-static void PutLoadedFile(char *pData);
-static void ReportTestCase(TestCase *pCtx);
-static TCSOffset CbScanGetSize(void *pPrivate);
-static unsigned int CbScanRead(void *pPrivate, TCSOffset uOffset,
-                               void *pBuffer, unsigned int uSize);
-static unsigned int CbScanWrite(void *pPrivate, TCSOffset uOffset,
-                                void const *pBuffer, unsigned int uSize);
-static int CbScanSetSize(void *pPrivate, TCSOffset uSize);
-static void CheckDetected(TestCase *pCtx, TCSDetected *pFound);
-static void CheckDetectedList(TestCase *pCtx, TCSScanResult *pSR);
-static int ScanBuffer(TestCase *pCtx);
-static int ScanFile(TestCase *pCtx);
-static char *GetTestRoot(void);
-static void PutTestRoot(char *pszRoot);
-static int BufferCompare(const char *pBuffer1, const char *pBuffer2, int iLen);
-static int FileCompare(const char *pszFile1, const char *pszFile2);
-static int VerifyRepairData(TestCase *pCtx, const char *pRepairedBuffer,
-                            int iRepairedLen);
-static int VerifyRepairFile(TestCase *pCtx);
-static void PutBenignSamplePath(char *pszPath);
-static char *GetBenignSamplePath(int iTType);
-static int Infected(TestCase *pCtx, char *pData, int iDataLen);
-static int InfectedFile(TestCase *pCtx, const char *pszPath);
-static void TestCaseCtorEx(TestCase *pCtx, const char *pszAPI, int iTestType,
-                           int iPolarity, int iAction, int iCompressFlag,
-                           PFScan pfCallback);
-
-/* Concurrency test functions. */
-static char *ConGetSampleDir(int iCid);
-static void ConPutSampleDir(char *pszDir);
-static void ConCreateSampleDirs(void);
-static void ConDestorySampleDirs(void);
-static char *ConGetSamplePath(int iTType, int iPolarity, int iCid);
-static void ConPutSamplePath(char *pszSamplePath);
-static void ConTestCaseCtor(ConTestContext *pConCtx, int iCid, TestCase *pCtx);
-static void ConTestCaseDtor(ConTestContext *pConCtx);
-
-static int ConWaitOnTestCond(ConTestContext *pConCtxAry);
-static void ReleaseTestObject(ConTestContext *pConCtx, int iResult);
-
-static int ConCheckDetected(int iTType, TCSDetected *pFound, int *pFlags);
-static int ConCheckDetectedList(int iTType, TCSScanResult *pSR, int *pFlags);
-static int ConVerifyRepairData(int iTType, int iCompressFlag, const char *pRepairedBuffer,
-                               int iRepairedLen);
-static int ConVerifyRepairFile(char *pszSamplePath, int iTType, int iCompressFlag);
-
-static TCSOffset ConCbScanGetSize(void *pPrivate);
-static unsigned int ConCbScanRead(void *pPrivate, TCSOffset uOffset,
-                                  void *pBuffer, unsigned int uSize);
-static unsigned int ConCbScanWrite(void *pPrivate, TCSOffset uOffset,
-                                void const *pBuffer, unsigned int uSize);
-static int ConCbScanSetSize(void *pPrivate, TCSOffset uSize);
-static int ConCbScanCallback(void *pPrivate, int nReason, void *pParam);
-static void ConScanDataProc(ConTestContext *pConCtx, int iAction);
-static void *ConScanDataSCProc(void *pConCtxParam);
-static void *ConScanDataSRProc(void *pConCtxParam);
-
-static int ConTestSuccess(ConTestContext *pConCtxAry);
-static int ConTestComplete(ConTestContext *pConCtxAry);
-
-static void ConScanFileProc(ConTestContext *pConCtx, int iAction);
-static void *ConScanFileSCProc(void *pConCtxParam);
-static void *ConScanFileSRProc(void *pConCtxParam);
-static int ConInfectedFile(int iType, int iCompressFlag, const char *pszPath);
-static int ConInfected(int iType, int iCompressFlag, char *pData, int iDataLen);
-
-
-int TestCasesCount = 0;
-int Success = 0;
-int Failures = 0;
-jmp_buf JmpBuf; 
-
-
-static char *LoadFile(char const *pszFileName, int *piSize)
-{
-    FILE *pFile = NULL;
-    char *pData = NULL;
-
-    if ((pFile = fopen(pszFileName, "rb")) == NULL)
-        return NULL;
-
-    fseek(pFile, 0, SEEK_END);
-    *piSize = (long) ftell(pFile);
-    fseek(pFile, 0, SEEK_SET);
-    if ((pData = (char *) malloc(*piSize + 1)) == NULL)
-    {
-        fclose(pFile);
-        return NULL;
-    }
-    if (fread(pData, 1, (size_t) *piSize, pFile) != *piSize)
-    {
-        free(pData);
-        fclose(pFile);
-        return NULL;
-    }
-    fclose(pFile);
-    pData[*piSize] = '\0';
-
-    return pData;
-}
-
-
-static void PutLoadedFile(char *pData)
-{
-
-    if (pData != NULL)
-        free(pData);
-}
-
-
-/**
- * Output for test case result.
- */
-static void ReportTestCase(TestCase *pCtx)
-{
-    char *pszTmp;
-
-    LOG_OUT("@@@@@@@@@@@@@@@@@@@@@@@@\n");
-
-    LOG_OUT("@ID: TC_SEC_CS_%s\n", pCtx->szAPIName);
-    pszTmp = strchr(pCtx->szAPIName, '_');
-    *pszTmp = 0;
-    LOG_OUT("@API Name: %s\n", pCtx->szAPIName);
-    *pszTmp = '_';
-
-    TestCasesCount++;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static TCSOffset CbScanGetSize(void *pPrivate)
-{
-    ScanContext *pCtx = (ScanContext *) pPrivate;
-
-    return pCtx->uSize;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static unsigned int CbScanRead(void *pPrivate, TCSOffset uOffset,
-                               void *pBuffer, unsigned int uSize)
-{
-    unsigned int uRead = 0;
-    ScanContext *pCtx = (ScanContext *) pPrivate;
-
-    if (uOffset < pCtx->uSize)
-    {
-        if ((uRead = pCtx->uSize - uOffset) > uSize)
-            uRead = uSize;
-    }
-    if (uRead)
-        memcpy(pBuffer, pCtx->pData + uOffset, uRead);
-
-    return uRead;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static unsigned int CbScanWrite(void *pPrivate, TCSOffset uOffset,
-                                void const *pBuffer, unsigned int uSize)
-{
-    unsigned int uWrite = 0;
-    ScanContext *pCtx = (ScanContext *) pPrivate;
-
-    if (uOffset < pCtx->uSize)
-    {
-        if ((uWrite = pCtx->uSize - uOffset) > uSize)
-            uWrite = uSize;
-    }
-    if (uWrite)
-        memcpy(pCtx->pData + uOffset, pBuffer, uWrite);
-
-    return uWrite;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static int CbScanSetSize(void *pPrivate, TCSOffset uSize)
-{
-
-    return 0;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-int CbScanCallback(void *pPrivate, int nReason, void *pParam)
-{
-    ScanContext *pCtx = (ScanContext *) pPrivate;
-    const char *pszMalName = NULL, *pszVarName = NULL;
-    int i, iTType = pCtx->pCurrentTestCase->iTestType;
-    int n = SampleGetCount(iTType);
-
-    /*
-     * Fix this is important since pParam could be different
-     * if the nReason is not DETECTED.
-     */
-    if (nReason != TCS_CB_DETECTED)
-        return 0;
-    TEST_ASSERT(nReason == TCS_CB_DETECTED);
-    TEST_ASSERT(pCtx->pCurrentTestCase->iPolarity == INFECTED_DATA);
-
-    pCtx->pCurrentTestCase->iInfected++;
-
-    for (i = 0; i < n; i++)
-    {
-        if (pCtx->pCurrentTestCase->pFlags[i])
-            continue;
-
-        pszMalName = SampleGetMalName(iTType, i);
-        if (pszMalName != NULL)
-        {
-            TEST_ASSERT(((TCSDetected *) pParam)->pszName != NULL);
-            if (((TCSDetected *) pParam)->pszName == NULL ||
-                strcmp(((TCSDetected *) pParam)->pszName, pszMalName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        pszVarName = SampleGetVarName(iTType, i);
-        if (pszVarName != NULL)
-        {
-            TEST_ASSERT(((TCSDetected *) pParam)->pszVariant != NULL);
-            if (((TCSDetected *) pParam)->pszVariant == NULL ||
-                strcmp(((TCSDetected *) pParam)->pszVariant, pszVarName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        TEST_ASSERT(TCS_ACTION_CLASS(((TCSDetected *) pParam)->uAction) ==
-                    SampleGetSeverity(iTType, i));
-
-        TEST_ASSERT(TCS_ACTION_BEHAVIOR(((TCSDetected *) pParam)->uAction) ==
-                    SampleGetBehavior(iTType, i));
-
-        pCtx->pCurrentTestCase->pFlags[i] = 1;
-        break;
-    }
-
-    TEST_ASSERT(i != n);
-
-    return 0;
-}
-
-
-/**
- * The difference between ScanFile and ScanBuffer is:
- * ScanBuffer is the helper function to test scan data.
- */
-static int ScanBuffer(TestCase *pCtx)
-{
-    int iFSize;
-    char *pData, *pszFilePath;
-
-    if ((pszFilePath = GetSamplePath(pCtx)) == NULL)
-        return -1;
-
-    if ((pData = LoadFile(pszFilePath, &iFSize)) == NULL)
-    {
-        PutSamplePath(pszFilePath);
-        return -1;
-    }
-
-    TEST_ASSERT(ScanBufferProc(pCtx, pData, iFSize) == 0);
-    PutLoadedFile(pData);
-    PutSamplePath(pszFilePath);
-
-    return 0;
-}
-
-
-/**
- * Scan file test helper function.
- */
-static int ScanFile(TestCase *pCtx)
-{
-    int iErr, iExpected = SampleGetCount(pCtx->iTestType);
-    TCSScanResult SR;
-    TCSLIB_HANDLE hLib;
-    char *pszFilePath;
-
-    if ((pszFilePath = GetSamplePath(pCtx)) == NULL)
-        return -1;
-
-    hLib = TCSLibraryOpen();
-    if (hLib == INVALID_TCSLIB_HANDLE)
-    {
-        PutSamplePath(pszFilePath);
-        return -1;
-    }
-
-    if (iExpected > 0)
-    {
-        pCtx->pFlags = (int *) calloc(iExpected, sizeof(int));
-        if (pCtx->pFlags == NULL)
-            TEST_ASSERT(0);
-    }
-    else
-        pCtx->pFlags = NULL;
-
-    if (pCtx->iAction == TCS_SA_SCANREPAIR && IsTestRepair() == 0)
-    {
-        TEST_ASSERT(TCSScanFile(hLib, pszFilePath,
-                                GetSampleDataType(pCtx->iTestType),
-                                pCtx->iAction, pCtx->iCompressFlag, &SR) == -1);
-        iErr = TCSGetLastError(hLib);
-        TEST_ASSERT(TCS_ERRMODULE(iErr) == TCS_ERROR_MODULE_GENERIC);
-        TEST_ASSERT(TCS_ERRCODE(iErr) == TCS_ERROR_NOT_IMPLEMENTED);
-    }
-    else
-    {
-        TEST_ASSERT(TCSScanFile(hLib, pszFilePath,
-                                GetSampleDataType(pCtx->iTestType),
-                                pCtx->iAction, pCtx->iCompressFlag, &SR) == 0);
-        if (pCtx->pFlags)
-            memset(pCtx->pFlags, 0, sizeof(int) * iExpected);
-
-
-        if (pCtx->iAction == TCS_SA_SCANONLY)
-        {
-            if (pCtx->iPolarity == INFECTED_DATA)
-            {
-                if (pCtx->iTestType == MALWARE_TTYPE_COMPRESS &&
-                    pCtx->iCompressFlag == 0)
-                /* Not suppose to detect when compress flag is
-                 * set to 0 for compressed samples. */
-                {
-                    TEST_ASSERT(SR.iNumDetected == 0);
-                }
-                else
-                {
-                    TEST_ASSERT(SR.iNumDetected == SampleGetCount(pCtx->iTestType));
-                    if (SR.iNumDetected == SampleGetCount(pCtx->iTestType))
-                        CheckDetectedList(pCtx, &SR);
-                }
-            }
-            else
-            {
-                TEST_ASSERT(SR.iNumDetected == 0);
-            }
-        }
-        else
-        {
-            /* Verify */
-            TEST_ASSERT(VerifyRepairFile(pCtx) == 0);
-        }
-        if (*SR.pfFreeResult != NULL)
-            (*SR.pfFreeResult)(&SR);
-    }
-
-    if (pCtx->pFlags)
-        free(pCtx->pFlags);
-
-    TCSLibraryClose(hLib);
-    PutSamplePath(pszFilePath);
-
-    return 0;
-}
-
-
-/**
- * Helper function for detected one malware.
- */
-static void CheckDetected(TestCase *pCtx, TCSDetected *pFound)
-{
-    const char *pszMalName = NULL, *pszVarName = NULL;
-    int i, iTType = pCtx->iTestType, n = SampleGetCount(iTType);
-
-    for (i = 0; i < n; i++)
-    {
-        if (pCtx->pFlags[i])
-            continue;
-
-        pszMalName = SampleGetMalName(iTType, i);
-        if (pszMalName != NULL)
-        {
-            TEST_ASSERT(pFound->pszName != NULL);
-            if (pFound->pszName == NULL ||
-                strcmp(pFound->pszName, pszMalName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        pszVarName = SampleGetVarName(iTType, i);
-        if (pszVarName != NULL)
-        {
-            TEST_ASSERT(pFound->pszVariant != NULL);
-            if (pFound->pszVariant == NULL ||
-                strcmp(pFound->pszVariant, pszVarName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        TEST_ASSERT(TCS_ACTION_CLASS(pFound->uAction) ==
-                    SampleGetSeverity(iTType, i));
-
-        TEST_ASSERT(TCS_ACTION_BEHAVIOR(pFound->uAction) ==
-                    SampleGetBehavior(iTType, i));
-
-        pCtx->pFlags[i] = 1;
-        break;
-    }
-
-    TEST_ASSERT(i != n);
-}
-
-
-/**
- * Helper function for detected malware list checking.
- */
-static void CheckDetectedList(TestCase *pCtx, TCSScanResult *pSR)
-{
-    TCSDetected *pFound = pSR->pDList;
-
-    while (pFound != NULL)
-    {
-        CheckDetected(pCtx, pFound);
-        pFound = pFound->pNext;
-    }
-}
-
-
-/**
- * Helper function for data scan, see ScanBuffer()
- */
-static int ScanBufferProc(TestCase *pCtx, char *pData, int iDataLen)
-{
-    TCSLIB_HANDLE hLib;
-    TCSScanParam SP = {0};
-    TCSScanResult SR = {0};
-    ScanContext ScanCtx = {0};
-    int iErr, iExpected = SampleGetCount(pCtx->iTestType);
-
-    hLib = TCSLibraryOpen();
-    if (hLib == INVALID_TCSLIB_HANDLE)
-        return -1;
-
-    ScanCtx.pData = pData;
-    ScanCtx.uSize = (unsigned int) iDataLen;
-    ScanCtx.pCurrentTestCase = pCtx;
-
-    if (iExpected > 0)
-    {
-        pCtx->pFlags = (int *) calloc(iExpected, sizeof(int));
-        if (pCtx->pFlags == NULL)
-            TEST_ASSERT(0);
-    }
-    else
-        pCtx->pFlags = NULL;
-
-    SP.iAction = pCtx->iAction;
-    SP.iDataType = GetSampleDataType(pCtx->iTestType);
-    SP.iCompressFlag = pCtx->iCompressFlag;
-    SP.pPrivate = &ScanCtx;
-    SP.pfGetSize = CbScanGetSize;
-    SP.pfSetSize = CbScanSetSize;
-    SP.pfRead = CbScanRead;
-    SP.pfWrite = CbScanWrite;
-    SP.pfCallBack = pCtx->pfCallback;
-
-    if (pCtx->pfCallback == &CbAbortCallback)
-    {
-        TEST_ASSERT(TCSScanData(hLib, &SP, &SR) == -1);
-        iErr = TCSGetLastError(hLib);
-    }
-    else if (pCtx->iAction == TCS_SA_SCANREPAIR && IsTestRepair() == 0)
-    {
-        TEST_ASSERT(TCSScanData(hLib, &SP, &SR) == -1);
-        iErr = TCSGetLastError(hLib);
-        TEST_ASSERT(TCS_ERRMODULE(iErr) == TCS_ERROR_MODULE_GENERIC);
-        TEST_ASSERT(TCS_ERRCODE(iErr) == TCS_ERROR_NOT_IMPLEMENTED);
-    }
-    else
-    {
-        TEST_ASSERT(TCSScanData(hLib, &SP, &SR) == 0);
-        if (pCtx->pFlags)
-            memset(pCtx->pFlags, 0, sizeof(int) * iExpected);
-
-        /* Make sure pfCallback is called as expected. */
-        if (pCtx->pfCallback == &CbScanCallback &&
-            pCtx->iAction == TCS_SA_SCANONLY &&
-            pCtx->iPolarity == INFECTED_DATA)
-        {
-            if (pCtx->iTestType == MALWARE_TTYPE_COMPRESS &&
-                pCtx->iCompressFlag == 0)
-            /* Not suppose to detect virus when compress flag is
-             * disabled for compress test sample */
-            {
-                TEST_ASSERT(SR.iNumDetected == 0);
-            }
-            else
-            {
-                TEST_ASSERT(pCtx->iInfected == iExpected);
-            }
-        }
-
-        if (pCtx->iAction == TCS_SA_SCANONLY)
-        {
-            if (pCtx->iPolarity == INFECTED_DATA)
-            {
-                if (pCtx->iTestType == MALWARE_TTYPE_COMPRESS &&
-                    pCtx->iCompressFlag == 0)
-                /* Not suppose to detect virus when compress flag is
-                 * disabled for compress test sample */
-                {
-                    TEST_ASSERT(SR.iNumDetected == 0);
-                }
-                else
-                {
-                    TEST_ASSERT(SR.iNumDetected == iExpected);
-                    if (SR.iNumDetected == iExpected)
-                        CheckDetectedList(pCtx, &SR);
-                }
-            }
-            else
-            {
-                TEST_ASSERT(SR.iNumDetected == 0);
-            }
-        }
-        else
-        {
-            TEST_ASSERT(VerifyRepairData(pCtx, ScanCtx.pData,
-                                         ScanCtx.uSize) == 0);
-        }
-
-        if (*SR.pfFreeResult)
-            (*SR.pfFreeResult)(&SR);
-    }
-
-    if (pCtx->pFlags)
-        free(pCtx->pFlags);
-
-    TCSLibraryClose(hLib);
-
-    return 0;
-}
-
-
-/**
- * Abort test callback helper function for data scan.
- */
-int CbAbortCallback(void *pPrivate, int nReason, void *pParam)
-{
-
-    return -1;
-}
-
-
-int CreateTestDirs(void)
-{
-    int iLen, iRet = -1;
-    char *pszCommand, *pszRoot = GetTestRoot(), *pszEnv, *pszBackup;
-
-    if (pszRoot != NULL)
-    {
-        pszBackup = GetBackupDir();
-        if (pszBackup != NULL)
-        {
-            iLen = MAX(strlen(pszRoot) * 2, strlen(pszBackup));
-            iLen += 64; /* Reserved for "mkdir -p", "cp -f " */
-            pszCommand = (char *) calloc(iLen + 1, sizeof(char));
-            if (pszCommand != NULL)
-            {
-                snprintf(pszCommand, iLen, "mkdir -p %s", pszRoot);
-                CallSys(pszCommand);
-                pszCommand[0] = 0;
-
-                snprintf(pszCommand, iLen, "mkdir -p %s", pszBackup);
-                CallSys(pszCommand);
-                pszCommand[0] = 0;
-
-                pszEnv = getenv("TCS_CONTENT_PATH");
-                if (pszEnv == NULL)
-                    pszEnv = "./";
-                if (pszEnv[strlen(pszEnv) - 1] == '/')
-                    snprintf(pszCommand, iLen, "cp -f %s* %s", pszEnv, pszRoot);
-                else
-                    snprintf(pszCommand, iLen, "cp -f %s/* %s", pszEnv, pszRoot);
-                CallSys(pszCommand);
-
-                free(pszCommand);
-
-                iRet = 0;
-            }
-            PutBackupDir(pszBackup);
-        }
-        PutTestRoot(pszRoot);
-    }
-
-    return iRet;
-}
-
-
-void DestoryTestDirs(void)
-{
-    int iLen, iEnvLen;
-    char *pszCommand, *pszEnv = getenv("TCS_CONTENT_PATH");
-
-    if (pszEnv == NULL || strlen(pszEnv) == 0)
-        pszEnv = "./";
-    iEnvLen = strlen(pszEnv);
-    iLen = iEnvLen;
-    iLen += 72; /* Reserved for "rm -rf" and PID */
-    pszCommand = (char *) calloc(iLen + 1, sizeof(char));
-    if (pszCommand != NULL)
-    {
-        if (pszEnv[iEnvLen - 1] == '/')
-            snprintf(pszCommand, iLen, "rm -rf %s%d", pszEnv, (int) getpid());
-        else
-            snprintf(pszCommand, iLen, "rm -rf %s/%d", pszEnv, (int) getpid());
-        CallSys(pszCommand);
-        free(pszCommand);
-    }
-}
-
-
-/**
- * Test framework helper function: get content files' root path.
- */
-static char *GetTestRoot(void)
-{
-    int iLen, iEnvLen;
-    char *pszRoot = NULL, *pszEnv = getenv("TCS_CONTENT_PATH");
-
-    if (pszEnv != NULL &&
-        (iEnvLen = strlen(pszEnv)) > 0)
-    {
-        iLen = iEnvLen;
-        iLen += 64; /* Reserved 64 bytes for PID. */
-        iLen += strlen(TCS_TEST_CONTENT_DIR);
-        pszRoot = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszRoot != NULL)
-        {
-            if (pszEnv[iEnvLen - 1] != '/')
-                snprintf(pszRoot, iLen, "%s/%d/%s", pszEnv, (int) getpid(),
-                         TCS_TEST_CONTENT_DIR);
-            else
-                snprintf(pszRoot, iLen, "%s%d/%s", pszEnv, (int) getpid(),
-                         TCS_TEST_CONTENT_DIR);
-        }
-    }
-    else
-    {
-        iLen = sizeof("./") + 64; /* Reserved 64 bytes for PID. */
-        pszRoot = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszRoot != NULL)
-        {
-            snprintf(pszRoot, iLen, "./%d", (int) getpid());
-        }
-    }
-
-    return pszRoot;
-}
-
-
-static void PutTestRoot(char *pszRoot)
-{
-
-    if (pszRoot != NULL)
-        free(pszRoot);
-}
-
-
-void TestCaseCtor(TestCase *pCtx, const char *pszAPI, int iTestType,
-                  int iPolarity, int iAction, PFScan pfCallback)
-{
-
-    TestCaseCtorEx(pCtx, pszAPI, iTestType, iPolarity, iAction, 1, pfCallback);
-}
-
-
-/**
- * Test case constructor.
- */
-static void TestCaseCtorEx(TestCase *pCtx, const char *pszAPI, int iTestType,
-                           int iPolarity, int iAction, int iCompressFlag,
-                           PFScan pfCallback)
-{
-
-    strncpy(pCtx->szAPIName, pszAPI, sizeof(pCtx->szAPIName) - 1);
-    pCtx->iInfected = 0;
-    pCtx->iTestType = iTestType;
-    pCtx->iPolarity = iPolarity;
-    pCtx->iAction = iAction;
-    pCtx->iCompressFlag = iCompressFlag;
-    pCtx->pfCallback = pfCallback;
-    pCtx->pFlags = NULL;
-    TEST_ASSERT(SaveTestContents() == 0);
-}
-
-
-/**
- * Test case destructor.
- */
-void TestCaseDtor(TestCase *pCtx)
-{
-
-    ReportTestCase(pCtx);
-    TEST_ASSERT(LoadTestContents() == 0);
-    Success++;
-}
-
-
-static char *GetBackupDir(void)
-{
-    int iLen, iEnvLen;
-    char *pszEnv = getenv("TCS_CONTENT_PATH"), *pszPath;
-
-    if (pszEnv == NULL || strlen(pszEnv) == 0)
-        pszEnv = "./";
-    iEnvLen = strlen(pszEnv);
-    iLen = iEnvLen;
-    iLen += strlen(TCS_BACKUP_CONTENT_DIR);
-    iLen += 64; /* Reserved for slash char and PID. */
-    pszPath = (char *) calloc(iLen + 1, sizeof(char));
-
-    if (pszPath)
-    {
-        if (pszEnv[iEnvLen - 1] == '/')
-            snprintf(pszPath, iLen, "%s%d/%s", pszEnv, (int) getpid(),
-                     TCS_BACKUP_CONTENT_DIR);
-        else
-            snprintf(pszPath, iLen, "%s/%d/%s", pszEnv, (int) getpid(),
-                     TCS_BACKUP_CONTENT_DIR);
-    }
-
-    return pszPath;
-}
-
-
-static void PutBackupDir(char *pszBackupDir)
-{
-
-    if (pszBackupDir != NULL)
-        free(pszBackupDir);
-}
-
-
-static int SaveTestContents(void)
-{
-    int iLen = 0, iRet = -1;
-    char *pszRoot = NULL, *pszCommand = NULL, *pszBackupDir = GetBackupDir();
-
-    if (pszBackupDir != NULL)
-    {
-        pszRoot = GetTestRoot();
-        if (pszRoot != NULL)
-        {
-            iLen = strlen(pszBackupDir);
-            iLen += strlen(pszRoot);
-            iLen += 32; /* Reserved for unix commmand. */
-
-            pszCommand = (char *) calloc(iLen, sizeof(char));
-            if (pszCommand != NULL)
-            {
-                snprintf(pszCommand, iLen - sizeof(char), "cp -f %s/* %s/",
-                         pszRoot, pszBackupDir);
-
-                CallSys(pszCommand);
-                free(pszCommand);
-                iRet = 0;
-            }
-
-            PutTestRoot(pszRoot);
-        }
-
-        PutBackupDir(pszBackupDir);
-    }
-
-    return iRet;
-}
-
-
-static int LoadTestContents(void)
-{
-    int iLen = 0, iRet = -1;
-    char *pszRoot = NULL, *pszCommand = NULL, *pszBackupDir = GetBackupDir();
-
-    if (pszBackupDir != NULL)
-    {
-        pszRoot = GetTestRoot();
-        if (pszRoot != NULL)
-        {
-            iLen = strlen(pszBackupDir);
-            iLen += strlen(pszRoot);
-            iLen += 32; /* Reserved for unix command. */
-
-            pszCommand = (char *) calloc(iLen, sizeof(char));
-            if (pszCommand != NULL)
-            {
-                snprintf(pszCommand, iLen - sizeof(char), "cp -f %s/* %s/",
-                         pszBackupDir, pszRoot);
-
-                CallSys(pszCommand);
-                free(pszCommand);
-                iRet = 0;
-            }
-            PutTestRoot(pszRoot);
-        }
-
-        PutBackupDir(pszBackupDir);
-    }
-
-    return iRet;
-}
-
-
-static char *GetSamplePath(TestCase *pCtx)
-{
-    const char *pszSampleFileName;
-    char *pszSamplePath = NULL, *pszRoot = GetTestRoot();
-    int iLen, iTType = pCtx->iTestType, iPolarity = pCtx->iPolarity;
-    char *pwd = getenv("PWD");
-
-    if (pszRoot != NULL)
-    {
-        pszSampleFileName = (iPolarity == INFECTED_DATA ?
-                             SampleGetInfectedFileName(iTType) :
-                             SampleGetBenignFileName(iTType));
-
-        iLen = strlen(pszRoot);
-        iLen += strlen(pszSampleFileName);
-        iLen++; /* Reserved for slash char. */
-        iLen += strlen(pwd) + 3;
-
-        pszSamplePath = (char *) calloc(iLen + 1, sizeof(char));
-
-        if (pszSamplePath != NULL)
-        {
-            if (pszRoot[strlen(pszRoot) - 1] == '/')
-                snprintf(pszSamplePath, iLen, "%s/%s%s", pwd, pszRoot, pszSampleFileName);
-            else
-                snprintf(pszSamplePath, iLen, "%s/%s/%s", pwd, pszRoot, pszSampleFileName);
-        }
-
-        PutTestRoot(pszRoot);
-    }
-
-    return pszSamplePath;
-}
-
-
-static void PutSamplePath(char *pszSamplePath)
-{
-
-    if (pszSamplePath != NULL)
-        free(pszSamplePath);
-}
-
-
-static int GetSampleDataType(int iTType)
-{
-    switch (iTType)
-    {
-    case MALWARE_TTYPE_BUFFER:
-        return TCS_DTYPE_UNKNOWN;
-    case MALWARE_TTYPE_HTML:
-        return TCS_DTYPE_HTML;
-    case MALWARE_TTYPE_URL:
-        return TCS_DTYPE_URL;
-    case MALWARE_TTYPE_EMAIL:
-        return TCS_DTYPE_EMAIL;
-    case MALWARE_TTYPE_PHONE:
-        return TCS_DTYPE_PHONE;
-    case MALWARE_TTYPE_TEXT:
-        return TCS_DTYPE_TEXT;
-    case MALWARE_TTYPE_JAVA:
-        return TCS_DTYPE_JAVA;
-    case MALWARE_TTYPE_JAVAS:
-        return TCS_DTYPE_JAVAS;
-    case MALWARE_TTYPE_MULTIPLE:
-        return TCS_DTYPE_UNKNOWN;
-    case MALWARE_TTYPE_COMPRESS:
-        return TCS_DTYPE_UNKNOWN;
-    default:
-        return 0; /* Unlikely be here. */
-    }
-}
-
-
-void TestScanData(const char *pszFunc, int iTType, int iPolarity,
-                  int iAction, PFScan pfCallback)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOREX(&TestCtx, pszFunc, iTType, iPolarity, iAction, 1, pfCallback);
-    ScanBuffer(&TestCtx);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-void TestScanFile(const char *pszFunc, int iTType, int iPolarity, int iAction)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOREX(&TestCtx, pszFunc, iTType, iPolarity, iAction, 1, NULL);
-    TEST_ASSERT(ScanFile(&TestCtx) == 0);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-void TestScanDataEx(const char *pszFunc, int iTType, int iPolarity,
-                    int iAction, int iCompressFlag, PFScan pfCallback)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOREX(&TestCtx, pszFunc, iTType, iPolarity, iAction,
-                   iCompressFlag, pfCallback);
-    TEST_ASSERT(ScanBuffer(&TestCtx) == 0);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-void TestScanFileEx(const char *pszFunc, int iTType, int iPolarity,
-                    int iAction, int iCompressFlag)
-{
-    TestCase TestCtx;
-
-    TESTCASECTOREX(&TestCtx, pszFunc, iTType, iPolarity,
-                   iAction, iCompressFlag, NULL);
-    TEST_ASSERT(ScanFile(&TestCtx) == 0);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static int BufferCompare(const char *pBuffer1, const char *pBuffer2, int iLen)
-{
-
-    return memcmp(pBuffer1, pBuffer2, iLen);
-}
-
-
-static int FileCompare(const char *pszFile1, const char *pszFile2)
-{
-    int iLen1 = 0, iLen2 = 0, iRet = -1;
-    char *pBuffer1 = NULL, *pBuffer2 = NULL;
-
-    pBuffer1 = LoadFile(pszFile1, &iLen1);
-    if (pBuffer1 != NULL)
-    {
-        pBuffer2 = LoadFile(pszFile2, &iLen2);
-        if (pBuffer2 != NULL)
-        {
-            if (iLen1 != iLen2)
-                iRet = iLen1 - iLen2;
-
-            iRet = BufferCompare(pBuffer1, pBuffer2, iLen1);
-            PutLoadedFile(pBuffer2);
-        }
-        PutLoadedFile(pBuffer1);
-    }
-
-    return iRet;
-}
-
-
-static int ConInfectedFile(int iType, int iCompressFlag, const char *pszPath)
-{
-    int iRet = -1;
-    TCSScanResult SR = {0};
-    TCSLIB_HANDLE hLib = INVALID_TCSLIB_HANDLE;
-
-    hLib = TCSLibraryOpen();
-    if (hLib == INVALID_TCSLIB_HANDLE)
-        return -1;
-    iRet = TCSScanFile(hLib, pszPath, GetSampleDataType(iType),
-                       TCS_SA_SCANONLY, iCompressFlag, &SR);
-    if (iRet != 0)
-    {
-        TCSLibraryClose(hLib);
-        return -1;
-    }
-    iRet = SR.iNumDetected;
-    if (SR.pfFreeResult != NULL)
-        SR.pfFreeResult(&SR);
-    TCSLibraryClose(hLib);
-
-    return iRet;
-}
-
-
-static int ConInfected(int iType, int iCompressFlag, char *pData, int iDataLen)
-{
-    int iRet = -1;
-    TCSScanParam SP = {0};
-    TCSScanResult SR = {0};
-    ScanContext ScanCtx = {0};
-    TCSLIB_HANDLE hLib = INVALID_TCSLIB_HANDLE;
-
-    ScanCtx.pData = pData;
-    ScanCtx.uSize = (unsigned int) iDataLen;
-
-    SP.iAction = TCS_SA_SCANONLY;
-    SP.iDataType = GetSampleDataType(iType);
-    SP.iCompressFlag = iCompressFlag;
-    SP.pPrivate = &ScanCtx;
-    SP.pfGetSize = CbScanGetSize;
-    SP.pfSetSize = CbScanSetSize;
-    SP.pfRead = CbScanRead;
-    SP.pfWrite = CbScanWrite;
-    SP.pfCallBack = NULL;
-
-    hLib = TCSLibraryOpen();
-    if (hLib == INVALID_TCSLIB_HANDLE)
-        return -1;
-    iRet = TCSScanData(hLib, &SP, &SR);
-    if (iRet != 0)
-    {
-        TCSLibraryClose(hLib);
-        return -1;
-    }
-    iRet = SR.iNumDetected;
-    if (SR.pfFreeResult != NULL)
-        SR.pfFreeResult(&SR);
-    TCSLibraryClose(hLib);
-
-    return iRet;
-}
-
-
-static int InfectedFile(TestCase *pCtx, const char *pszPath)
-{
-    int iRet = -1;
-    TCSScanResult SR = {0};
-    TCSLIB_HANDLE hLib = INVALID_TCSLIB_HANDLE;
-
-    hLib = TCSLibraryOpen();
-    TEST_ASSERT(hLib != INVALID_TCSLIB_HANDLE);
-    TEST_ASSERT(TCSScanFile(hLib, pszPath,
-                            GetSampleDataType(pCtx->iTestType),
-                            TCS_SA_SCANONLY, pCtx->iCompressFlag, &SR) == 0);
-    iRet = SR.iNumDetected;
-    if (SR.pfFreeResult != NULL)
-        SR.pfFreeResult(&SR);
-    TCSLibraryClose(hLib);
-
-    return iRet;
-}
-
-
-static int Infected(TestCase *pCtx, char *pData, int iDataLen)
-{
-    int iRet = -1;
-    TCSScanParam SP = {0};
-    TCSScanResult SR = {0};
-    ScanContext ScanCtx = {0};
-    TCSLIB_HANDLE hLib = INVALID_TCSLIB_HANDLE;
-
-    ScanCtx.pData = pData;
-    ScanCtx.uSize = (unsigned int) iDataLen;
-    ScanCtx.pCurrentTestCase = pCtx;
-
-    SP.iAction = TCS_SA_SCANONLY;
-    SP.iDataType = GetSampleDataType(pCtx->iTestType);
-    SP.iCompressFlag = pCtx->iCompressFlag;
-    SP.pPrivate = &ScanCtx;
-    SP.pfGetSize = CbScanGetSize;
-    SP.pfSetSize = CbScanSetSize;
-    SP.pfRead = CbScanRead;
-    SP.pfWrite = CbScanWrite;
-    SP.pfCallBack = NULL;
-
-    hLib = TCSLibraryOpen();
-    TEST_ASSERT(hLib != INVALID_TCSLIB_HANDLE);
-    TEST_ASSERT(TCSScanData(hLib, &SP, &SR) == 0);
-    iRet = SR.iNumDetected;
-    if (SR.pfFreeResult != NULL)
-        SR.pfFreeResult(&SR);
-    TCSLibraryClose(hLib);
-
-    return iRet;
-}
-
-
-static int VerifyRepairData(TestCase *pCtx, const char *pRepairedBuffer,
-                            int iRepairedLen)
-{
-
-    return Infected(pCtx, pRepairedBuffer, iRepairedLen);
-}
-
-
-static int VerifyRepairFile(TestCase *pCtx)
-{
-
-    return InfectedFile(pCtx, GetSamplePath(pCtx));
-}
-
-
-static void ConTestCaseCtor(ConTestContext *pConCtx, int iCid, TestCase *pCtx)
-{
-
-    pConCtx->pTestCtx = pCtx;
-    pConCtx->iCid = iCid;
-    pConCtx->iConTestRet = 0; /* running. */
-}
-
-
-static void ConTestCaseDtor(ConTestContext *pConCtx)
-{
-
-}
-
-
-static char *GetBenignSamplePath(int iTType)
-{
-    int iLen, iRootLen;
-    char *pszSamplePath = NULL, *pszRoot = GetTestRoot();
-    const char *pszSampleFileName = NULL;
-
-    if (pszRoot != NULL)
-    {
-        pszSampleFileName = SampleGetBenignFileName(iTType);
-        iRootLen = strlen(pszRoot);
-        iLen = iRootLen;
-        iLen += strlen(pszSampleFileName);
-        iLen += 2; /* Slash char and \0 */
-
-        pszSamplePath = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszSamplePath != NULL)
-        {
-            if (pszRoot[iRootLen - 1] == '/')
-                snprintf(pszSamplePath, iLen, "%s%s", pszRoot, pszSampleFileName);
-            else
-                snprintf(pszSamplePath, iLen, "%s/%s", pszRoot, pszSampleFileName);
-        }
-        PutTestRoot(pszRoot);
-    }
-
-    return pszSamplePath;
-}
-
-
-static void PutBenignSamplePath(char *pszPath)
-{
-    if (pszPath != NULL)
-        free(pszPath);
-}
-
-
-static int ConVerifyRepairData(int iTType, int iCompressFlag, const char *pRepairedBuffer,
-                               int iRepairedLen)
-{
-
-    return ConInfected(iTType, iCompressFlag, pRepairedBuffer, iRepairedLen);
-}
-
-
-static int ConVerifyRepairFile(char *pszSamplePath, int iTType, int iCompressFlag)
-{
-
-    return ConInfectedFile(iTType, iCompressFlag, pszSamplePath);
-}
-
-
-static int ConTestComplete(ConTestContext *pConCtxAry)
-{
-    int i;
-
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-    {
-        if (pConCtxAry[i].iConTestRet == 0)
-            return 0; /* not complete */
-    }
-
-    return 1; /* Complete */
-}
-
-
-static int ConTestSuccess(ConTestContext *pConCtxAry)
-{
-    int i;
-
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-    {
-        if (pConCtxAry[i].iConTestRet != 1)
-            return 0; /* failure */
-    }
-
-    return 1; /* success */
-}
-
-
-static void ReleaseTestObject(ConTestContext *pConCtx, int iResult)
-{
-
-    pthread_mutex_lock(&g_Mutex);
-    pConCtx->iConTestRet = iResult;
-    pthread_cond_broadcast(&g_Cond);
-    pthread_mutex_unlock(&g_Mutex);
-}
-
-
-static int ConCheckDetected(int iTType, TCSDetected *pFound, int *pFlags)
-{
-    const char *pszMalName = NULL, *pszVarName = NULL;
-    int i, n = SampleGetCount(iTType), iRet = 0;
-
-    for (i = 0; i < n; i++)
-    {
-        if (pFlags[i])
-            continue;
-
-        pszMalName = SampleGetMalName(iTType, i);
-        if (pszMalName != NULL)
-        {
-            if (pFound->pszName == NULL ||
-                strcmp(pFound->pszName, pszMalName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        pszVarName = SampleGetVarName(iTType, i);
-        if (pszVarName != NULL)
-        {
-            if (pFound->pszVariant == NULL ||
-                strcmp(pFound->pszVariant, pszVarName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        if (TCS_ACTION_CLASS(pFound->uAction) != SampleGetSeverity(iTType, i))
-            iRet = -1;
-
-        if (TCS_ACTION_BEHAVIOR(pFound->uAction) != SampleGetBehavior(iTType, i))
-            iRet = -1;
-
-        pFlags[i] = 1;
-        break;
-    }
-
-    if (i >= n)
-        iRet = -1;
-
-    return iRet;
-}
-
-
-static int ConCheckDetectedList(int iTType, TCSScanResult *pSR, int *pFlags)
-{
-    int iRet = 0;
-    TCSDetected *pFound = pSR->pDList;
-
-    while (pFound != NULL)
-    {
-        iRet = ConCheckDetected(iTType, pFound, pFlags);
-        if (iRet == -1)
-            break;
-        pFound = pFound->pNext;
-    }
-
-    return iRet;
-}
-
-
-static void *ConScanDataSCProc(void *pConCtxParam)
-{
-    ConTestContext *pConCtx = (ConTestContext *) pConCtxParam;
-
-    ConScanDataProc(pConCtx, TCS_SA_SCANONLY);
-
-    return NULL;
-}
-
-
-static void *ConScanDataSRProc(void *pConCtxParam)
-{
-    ConTestContext *pConCtx = (ConTestContext *) pConCtxParam;
-
-    ConScanDataProc(pConCtx, TCS_SA_SCANREPAIR);
-
-    return NULL;
-}
-
-
-static void ConScanDataProc(ConTestContext *pConCtx, int iAction)
-{
-    TCSLIB_HANDLE hLib;
-    TCSScanParam SP;
-    TCSScanResult SR = {0};
-    ConScanContext ScanCtx = {0};
-    char *pszSamplePath = NULL, *pData;
-    int i, j, iDataLen = 0, iCid= pConCtx->iCid, iOldType, iExpected;
-    int *pFlags;
-
-    CONTEST_START
-
-    pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &iOldType);
-
-    i = MALWARE_TTYPE_BUFFER;
-    for (i = MALWARE_TTYPE_BUFFER; i < MALWARE_TTYPE_MULTIPLE; i++)
-    {
-        if ((iExpected = SampleGetCount(i)) > 0)
-        {
-            pFlags = (int *) malloc(sizeof(int) * iExpected);
-            if (pFlags == NULL)
-                CONTEST_ERROR
-        }
-        else
-            pFlags = NULL;
-
-        for (j = BENIGN_DATA; j <= INFECTED_DATA; j++)
-        {
-            hLib = TCSLibraryOpen();
-            if (hLib != INVALID_TCSLIB_HANDLE)
-            {
-                /* Test benign data. */
-                pszSamplePath = ConGetSamplePath(i, j, iCid);
-                pData = LoadFile(pszSamplePath, &iDataLen);
-
-                ConPutSamplePath(pszSamplePath);
-                ScanCtx.pData = pData;
-                ScanCtx.uSize = (unsigned int) iDataLen;
-                ScanCtx.iTestType = i;
-                ScanCtx.iInfected = 0;
-                ScanCtx.iPolarity = j;
-                ScanCtx.iTestRet = 1;
-                ScanCtx.pFlags = pFlags;
-
-                SP.iAction = iAction;
-                SP.iDataType = GetSampleDataType(i);
-                SP.pPrivate = &ScanCtx;
-                SP.pfGetSize = ConCbScanGetSize;
-                SP.pfSetSize = ConCbScanSetSize;
-                SP.pfRead = ConCbScanRead;
-                SP.pfWrite = ConCbScanWrite;
-                SP.pfCallBack = ConCbScanCallback;
-
-                if (pFlags)
-                    memset(pFlags, 0, sizeof(int) * iExpected);
-
-                if (TCSScanData(hLib, &SP, &SR) == 0)
-                {
-                    if (pFlags)
-                        memset(pFlags, 0, sizeof(int) * iExpected);
-
-                    if (j == BENIGN_DATA)
-                    {
-                        CONTEST_ASSERT(SR.iNumDetected == 0)
-                    }
-                    else
-                    {
-                        if (iAction == TCS_SA_SCANONLY)
-                        {
-                            CONTEST_ASSERT(SR.iNumDetected == iExpected &&
-                                           ConCheckDetectedList(i, &SR, pFlags) == 0)
-                        }
-                        else /* Repair */
-                        {
-                            CONTEST_ASSERT(ConVerifyRepairData(i, pConCtx->pTestCtx->iCompressFlag,
-                                                               ScanCtx.pData, ScanCtx.uSize) == 0)
-                        }
-                    }
-
-                    CONTEST_ASSERT(ScanCtx.iTestRet == 1)
-                    (*SR.pfFreeResult)(&SR);
-                }
-                else
-                {
-                    CONTEST_ERROR
-                }
-
-                PutLoadedFile(pData);
-
-                TCSLibraryClose(hLib);
-            }
-            else
-            {
-                CONTEST_ERROR
-            }
-
-            pthread_testcancel();
-            usleep(SLEEP_INTERVAL);
-            pthread_testcancel();
-        }
-
-        if (pFlags)
-            free(pFlags);
-    }
-    CONTEST_RELEASE(pConCtx);
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static TCSOffset ConCbScanGetSize(void *pPrivate)
-{
-    ConScanContext *pCtx = (ConScanContext *) pPrivate;
-
-    return pCtx->uSize;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static unsigned int ConCbScanRead(void *pPrivate, TCSOffset uOffset,
-                               void *pBuffer, unsigned int uSize)
-{
-    unsigned int uRead = 0;
-    ConScanContext *pCtx = (ConScanContext *) pPrivate;
-
-    if (uOffset < pCtx->uSize)
-    {
-        if ((uRead = pCtx->uSize - uOffset) > uSize)
-            uRead = uSize;
-    }
-    if (uRead)
-        memcpy(pBuffer, pCtx->pData + uOffset, uRead);
-
-    return uRead;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static unsigned int ConCbScanWrite(void *pPrivate, TCSOffset uOffset,
-                                   void const *pBuffer, unsigned int uSize)
-{
-    unsigned int uWrite = 0;
-    ConScanContext *pCtx = (ConScanContext *) pPrivate;
-
-    if (uOffset < pCtx->uSize)
-    {
-        if ((uWrite = pCtx->uSize - uOffset) > uSize)
-            uWrite = uSize;
-    }
-    if (uWrite)
-        memcpy(pCtx->pData + uOffset, pBuffer, uWrite);
-
-    return uWrite;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static int ConCbScanSetSize(void *pPrivate, TCSOffset uSize)
-{
-
-    return 0;
-}
-
-
-/**
- * Callback helper for data scan, please reference API
- * specification for more information about data scan.
- */
-static int ConCbScanCallback(void *pPrivate, int nReason, void *pParam)
-{
-    ConScanContext *pCtx = (ConScanContext *) pPrivate;
-    const char *pszMalName = NULL, *pszVarName = NULL;
-    int i, iTType = pCtx->iTestType, n = SampleGetCount(iTType);
-
-    CONTEST_START
-
-    /*
-     * Fix this is important since pParam could be different
-     * if the nReason is not DETECTED.
-     */
-    if (nReason != TCS_CB_DETECTED)
-        return 0;
-
-    CONTEST_ASSERT(nReason == TCS_CB_DETECTED)
-    CONTEST_ASSERT(pCtx->iPolarity == INFECTED_DATA)
-
-    pCtx->iInfected++;
-
-    for (i = 0; i < n; i++)
-    {
-        if (pCtx->pFlags[i])
-            continue;
-
-        pszMalName = SampleGetMalName(iTType, i);
-        if (pszMalName != NULL)
-        {
-            CONTEST_ASSERT(pParam != NULL);
-            CONTEST_ASSERT(((TCSDetected *) pParam)->pszName != NULL);
-            if (((TCSDetected *) pParam)->pszName == NULL ||
-                strcmp(((TCSDetected *) pParam)->pszName, pszMalName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        pszVarName = SampleGetVarName(iTType, i);
-        if (pszVarName != NULL)
-        {
-            CONTEST_ASSERT(((TCSDetected *) pParam)->pszVariant != NULL);
-            if (((TCSDetected *) pParam)->pszVariant == NULL ||
-                strcmp(((TCSDetected *) pParam)->pszVariant, pszVarName) != 0)
-                continue;
-        }
-        else
-        {
-            continue;
-        }
-        CONTEST_ASSERT(TCS_ACTION_CLASS(((TCSDetected *) pParam)->uAction) ==
-                       SampleGetSeverity(iTType, i));
-
-        CONTEST_ASSERT(TCS_ACTION_BEHAVIOR(((TCSDetected *) pParam)->uAction) ==
-                       SampleGetBehavior(iTType, i));
-
-        pCtx->pFlags[i] = 1;
-        break;
-    }
-
-    CONTEST_ASSERT(i != n);
-
-    CONTEST_RETURN(pCtx->iTestRet)
-
-    return 0;
-}
-
-
-void ConScanData(TestCase *pCtx, int iAction)
-{
-    int i, iRet = 0;
-    ConTestContext ConCtxs[MAX_TEST_THREADS];
-    pthread_t Threads[MAX_TEST_THREADS];
-
-    /* Prepare for concurrency tests. */
-    ConCreateSampleDirs();
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-        ConTestCaseCtor(&ConCtxs[i], i + 1, pCtx);
-
-    /* Concurrency tests. */
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-    {
-        if (iAction == TCS_SA_SCANONLY)
-            pthread_create(&Threads[i], NULL, ConScanDataSCProc, &ConCtxs[i]);
-        else
-            pthread_create(&Threads[i], NULL, ConScanDataSRProc, &ConCtxs[i]);
-    }
-
-    /* Wait for all tests completed. */
-    iRet = ConWaitOnTestCond(&ConCtxs[0]);
-    if (iRet == ETIMEDOUT)
-    {
-        usleep(SLEEP_INTERVAL);
-        /* Cancel them all, if timeout. */
-        for (i = 0; i < MAX_TEST_THREADS; i++)
-        {
-            pthread_cancel(Threads[i]);
-            /* Wait for cancelling. */
-            usleep(SLEEP_INTERVAL);
-        }
-    }
-
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-        pthread_join(Threads[i], NULL);
-
-    /* Check test result. */
-    TEST_ASSERT(ConTestSuccess(&ConCtxs[0]) == 1);
-
-    /* Release concurrency tests. */
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-        ConTestCaseDtor(&ConCtxs[i]);
-    ConDestorySampleDirs();
-}
-
-
-static void *ConScanFileSCProc(void *pConCtxParam)
-{
-    ConTestContext *pConCtx = (ConTestContext *) pConCtxParam;
-
-    ConScanFileProc(pConCtx, TCS_SA_SCANONLY);
-
-    return NULL;
-}
-
-
-static void *ConScanFileSRProc(void *pConCtxParam)
-{
-    ConTestContext *pConCtx = (ConTestContext *) pConCtxParam;
-
-    ConScanFileProc(pConCtx, TCS_SA_SCANREPAIR);
-
-    return NULL;
-}
-
-
-static void ConScanFileProc(ConTestContext *pConCtx, int iAction)
-{
-    TCSLIB_HANDLE hLib;
-    TCSScanResult SR = {0};
-    char *pszSamplePath = NULL;
-    int i, j, iOldType, iCid = pConCtx->iCid, iExpected;
-    int *pFlags;
-
-    CONTEST_START
-
-    pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &iOldType);
-
-    for (i = MALWARE_TTYPE_BUFFER; i < MALWARE_TTYPE_MULTIPLE; i++)
-    {
-        if ((iExpected = SampleGetCount(i)) > 0)
-        {
-            pFlags = (int *) malloc(sizeof(int) * iExpected);
-            if (pFlags == NULL)
-                CONTEST_ERROR
-        }
-        else
-            pFlags = NULL;
-
-        for (j = BENIGN_DATA; j <= INFECTED_DATA; j++)
-        {
-            hLib = TCSLibraryOpen();
-            if (hLib != INVALID_TCSLIB_HANDLE)
-            {
-                /* Test benign data. */
-                pszSamplePath = ConGetSamplePath(i, j, iCid);
-
-                if (TCSScanFile(hLib, pszSamplePath, GetSampleDataType(i),
-                                iAction, pConCtx->pTestCtx->iCompressFlag, &SR) == 0)
-                {
-                    if (pFlags)
-                        memset(pFlags, 0, sizeof(int) * iExpected);
-
-                    if (j == BENIGN_DATA)
-                    {
-                        CONTEST_ASSERT(SR.iNumDetected == 0)
-                    }
-                    else
-                    {
-                        if (iAction == TCS_SA_SCANONLY)
-                        {
-                            CONTEST_ASSERT(SR.iNumDetected == iExpected &&
-                                           ConCheckDetectedList(i, &SR, pFlags) == 0)
-                        }
-                        else /* Repair */
-                        {
-                            CONTEST_ASSERT(ConVerifyRepairFile(pszSamplePath, i,
-                                           pConCtx->pTestCtx->iCompressFlag) == 0)
-                        }
-                    }
-
-                    (*SR.pfFreeResult)(&SR);
-                }
-                else
-                {
-                    CONTEST_ERROR
-                }
-                ConPutSamplePath(pszSamplePath);
-                TCSLibraryClose(hLib);
-            }
-            else
-            {
-                CONTEST_ERROR
-            }
-
-            pthread_testcancel();
-            usleep(SLEEP_INTERVAL);
-            pthread_testcancel();
-        }
-
-        if (pFlags)
-            free(pFlags);
-    }
-
-    CONTEST_RELEASE(pConCtx)
-}
-
-
-static int ConWaitOnTestCond(ConTestContext *pConCtxAry)
-{
-    int iRet;
-    struct timeval Now;
-    struct timespec Timeout;
-
-    gettimeofday(&Now, NULL);
-    Timeout.tv_sec = Now.tv_sec + DEFAULT_CONCURRENCY_TEST_TIMEOUT;
-    Timeout.tv_nsec = Now.tv_usec * 1000;
-    iRet = 0;
-
-    pthread_mutex_lock(&g_Mutex);
-    while (ConTestComplete(pConCtxAry) != 1 && iRet != ETIMEDOUT)
-        iRet = pthread_cond_timedwait(&g_Cond, &g_Mutex, &Timeout);
-    pthread_mutex_unlock(&g_Mutex);
-
-    return iRet;
-}
-
-
-void ConScanFile(TestCase *pCtx, int iAction)
-{
-    int i, iRet = 0;
-    ConTestContext ConCtxs[MAX_TEST_THREADS];
-    pthread_t Threads[MAX_TEST_THREADS];
-
-    /* Prepare for concurrency tests. */
-    ConCreateSampleDirs();
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-        ConTestCaseCtor(&ConCtxs[i], i + 1, pCtx);
-
-    /* Concurrency tests. */
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-    {
-        if (iAction == TCS_SA_SCANONLY)
-            pthread_create(&Threads[i], NULL, ConScanFileSCProc, &ConCtxs[i]);
-        else
-            pthread_create(&Threads[i], NULL, ConScanFileSRProc, &ConCtxs[i]);
-    }
-    /* Wait for all tests completed. */
-    iRet = ConWaitOnTestCond(&ConCtxs[0]);
-    if (iRet == ETIMEDOUT)
-    {
-        usleep(SLEEP_INTERVAL);
-        /* Cancel them all, if timeout. */
-        for (i = 0; i < MAX_TEST_THREADS; i++)
-        {
-            pthread_cancel(Threads[i]);
-            /* Wait for cancelling. */
-            usleep(SLEEP_INTERVAL);
-        }
-    }
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-        pthread_join(Threads[i], NULL);
-    
-    /* Check test result. */
-    TEST_ASSERT(ConTestSuccess(ConCtxs) == 1);
-
-    /* Release concurrency tests. */
-    for (i = 0; i < MAX_TEST_THREADS; i++)
-        ConTestCaseDtor(&ConCtxs[i]);
-    ConDestorySampleDirs();
-}
-
-
-static char *ConGetSampleDir(int iCid)
-{
-    int iLen;
-    char *pszDir = NULL, *pszRoot = GetTestRoot();
-
-    if (pszRoot != NULL)
-    {
-        iLen = strlen(pszRoot);
-        iLen++; /* Reserved for slash char. */
-        iLen += 64; /* Reserved for thread id. */
-
-        pszDir = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszDir != NULL)
-        {
-            if (pszRoot[strlen(pszRoot) - 1] == '/')
-                snprintf(pszDir, iLen, "%s%s/t-%d", pszRoot, CONTENTS_ROOT, iCid);
-            else
-                snprintf(pszDir, iLen, "%s/%s/t-%d", pszRoot, CONTENTS_ROOT, iCid);
-        }
-        PutTestRoot(pszRoot);
-    }
-
-    return pszDir;
-}
-
-
-static void ConPutSampleDir(char *pszDir)
-{
-    if (pszDir != NULL)
-        free(pszDir);
-}
-
-
-static void ConCreateSampleDirs(void)
-{
-    int i, iLen, iRootLen;
-    char *pszRoot = GetTestRoot(), *pszCommand;
-
-    if (pszRoot != NULL)
-    {
-        for (i = 0; i < MAX_TEST_THREADS; i++)
-        {
-            iRootLen = strlen(pszRoot);
-            iLen = iRootLen * 2;
-            iLen += 72; /* Reserved for "mkdir t-" , "cp -f "*/
-            pszCommand = (char *) calloc(iLen + 1, sizeof(char));
-            if (pszCommand)
-            {
-                if (pszRoot[iRootLen - 1] == '/')
-                    snprintf(pszCommand, iLen, "mkdir -p %s%st-%d", pszRoot, CONTENTS_ROOT, i + 1);
-                else
-                    snprintf(pszCommand, iLen, "mkdir -p %s/%s/t-%d", pszRoot, CONTENTS_ROOT, i + 1);
-                CallSys(pszCommand);
-
-                pszCommand[0] = 0;
-                if (pszRoot[iRootLen - 1] == '/')
-                    snprintf(pszCommand, iLen, "cp -f %s*.* %s%s/t-%d/",
-                             pszRoot, pszRoot, CONTENTS_ROOT, i + 1);
-                else
-                    snprintf(pszCommand, iLen, "cp -f %s/*.* %s/%s/t-%d/",
-                             pszRoot, pszRoot, CONTENTS_ROOT, i + 1);
-                CallSys(pszCommand);
-
-                free(pszCommand);
-                pszCommand = NULL;
-            }
-        }
-        PutTestRoot(pszRoot);
-    }
-}
-
-
-static void ConDestorySampleDirs(void)
-{
-    int iLen, iRootLen;
-    char *pszRoot = GetTestRoot(), *pszCommand;
-
-    if (pszRoot != NULL)
-    {
-        iRootLen = strlen(pszRoot);
-        iLen = iRootLen;
-        iLen += 72; /* "rm -rf "*/
-        pszCommand = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszCommand)
-        {
-            if (pszRoot[iRootLen - 1] == '/')
-                snprintf(pszCommand, iLen, "rm -rf %s%s/t-*", pszRoot, CONTENTS_ROOT);
-            else
-                snprintf(pszCommand, iLen, "rm -rf %s/%s/t-*", pszRoot, CONTENTS_ROOT);
-            CallSys(pszCommand);
-
-            free(pszCommand);
-            pszCommand = NULL;
-        }
-        PutTestRoot(pszRoot);
-    }
-}
-
-
-static char *ConGetSamplePath(int iTType, int iPolarity, int iCid)
-{
-    int iLen, iDirLen;
-    const char *pszSampleFileName;
-    char *pszSamplePath = NULL, *pszDir = ConGetSampleDir(iCid);
-    char *pwd = getenv("PWD");
-
-    if (pszDir != NULL)
-    {
-        pszSampleFileName = (iPolarity == INFECTED_DATA ?
-                             SampleGetInfectedFileName(iTType) :
-                             SampleGetBenignFileName(iTType));
-
-        iDirLen = strlen(pszDir);
-        iLen = iDirLen;
-        iLen += strlen(pszSampleFileName);
-        iLen++; /* Reserved for slash char. */
-        iLen++; /* Reserved for \0. */
-        iLen += strlen(pwd) + 1;
-
-        pszSamplePath = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszSamplePath != NULL)
-        {
-            if (pszDir[iDirLen - 1] == '/')
-                snprintf(pszSamplePath, iLen, "%s/%s%s", pwd, pszDir, pszSampleFileName);
-            else
-                snprintf(pszSamplePath, iLen, "%s/%s/%s", pwd, pszDir, pszSampleFileName);
-        }
-        ConPutSampleDir(pszDir);
-    }
-
-    return pszSamplePath;
-}
-
-
-static void ConPutSamplePath(char *pszSamplePath)
-{
-
-    if (pszSamplePath != NULL)
-        free(pszSamplePath);
-}
-
-
-int DetectRepairFunc(void)
-{
-    int iRet = 0; /* Not support by default. */
-    TCSScanResult SR = {0};
-    char *pszTestSamplePath;
-    TCSLIB_HANDLE hLib = INVALID_TCSLIB_HANDLE;
-
-    hLib = TCSLibraryOpen();
-    if (hLib != INVALID_TCSLIB_HANDLE)
-    {
-        pszTestSamplePath = GetBenignSamplePath(MALWARE_TTYPE_BUFFER);
-        if (pszTestSamplePath != NULL)
-        {
-            if (TCSScanFile(hLib, pszTestSamplePath,
-                            GetSampleDataType(MALWARE_TTYPE_BUFFER),
-                            TCS_SA_SCANREPAIR, 1, &SR) == 0)
-            {
-                (*SR.pfFreeResult)(&SR);
-                iRet = 1; /* Supported. */
-            }
-
-            PutBenignSamplePath(pszTestSamplePath);
-        }
-        TCSLibraryClose(hLib);
-    }
-
-    return iRet;
-}
-
-
-int IsTestRepair()
-{
-    const char *pszType = getenv("TCS_SCAN_TYPE");
-    if (pszType != NULL)
-        return atoi(pszType);
-
-    return 0;
-}
-
-
-void BackupEngine()
-{
-    char *pszRoot = GetTestRoot(), *pszCommand;
-
-    if (pszRoot != NULL)
-    {
-        asprintf(&pszCommand, "mkdir %s/backup", pszRoot);
-        CallSys(pszCommand);
-        free(pszCommand);
-
-        asprintf(&pszCommand, "cp -f %s %s/backup", PLUGIN_PATH, pszRoot);
-        CallSys(pszCommand);
-        free(pszCommand);
-
-        PutTestRoot(pszRoot);
-    }
-}
-
-
-void RestoreEngine()
-{
-    char *pszRoot = GetTestRoot(), *pszCommand;
-
-    if (pszRoot != NULL)
-    {
-        asprintf(&pszCommand, "cp -f %s/backup/libengine.so %s", pszRoot, PLUGIN_DIR);
-        CallSys(pszCommand);
-        free(pszCommand);
-
-        PutTestRoot(pszRoot);
-    }
-}
-
-
-void CallSys(const char *pszCmd)
-{
-    int iRet = system(pszCmd);
-    if (iRet != 0)
-    {
-        // LOG_OUT("system returns %d for command %s\n", iRet, pszCmd);
-    }
-}
-
diff --git a/test/TWPTest.c b/test/TWPTest.c
deleted file mode 100644 (file)
index ee72e97..0000000
+++ /dev/null
@@ -1,1176 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <errno.h>
-#include <string.h>
-#include <assert.h>
-#include <time.h>
-#include "TWPImpl.h"
-
-#include "XMHttp.h"
-#include "TWPTest.h"
-#include "UrlInfo.h"
-
-/* Test cases. */
-static void TWPStartup(void);
-static void TWPCleanup(void);
-static void TWPInitLibrary_0001(void);
-static void TWPInitLibrary_0002(void);
-static void TWPInitLibrary_0003(void);
-static void TWPInitLibrary_0004(void);
-static void TWPConfigurationCreate_0001(void);
-static void TWPConfigurationCreate_0002(void);
-static void TWPConfigurationCreate_0003(void);
-static void TWPPolicyCreate_0001(void);
-static void TWPPolicyCreate_0002(void);
-static void TWPPolicyCreate_0003(void);
-static void TWPLookupUrls_0001(void);
-static void TWPLookupUrls_0002(void);
-static void TWPLookupUrls_0003(void);
-static void TWPLookupUrls_0004(void);
-static void TWPLookupUrls_0005(void);
-static void TWPGetUrlRating_0001(void);
-static void TWPGetUrlRating_0002(void);
-static void TWPGetUrlRating_0003(void);
-static void TWPGetUrlRating_0004(void);
-static void TWPGetUrlRating_0005(void);
-static void TWPGetUrlRating_0006(void);
-static void TWPGetUrlRatingsCount_0001(void);
-static void TWPGetUrlRatingsCount_0002(void);
-static void TWPGetRedirUrlFor_0001(void);
-static void TWPGetRedirUrlFor_0002(void);
-static void TWPPolicyValidate_0001(void);
-static void TWPPolicyValidate_0002(void);
-static void TWPPolicyValidate_0003(void);
-static void TWPPolicyGetViolations_0001(void);
-static void TWPPolicyGetViolations_0002(void);
-static void TWPPolicyGetViolations_0003(void);
-static void TWPRatingGetScore_0001(void);
-static void TWPRatingGetScore_0002(void);
-static void TWPRatingGetUrl_0001(void);
-static void TWPRatingGetUrl_0002(void);
-static void TWPRatingGetDLAUrl_0001(void);
-static void TWPRatingGetDLAUrl_0002(void);
-static void TWPRatingHasCategory_0001(void);
-static void TWPRatingHasCategory_0002(void);
-static void TWPRatingHasCategory_0003(void);
-static void TWPRatingGetCategories_0001(void);
-static void TWPRatingGetCategories_0002(void);
-static void TWPRatingGetCategories_0003(void);
-
-static void TestCases(void);
-
-
-extern int TestCasesCount;
-extern int Success;
-extern int Failures;
-extern TWPResponseHandle hAResponse;
-
-TWPAPIInit Init;
-TWPConfiguration Cfg;
-TRequest Request;
-
-
-int main(int argc, char **argv)
-{
-    TWPStartup();
-    TestCases();
-    TWPCleanup();
-
-    return 0;
-}
-
-
-static void TestCases(void)
-{
-    TWPInitLibrary_0001();
-    TWPInitLibrary_0002();
-    TWPInitLibrary_0003();
-    TWPInitLibrary_0004();
-    TWPConfigurationCreate_0001();
-    TWPConfigurationCreate_0002();
-    TWPConfigurationCreate_0003();
-    TWPPolicyCreate_0001();
-    TWPPolicyCreate_0002();
-    TWPPolicyCreate_0003();
-    TWPLookupUrls_0001();
-    TWPLookupUrls_0002();
-    TWPLookupUrls_0003();
-    TWPLookupUrls_0004();
-    TWPLookupUrls_0005();
-    TWPGetUrlRating_0001();
-    TWPGetUrlRating_0002();
-    TWPGetUrlRating_0003();
-    TWPGetUrlRating_0004();
-    TWPGetUrlRating_0005();
-    TWPGetUrlRating_0006();
-    TWPGetUrlRatingsCount_0001();
-    TWPGetUrlRatingsCount_0002();
-    TWPGetRedirUrlFor_0001();
-    TWPGetRedirUrlFor_0002();
-    TWPPolicyValidate_0001();
-    TWPPolicyValidate_0002();
-    TWPPolicyValidate_0003();
-    TWPPolicyGetViolations_0001();
-    TWPPolicyGetViolations_0002();
-    TWPPolicyGetViolations_0003();
-    TWPRatingGetScore_0001();
-    TWPRatingGetScore_0002();
-    TWPRatingGetUrl_0001();
-    TWPRatingGetUrl_0002();
-    TWPRatingGetDLAUrl_0001();
-    TWPRatingGetDLAUrl_0002();
-    TWPRatingHasCategory_0001();
-    TWPRatingHasCategory_0002();
-    TWPRatingHasCategory_0003();
-    TWPRatingGetCategories_0001();
-    TWPRatingGetCategories_0002();
-    TWPRatingGetCategories_0003();
-}
-
-
-static void TWPInitLibrary_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib = INVALID_TWPLIB_HANDLE;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TESTCASEDTOR(&TestCtx);
-    TWPUninitLibrary(hLib);
-}
-
-
-static void TWPInitLibrary_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-
-    RemoveEngine();
-
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) == INVALID_TWPLIB_HANDLE);
-    TESTCASEDTOR(&TestCtx);
-
-    RestoreEngine();
-}
-
-
-static void TWPInitLibrary_0003(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-
-    RemoveEngine();
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) == INVALID_TWPLIB_HANDLE);
-    RestoreEngine();
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TWPUninitLibrary(hLib);
-
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPInitLibrary_0004(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TWPUninitLibrary(hLib);
-    RemoveEngine();
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) == INVALID_TWPLIB_HANDLE);
-    TESTCASEDTOR(&TestCtx);
-    RestoreEngine();
-}
-
-
-static void TWPConfigurationCreate_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPConfigurationCreate_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, NULL, &hCfg) != TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPConfigurationCreate_0003(void)
-{
-    TestCase TestCtx;
-    TWPConfigurationHandle hCfg;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT(TWPConfigurationCreate(INVALID_TWPLIB_HANDLE, NULL, &hCfg) != TWP_SUCCESS);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyCreate_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPPolicyHandle hPolicy;
-    TWPConfigurationHandle hCfg;
-    TWPCategories Categories[1] =
-    {
-        TWP_Artcultureheritage, 
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyCreate(hLib, hCfg, Categories, ELEMENT_NUM(Categories), &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(hPolicy != NULL);
-    TEST_ASSERT(TWPPolicyDestroy(hLib, &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyCreate_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPPolicyHandle hPolicy;
-    TWPConfigurationHandle hCfg;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyCreate(hLib, hCfg, NULL, 0, &hPolicy) != TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyCreate_0003(void)
-{
-    TestCase TestCtx;
-    TWPPolicyHandle hPolicy;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT(TWPPolicyCreate(INVALID_TWPLIB_HANDLE, NULL, NULL, 0, &hPolicy) != TWP_SUCCESS);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPLookupUrls_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0, ppUrls,
-                              ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPLookupUrls_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                NULL, 0, &hResponse) != TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPLookupUrls_0003(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TRequest ARequest = Request;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    ARequest.Request.receivefunc = NULL;
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &ARequest, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseWrite(hLib, hAResponse, ARequest.ResponseBody, ARequest.ResponseLength) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseWrite(hLib, hAResponse, "", 0) == TWP_SUCCESS);
-    TEST_ASSERT(hAResponse != NULL);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hAResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPLookupUrls_0004(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0, ppUrls,
-                ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPLookupUrls_0005(void)
-{
-    TestCase TestCtx;
-    TWPResponseHandle hResponse;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    RemoveEngine();
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT(TWPLookupUrls(INVALID_TWPLIB_HANDLE, NULL, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRating_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByIndex(hLib, hResponse, 0, &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRating_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, URL_0_0,
-                strlen(URL_0_0), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRating_0003(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, NULL, 0, &hRating) != TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRating_0004(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByIndex(hLib, hResponse, 0, &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRating_0005(void)
-{
-    TestCase TestCtx;
-    TWPUrlRatingHandle hRating;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    /* pre-condition is stub library */
-    RemoveEngine();
-    TEST_ASSERT(TWPResponseGetUrlRatingByIndex(INVALID_TWPLIB_HANDLE,
-                NULL, 0, &hRating) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRating_0006(void)
-{
-    TestCase TestCtx;
-    TWPUrlRatingHandle hRating;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    /* pre-condition is stub library */
-    RemoveEngine();
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(INVALID_TWPLIB_HANDLE, NULL,
-                NULL, 0, &hRating) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRatingsCount_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[] =
-    {
-        URL_0_0,
-        URL_1_0
-    };
-    unsigned int uCount = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByIndex(hLib, hResponse, 0, &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseGetUrlRatingsCount(hLib, hResponse, &uCount) == TWP_SUCCESS);
-    TEST_ASSERT(uCount == ELEMENT_NUM(ppUrls));
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetUrlRatingsCount_0002(void)
-{
-    unsigned int uCount;
-    TestCase TestCtx;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    /* pre-condition is stub library */
-    RemoveEngine();
-    TEST_ASSERT(TWPResponseGetUrlRatingsCount(INVALID_TWPLIB_HANDLE,
-                NULL, &uCount) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetRedirUrlFor_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_3_0
-    };
-    char *pUrl = NULL;
-    unsigned int uLength = 0;
-    TWPPolicyHandle hPolicy;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 1,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByIndex(hLib, hResponse, 0, &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(hRating != NULL);
-    TEST_ASSERT(TWPPolicyCreate(hLib, hCfg, CATEGORIES_0_0_1, ELEMENT_NUM(CATEGORIES_0_0_1), &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(hPolicy != NULL);
-    TEST_ASSERT(TWPResponseGetRedirUrlFor(hLib, hResponse, hRating, hPolicy, &pUrl, &uLength) == TWP_SUCCESS);
-    TEST_ASSERT(pUrl != NULL);
-    free(pUrl);
-    TEST_ASSERT(TWPPolicyDestroy(hLib, &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPGetRedirUrlFor_0002(void)
-{
-    TestCase TestCtx;
-    TWPPolicyHandle hPolicy = NULL;
-    char *pUrl = NULL;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    /* pre-condition is stub library */
-    RemoveEngine();
-    TEST_ASSERT(TWPResponseGetRedirUrlFor(INVALID_TWPLIB_HANDLE,
-                NULL, NULL, hPolicy, &pUrl, &uLength) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyValidate_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    TWPPolicyHandle hPolicy;
-    int iViolated = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyCreate(hLib, hCfg, CATEGORIES_0_0_1, ELEMENT_NUM(CATEGORIES_0_0_1), &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyValidate(hLib, hPolicy, hRating, &iViolated) == TWP_SUCCESS);
-    TEST_ASSERT(iViolated == 1);
-    TEST_ASSERT(TWPPolicyDestroy(hLib, &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyValidate_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    TWPPolicyHandle hPolicy;
-    int iViolated = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyCreate(hLib, hCfg, CATEGORIES_0_0_0, ELEMENT_NUM(CATEGORIES_0_0_0), &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyValidate(hLib, hPolicy, hRating, &iViolated) == TWP_SUCCESS);
-    TEST_ASSERT(iViolated == 0);
-    TEST_ASSERT(TWPPolicyDestroy(hLib, &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyValidate_0003(void)
-{
-    TestCase TestCtx;
-    int iViolated = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    RemoveEngine();
-    TEST_ASSERT(TWPPolicyValidate(INVALID_TWPLIB_HANDLE,
-                NULL, NULL, &iViolated) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyGetViolations_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    TWPPolicyHandle hPolicy;
-    TWPCategories *pViolated = NULL;
-    unsigned int uLength = 0;
-    int i;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyCreate(hLib, hCfg, CATEGORIES_0_0_2, ELEMENT_NUM(CATEGORIES_0_0_2), &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyGetViolations(hLib, hPolicy, hRating, &pViolated, &uLength) == TWP_SUCCESS);
-    TEST_ASSERT(uLength == ELEMENT_NUM(VIOLATIONS_0_0_2));
-    for (i = 0; i < uLength; i++)
-    {
-        TEST_ASSERT(pViolated[i] == VIOLATIONS_0_0_2[i]);
-    }
-    free(pViolated);
-    TEST_ASSERT(TWPPolicyDestroy(hLib, &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyGetViolations_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    TWPPolicyHandle hPolicy;
-    TWPCategories *pViolated = NULL;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyCreate(hLib, hCfg, CATEGORIES_0_0_0, ELEMENT_NUM(CATEGORIES_0_0_0), &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPPolicyGetViolations(hLib, hPolicy, hRating, &pViolated, &uLength) == TWP_SUCCESS);
-    TEST_ASSERT(uLength == 0);
-    TEST_ASSERT(pViolated == NULL);
-    TEST_ASSERT(TWPPolicyDestroy(hLib, &hPolicy) == TWP_SUCCESS);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPPolicyGetViolations_0003(void)
-{
-    TestCase TestCtx;
-    TWPCategories *pViolated = NULL;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    RemoveEngine();
-    TEST_ASSERT(TWPPolicyGetViolations(INVALID_TWPLIB_HANDLE, NULL, NULL,
-        &pViolated, &uLength) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetScore_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    int iScore;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPUrlRatingGetScore(hLib, hRating, &iScore) == TWP_SUCCESS);
-    TEST_ASSERT(iScore == SCORE_0_0);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetScore_0002(void)
-{
-    TestCase TestCtx;
-    int iScore;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    RemoveEngine();
-    TEST_ASSERT(TWPUrlRatingGetScore(INVALID_TWPLIB_HANDLE, NULL, &iScore) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetUrl_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    char *pUrl;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPUrlRatingGetUrl(hLib, hRating, &pUrl, &uLength) == TWP_SUCCESS);
-    TEST_ASSERT(strcmp(pUrl, ppUrls[0]) == 0);
-    TEST_ASSERT(uLength == strlen(ppUrls[0]));
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetUrl_0002(void)
-{
-    TestCase TestCtx;
-    char *pUrl;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    RemoveEngine();
-    TEST_ASSERT(TWPUrlRatingGetUrl(INVALID_TWPLIB_HANDLE, NULL, &pUrl, &uLength) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetDLAUrl_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_2_0
-    };
-    char *pUrl;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPUrlRatingGetDLAUrl(hLib, hRating, &pUrl, &uLength) == TWP_SUCCESS);
-    TEST_ASSERT(pUrl != NULL);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetDLAUrl_0002(void)
-{
-    TestCase TestCtx;
-    char *pUrl;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    RemoveEngine();
-    TEST_ASSERT(TWPUrlRatingGetDLAUrl(INVALID_TWPLIB_HANDLE, NULL, &pUrl, &uLength) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingHasCategory_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    int iPresent = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPUrlRatingHasCategory(hLib, hRating, CATEGORY_0_0_1, &iPresent) == TWP_SUCCESS);
-    TEST_ASSERT(iPresent == 1);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingHasCategory_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    int iPresent = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPUrlRatingHasCategory(hLib, hRating, CATEGORY_0_0_0, &iPresent) == TWP_SUCCESS);
-    TEST_ASSERT(iPresent == 0);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingHasCategory_0003(void)
-{
-    TestCase TestCtx;
-    int iPresent = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    RemoveEngine();
-    TEST_ASSERT(TWPUrlRatingHasCategory(INVALID_TWPLIB_HANDLE, NULL, CATEGORY_0_0_0, &iPresent) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetCategories_0001(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_0_0
-    };
-    TWPCategories *pCategories;
-    unsigned int uLength;
-    int i;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPUrlRatingGetCategories(hLib, hRating, &pCategories, &uLength) == TWP_SUCCESS);
-    TEST_ASSERT(uLength == ELEMENT_NUM(CATEGORIES_0_0_1));
-    for (i = 0; i < uLength; i++)
-    {
-        TEST_ASSERT(pCategories[i] == CATEGORIES_0_0_1[i]);
-    }
-    free(pCategories);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetCategories_0002(void)
-{
-    TestCase TestCtx;
-    TWPLIB_HANDLE hLib;
-    TWPConfigurationHandle hCfg;
-    TWPResponseHandle hResponse;
-    TWPUrlRatingHandle hRating;
-    const char *ppUrls[1] =
-    {
-        URL_1_0
-    };
-    TWPCategories *pCategories = NULL;
-    unsigned int uLength = 0;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    TEST_ASSERT((hLib = TWPInitLibrary(&Init)) != INVALID_TWPLIB_HANDLE);
-    TEST_ASSERT(TWPConfigurationCreate(hLib, &Cfg, &hCfg) == TWP_SUCCESS);
-    TEST_ASSERT(hCfg != NULL);
-    TEST_ASSERT(TWPLookupUrls(hLib, hCfg, (TWPRequest *) &Request, 0,
-                              ppUrls, ELEMENT_NUM(ppUrls), &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(hResponse != NULL);
-    TEST_ASSERT(TWPResponseGetUrlRatingByUrl(hLib, hResponse, ppUrls[0], strlen(ppUrls[0]), &hRating) == TWP_SUCCESS);
-    TEST_ASSERT(TWPUrlRatingGetCategories(hLib, hRating, &pCategories, &uLength) == TWP_SUCCESS);
-    TEST_ASSERT(pCategories != NULL);
-    TEST_ASSERT(TWPResponseDestroy(hLib, &hResponse) == TWP_SUCCESS);
-    TEST_ASSERT(TWPConfigurationDestroy(hLib, &hCfg) == TWP_SUCCESS);
-    TWPUninitLibrary(hLib);
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPRatingGetCategories_0003(void)
-{
-    TestCase TestCtx;
-    TWPCategories *pCategories;
-    unsigned int uLength;
-
-    TESTCASECTOR(&TestCtx, __FUNCTION__);
-    RemoveEngine();
-    TEST_ASSERT(TWPUrlRatingGetCategories(INVALID_TWPLIB_HANDLE, NULL, &pCategories, &uLength) != TWP_SUCCESS);
-    RestoreEngine();
-    TESTCASEDTOR(&TestCtx);
-}
-
-
-static void TWPStartup(void)
-{
-    extern int TestCasesCount;
-    extern int Success;
-    extern int Failures;
-
-    TestCasesCount = 0;
-    Success = 0;
-    Failures = 0;
-
-    Init.api_version = TWPAPI_VERSION;
-    Init.memallocfunc = (TWPFnMemAlloc) malloc;
-    Init.memfreefunc = free;
-
-    srandom(time(NULL));
-
-    Cfg.config_version = TWPCONFIG_VERSION;
-    Cfg.client_id = "SamsungTizen";
-       Cfg.client_key = "{3353DFB5-6978-43E7-AFBE-E3B251B4C303}";
-    Cfg.host = NULL;
-    Cfg.secure_connection = 0;
-    Cfg.skip_dla = 0;
-    Cfg.obfuscate_request = 1;
-    Cfg.randomfunc = GenerateRandomNumber;
-
-    Request.Request.request_version = TWPREQUEST_VERSION;
-    Request.Request.seturlfunc = CbSetUrl;
-    Request.Request.setmethodfunc = CbSetMethod;
-    Request.Request.sendfunc = CbSend;
-    Request.Request.receivefunc = CbRecv;
-
-    CreateTestDirs();
-}
-
-
-static void TWPCleanup(void)
-{
-    LOG_OUT("@@@@@@@@@@@@@@@@@@@@@@@@\n");
-    LOG_OUT("Test done: %d executed, %d passed, %d failure\n", TestCasesCount, Success, Failures);
-    
-    if (Request.hHttp != INVALID_XM_HTTP_HANDLE)
-        XmHttpClose(Request.hHttp);
-
-    DestoryTestDirs();
-}
diff --git a/test/TWPTest.h b/test/TWPTest.h
deleted file mode 100644 (file)
index 88131ac..0000000
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef TWPTEST_H
-#define TWPTEST_H
-
-
-#include <setjmp.h>
-
-
-#ifdef __cplusplus 
-extern "C" {
-#endif
-
-#define TEST_SUITE_VERSION "0.0.1"
-
-/* Immediate value definitions. */
-#define MAX_TEST_NUM 128
-
-/* Maximum WP API name length. */
-#define MAX_TWP_API_NAME_LEN 128
-
-/* Output methods. */
-#define LOG_OUT(fmt, x...) printf("Log:"fmt, ##x)
-
-#define TRY_TEST { \
-    int _ret_ = setjmp(WPJmpBuf); \
-    if (_ret_ == 1) { \
-        Failures++; \
-    } else { \
-
-#define FAIL_TEST longjmp(WPJmpBuf, 1);
-
-#define TESTCASECTOR(_ctx_, _api_) \
-        TRY_TEST \
-        TestCaseCtor(_ctx_, _api_);
-
-#define TESTCASEDTOR(_ctx_) \
-        TestCaseDtor(_ctx_); \
-    } \
-} \
-
-/* Test assert method. */
-#define TEST_ASSERT(cond) if (!(cond)) {LOG_OUT("Test failed!! at : %s, %d\n", __FILE__, __LINE__); FAIL_TEST}
-
-#define ELEMENT_NUM(ary) (sizeof(ary) / sizeof((ary)[0]))
-
-/* Content directory for testing. */
-#define TWP_TEST_CONTENT_DIR "contents_test"
-
-/* Content backup directory. */
-#define TWP_BACKUP_CONTENT_DIR "contents_bak"
-
-
-/**
- * Test case information data
- */
-typedef struct TestCase_struct
-{
-    char szAPIName[MAX_TWP_API_NAME_LEN]; /* TWP API names */
-} TestCase;
-
-/**
- * Test request data structure
- */
-typedef struct TRequest
-{
-    TWPRequest Request;
-    const char *pszUrl;
-    size_t ResponseLength;
-    char *ResponseBody;
-    XM_HTTP_HANDLE hHttp;
-    char *pData;
-    unsigned int uLength;
-    unsigned int uRead;
-    size_t ResponseBytesRead;
-} TRequest;
-
-
-/*
- * Very simple/thin porting layer
- */
-
-/* Test framework */
-extern void TestCaseCtor(TestCase *pCtx, const char *pszAPI);
-extern void TestCaseDtor(TestCase *pCtx);
-extern void RestoreEngine();
-extern void RemoveEngine();
-extern void BackupEngine();
-
-extern TWP_RESULT CbSend(struct TWPRequest *pRequest, TWPResponseHandle hResponse,
-                         const void *pData, unsigned int uLength);
-extern TWP_RESULT CbRecv(struct TWPRequest *pRequest, void *pBuffer, unsigned int uBufferLength,
-                         unsigned int *puLength);
-extern TWP_RESULT CbSetUrl(struct TWPRequest *pRequest, const char *pszUrl, unsigned int uLength);
-extern TWP_RESULT CbSetMethod(struct TWPRequest *pRequest, TWPSubmitMethod Method);
-extern long GenerateRandomNumber();
-extern void DestoryTestDirs(void);
-extern int CreateTestDirs(void);
-extern void CallSys(const char *pszCmd);
-
-extern jmp_buf WPJmpBuf;
-
-#ifdef __cplusplus 
-}
-#endif
-
-#endif /* TWPTEST_H */
diff --git a/test/TWPTestUtils.c b/test/TWPTestUtils.c
deleted file mode 100644 (file)
index 0fedbfa..0000000
+++ /dev/null
@@ -1,460 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#define _GNU_SOURCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <pthread.h>
-#include <sys/time.h>
-#include <sys/stat.h>
-#include <errno.h>
-
-/* For multi-user support */
-#include <tzplatform_config.h>
-
-#include "TWPImpl.h"
-#include "XMHttp.h"
-#include "TWPTest.h"
-
-
-#if !defined(MIN)
-#define MIN(a, b) ((a) > (b) ? (b) : (a))
-#endif
-
-#ifndef MAX
-#define MAX(a, b) ((a) > (b) ? (a) : (b))
-#endif
-
-#define PLUGIN_PATH tzplatform_mkpath(TZ_USER_SHARE, "sec_plugin/libengine.so")
-#define PLUGIN_DIR tzplatform_mkpath(TZ_USER_SHARE, "sec_plugin/")
-
-static void ReportTestCase(TestCase *pCtx);
-static void PutTestRoot(char *pszRoot);
-static char *GetTestRoot(void);
-static char *GetBackupDir(void);
-static void PutBackupDir(char *pszBackupDir);
-
-
-int TestCasesCount = 0;
-int Success = 0;
-int Failures = 0;
-jmp_buf WPJmpBuf;
-TWPResponseHandle hAResponse = NULL;
-
-
-/**
- * Output for test case result.
- */
-static void ReportTestCase(TestCase *pCtx)
-{
-    char *pszTmp;
-
-    LOG_OUT("@@@@@@@@@@@@@@@@@@@@@@@@\n");
-
-    LOG_OUT("@ID: TC_SEC_WP_%s\n", pCtx->szAPIName);
-    pszTmp = strchr(pCtx->szAPIName, '_');
-    *pszTmp = 0;
-    LOG_OUT("@API Name: %s\n", pCtx->szAPIName);
-    *pszTmp = '_';
-
-    TestCasesCount++;
-}
-
-
-/**
- * Test case constructor.
- */
-void TestCaseCtor(TestCase *pCtx, const char *pszAPI)
-{
-
-    strncpy(pCtx->szAPIName, pszAPI, sizeof(pCtx->szAPIName) - 1);
-}
-
-
-/**
- * Test case destructor.
- */
-void TestCaseDtor(TestCase *pCtx)
-{
-
-    ReportTestCase(pCtx);
-    Success++;
-    
-    extern TRequest Request;
-    if (Request.ResponseBody != NULL)
-        free(Request.ResponseBody);
-
-    Request.pszUrl = NULL;
-    Request.ResponseLength = 0;
-    Request.ResponseBody = NULL;
-    
-    Request.pData = NULL;
-    Request.uLength = 0;
-    Request.uRead = 0;
-    Request.ResponseBytesRead = 0;
-}
-
-
-void BackupEngine()
-{
-    char *pszRoot = GetTestRoot(), *pszCommand;
-
-    if (pszRoot != NULL)
-    {
-        asprintf(&pszCommand, "mkdir %s/backup", pszRoot);
-        CallSys(pszCommand);
-        free(pszCommand);
-
-        asprintf(&pszCommand, "cp -f %s %s/backup", PLUGIN_PATH, pszRoot);
-        CallSys(pszCommand);
-        free(pszCommand);
-
-        PutTestRoot(pszRoot);
-    }
-}
-
-
-void RestoreEngine()
-{
-    char *pszRoot = GetTestRoot(), *pszCommand;
-
-    if (pszRoot != NULL)
-    {
-        asprintf(&pszCommand, "cp -f %s/backup/libwpengine.so %s", pszRoot, PLUGIN_DIR);
-        CallSys(pszCommand);
-        free(pszCommand);
-
-        PutTestRoot(pszRoot);
-    }
-}
-
-
-void RemoveEngine()
-{
-    char *pszRoot = GetTestRoot(), *pszCommand;
-
-    BackupEngine();
-    if (pszRoot != NULL)
-    {
-        asprintf(&pszCommand, "rm -f %s", PLUGIN_PATH);
-        CallSys(pszCommand);
-        free(pszCommand);
-    }
-}
-
-
-long GenerateRandomNumber()
-{
-
-       return rand();
-}
-
-
-TWP_RESULT CbSetUrl(struct TWPRequest *pRequest, const char *pszUrl, unsigned int uLength)
-{
-    TRequest *pCtx = (TRequest *) pRequest;
-
-    // LOG_OUT("url is: %s\n", pszUrl);
-    if (pCtx->pszUrl != NULL)
-        free((void *) pCtx->pszUrl);
-    pCtx->pszUrl = strdup(pszUrl);
-
-    return pCtx->pszUrl ? TWP_SUCCESS : TWP_NOMEM;
-}
-
-
-TWP_RESULT CbSetMethod(struct TWPRequest *pRequest, TWPSubmitMethod Method)
-{
-
-    return Method == TWPPOST ? TWP_SUCCESS : TWP_INVALID_PARAMETER;
-}
-
-
-static int CbHttpWrite(void *pPrivate, void const *pData, int iSize)
-{
-    TRequest *pCtx = (TRequest *) pPrivate;
-    char *pTmp = NULL;
-
-    // LOG_OUT("[http] recv data\n");
-    pTmp = (char *) realloc(pCtx->ResponseBody, pCtx->ResponseLength + iSize);
-    if (pTmp == NULL)
-    {
-        LOG_OUT("failed to alloc mem\n");
-        return 0;
-    }
-
-    pCtx->ResponseBody = pTmp;
-    memcpy(pCtx->ResponseBody + pCtx->ResponseLength, pData, iSize);
-    pCtx->ResponseLength += iSize;
-
-    return iSize;
-}
-
-
-static int CbHttpRead(void *pPrivate, void *pData, int iSize)
-{
-    TRequest *pCtx = (TRequest *) pPrivate;
-    unsigned int uToRead = MIN(iSize, pCtx->uLength - pCtx->uRead);
-
-    // LOG_OUT("[http] send data\n");
-
-    memcpy(pData, pCtx->pData + pCtx->uRead, uToRead);
-
-    return (int) uToRead;
-}
-
-
-static long CbHttpGetSize(void *pPrivate)
-{
-    TRequest *pCtx = (TRequest *) pPrivate;
-
-    // LOG_OUT("[http] get size\n");
-
-    return (long) (pCtx->uLength - pCtx->uRead);
-}
-
-
-static TWP_RESULT HttpSend(TRequest *pCtx, const void *pData, unsigned int uLength)
-{
-    int iRet;
-    XmHttpCallbacks HttpCb;
-
-    if (pCtx->hHttp == INVALID_XM_HTTP_HANDLE)
-    {
-        pCtx->hHttp = XmHttpOpen();
-        if (pCtx->hHttp == NULL)
-            return TWP_NOMEM;
-    }
-
-    HttpCb.pfWrite = CbHttpWrite;
-    HttpCb.pfRead = CbHttpRead;
-    HttpCb.pfGetSize = CbHttpGetSize;
-
-    pCtx->pData = (char *) pData;
-    pCtx->uLength = uLength;
-
-    iRet = XmHttpExec(pCtx->hHttp, "POST", pCtx->pszUrl, &HttpCb, pCtx);
-
-    return iRet == 0 ? TWP_SUCCESS : TWP_ERROR;
-}
-
-
-TWP_RESULT CbSend(struct TWPRequest *pRequest, TWPResponseHandle hResponse,
-                  const void *pData, unsigned int uLength)
-{
-
-    // For a-sync call
-    hAResponse = hResponse;
-    return HttpSend((TRequest *) pRequest, pData, uLength);
-}
-
-
-TWP_RESULT CbRecv(struct TWPRequest *pRequest, void *pBuffer, unsigned int uBufferLength,
-                  unsigned int *puLength)
-{
-    TRequest* pCtx = (TRequest*) pRequest;
-    size_t BytesToCopy = 0;
-
-    if ( pCtx->ResponseBytesRead < pCtx->ResponseLength )
-    {
-       BytesToCopy = uBufferLength < (pCtx->ResponseLength - pCtx->ResponseBytesRead) ? uBufferLength : (pCtx->ResponseLength - pCtx->ResponseBytesRead);
-       memcpy(pBuffer, (void*) (pCtx->ResponseBody + pCtx->ResponseBytesRead), BytesToCopy);
-       pCtx->ResponseBytesRead += BytesToCopy;
-    }
-
-    *puLength = (int) BytesToCopy;
-
-    return TWP_SUCCESS;
-}
-
-
-void CallSys(const char *pszCmd)
-{
-    int iRet = 0;
-    iRet = system(pszCmd);
-    if (iRet != 0)
-    {
-        // LOG_OUT("failed to exe command: %x\n", (int) pszCmd);
-    }
-}
-
-
-/**
- * Test framework helper function: get content files' root path.
- */
-static char *GetTestRoot(void)
-{
-    int iLen, iEnvLen;
-    char *pszRoot = NULL, *pszEnv = getenv("TWP_CONTENT_PATH");
-
-    if (pszEnv != NULL &&
-        (iEnvLen = strlen(pszEnv)) > 0)
-    {
-        iLen = iEnvLen;
-        iLen += 64; /* Reserved 64 bytes for PID. */
-        iLen += strlen(TWP_TEST_CONTENT_DIR);
-        pszRoot = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszRoot != NULL)
-        {
-            if (pszEnv[iEnvLen - 1] != '/')
-                snprintf(pszRoot, iLen, "%s/%d/%s", pszEnv, (int) getpid(),
-                         TWP_TEST_CONTENT_DIR);
-            else
-                snprintf(pszRoot, iLen, "%s%d/%s", pszEnv, (int) getpid(),
-                         TWP_TEST_CONTENT_DIR);
-        }
-    }
-    else
-    {
-        iLen = sizeof("./") + 64; /* Reserved 64 bytes for PID. */
-        pszRoot = (char *) calloc(iLen + 1, sizeof(char));
-        if (pszRoot != NULL)
-        {
-            snprintf(pszRoot, iLen, "./%d", (int) getpid());
-        }
-    }
-
-    return pszRoot;
-}
-
-
-static void PutTestRoot(char *pszRoot)
-{
-
-    if (pszRoot != NULL)
-        free(pszRoot);
-}
-
-
-int CreateTestDirs(void)
-{
-    int iLen, iRet = -1;
-    char *pszCommand, *pszRoot = GetTestRoot(), *pszEnv, *pszBackup;
-
-    if (pszRoot != NULL)
-    {
-        pszBackup = GetBackupDir();
-        if (pszBackup != NULL)
-        {
-            iLen = MAX(strlen(pszRoot) * 2, strlen(pszBackup));
-            iLen += 64; /* Reserved for "mkdir -p", "cp -f " */
-            pszCommand = (char *) calloc(iLen + 1, sizeof(char));
-            if (pszCommand != NULL)
-            {
-                snprintf(pszCommand, iLen, "mkdir -p %s", pszRoot);
-                CallSys(pszCommand);
-                pszCommand[0] = 0;
-
-                snprintf(pszCommand, iLen, "mkdir -p %s", pszBackup);
-                CallSys(pszCommand);
-                pszCommand[0] = 0;
-
-                pszEnv = getenv("TWP_CONTENT_PATH");
-                if (pszEnv == NULL)
-                    pszEnv = "./";
-                if (pszEnv[strlen(pszEnv) - 1] == '/')
-                    snprintf(pszCommand, iLen, "cp -f %s* %s", pszEnv, pszRoot);
-                else
-                    snprintf(pszCommand, iLen, "cp -f %s/* %s", pszEnv, pszRoot);
-                CallSys(pszCommand);
-
-                free(pszCommand);
-
-                iRet = 0;
-            }
-            PutBackupDir(pszBackup);
-        }
-        PutTestRoot(pszRoot);
-    }
-
-    return iRet;
-}
-
-
-void DestoryTestDirs(void)
-{
-    int iLen, iEnvLen;
-    char *pszCommand, *pszEnv = getenv("TWP_CONTENT_PATH");
-
-    if (pszEnv == NULL || strlen(pszEnv) == 0)
-        pszEnv = "./";
-    iEnvLen = strlen(pszEnv);
-    iLen = iEnvLen;
-    iLen += 72; /* Reserved for "rm -rf" and PID */
-    pszCommand = (char *) calloc(iLen + 1, sizeof(char));
-    if (pszCommand != NULL)
-    {
-        if (pszEnv[iEnvLen - 1] == '/')
-            snprintf(pszCommand, iLen, "rm -rf %s%d", pszEnv, (int) getpid());
-        else
-            snprintf(pszCommand, iLen, "rm -rf %s/%d", pszEnv, (int) getpid());
-        CallSys(pszCommand);
-        free(pszCommand);
-    }
-}
-
-
-static char *GetBackupDir(void)
-{
-    int iLen, iEnvLen;
-    char *pszEnv = getenv("TWP_CONTENT_PATH"), *pszPath;
-
-    if (pszEnv == NULL || strlen(pszEnv) == 0)
-        pszEnv = "./";
-    iEnvLen = strlen(pszEnv);
-    iLen = iEnvLen;
-    iLen += strlen(TWP_BACKUP_CONTENT_DIR);
-    iLen += 64; /* Reserved for slash char and PID. */
-    pszPath = (char *) calloc(iLen + 1, sizeof(char));
-
-    if (pszPath)
-    {
-        if (pszEnv[iEnvLen - 1] == '/')
-            snprintf(pszPath, iLen, "%s%d/%s", pszEnv, (int) getpid(),
-                     TWP_BACKUP_CONTENT_DIR);
-        else
-            snprintf(pszPath, iLen, "%s/%d/%s", pszEnv, (int) getpid(),
-                     TWP_BACKUP_CONTENT_DIR);
-    }
-
-    return pszPath;
-}
-
-
-static void PutBackupDir(char *pszBackupDir)
-{
-
-    if (pszBackupDir != NULL)
-        free(pszBackupDir);
-}
-
diff --git a/test/UrlInfo.h b/test/UrlInfo.h
deleted file mode 100644 (file)
index 5c37555..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef URL_INFO_H
-#define URL_INFO_H
-
-#ifdef __cplusplus 
-extern "C" {
-#endif
-
-#define MAX_CATEGORIES 8
-
-#define URL_0_0 "http://www.screensavers.com"
-#define URL_1_0 "http://www.google.com"
-#define URL_2_0 "http://www.targetingnow.com/delivery"
-#define URL_3_0 "www.zcrack.com"
-
-TWPCategories CATEGORIES_0_0_1[2] =
-{
-    TWP_Malicioussites,
-    TWP_OverallRiskHigh
-};
-
-TWPCategories CATEGORIES_0_0_0[2] =
-{
-    TWP_Pharmacy,
-    TWP_Restaurants
-};
-
-TWPCategories CATEGORIES_0_0_2[2] =
-{
-    TWP_Malicioussites,
-    TWP_OverallRiskHigh
-};
-
-TWPCategories VIOLATIONS_0_0_2[2] =
-{
-    TWP_Malicioussites,
-    TWP_OverallRiskHigh
-};
-
-#define SCORE_0_0 127
-#define CATEGORY_0_0_0 TWP_Pharmacy
-#define CATEGORY_0_0_1 TWP_OverallRiskHigh
-
-#ifdef __cplusplus 
-}
-#endif
-
-#endif /* URL_INFO_H */
-
diff --git a/test/XMHttp.c b/test/XMHttp.c
deleted file mode 100644 (file)
index 5aee19c..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <malloc.h>
-
-#include "XMPHttp.h"
-
-
-typedef struct XmHttpCtx_struct
-{
-    XmPHttpCtx PCtx;
-} XmHttpCtx;
-
-
-XM_HTTP_HANDLE XmHttpOpen()
-{
-    XmHttpCtx *pCtx;
-
-    if ((pCtx = (XmHttpCtx *) malloc(sizeof(XmHttpCtx))) == NULL)
-        return INVALID_XM_HTTP_HANDLE;
-    if (XmPHttpInit(&pCtx->PCtx) < 0)
-    {
-        free(pCtx);
-        return INVALID_XM_HTTP_HANDLE;
-    }
-
-    return (XM_HTTP_HANDLE) pCtx;
-}
-
-
-void XmHttpClose(XM_HTTP_HANDLE hHTTP)
-{
-    XmHttpCtx *pCtx = (XmHttpCtx *) hHTTP;
-
-    XmPHttpCleanup(&pCtx->PCtx);
-    free(pCtx);
-}
-
-
-int XmHttpExec(XM_HTTP_HANDLE hHTTP, char const *pszMethod, char const *pszURL,
-               XmHttpCallbacks *pHCB, void *pPrivate)
-{
-    XmHttpCtx *pCtx = (XmHttpCtx *) hHTTP;
-
-    return XmPHttpExec(&pCtx->PCtx, pszMethod, pszURL, pHCB, pPrivate);
-}
-
diff --git a/test/XMHttp.h b/test/XMHttp.h
deleted file mode 100644 (file)
index e6a8d24..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#if !defined(_XMHTTP_H)
-#define _XMHTTP_H
-
-#if defined(__cplusplus)
-#define EXTERNC_BEGIN extern "C" {
-#define EXTERNC_END }
-#define EXTERNC extern "C"
-#else
-#define EXTERNC_BEGIN
-#define EXTERNC_END
-#define EXTERNC
-#endif
-
-#define XMHANDLE(n)         struct n##_struct { int iDummy; }; typedef struct n##_struct *n
-
-XMHANDLE(XM_HTTP_HANDLE);
-
-#define INVALID_XM_HTTP_HANDLE ((XM_HTTP_HANDLE) 0)
-
-typedef struct XmHttpCallbacks_struct
-{
-    int (*pfWrite)(void *pPrivate, void const *pData, int iSize);
-    int (*pfRead)(void *pPrivate, void *pData, int iSize);
-    long (*pfGetSize)(void *pPrivate);
-} XmHttpCallbacks;
-
-
-EXTERNC_BEGIN;
-
-XM_HTTP_HANDLE XmHttpOpen();
-void XmHttpClose(XM_HTTP_HANDLE hHTTP);
-int XmHttpExec(XM_HTTP_HANDLE hHTTP, char const *pszMethod, char const *pszURL,
-               XmHttpCallbacks *pHCB, void *pPrivate);
-
-EXTERNC_END;
-
-#endif
-
diff --git a/test/XMPHttp.c b/test/XMPHttp.c
deleted file mode 100644 (file)
index f7953ae..0000000
+++ /dev/null
@@ -1,788 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <string.h>
-#include <malloc.h>
-#include <unistd.h>
-#include <ctype.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-#include <stdarg.h>
-
-#include <XMPHttp.h>
-
-#define XME_HTTP_TIMEOUT 11300
-#define XME_HTTP_SELECT 11301
-#define XME_HTTP_SKREAD 11302
-#define XME_HTTP_SKWRITE 11303
-#define XME_HTTP_SETSOCKOPT 11003
-#define XME_HTTP_DISCONNECT 11005
-#define XME_HTTP_UNKNOWN_HOST 11006
-#define XME_HTTP_CONNECT 11007
-
-#define SOCK_STD_CONTIMEO 60
-#define SOCK_STD_RCVTIMEO 60
-#define SOCK_STD_SNDTIMEO 60
-#define HTTP_DEFAULT_PORT 80
-#define HTTPS_DEFAULT_PORT 443
-#define CONTLEN_HEADER "Content-Length:"
-#define CONTENC_HEADER "Transfer-Encoding:"
-#define CHUNKED_ENCODED(s) (strcasecmp(s, "chunked") == 0)
-#define XM_HTTP_HEADERS "XM_HTTP_HEADERS"
-#define XM_HTTP_VERSION "XM_HTTP_VERSION"
-#define XM_SKRECV_TIMEO "XM_NET_RECVTIMEO"
-#define XM_SKSEND_TIMEO "XM_NET_SENDTIMEO"
-#define XM_SKCONN_TIMEO "XM_NET_CONNTIMEO"
-
-
-#define SSTREAM_BUFFER_SIZE 4096
-
-#define URL_PROTO_HTTP  1
-#define URL_PROTO_HTTPS 2
-
-#if !defined(INADDR_NONE)
-#define INADDR_NONE ((XmUInt32) -1)
-#endif
-
-#define URL_PARSE_INIT  { 0, NULL, 0, NULL, NULL }
-
-#define PHTTP_MIN(a, b) ((a) < (b) ? (a): (b))
-#define PHTTP_SKIPSPACE(p) for(; *(p) == ' ' || *(p) == '\t'; (p)++)
-#define PHTTP_CSTRSIZE(s) (sizeof(s) - 1)
-
-#define PHTTP_DBGPRINT(c, args) do { if ((c)->iPHttpDebug) XmPHttpDbgPrintf args; } while (0)
-
-#define PHTTP_ENVGET(c, s) getenv(s)
-#define PHTTP_ENVFREE(e) free(e)
-
-
-#define INVALID_SOCKET (-1)
-#define closesocket(s) close(s)
-#define PHTTP_INPROGRESS(SockFd) (errno == EINPROGRESS || errno == EWOULDBLOCK)
-
-typedef int SOCKET;
-
-
-struct PHttpUrl
-{
-    int iProto;
-    char const *pszHost;
-    int iPort;
-    char const *pszDoc;
-    char const *pszUrl;
-};
-
-struct SStream
-{
-    XmPHttpCtx *pCtx;
-    SOCKET SockFd;
-    int iReadTimeo, iWriteTimeo;
-    int iIndex;
-    int iInBuffer;
-    char Buffer[SSTREAM_BUFFER_SIZE];
-};
-
-
-static int XmPHttpDbgPrintf(char const *pszFmt, ...)
-{
-    int iPrintRes;
-    va_list Args;
-
-    va_start(Args, pszFmt);
-    iPrintRes = vfprintf(stderr, pszFmt, Args);
-    va_end(Args);
-
-    return iPrintRes;
-}
-
-static int XmPHttpGetIntEnv(XmPHttpCtx *pCtx, char const *pszVar, int iDefault)
-{
-    int iValue = iDefault;
-    char *pszValue;
-
-    if ((pszValue = (char *) PHTTP_ENVGET(pCtx, pszVar)) != NULL)
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] %s environment is '%s'\n", pszVar, pszValue));
-
-        iValue = atoi(pszValue);
-        PHTTP_ENVFREE(pszValue);
-    }
-
-    return iValue;
-}
-
-static int XmPHttpSkBlocking(SOCKET SockFd, int iOn)
-{
-    int iFlags, iError;
-
-    if ((iFlags = fcntl(SockFd, F_GETFL, 0)) == -1)
-        return -XME_HTTP_SETSOCKOPT;
-    if (iOn)
-        iError = fcntl(SockFd, F_SETFL, iFlags & ~O_NONBLOCK);
-    else
-        iError = fcntl(SockFd, F_SETFL, iFlags | O_NONBLOCK);
-
-    return iError == -1 ? -XME_HTTP_SETSOCKOPT: 0;
-}
-
-static int XmPHttpSkConnect(SOCKET SockFd, struct sockaddr *pAddr, int iAddrSize,
-                            int iTimeout)
-{
-    int iError;
-
-    if ((iError = XmPHttpSkBlocking(SockFd, 0)) < 0)
-        return iError;
-    if (connect(SockFd, pAddr, iAddrSize) != 0)
-    {
-        struct timeval TV;
-        fd_set FdSet;
-
-        if (!PHTTP_INPROGRESS(SockFd))
-            return -XME_HTTP_CONNECT;
-        FD_ZERO(&FdSet);
-        FD_SET(SockFd, &FdSet);
-        TV.tv_sec = iTimeout;
-        TV.tv_usec = 0;
-        if (select((int) SockFd + 1, NULL, &FdSet, NULL, &TV) < 0)
-            return -XME_HTTP_SELECT;
-        if (!FD_ISSET(SockFd, &FdSet))
-            return -XME_HTTP_TIMEOUT;
-    }
-
-    return XmPHttpSkBlocking(SockFd, 1);
-}
-
-static int XmPHttpSkRead(SOCKET SockFd, void *pData, int iSize, int iTimeout)
-{
-    int iRead;
-    struct timeval TV;
-    fd_set FdSet;
-
-    FD_ZERO(&FdSet);
-    FD_SET(SockFd, &FdSet);
-    TV.tv_sec = iTimeout;
-    TV.tv_usec = 0;
-    if (select((int) SockFd + 1, &FdSet, NULL, NULL, &TV) < 0)
-        return -XME_HTTP_SELECT;
-    if (!FD_ISSET(SockFd, &FdSet))
-        return -XME_HTTP_TIMEOUT;
-    if ((iRead = recv(SockFd, pData, iSize, 0)) < 0)
-        return -XME_HTTP_SKREAD;
-    else if (iRead == 0)
-        return -XME_HTTP_DISCONNECT;
-
-    return iRead;
-}
-
-static int XmPHttpSkWrite(SOCKET SockFd, void const *pData, int iSize, int iTimeout)
-{
-    int iWrite;
-    struct timeval TV;
-    fd_set FdSet;
-
-    FD_ZERO(&FdSet);
-    FD_SET(SockFd, &FdSet);
-    TV.tv_sec = iTimeout;
-    TV.tv_usec = 0;
-    if (select((int) SockFd + 1, NULL, &FdSet, NULL, &TV) < 0)
-        return -XME_HTTP_SELECT;
-    if (!FD_ISSET(SockFd, &FdSet))
-        return -XME_HTTP_TIMEOUT;
-    if ((iWrite = send(SockFd, pData, iSize, 0)) < 0)
-        return -XME_HTTP_SKWRITE;
-
-    return iWrite;
-}
-
-static SOCKET XmPHttpSocket(XmPHttpCtx *pCtx)
-{
-    SOCKET SockFd;
-
-    if ((SockFd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Socket creation failed\n"));
-        return INVALID_SOCKET;
-    }
-
-    return SockFd;
-}
-
-int XmPHttpInit(XmPHttpCtx *pCtx)
-{
-    pCtx->iPHttpDebug = 0;
-    pCtx->iPHttpConnTimeo = XmPHttpGetIntEnv(pCtx, XM_SKCONN_TIMEO, SOCK_STD_CONTIMEO);
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Library initialization succeeded\n"));
-
-    return 0;
-}
-
-void XmPHttpCleanup(XmPHttpCtx *pCtx)
-{
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Library cleanup done\n"));
-}
-
-static struct SStream *XmPHttpStreamAttach(XmPHttpCtx *pCtx, SOCKET SockFd)
-{
-    struct SStream *pStream;
-
-    if ((pStream = (struct SStream *) malloc(sizeof(struct SStream))) == NULL)
-        return NULL;
-
-    pStream->pCtx = pCtx;
-    pStream->SockFd = SockFd;
-    pStream->iIndex = 0;
-    pStream->iInBuffer = 0;
-    pStream->iReadTimeo = XmPHttpGetIntEnv(pCtx, XM_SKRECV_TIMEO, SOCK_STD_RCVTIMEO);
-    pStream->iWriteTimeo = XmPHttpGetIntEnv(pCtx, XM_SKSEND_TIMEO, SOCK_STD_SNDTIMEO);
-
-    return pStream;
-}
-
-static void XmPHttpStreamClose(struct SStream *pStream)
-{
-    closesocket(pStream->SockFd);
-    PHTTP_DBGPRINT(pStream->pCtx, ("[phttp] Socket closed: sock=%u\n", pStream->SockFd));
-    free(pStream);
-}
-
-static int XmPHttpStreamBRefil(struct SStream *pStream)
-{
-    XmPHttpCtx *pCtx = pStream->pCtx;
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Reading socket: sock=%u\n", pStream->SockFd));
-    pStream->iIndex = 0;
-
-    pStream->iInBuffer = XmPHttpSkRead(pStream->SockFd, pStream->Buffer,
-                                       SSTREAM_BUFFER_SIZE, pStream->iReadTimeo);
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Socket read done: sock=%u recv=%d\n", pStream->SockFd,
-                          pStream->iInBuffer));
-    if (pStream->iInBuffer < 0)
-        PHTTP_DBGPRINT(pCtx, ("[phttp] error is %d\n", (unsigned int) -pStream->iInBuffer));
-
-    return pStream->iInBuffer;
-}
-
-static char *XmPHttpRdLine(char *pszLine, int iSize, struct SStream *pStream)
-{
-    int iLnSize, iTxSize;
-    XmPHttpCtx *pCtx = pStream->pCtx;
-    char *pszNL;
-
-    for (iLnSize = 0, iSize--; iLnSize < iSize;)
-    {
-        if (pStream->iIndex >= pStream->iInBuffer &&
-            XmPHttpStreamBRefil(pStream) <= 0)
-            break;
-
-        if ((pszNL = (char *) memchr(pStream->Buffer + pStream->iIndex, '\n',
-                                     pStream->iInBuffer - pStream->iIndex)) != NULL)
-        {
-            iTxSize = PHTTP_MIN(iSize - iLnSize,
-                                (int) (pszNL - (pStream->Buffer + pStream->iIndex) + 1));
-            memcpy(pszLine + iLnSize, pStream->Buffer + pStream->iIndex, iTxSize);
-            pStream->iIndex += iTxSize;
-            iLnSize += iTxSize;
-            break;
-        }
-        else
-        {
-            iTxSize = PHTTP_MIN(iSize - iLnSize, pStream->iInBuffer - pStream->iIndex);
-            memcpy(pszLine + iLnSize, pStream->Buffer + pStream->iIndex, iTxSize);
-            pStream->iIndex += iTxSize;
-            iLnSize += iTxSize;
-        }
-    }
-
-    if (iLnSize == 0)
-        return NULL;
-
-    for (; iLnSize > 0 && (pszLine[iLnSize - 1] == '\r' ||
-                           pszLine[iLnSize - 1] == '\n'); iLnSize--);
-    pszLine[iLnSize] = '\0';
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Line read: sock=%u\n"
-                          "\t'%s'\n", pStream->SockFd, pszLine));
-
-    return pszLine;
-}
-
-static int XmPHttpRead(char *pData, int iSize, struct SStream *pStream)
-{
-    int iRead = 0, iRxSize;
-    XmPHttpCtx *pCtx = pStream->pCtx;
-
-    if (pStream->iIndex < pStream->iInBuffer)
-    {
-        iRxSize = PHTTP_MIN(iSize, pStream->iInBuffer - pStream->iIndex);
-        memcpy(pData, pStream->Buffer + pStream->iIndex, iRxSize);
-        pStream->iIndex += iRxSize;
-        iRead += iRxSize;
-    }
-    while (iRead < iSize)
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Reading socket: sock=%u\n", pStream->SockFd));
-
-        iRxSize = XmPHttpSkRead(pStream->SockFd, pData + iRead,
-                                iSize - iRead, pStream->iReadTimeo);
-
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Socket read done: sock=%u recv=%d\n", pStream->SockFd,
-                              iRxSize));
-        if (iRxSize < 0)
-            break;
-        iRead += iRxSize;
-    }
-
-    return iRead;
-}
-
-static int XmPHttpPrintf(struct SStream *pStream, char const *pszFmt, ...)
-{
-    int iSize, iSent, iTxSize;
-    XmPHttpCtx *pCtx = pStream->pCtx;
-    va_list Args;
-    char szBuffer[4096];
-
-    va_start(Args, pszFmt);
-
-    iSize = vsnprintf(szBuffer, sizeof(szBuffer) - 1, pszFmt, Args);
-
-    va_end(Args);
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Sending ...\n"
-                          "(\n"
-                          "%s"
-                          ")\n", szBuffer));
-    for (iSent = 0; iSent < iSize;)
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Writing socket: sock=%u\n", pStream->SockFd));
-
-        iTxSize = XmPHttpSkWrite(pStream->SockFd, szBuffer + iSent,
-                                 iSize - iSent, pStream->iWriteTimeo);
-
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Socket write done: sock=%u send=%d\n", pStream->SockFd,
-                              iTxSize));
-        if (iTxSize < 0)
-            break;
-        iSent += iTxSize;
-    }
-
-    return iSize;
-}
-
-static int XmPHttpWrite(char const *pData, int iSize, struct SStream *pStream)
-{
-    int iSent, iTxSize;
-    XmPHttpCtx *pCtx = pStream->pCtx;
-
-    for (iSent = 0; iSent < iSize;)
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Writing socket: sock=%u\n", pStream->SockFd));
-
-        iTxSize = XmPHttpSkWrite(pStream->SockFd, pData + iSent,
-                                 iSize - iSent, pStream->iWriteTimeo);
-
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Socket write done: sock=%u send=%d\n", pStream->SockFd,
-                              iTxSize));
-        if (iTxSize < 0)
-            break;
-        iSent += iTxSize;
-    }
-
-    return iSize;
-}
-
-static struct SStream *XmPHttpConnect(XmPHttpCtx *pCtx, char const *pszServer, int iPort)
-{
-    int iError;
-    SOCKET SockFd;
-    struct hostent *pHE;
-    struct SStream *pStream;
-    struct in_addr InAddr;
-    struct sockaddr_in SAIn;
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Resolving server name: server='%s'\n", pszServer));
-    if ((InAddr.s_addr = inet_addr(pszServer)) == INADDR_NONE)
-    {
-        if ((pHE = gethostbyname(pszServer)) == NULL)
-        {
-            PHTTP_DBGPRINT(pCtx, ("[phttp] Server name resolve error: server='%s'\n", pszServer));
-            return NULL;
-        }
-
-        memcpy(&InAddr.s_addr, pHE->h_addr_list[0], pHE->h_length);
-    }
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Server name resolved: server='%s'\n", pszServer));
-
-    if ((SockFd = XmPHttpSocket(pCtx)) == INVALID_SOCKET)
-        return NULL;
-
-    memset(&SAIn, 0, sizeof(SAIn));
-    memcpy(&SAIn.sin_addr, &InAddr.s_addr, 4);
-    SAIn.sin_port = htons((short int) iPort);
-    SAIn.sin_family = AF_INET;
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Connecting to remote server: server='%s'\n", pszServer));
-    if ((iError = XmPHttpSkConnect(SockFd, (struct sockaddr *) &SAIn, sizeof(SAIn),
-                                   pCtx->iPHttpConnTimeo)) < 0)
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Connect failed: server='%s'\n", pszServer));
-        closesocket(SockFd);
-        return NULL;
-    }
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Connect succeeded: server='%s'\n", pszServer));
-
-    if ((pStream = XmPHttpStreamAttach(pCtx, SockFd)) == NULL)
-    {
-        closesocket(SockFd);
-        return NULL;
-    }
-
-    return pStream;
-}
-
-static int XmPHttpSendRequest(struct SStream *pStream, char const *pszServer,
-                              char const *pszReq, char const *pszDoc,
-                              char const * const *ppszHdrs,
-                              XmHttpCallbacks *pHCB, void *pPrivate)
-{
-    int i, iCurr;
-    long lReqSize, lRead;
-    XmPHttpCtx *pCtx = pStream->pCtx;
-    char *pszHttpVer;
-    char TxBuff[512];
-
-    if ((lReqSize = pHCB->pfGetSize(pPrivate)) < 0)
-        return -1;
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Outbound data length retrieved: size=%ld\n",
-                          lReqSize));
-
-    pszHttpVer = (char *) PHTTP_ENVGET(pCtx, XM_HTTP_VERSION);
-    if (XmPHttpPrintf(pStream, "%s %s %s\r\n", pszReq, pszDoc,
-                      pszHttpVer != NULL ? pszHttpVer: "HTTP/1.0") < 0 ||
-        XmPHttpPrintf(pStream, "Host: %s\r\n", pszServer) < 0)
-    {
-        PHTTP_ENVFREE(pszHttpVer);
-        return -1;
-    }
-    PHTTP_ENVFREE(pszHttpVer);
-    if (ppszHdrs)
-        for (i = 0; ppszHdrs[i]; i++)
-            if (XmPHttpPrintf(pStream, "%s\r\n", ppszHdrs[i]) < 0)
-                return -1;
-
-    if (XmPHttpPrintf(pStream, "Content-Length: %ld\r\n\r\n", lReqSize) < 0)
-        return -1;
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Reading and sending outbound data: sock=%u\n",
-                          pStream->SockFd));
-    for (lRead = 0; lRead < lReqSize;)
-    {
-        iCurr = (int) PHTTP_MIN(lReqSize - lRead, sizeof(TxBuff));
-        if (pHCB->pfRead(pPrivate, TxBuff, iCurr) != iCurr ||
-            XmPHttpWrite(TxBuff, iCurr, pStream) != iCurr)
-            return -1;
-        lRead += iCurr;
-    }
-    PHTTP_DBGPRINT(pCtx, ("[phttp] Outbound data sent: sock=%u\n", pStream->SockFd));
-
-    return 0;
-}
-
-static void XmPHttpParseInit(struct PHttpUrl *pPU)
-{
-    memset(pPU, 0, sizeof(*pPU));
-}
-
-static int XmPHttpParseUrl(XmPHttpCtx *pCtx, struct PHttpUrl *pPU, char const *pszUrl)
-{
-    char *pszDUrl = strdup(pszUrl), *pszTmp;
-
-    if (pszDUrl == NULL)
-    {
-        return -1;
-    }
-
-    memset(pPU, 0, sizeof(*pPU));
-    pPU->pszUrl = pszDUrl;
-    if (!strncasecmp(pszDUrl, "http://", 7))
-        pPU->iProto = URL_PROTO_HTTP, pszDUrl += 7, pPU->iPort = HTTP_DEFAULT_PORT;
-    else if (!strncasecmp(pszDUrl, "https://", 8))
-        pPU->iProto = URL_PROTO_HTTPS, pszDUrl += 8, pPU->iPort = HTTPS_DEFAULT_PORT;
-    else
-        pPU->iProto = URL_PROTO_HTTP, pPU->iPort = HTTP_DEFAULT_PORT;
-
-    pPU->pszHost = pszDUrl;
-
-    if ((pszTmp = strchr(pszDUrl, ':')) != NULL)
-    {
-        *pszTmp++ = '\0';
-        if (!isdigit(*pszTmp))
-        {
-            free((char *) pPU->pszUrl);
-            memset(pPU, 0, sizeof(*pPU));
-            return -1;
-        }
-        pPU->iPort = atoi(pszTmp);
-        pszDUrl = pszTmp;
-    }
-
-    if ((pszTmp = strchr(pszDUrl, '/')) != NULL)
-    {
-        pPU->pszDoc = strdup(pszTmp);
-        *pszTmp++ = '\0';
-    }
-    else
-        pPU->pszDoc = strdup("/");
-
-    if (pPU->pszDoc == NULL)
-    {
-        free((char *) pPU->pszUrl);
-        memset(pPU, 0, sizeof(*pPU));
-        return -1;
-    }
-
-    return 0;
-}
-
-static void XmPHttpParseFree(struct PHttpUrl *pPU)
-{
-    free((char *) pPU->pszUrl);
-    free((char *) pPU->pszDoc);
-    memset(pPU, 0, sizeof(*pPU));
-}
-
-static int XmPHttpReadChunked(struct SStream *pStream, XmHttpCallbacks *pHCB,
-                              void *pPrivate)
-{
-    int iCkSize;
-    // XmPHttpCtx *pCtx = pStream->pCtx;
-    char RxBuff[512];
-
-    do
-    {
-        if (!XmPHttpRdLine(RxBuff, sizeof(RxBuff) - 1, pStream))
-            return -1;
-        if (!sscanf(RxBuff, "%d", &iCkSize))
-            return -1;
-        if (iCkSize)
-        {
-            int iSize, iRead;
-
-            for (iSize = 0; iSize < iCkSize;)
-            {
-                iRead = PHTTP_MIN(iCkSize - iSize, sizeof(RxBuff));
-                if (XmPHttpRead(RxBuff, iRead, pStream) != iRead)
-                    return -1;
-                if (pHCB && pHCB->pfWrite &&
-                    pHCB->pfWrite(pPrivate, RxBuff, iRead) != iRead)
-                    return -1;
-                iSize += iRead;
-            }
-        }
-    } while (iCkSize);
-    while (XmPHttpRdLine(RxBuff, sizeof(RxBuff) - 1, pStream))
-        if (strlen(RxBuff) == 0)
-            break;
-
-    return 0;
-}
-
-static int XmPHttpReadResponse(struct SStream *pStream, XmHttpCallbacks *pHCB,
-                               void *pPrivate)
-{
-    int iHttpRCode, iChunked = 0, iValidRCode;
-    long lContLen = -1;
-    char *pszValue;
-    XmPHttpCtx *pCtx = pStream->pCtx;
-    char szBuffer[512];
-
-    if (!XmPHttpRdLine(szBuffer, sizeof(szBuffer) - 1, pStream))
-        return -1;
-
-    PHTTP_DBGPRINT(pCtx, ("[phttp] HTTP response: sock=%u resp='%s'\n", pStream->SockFd, szBuffer));
-    if (!sscanf(szBuffer, "%*s %d %*s", &iHttpRCode))
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] Wrong HTTP response: sock=%u resp='%s'\n", pStream->SockFd, szBuffer));
-        return -1;
-    }
-
-    // printf("[XMPHTTP] : HTTP CODE = %d\n", iHttpRCode);
-    iValidRCode = iHttpRCode == 200 || iHttpRCode == 204;
-    if ((iHttpRCode >= 100 && iHttpRCode < 200) || iHttpRCode == 204 || iHttpRCode == 304)
-        lContLen = 0;
-
-    while (XmPHttpRdLine(szBuffer, sizeof(szBuffer) - 1, pStream) != NULL)
-    {
-        PHTTP_DBGPRINT(pCtx, ("[phttp] HTTP header: sock=%u hdr='%s'\n", pStream->SockFd, szBuffer));
-        if (strlen(szBuffer) == 0)
-            break;
-        if (!strncasecmp(szBuffer, CONTLEN_HEADER, PHTTP_CSTRSIZE(CONTLEN_HEADER)))
-        {
-            pszValue = szBuffer + PHTTP_CSTRSIZE(CONTLEN_HEADER);
-            PHTTP_SKIPSPACE(pszValue);
-            lContLen = atol(pszValue);
-        }
-        else if (!strncasecmp(szBuffer, CONTENC_HEADER, PHTTP_CSTRSIZE(CONTENC_HEADER)))
-        {
-            pszValue = szBuffer + PHTTP_CSTRSIZE(CONTENC_HEADER);
-            PHTTP_SKIPSPACE(pszValue);
-            iChunked = CHUNKED_ENCODED(pszValue);
-        }
-    }
-    if (lContLen >= 0)
-    {
-        int iRead;
-        long lSize;
-
-        for (lSize = 0; lSize < lContLen;)
-        {
-            iRead = (int) PHTTP_MIN(lContLen - lSize, sizeof(szBuffer));
-            if (XmPHttpRead(szBuffer, iRead, pStream) != iRead)
-                return -1;
-            if (iValidRCode && pHCB->pfWrite &&
-                pHCB->pfWrite(pPrivate, szBuffer, iRead) != iRead)
-                return -1;
-            lSize += iRead;
-        }
-    }
-    else if (iChunked)
-    {
-        if (XmPHttpReadChunked(pStream, iValidRCode ? pHCB: NULL, pPrivate) < 0)
-            return -1;
-    }
-    else
-    {
-        int iRead;
-        long lSize;
-
-        for (lSize = 0;;)
-        {
-            if ((iRead = XmPHttpRead(szBuffer, sizeof(szBuffer), pStream)) <= 0)
-                break;
-            if (iValidRCode && pHCB->pfWrite &&
-                pHCB->pfWrite(pPrivate, szBuffer, iRead) != iRead)
-                return -1;
-            lSize += iRead;
-        }
-    }
-
-    return iValidRCode ? 0: -1;
-}
-
-static char **XmPHttpHdrSplit(char const *pszStr)
-{
-    int i, j, k, iNumStrs;
-    void *pMemBlk;
-    char **ppszPtrs;
-    char *pszDupStr;
-
-    for (i = 0, iNumStrs = 1; pszStr[i]; i++)
-        if (pszStr[i] == '|')
-            iNumStrs++;
-    if ((pMemBlk = malloc(i + 1 +
-                          (iNumStrs + 1) * sizeof(char *))) == NULL)
-        return NULL;
-    ppszPtrs = (char **) pMemBlk;
-    pszDupStr = (char *) pMemBlk + (iNumStrs + 1) * sizeof(char *);
-    memcpy(pszDupStr, pszStr, i + 1);
-    for (i = j = 0, k = -1; pszDupStr[i]; i++)
-        if (pszDupStr[i] == '|')
-        {
-            if (k >= 0)
-                ppszPtrs[j++] = pszDupStr + k;
-            pszDupStr[i] = '\0';
-            k = -1;
-        }
-        else if (k < 0)
-            k = i;
-    if (k >= 0)
-        ppszPtrs[j++] = pszDupStr + k;
-    ppszPtrs[j] = NULL;
-
-    return ppszPtrs;
-}
-
-int XmPHttpExec(XmPHttpCtx *pCtx, char const *pszMethod, char const *pszUrl,
-                XmHttpCallbacks *pHCB, void *pPrivate)
-{
-    char *pszEnv = NULL;
-    char **ppszHdrs = NULL;
-    struct SStream *pStream;
-    struct PHttpUrl PU;
-
-    XmPHttpParseInit(&PU);
-    if (XmPHttpParseUrl(pCtx, &PU, pszUrl) < 0)
-        return -1;
-    if ((pStream = XmPHttpConnect(pCtx, PU.pszHost, PU.iPort)) == NULL)
-    {
-
-        XmPHttpParseFree(&PU);
-        return -1;
-    }
-    if ((pszEnv = (char *) PHTTP_ENVGET(pCtx, XM_HTTP_HEADERS)) != NULL &&
-        (ppszHdrs = XmPHttpHdrSplit(pszEnv)) == NULL)
-    {
-
-        PHTTP_ENVFREE(pszEnv);
-        XmPHttpStreamClose(pStream);
-        XmPHttpParseFree(&PU);
-        return -1;
-    }
-    PHTTP_ENVFREE(pszEnv);
-
-    if (XmPHttpSendRequest(pStream, PU.pszHost, pszMethod, PU.pszDoc,
-                           (char const * const *) ppszHdrs, pHCB, pPrivate) < 0 ||
-        XmPHttpReadResponse(pStream, pHCB, pPrivate) < 0)
-    {
-
-        if (ppszHdrs != NULL)
-            free(ppszHdrs);
-        XmPHttpStreamClose(pStream);
-        XmPHttpParseFree(&PU);
-        return -1;
-    }
-    free(ppszHdrs);
-    XmPHttpStreamClose(pStream);
-    XmPHttpParseFree(&PU);
-
-    return 0;
-}
-
diff --git a/test/XMPHttp.h b/test/XMPHttp.h
deleted file mode 100644 (file)
index 08ce721..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
-    Copyright (c) 2013, McAfee, Inc.
-    
-    All rights reserved.
-    
-    Redistribution and use in source and binary forms, with or without modification,
-    are permitted provided that the following conditions are met:
-    
-    Redistributions of source code must retain the above copyright notice, this list
-    of conditions and the following disclaimer.
-    
-    Redistributions in binary form must reproduce the above copyright notice, this
-    list of conditions and the following disclaimer in the documentation and/or other
-    materials provided with the distribution.
-    
-    Neither the name of McAfee, Inc. nor the names of its contributors may be used
-    to endorse or promote products derived from this software without specific prior
-    written permission.
-    
-    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-    OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#if !defined(_XMPOSIXHTTP_H)
-#define _XMPOSIXHTTP_H
-
-#include "XMHttp.h"
-
-
-typedef struct XmPHttpCtx_struct
-{
-    int iPHttpConnTimeo;
-    int iPHttpDebug;
-} XmPHttpCtx;
-
-
-EXTERNC_BEGIN;
-
-int XmPHttpInit(XmPHttpCtx *pCtx);
-void XmPHttpCleanup(XmPHttpCtx *pCtx);
-int XmPHttpExec(XmPHttpCtx *pCtx, char const *pszMethod, char const *pszUrl,
-                XmHttpCallbacks *pHCB, void *pPrivate);
-
-EXTERNC_END;
-
-#endif
-
diff --git a/test/colour_log_formatter.cpp b/test/colour_log_formatter.cpp
new file mode 100644 (file)
index 0000000..94738f7
--- /dev/null
@@ -0,0 +1,252 @@
+/*
+ *  Boost Software License - Version 1.0 - August 17th, 2003
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *  FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+ *  SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+ *  FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ *  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ *  DEALINGS IN THE SOFTWARE.
+ */
+#include "colour_log_formatter.h"
+
+#include <iostream>
+#include <string>
+
+#include <boost/test/unit_test_suite_impl.hpp>
+#include <boost/test/framework.hpp>
+#include <boost/test/utils/basic_cstring/io.hpp>
+#include <boost/test/utils/lazy_ostream.hpp>
+#include <boost/version.hpp>
+
+// ************************************************************************** //
+// **************            colour_log_formatter            ************** //
+// ************************************************************************** //
+
+using namespace boost::unit_test;
+namespace Csr {
+namespace Test {
+
+namespace {
+
+const char* GREEN_BEGIN = "\033[0;32m";
+const char* RED_BEGIN = "\033[0;31m";
+const char* CYAN_BEGIN = "\033[0;36m";
+const char* BOLD_YELLOW_BEGIN = "\033[1;33m";
+const char* COLOR_END = "\033[m";
+
+const_string
+test_phase_identifier()
+{
+       return framework::is_initialized()
+                       ? const_string(framework::current_test_case().p_name.get())
+                       : BOOST_TEST_L("Test setup");
+}
+
+const_string
+get_basename(const const_string &file_name) {
+       return basename(file_name.begin());
+}
+
+std::string
+get_basename(const std::string &file_name) {
+       return basename(file_name.c_str());
+}
+
+} // local namespace
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_start(
+               std::ostream& output,
+               counter_t test_cases_amount)
+{
+       if (test_cases_amount > 0)
+               output  << "Running " << test_cases_amount << " test "
+                               << (test_cases_amount > 1 ? "cases" : "case") << "..." << std::endl;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_finish( std::ostream& ostr )
+{
+       ostr.flush();
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_build_info( std::ostream& output)
+{
+       output << "Platform: " << BOOST_PLATFORM << std::endl
+                       << "Compiler: " << BOOST_COMPILER << std::endl
+                       << "STL  : " << BOOST_STDLIB << std::endl
+                       << "Boost   : " << BOOST_VERSION/100000 << "."
+                                                       << BOOST_VERSION/100 % 1000 << "."
+                                                       << BOOST_VERSION % 100 << std::endl;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::test_unit_start(
+               std::ostream& output,
+               test_unit const& tu)
+{
+       if (tu.p_type_name->find(const_string("suite")) == 0)
+               output << "Starting test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl;
+       else
+               output << "Running test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::test_unit_finish(
+               std::ostream& output,
+               test_unit const& tu,
+               unsigned long elapsed)
+{
+       if (tu.p_type_name->find(const_string("suite")) == 0) {
+               output << "Finished test " << tu.p_type_name << " \"" << tu.p_name << "\""<< std::endl;
+               return;
+       }
+
+       std::string color = GREEN_BEGIN;
+       std::string status = "OK";
+
+       if (m_isTestCaseFailed) {
+               color = RED_BEGIN;
+               status = "FAIL";
+       }
+
+       output << "\t" << "[   " << color << status << COLOR_END << "   ]";
+
+       output << ", " << CYAN_BEGIN << "time: ";
+       if (elapsed > 0) {
+               if( elapsed % 1000 == 0 )
+                       output << elapsed/1000 << "ms";
+               else
+                       output << elapsed << "mks";
+       } else {
+               output << "N/A";
+       }
+
+       output << COLOR_END << std::endl;
+       m_isTestCaseFailed = false;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::test_unit_skipped(
+               std::ostream& output,
+               test_unit const& tu)
+{
+       output  << "Test " << tu.p_type_name << " \"" << tu.p_name << "\"" << "is skipped" << std::endl;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_exception(
+               std::ostream& output,
+               log_checkpoint_data const& checkpoint_data,
+               boost::execution_exception const& ex)
+{
+       boost::execution_exception::location const& loc = ex.where();
+       output << '\t' << BOLD_YELLOW_BEGIN << get_basename(loc.m_file_name)
+                       << '(' << loc.m_line_num << "), ";
+
+       output << "fatal error in \""
+                       << (loc.m_function.is_empty() ? test_phase_identifier() : loc.m_function ) << "\": ";
+
+       output << COLOR_END << ex.what();
+
+       if (!checkpoint_data.m_file_name.is_empty()) {
+               output << '\n';
+               output << "\tlast checkpoint : " << get_basename(checkpoint_data.m_file_name)
+                               << '(' << checkpoint_data.m_line_num << ")";
+               if (!checkpoint_data.m_message.empty())
+                       output << ": " << checkpoint_data.m_message;
+       }
+
+       output << std::endl;
+       m_isTestCaseFailed = true;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_entry_start(
+               std::ostream& output,
+               log_entry_data const& entry_data,
+               log_entry_types let)
+{
+       switch (let) {
+       case BOOST_UTL_ET_INFO:
+               output << '\t' << entry_data.m_file_name << '(' << entry_data.m_line_num << "), ";
+               output << "info: ";
+               break;
+       case BOOST_UTL_ET_MESSAGE:
+               break;
+       case BOOST_UTL_ET_WARNING:
+               output << '\t' << get_basename(entry_data.m_file_name) << '(' << entry_data.m_line_num << "), ";
+               output << "warning in \"" << test_phase_identifier() << "\": ";
+               break;
+       case BOOST_UTL_ET_ERROR:
+               output << '\t' << BOLD_YELLOW_BEGIN <<  get_basename(entry_data.m_file_name)
+                       << '(' << entry_data.m_line_num << "), ";
+               output << "error in \"" << test_phase_identifier() << "\": ";
+               m_isTestCaseFailed = true;
+               break;
+       case BOOST_UTL_ET_FATAL_ERROR:
+               output << '\t' << BOLD_YELLOW_BEGIN <<  get_basename(entry_data.m_file_name)
+                       << '(' << entry_data.m_line_num << "),  ";
+               output <<  " fatal error in \"" << test_phase_identifier() << "\": ";
+               m_isTestCaseFailed = true;
+               break;
+       }
+       output << COLOR_END;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_entry_value(
+               std::ostream& output,
+               const_string value)
+{
+       output << value;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_entry_value(
+               std::ostream& output,
+               lazy_ostream const& value)
+{
+       output << value;
+}
+
+//____________________________________________________________________________//
+
+void
+colour_log_formatter::log_entry_finish(
+               std::ostream& output)
+{
+       output << std::endl;
+}
+
+//____________________________________________________________________________//
+
+//____________________________________________________________________________//
+} // namespace Test
+} // namespace Csr
+
+//____________________________________________________________________________//
+
diff --git a/test/colour_log_formatter.h b/test/colour_log_formatter.h
new file mode 100644 (file)
index 0000000..4c3140f
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ *  Boost Software License - Version 1.0 - August 17th, 2003
+ *
+ *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ *  FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+ *  SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+ *  FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ *  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ *  DEALINGS IN THE SOFTWARE.
+ */
+
+
+#pragma once
+
+#include <boost/test/unit_test_log_formatter.hpp>
+
+namespace Csr {
+namespace Test {
+
+class colour_log_formatter : public boost::unit_test::unit_test_log_formatter {
+public:
+       // Formatter interface
+       colour_log_formatter() : m_isTestCaseFailed(false) {}
+       void log_start(
+                               std::ostream&,
+                               boost::unit_test::counter_t test_cases_amount);
+       void log_finish(std::ostream&);
+       void log_build_info(std::ostream&);
+
+       void test_unit_start(
+                               std::ostream&,
+                               boost::unit_test::test_unit const& tu);
+       void test_unit_finish(
+                               std::ostream&,
+                               boost::unit_test::test_unit const& tu,
+                               unsigned long elapsed);
+       void test_unit_skipped(
+                               std::ostream&,
+                               boost::unit_test::test_unit const& tu);
+
+       void log_exception(
+                               std::ostream&,
+                               boost::unit_test::log_checkpoint_data const&,
+                               boost::execution_exception const& ex);
+
+       void log_entry_start(
+                               std::ostream&,
+                               boost::unit_test::log_entry_data const&,
+                               log_entry_types let);
+       void log_entry_value(
+                               std::ostream&,
+                               boost::unit_test::const_string value);
+       void log_entry_value(
+                               std::ostream&,
+                               boost::unit_test::lazy_ostream const& value);
+       void log_entry_finish(std::ostream&);
+
+private:
+       bool m_isTestCaseFailed;
+};
+
+}
+}
diff --git a/test/test-api.cpp b/test/test-api.cpp
new file mode 100644 (file)
index 0000000..0c060d1
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file        test-api.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#define BOOST_TEST_MODULE CSR_API_TEST
+#include <csr/api.h>
+
+#include <string>
+#include <iostream>
+#include <boost/test/unit_test.hpp>
+
+BOOST_AUTO_TEST_SUITE(API_TEST)
+
+BOOST_AUTO_TEST_CASE(FILE_SCAN)
+{
+       std::string filepath = "this is not real file path";
+       int ret = CSR_ERROR_UNKNOWN;
+
+       BOOST_REQUIRE_NO_THROW(ret = csr_file_scan(filepath.c_str()));
+       BOOST_REQUIRE(ret == CSR_ERROR_NONE);
+}
+
+BOOST_AUTO_TEST_CASE(FILE_JUDGE)
+{
+       std::string filepath = "this is not real file path";
+       int ret = CSR_ERROR_UNKNOWN;
+       int judge = 1;
+
+       BOOST_REQUIRE_NO_THROW(ret = csr_file_judge(filepath.c_str(), judge));
+       BOOST_REQUIRE(ret == CSR_ERROR_NONE);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/test/test-main.cpp b/test/test-main.cpp
new file mode 100644 (file)
index 0000000..581e3ed
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file       test-main.cpp
+ * @author     Kyungwook Tak(k.tak@samsung.com)
+ * @version    1.0
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/unit_test_log.hpp>
+#include <boost/test/results_reporter.hpp>
+#include <colour_log_formatter.h>
+
+struct TestConfig {
+       TestConfig()
+       {
+               boost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_test_units);
+               boost::unit_test::results_reporter::set_level(boost::unit_test::SHORT_REPORT);
+               boost::unit_test::unit_test_log.set_formatter(new Csr::Test::colour_log_formatter);
+       }
+};
+
+BOOST_GLOBAL_FIXTURE(TestConfig)